The roofline lesson placed prefill attention far to the right of the ridge: FLOPs on inputs. That is true of the math. A straightforward implementation is memory-bound anyway, and the story of attention kernels since 2022 is about closing that gap — first for HBM traffic, then for the parts of the GPU that are not tensor cores. One algebraic fact carries the whole lesson: softmax-weighted sums can be computed in pieces and merged.
What standard attention moves
Per head, with :
The textbook implementation writes to HBM, reads it back for the softmax, writes , and reads again for the second GEMM: HBM accesses (FlashAttention, Theorem 2). With and bf16, alone is 128 MiB per head per sequence. Intensity: FLOPs over roughly bytes gives for — below the H100 ridge of ~295, so the “compute-bound” operation runs memory-bound. The fix is to never let or leave on-chip SRAM.
Online softmax: a merge operator
To normalise a row we need its max (for stability) and its sum. Both can be maintained while streaming. Represent a partial result over a set of keys by three things: the running max, the running denominator, and an unnormalised output,
Two partial states over disjoint key sets combine exactly:
and the answer is , with . Check: every term multiplied by becomes , so the merged state is the state you would have computed in one pass. is associative and commutative, which means any blocking and any reduction order gives the exact answer (up to floating-point rounding). FlashAttention folds K/V tiles in one at a time; Flash-Decoding splits the keys across thread blocks and merges at the end; the fused cross-entropy below uses the same LSE bookkeeping over chunks of tokens.
FlashAttention: tiling and recomputation
Keep a tile of queries on chip, stream through in tiles of keys, and fold each tile into with . and exist only as a tile in SRAM. With SRAM of elements the paper picks , .
IO count. is read once and written once (). and are re-streamed once per resident block; with blocks of size there are of them:
For this is far below , and Proposition 3 of the paper shows no exact algorithm does asymptotically better for all . The paper reports up to 9× fewer HBM accesses and up to 7.6× faster attention on GPT-2.
Backward. Storing for the backward pass would bring back the term. FlashAttention stores only the per-row LSE ( floats per head) and recomputes and tile by tile in the backward. That is more FLOPs and fewer bytes — the right trade when you are below the ridge.
roofline 레슨은 prefill attention을 ridge의 한참 오른쪽에 놓았다. 입력 에 FLOPs 이다. 이것은 수식에 대해서는 맞다. 그런데 곧이곧대로 구현하면 memory-bound가 된다. 2022년 이후 attention kernel의 역사는 이 간극을 메우는 이야기다. 처음엔 HBM 트래픽, 그다음엔 tensor core가 아닌 GPU 부품들. 레슨 전체를 끌고 가는 대수적 사실은 하나다. softmax 가중합은 조각으로 계산해 합칠 수 있다.
표준 attention이 옮기는 것
head 하나, 에 대해
교과서식 구현은 를 HBM에 쓰고, softmax를 위해 다시 읽고, 를 쓰고, 두 번째 GEMM을 위해 를 또 읽는다. HBM 접근이 이다(FlashAttention, Theorem 2). , bf16이면 만 시퀀스·head당 128 MiB다. 산술 강도는 FLOPs ÷ 약 바이트로 일 때 . H100 ridge ~295보다 낮다. “compute-bound” 연산이 memory-bound로 돈다. 해법은 와 가 칩 안 SRAM을 떠나지 않게 하는 것이다.
Online softmax: 결합 연산
행을 정규화하려면 최댓값(안정성)과 합이 필요하다. 둘 다 흘려보내며 유지할 수 있다. key 집합 에 대한 부분 결과를 세 가지로 나타낸다. running max, running 분모, 그리고 정규화하지 않은 출력.
서로소인 key 집합에 대한 두 부분 상태는 정확히 합쳐진다.
답은 , 이다. 확인: 항 에 을 곱하면 이 되므로, 합친 상태는 한 번에 계산했을 상태와 같다. 는 결합법칙과 교환법칙을 만족한다. 즉 어떻게 블록을 나누든, 어떤 순서로 reduce하든 정확한 답이 나온다(부동소수점 반올림을 빼면). FlashAttention은 K/V tile을 하나씩 접어 넣고, Flash-Decoding은 key를 thread block들에 나눠 끝에 합치며, 아래의 fused cross-entropy는 토큰 chunk에 대해 같은 LSE 장부를 쓴다.
FlashAttention: tiling과 재계산
query 개짜리 tile을 칩에 두고, 를 key 개짜리 tile로 흘려보내며 각 tile을 로 에 접어 넣는다. 와 는 SRAM 안의 tile로만 존재한다. SRAM이 원소 개라면 논문은 , 를 고른다.
IO 세기. 는 한 번 읽고 는 한 번 쓴다(). 와 는 칩에 상주하는 블록마다 한 번씩 다시 흘러가는데, 블록 크기가 이면 블록이 개다.
이면 보다 훨씬 작고, 논문의 Proposition 3은 모든 에 대해 점근적으로 이보다 나은 정확한 알고리즘이 없음을 보인다. 논문은 HBM 접근이 최대 9배 줄고 GPT-2의 attention이 최대 7.6배 빨라졌다고 보고한다.
역전파. 역전파를 위해 를 저장하면 항이 돌아온다. FlashAttention은 행마다 LSE(개 float/head)만 저장하고 역전파에서 와 를 tile 단위로 다시 계산한다. FLOPs는 늘고 바이트는 준다. ridge 아래에 있을 때 옳은 거래다.
Step through the first Q tile with : the key columns 5, 11 and 14 hold large scores, and when such a tile arrives turns red — the old accumulator is shrunk by . After the last tile of the row block every error bar is exactly zero. Switch on causal: tiles above the diagonal are skipped entirely, which is where causal attention’s 2× saving comes from in a kernel. With the kernel visits 10 of the 16 tiles, so K/V reads fall from 512 to 320 elements (plus 64 for : 576 → 384 reads in total); the diagonal tiles are still visited, so the saving approaches 2× only when the tiles are small relative to . The naive kernel in the readout materialises the full and either way: 704 reads and 576 writes against FlashAttention’s 64 writes of .
FlashAttention-2: the non-matmul FLOPs
FlashAttention reached only 25–40% of A100 peak. The reason is the other side of the roofline: an A100 does 312 TFLOP/s of FP16 matmul but only 19.5 TFLOP/s of non-matmul FP32, so every exponential, max and rescale is 16× more expensive than a tensor-core FLOP. FA2 (i) rescales only once at the end instead of per tile, (ii) parallelises over query blocks as well as batch and heads, so long sequences with small batch still fill the GPU, and (iii) splits Q rather than K across the warps of a block, so warps never exchange partial results through shared memory. Result: 50–73% of A100 peak, and 225 TFLOP/s per A100 (72% MFU) end-to-end in GPT training.
FlashAttention-3: overlap on Hopper
On the H100, FA2 reached only 35%. Hopper made the tensor cores asynchronous (WGMMA) and added a copy engine (TMA), so data movement, matmul and softmax can run concurrently — if the kernel is written for it. And they must, because of the exponential. The FA3 paper’s arithmetic: the H100 SXM5 has 989 TFLOP/s of FP16 matmul but only 3.9 TFLOP/s of special functions (16 ops/clock/SM × 132 SMs × 1.83 GHz). Per score, the two GEMMs cost FLOPs and the softmax one exponential, so at
Run serially, the tensor cores idle a third of the time. FA3 therefore uses warp specialisation (producer warps issue TMA loads; consumer warpgroups do WGMMA), ping-pong scheduling between two warpgroups so that one’s softmax runs under the other’s GEMMs, and pipelining inside a warpgroup. For FP8 it adds per-block scales and incoherent processing — multiplying and by a random orthogonal matrix, which leaves unchanged but spreads outliers — giving 2.6× lower error than a baseline FP8 attention. Headline: 740 TFLOP/s in FP16 (75% utilisation) and close to 1.2 PFLOP/s in FP8.
FlashAttention-4: asymmetric scaling on Blackwell
From H100 to B200 the BF16 tensor-core rate per SM doubled (4096 → 8192 ops/clock/SM) while the exponential unit (MUFU, 16 ops/clock/SM) and shared-memory bandwidth (128 B/clock/SM) stayed the same. Redo the ratio per SM per clock at : the MMA takes clock per score and the exponential clock. The exponentials now cost as much as the matmuls; even perfect overlap leaves no slack, and at the exponentials dominate. FA4’s answers:
- Software exponential. Compute on the FMA pipe as well as on the MUFU: Cody–Waite range reduction to , a degree-3 polynomial for , and the integer part placed straight into the float’s exponent bits. Only a subset of entries (10–25% per row) is emulated, so the two pipes share the load.
- Conditional rescaling. Rescale only when the running max grows by more than . Skipping a rescale is exact: and keep the same stale reference max, so their ratio is unchanged; the stale max only lets entries of exceed 1 by at most , harmless in FP32 accumulators.
- Blackwell plumbing. Accumulators live in tensor memory (TMEM, 256 KB per SM) and
tcgen05.mmais asynchronous; the 2-CTA MMA mode spans a pair of SMs for a 256×256×16 tile. The kernel is written in CuTeDSL.
Reported: up to 1613 TFLOP/s in BF16 on B200 (71% utilisation), 1.3× over cuDNN 9.13 and 2.7× over Triton.
로 첫 Q tile을 한 step씩 넘겨 보라. key 열 5, 11, 14에 큰 score가 있고, 그런 tile이 오면 가 빨개진다. 이전 누적값이 배로 줄어든다. 행 블록의 마지막 tile이 지나면 모든 오차 막대가 정확히 0이 된다. causal을 켜면 대각선 위의 tile은 통째로 건너뛴다. kernel에서 causal attention의 2배 절감은 여기서 나온다. 이면 kernel은 16개 tile 중 10개만 방문하므로 K/V 읽기가 512에서 320원소로 준다(의 64를 더하면 읽기 전체가 576 → 384). 대각선 tile은 여전히 방문하므로 2배 절감에 가까워지는 것은 tile이 에 비해 작을 때다. 수치의 naive kernel은 어느 쪽이든 전체 와 를 만든다. 읽기 704, 쓰기 576으로, FlashAttention이 를 쓰는 64와 대비된다.
FlashAttention-2: 행렬곱이 아닌 FLOPs
FlashAttention은 A100 peak의 25–40%밖에 쓰지 못했다. 이유는 roofline의 다른 쪽에 있다. A100은 FP16 행렬곱이 312 TFLOP/s지만 행렬곱이 아닌 FP32는 19.5 TFLOP/s라서, 지수함수·max·rescale 하나하나가 tensor core FLOP보다 16배 비싸다. FA2는 (i) 의 rescale을 tile마다가 아니라 끝에 한 번만 하고, (ii) 배치와 head뿐 아니라 query 블록 방향으로도 병렬화해서 배치가 작은 긴 시퀀스도 GPU를 채우며, (iii) 블록 안의 warp들에 K가 아니라 Q를 나눠 warp끼리 shared memory로 부분 결과를 주고받지 않게 한다. 결과: A100 peak의 50–73%, GPT 학습 end-to-end에서 A100당 225 TFLOP/s(MFU 72%).
FlashAttention-3: Hopper에서 겹치기
H100에서 FA2는 35%에 그쳤다. Hopper는 tensor core를 비동기로 만들고(WGMMA) 복사 엔진(TMA)을 더해, kernel을 그렇게 짜기만 하면 데이터 이동·행렬곱·softmax가 동시에 돌 수 있게 했다. 그리고 지수함수 때문에 반드시 그래야 한다. FA3 논문의 산수: H100 SXM5는 FP16 행렬곱 989 TFLOP/s에 특수함수는 3.9 TFLOP/s뿐이다(16 ops/clock/SM × SM 132개 × 1.83 GHz). score 하나당 GEMM 두 개가 FLOPs, softmax가 지수함수 하나이므로 에서
이다. 직렬로 돌리면 tensor core가 시간의 1/3을 논다. 그래서 FA3는 warp specialisation(producer warp가 TMA 로드를 내고 consumer warpgroup이 WGMMA를 한다), 한 warpgroup의 softmax가 다른 warpgroup의 GEMM 밑에서 돌게 하는 ping-pong scheduling, warpgroup 안의 pipelining을 쓴다. FP8에서는 블록별 scale과 incoherent processing을 더한다. 와 에 같은 무작위 직교행렬을 곱하면 은 그대로이고 outlier는 퍼진다. 기준 FP8 attention보다 오차가 2.6배 작다. 대표 수치: FP16 740 TFLOP/s(활용률 75%), FP8 1.2 PFLOP/s 근처.
FlashAttention-4: Blackwell의 비대칭 확장
H100에서 B200으로 오면서 SM당 BF16 tensor core 속도는 두 배가 됐지만(4096 → 8192 ops/clock/SM), 지수함수 유닛(MUFU, 16 ops/clock/SM)과 shared memory 대역폭(128 B/clock/SM)은 그대로다. 에서 SM·clock 단위로 비를 다시 계산하면, MMA는 score당 clock, 지수함수도 clock이다. 이제 지수함수가 행렬곱만큼 비싸다. 완벽하게 겹쳐도 여유가 없고, 에서는 지수함수가 지배한다. FA4의 답:
- 소프트웨어 지수함수. 를 MUFU뿐 아니라 FMA 파이프에서도 계산한다. Cody–Waite range reduction으로 로 나누고, 는 3차 다항식으로, 정수부는 float의 지수 비트에 바로 넣는다. 행마다 일부(10–25%)만 에뮬레이트해서 두 파이프가 부하를 나눈다.
- 조건부 rescaling. running max가 보다 많이 커질 때만 를 rescale한다. rescale을 건너뛰어도 정확하다. 과 가 같은 낡은 기준 max를 쓰므로 둘의 비는 변하지 않는다. 낡은 max 때문에 의 원소가 1을 넘을 수 있지만 많아야 배라서 FP32 누산기에서는 무해하다.
- Blackwell 배관. 누산기는 tensor memory(TMEM, SM당 256 KB)에 살고
tcgen05.mma는 비동기다. 2-CTA MMA 모드는 SM 두 개에 걸쳐 256×256×16 tile을 계산한다. kernel은 CuTeDSL로 썼다.
보고된 수치: B200 BF16에서 최대 1613 TFLOP/s(활용률 71%), cuDNN 9.13 대비 1.3배, Triton 대비 2.7배.
Things to try: on Hopper with overlap off the tile time is MMA + exp + FMA and the tensor cores are busy under 60% of it; turn overlap on and the MMA bar sets the time. Switch to B200: MMA halves, exp does not — even with overlap there is zero slack at and a 50% ceiling at . Drag the emulation share up to ~25–35% and the exp work splits across two pipes; on B300, whose MUFU is twice as fast (32 ops/clock/SM per the FA4 paper), the problem mostly disappears. The FMA-pipe costs per score are our estimates, not measured values.
Decode: Flash-Decoding and split-KV
In decode each sequence brings one query per head. A FlashAttention-style kernel parallelises over (batch × heads × query blocks), and with one query block there is little to parallelise: at batch 1 with 8 KV heads per GPU, 8 thread blocks run on a 132-SM H100. Each streams its share of the KV cache, but only 8 SMs’ worth of load bandwidth is in use. Recall from the roofline that decode attention is pure bandwidth (), so this is a direct loss.
Flash-Decoding adds a parallel dimension along the keys: split the KV sequence into chunks, let each thread block compute a partial — written out as a normalised output and its LSE — and merge them with in a small second kernel. The authors report up to 8× faster generation for very long sequences with CodeLlama-34B, with the attention itself up to 50× faster than FlashAttention. Two refinements matter in practice: GQA packing — process the query heads that share a KV head in the same block, turning matrix–vector products into one small matrix–matrix product over the same KV bytes — and choosing from the batch so the grid just fills the GPU.
해 볼 것: Hopper에서 overlap을 끄면 tile 시간은 MMA + exp + FMA이고 tensor core는 그중 60%도 일하지 못한다. overlap을 켜면 MMA 막대가 시간을 정한다. B200으로 바꾸면 MMA는 절반이 되고 exp는 그대로다. overlap을 해도 에서 여유가 0이고 에서는 상한이 50%다. 에뮬레이션 비율을 25–35% 정도로 끌면 exp 작업이 두 파이프로 나뉜다. MUFU가 두 배 빠른 B300(FA4 논문 기준 32 ops/clock/SM)에서는 문제가 대부분 사라진다. score당 FMA 파이프 비용은 측정값이 아니라 우리의 추정이다.
Decode: Flash-Decoding과 split-KV
decode에서 시퀀스는 head마다 query를 하나만 가져온다. FlashAttention식 kernel은 (배치 × head × query 블록)으로 병렬화하는데, query 블록이 하나면 병렬화할 것이 거의 없다. 배치 1, GPU당 KV head 8개라면 SM 132개짜리 H100에서 thread block 8개가 돈다. 각자 KV cache 몫을 흘려 읽지만, 쓰이는 로드 대역폭은 SM 8개 분량이다. roofline에서 봤듯 decode attention은 순수한 대역폭 문제()이므로 이것은 그대로 손실이다.
Flash-Decoding은 key 방향으로 병렬 차원을 하나 더한다. KV 시퀀스를 개 chunk로 나누고, thread block마다 부분 를 정규화된 출력과 LSE 형태로 써낸 뒤, 작은 두 번째 kernel에서 로 합친다. 저자들은 CodeLlama-34B에서 아주 긴 시퀀스의 생성이 최대 8배, attention 자체는 FlashAttention보다 최대 50배 빨라졌다고 보고한다. 실전에서는 두 가지가 중요하다. GQA packing: KV head 하나를 공유하는 query head 개를 같은 블록에서 처리해, 같은 KV 바이트에 대해 행렬–벡터 곱 개를 작은 행렬–행렬 곱 하나로 바꾼다. 그리고 격자가 GPU를 딱 채우도록 배치에 따라 를 고른다.
Paged-attention kernels
A serving engine stores the KV cache in fixed-size blocks scattered through memory (next lesson), so the decode kernel cannot assume a contiguous : it reads each sequence’s block table and gathers. The cost is an indirection per block and less regular memory access, which is why block size is a kernel parameter as much as a memory-manager one (vLLM’s default is 16 tokens; on the ShareGPT trace 16–128 performed best, on Alpaca 16–32). FlashInfer generalises this: paged, ragged and prefix-shared caches are all expressed as one block-sparse matrix, attention variants are JIT-compiled from templates, and a load-balancing scheduler splits uneven work (a mix of 100-token and 100K-token contexts) across SMs while staying CUDA-graph compatible. It reports 29–69% lower inter-token latency than compiler backends on serving benchmarks.
The same trick at the LM head: fused linear + cross-entropy
The other (something huge) matrix in a transformer is the logits: tokens × vocabulary. Liger Kernel’s example: Gemma’s 256K vocabulary at batch 8 and length 4096 gives a 16.8 GB bf16 logit tensor. Fused linear cross-entropy chunks the flattened hidden states, and for each chunk computes logits , the per-row LSE and loss, and the gradient in place; it then forms for the chunk and accumulates . Only a chunk × tile is ever alive. This is exactly what an RL trainer computes for every rollout token — the log-probabilities — so on long rollouts it is the difference between fitting a micro-batch and not.
Implementing it
The block checks every claim of this lesson in NumPy: online LSE, tiled FlashAttention (non-causal and causal) against naive attention, FA4-style lazy rescaling, the HBM-traffic count, split-KV decoding with the LSE merge, the float32 non-associativity that makes results depend on the split count, and the chunked linear-cross-entropy against the full one (loss and both gradients).
import numpy as np
rng = np.random.default_rng(0)
def naive_attention(Q, K, V, causal=False):
S = Q @ K.T / np.sqrt(Q.shape[1]) # N x N scores: materialised in HBM
if causal:
S = np.where(np.tril(np.ones(S.shape, dtype=bool)), S, -np.inf)
P = np.exp(S - S.max(axis=1, keepdims=True))
return (P / P.sum(axis=1, keepdims=True)) @ V
# 1) online softmax: one pass, running max m and running denominator l
x = rng.normal(size=1000) * 8
m, l = -np.inf, 0.0
for j in range(0, len(x), 64):
xb = x[j:j + 64]
m_new = max(m, xb.max())
l = l * np.exp(m - m_new) + np.exp(xb - m_new).sum() # rescale the old sum to the new max
m = m_new
ref = x.max() + np.log(np.exp(x - x.max()).sum())
print(f"online logsumexp {m + np.log(l):.12f} vs two-pass {ref:.12f}")
# 2) FlashAttention forward, FA2 loop order: outer over query blocks, inner over K/V blocks
def flash_attention(Q, K, V, Br=64, Bc=64, causal=False):
N, d = Q.shape
O, lse, hbm = np.zeros_like(Q), np.zeros(N), 0
for i in range(0, N, Br):
q = Q[i:i + Br]; hbm += q.size # load a Q tile once
m = np.full(len(q), -np.inf); l = np.zeros(len(q)); acc = np.zeros((len(q), d))
for j in range(0, N, Bc):
if causal and j > i + len(q) - 1:
break # tile entirely above the diagonal: skip
k, v = K[j:j + Bc], V[j:j + Bc]; hbm += k.size + v.size
s = q @ k.T / np.sqrt(d)
if causal:
rows, cols = np.arange(i, i + len(q))[:, None], np.arange(j, j + len(k))[None, :]
s = np.where(cols <= rows, s, -np.inf)
m_new = np.maximum(m, s.max(axis=1))
p = np.exp(s - m_new[:, None])
alpha = np.exp(m - m_new) # correction for the stale max
l = alpha * l + p.sum(axis=1)
acc = alpha[:, None] * acc + p @ v # unnormalised output, rescaled
m = m_new
O[i:i + Br] = acc / l[:, None] # normalise once at the end (FA2)
lse[i:i + Br] = m + np.log(l) # saved for the backward pass
hbm += acc.size
return O, lse, hbm
N, d = 512, 64
Q, K, V = (rng.normal(size=(N, d)) for _ in range(3))
for causal in [False, True]:
O, lse, hbm = flash_attention(Q, K, V, causal=causal)
err = np.abs(O - naive_attention(Q, K, V, causal)).max()
print(f"causal={causal!s:<5} max |flash - naive| = {err:.2e}")
# 2b) FA4-style conditional rescaling: keep a stale max unless the new one exceeds it by tau
def flash_lazy(Q, K, V, B=64, tau=np.log(256.0)): # tau = log 256, i.e. log2-threshold 8
N, d = Q.shape; O = np.zeros_like(Q); rescales = skipped = 0
for i in range(0, N, B):
q = Q[i:i + B]; m = np.full(len(q), -np.inf); l = np.zeros(len(q)); acc = np.zeros((len(q), d))
for j in range(0, N, B):
s = q @ K[j:j + B].T / np.sqrt(d)
grow = s.max(1) > m + tau # FA4 decides this per warp; per row here
m_new = np.where(grow, np.maximum(m, s.max(1)), m)
rescales += (grow & np.isfinite(m)).sum(); skipped += (~grow & (s.max(1) > m)).sum()
alpha = np.exp(m - m_new) # == 1 wherever the max was kept stale
p = np.exp(s - m_new[:, None]) # entries may now exceed 1 (at most e^tau)
l = alpha * l + p.sum(1); acc = alpha[:, None] * acc + p @ V[j:j + B]; m = m_new
O[i:i + B] = acc / l[:, None] # same stale max in acc and l: ratio exact
return O, rescales, skipped
Ob, nres, nskip = flash_lazy(Q * 3, K, V) # sharper scores: more max updates
print(f"lazy rescale: {nres} rescales done, {nskip} skipped; max err {np.abs(Ob - naive_attention(Q * 3, K, V)).max():.1e}")
# 3) HBM traffic (elements): naive writes and re-reads S and P; flash re-reads K,V once per Q tile
print("\nHBM elements moved, d=64: naive flash(B=64) flash(B=256)")
for N in [1024, 4096, 16384]:
naive = 4 * N * d + 4 * N * N
fl = lambda B: 2 * N * d + 2 * N * d * (N / B)
print(f" N={N:6d} {naive:14.3e} {fl(64):14.3e} {fl(256):14.3e}")
# 4) Flash-Decoding: one query, KV split into S chunks, partial results merged with their log-sum-exp
q = rng.normal(size=(1, d)); Kd, Vd = rng.normal(size=(8192, d)), rng.normal(size=(8192, d))
exact = naive_attention(q, Kd, Vd)
def split_kv(q, K, V, S, dtype=np.float64):
q, K, V = q.astype(dtype), K.astype(dtype), V.astype(dtype)
outs, lses = [], []
for Kc, Vc in zip(np.array_split(K, S), np.array_split(V, S)): # in a kernel: S thread blocks
s = (q @ Kc.T / q.shape[1] ** 0.5)[0] # python float keeps float32 inputs in float32
mc = s.max(); p = np.exp(s - mc)
outs.append((p @ Vc) / p.sum()); lses.append(mc + np.log(p.sum()))
lses = np.array(lses); w = np.exp(lses - lses.max()); w /= w.sum() # softmax over chunk LSEs
return (w[:, None] * np.array(outs)).sum(axis=0)
for S in [1, 4, 16, 64]:
print(f"split-KV S={S:3d}: max err vs exact {np.abs(split_kv(q, Kd, Vd, S) - exact).max():.1e}")
# 5) same math, different reduction tree -> different float32 bits (batch-invariance in RL)
o4, o16 = split_kv(q, Kd, Vd, 4, np.float32), split_kv(q, Kd, Vd, 16, np.float32)
print(f"float32: S=4 vs S=16 differ by up to {np.abs(o4 - o16).max():.1e} (bitwise equal: {np.array_equal(o4, o16)})")
# 6) the same "never materialise the big matrix" idea at the LM head: fused linear + cross-entropy
T, Hd, Vocab = 512, 64, 8192
h = rng.normal(size=(T, Hd)); W = rng.normal(size=(Hd, Vocab)) * 0.1; y = rng.integers(0, Vocab, size=T)
def ce_full(h, W, y):
z = h @ W # [T, V] logits, all at once
lse = z.max(1) + np.log(np.exp(z - z.max(1, keepdims=True)).sum(1))
g = np.exp(z - lse[:, None]); g[np.arange(len(y)), y] -= 1; g /= len(y) # dL/dz
return (lse - z[np.arange(len(y)), y]).mean(), g @ W.T, h.T @ g, z.size
def ce_chunked(h, W, y, chunk=64):
loss, dh, dW, peak = 0.0, np.zeros_like(h), np.zeros_like(W), 0
for s in range(0, len(y), chunk):
z = h[s:s + chunk] @ W; peak = max(peak, z.size) # only [chunk, V] alive at a time
lse = z.max(1) + np.log(np.exp(z - z.max(1, keepdims=True)).sum(1))
yc = y[s:s + chunk]; loss += (lse - z[np.arange(len(yc)), yc]).sum() / len(y)
g = np.exp(z - lse[:, None]); g[np.arange(len(yc)), yc] -= 1; g /= len(y)
dh[s:s + chunk] = g @ W.T; dW += h[s:s + chunk].T @ g # grads per chunk; dW accumulated
return loss, dh, dW, peak
L1, dh1, dW1, n1 = ce_full(h, W, y); L2, dh2, dW2, n2 = ce_chunked(h, W, y)
print(f"\nfused linear-CE: |dloss|={abs(L1 - L2):.1e} |d dh|={np.abs(dh1 - dh2).max():.1e} "
f"|d dW|={np.abs(dW1 - dW2).max():.1e}; peak logits {n2:,} vs {n1:,} floats ({n1 // n2}x less)")import torch
import torch.nn.functional as F
from torch.nn.attention import sdpa_kernel, SDPBackend # torch >= 2.3
B, H, N, d = 2, 16, 4096, 128
q, k, v = (torch.randn(B, H, N, d, device="cuda", dtype=torch.bfloat16) for _ in range(3))
def run(backend, *xs):
torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
with sdpa_kernel(backend):
o = F.scaled_dot_product_attention(*xs, is_causal=True)
torch.cuda.synchronize()
return o, (torch.cuda.max_memory_allocated() - base) / 2**20
o_flash, mem_flash = run(SDPBackend.FLASH_ATTENTION, q, k, v)
o_math, mem_math = run(SDPBackend.MATH, q.float(), k.float(), v.float()) # materialises B*H*N*N scores
print(f"max |flash - math(fp32)| = {(o_flash.float() - o_math).abs().max().item():.3e}")
print(f"extra memory: flash {mem_flash:.0f} MiB vs math {mem_math:.0f} MiB")
# Decode shape: one query per sequence against a long cache. SDPA picks a kernel; dedicated decode
# kernels (flash_attn_with_kvcache, FlashInfer) add split-KV and paged block tables.
qd = torch.randn(B, H, 1, d, device="cuda", dtype=torch.bfloat16)
od = F.scaled_dot_product_attention(qd, k, v) # no causal mask needed for the last position
print(od.shape)FA4 skips rescaling the accumulator unless the running max grows by more than 8 (in log2 units). Why is the final output still exact?
Both and are defined relative to the same ; any common gives the same . Updating only matters to keep the exponentials in range: with a stale , can exceed 1, by at most before a rescale is forced. The NumPy block confirms: 9 rescales instead of hundreds, error at machine precision.
For which decode workload does Flash-Decoding (splitting along the KV sequence) help most?
Split-KV helps when (batch × KV heads) is far below the number of SMs and each sequence is long enough to split. Batch 1 × 8 heads = 8 thread blocks on 132 SMs; splitting by 16 fills the GPU. With batch 64 × 64 heads the grid is already full and splitting only adds the combine pass. Prefill has many query blocks and needs no split.
Summary
- Naive attention is memory-bound () because it round-trips the scores through HBM.
- Online softmax is a merge operator on ; it is exact in any blocking and order, which enables tiling, split-KV and chunked cross-entropy.
- FlashAttention: HBM accesses (optimal), backward recomputes from the stored LSE.
- FA2 fought non-matmul FLOPs and occupancy; FA3 used Hopper asynchrony to hide the exponentials (3.9 vs 989 TFLOP/s); FA4 faces Blackwell, where exp per score costs as much as the MMA at , and answers with software exp2 and conditional rescaling.
- Decode attention needs parallelism along the keys (Flash-Decoding) and GQA packing; paged kernels add block-table gathers.
- Logit-sized tensors are the same problem at the LM head: fused linear cross-entropy never materialises them.
Paged attention kernel
서빙 엔진은 KV cache를 메모리 곳곳에 흩어진 고정 크기 블록에 저장한다(다음 레슨). 그래서 decode kernel은 가 연속이라고 가정할 수 없다. 시퀀스마다 block table을 읽고 모아 와야 한다. 블록마다 간접 참조 비용이 들고 메모리 접근이 덜 규칙적이다. 블록 크기가 메모리 관리자의 매개변수인 만큼 kernel의 매개변수이기도 한 이유다(vLLM 기본값은 16토큰. ShareGPT trace에서는 16–128, Alpaca에서는 16–32가 가장 좋았다). FlashInfer는 이것을 일반화한다. paged, ragged, prefix 공유 cache를 모두 하나의 block-sparse 행렬로 표현하고, attention 변형은 템플릿에서 JIT 컴파일하며, 부하 균형 스케줄러가 고르지 않은 작업(100토큰과 100K토큰 문맥이 섞인 배치)을 SM들에 나누면서 CUDA graph와 호환을 유지한다. 서빙 벤치마크에서 compiler backend보다 inter-token latency가 29–69% 낮다고 보고한다.
LM head에서의 같은 기법: fused linear + cross-entropy
transformer의 또 다른 (거대한 무엇) 행렬은 logits, 즉 토큰 × 어휘다. Liger Kernel의 예: Gemma의 256K 어휘에 배치 8, 길이 4096이면 bf16 logit tensor가 16.8 GB다. fused linear cross-entropy는 펼친 hidden state를 chunk로 나누고, chunk마다 logits , 행별 LSE와 loss, 기울기 를 그 자리에서 계산한다. 그다음 그 chunk의 를 만들고 를 누적한다. 살아 있는 것은 chunk × tile 하나뿐이다. RL trainer가 rollout 토큰마다 계산하는 것, 즉 log-probability 가 정확히 이것이므로, 긴 rollout에서는 micro-batch가 들어가느냐 마느냐가 여기서 갈린다.
구현하기
아래 블록은 이 레슨의 주장을 NumPy로 모두 확인한다. online LSE, tiled FlashAttention(non-causal, causal)과 naive attention 비교, FA4식 lazy rescaling, HBM 트래픽 세기, LSE 결합을 쓰는 split-KV decoding, 결과를 분할 수에 의존하게 만드는 float32 비결합성, 그리고 chunk로 나눈 linear-cross-entropy와 전체 계산의 비교(loss와 두 기울기).
import numpy as np
rng = np.random.default_rng(0)
def naive_attention(Q, K, V, causal=False):
S = Q @ K.T / np.sqrt(Q.shape[1]) # N x N scores: materialised in HBM
if causal:
S = np.where(np.tril(np.ones(S.shape, dtype=bool)), S, -np.inf)
P = np.exp(S - S.max(axis=1, keepdims=True))
return (P / P.sum(axis=1, keepdims=True)) @ V
# 1) online softmax: one pass, running max m and running denominator l
x = rng.normal(size=1000) * 8
m, l = -np.inf, 0.0
for j in range(0, len(x), 64):
xb = x[j:j + 64]
m_new = max(m, xb.max())
l = l * np.exp(m - m_new) + np.exp(xb - m_new).sum() # rescale the old sum to the new max
m = m_new
ref = x.max() + np.log(np.exp(x - x.max()).sum())
print(f"online logsumexp {m + np.log(l):.12f} vs two-pass {ref:.12f}")
# 2) FlashAttention forward, FA2 loop order: outer over query blocks, inner over K/V blocks
def flash_attention(Q, K, V, Br=64, Bc=64, causal=False):
N, d = Q.shape
O, lse, hbm = np.zeros_like(Q), np.zeros(N), 0
for i in range(0, N, Br):
q = Q[i:i + Br]; hbm += q.size # load a Q tile once
m = np.full(len(q), -np.inf); l = np.zeros(len(q)); acc = np.zeros((len(q), d))
for j in range(0, N, Bc):
if causal and j > i + len(q) - 1:
break # tile entirely above the diagonal: skip
k, v = K[j:j + Bc], V[j:j + Bc]; hbm += k.size + v.size
s = q @ k.T / np.sqrt(d)
if causal:
rows, cols = np.arange(i, i + len(q))[:, None], np.arange(j, j + len(k))[None, :]
s = np.where(cols <= rows, s, -np.inf)
m_new = np.maximum(m, s.max(axis=1))
p = np.exp(s - m_new[:, None])
alpha = np.exp(m - m_new) # correction for the stale max
l = alpha * l + p.sum(axis=1)
acc = alpha[:, None] * acc + p @ v # unnormalised output, rescaled
m = m_new
O[i:i + Br] = acc / l[:, None] # normalise once at the end (FA2)
lse[i:i + Br] = m + np.log(l) # saved for the backward pass
hbm += acc.size
return O, lse, hbm
N, d = 512, 64
Q, K, V = (rng.normal(size=(N, d)) for _ in range(3))
for causal in [False, True]:
O, lse, hbm = flash_attention(Q, K, V, causal=causal)
err = np.abs(O - naive_attention(Q, K, V, causal)).max()
print(f"causal={causal!s:<5} max |flash - naive| = {err:.2e}")
# 2b) FA4-style conditional rescaling: keep a stale max unless the new one exceeds it by tau
def flash_lazy(Q, K, V, B=64, tau=np.log(256.0)): # tau = log 256, i.e. log2-threshold 8
N, d = Q.shape; O = np.zeros_like(Q); rescales = skipped = 0
for i in range(0, N, B):
q = Q[i:i + B]; m = np.full(len(q), -np.inf); l = np.zeros(len(q)); acc = np.zeros((len(q), d))
for j in range(0, N, B):
s = q @ K[j:j + B].T / np.sqrt(d)
grow = s.max(1) > m + tau # FA4 decides this per warp; per row here
m_new = np.where(grow, np.maximum(m, s.max(1)), m)
rescales += (grow & np.isfinite(m)).sum(); skipped += (~grow & (s.max(1) > m)).sum()
alpha = np.exp(m - m_new) # == 1 wherever the max was kept stale
p = np.exp(s - m_new[:, None]) # entries may now exceed 1 (at most e^tau)
l = alpha * l + p.sum(1); acc = alpha[:, None] * acc + p @ V[j:j + B]; m = m_new
O[i:i + B] = acc / l[:, None] # same stale max in acc and l: ratio exact
return O, rescales, skipped
Ob, nres, nskip = flash_lazy(Q * 3, K, V) # sharper scores: more max updates
print(f"lazy rescale: {nres} rescales done, {nskip} skipped; max err {np.abs(Ob - naive_attention(Q * 3, K, V)).max():.1e}")
# 3) HBM traffic (elements): naive writes and re-reads S and P; flash re-reads K,V once per Q tile
print("\nHBM elements moved, d=64: naive flash(B=64) flash(B=256)")
for N in [1024, 4096, 16384]:
naive = 4 * N * d + 4 * N * N
fl = lambda B: 2 * N * d + 2 * N * d * (N / B)
print(f" N={N:6d} {naive:14.3e} {fl(64):14.3e} {fl(256):14.3e}")
# 4) Flash-Decoding: one query, KV split into S chunks, partial results merged with their log-sum-exp
q = rng.normal(size=(1, d)); Kd, Vd = rng.normal(size=(8192, d)), rng.normal(size=(8192, d))
exact = naive_attention(q, Kd, Vd)
def split_kv(q, K, V, S, dtype=np.float64):
q, K, V = q.astype(dtype), K.astype(dtype), V.astype(dtype)
outs, lses = [], []
for Kc, Vc in zip(np.array_split(K, S), np.array_split(V, S)): # in a kernel: S thread blocks
s = (q @ Kc.T / q.shape[1] ** 0.5)[0] # python float keeps float32 inputs in float32
mc = s.max(); p = np.exp(s - mc)
outs.append((p @ Vc) / p.sum()); lses.append(mc + np.log(p.sum()))
lses = np.array(lses); w = np.exp(lses - lses.max()); w /= w.sum() # softmax over chunk LSEs
return (w[:, None] * np.array(outs)).sum(axis=0)
for S in [1, 4, 16, 64]:
print(f"split-KV S={S:3d}: max err vs exact {np.abs(split_kv(q, Kd, Vd, S) - exact).max():.1e}")
# 5) same math, different reduction tree -> different float32 bits (batch-invariance in RL)
o4, o16 = split_kv(q, Kd, Vd, 4, np.float32), split_kv(q, Kd, Vd, 16, np.float32)
print(f"float32: S=4 vs S=16 differ by up to {np.abs(o4 - o16).max():.1e} (bitwise equal: {np.array_equal(o4, o16)})")
# 6) the same "never materialise the big matrix" idea at the LM head: fused linear + cross-entropy
T, Hd, Vocab = 512, 64, 8192
h = rng.normal(size=(T, Hd)); W = rng.normal(size=(Hd, Vocab)) * 0.1; y = rng.integers(0, Vocab, size=T)
def ce_full(h, W, y):
z = h @ W # [T, V] logits, all at once
lse = z.max(1) + np.log(np.exp(z - z.max(1, keepdims=True)).sum(1))
g = np.exp(z - lse[:, None]); g[np.arange(len(y)), y] -= 1; g /= len(y) # dL/dz
return (lse - z[np.arange(len(y)), y]).mean(), g @ W.T, h.T @ g, z.size
def ce_chunked(h, W, y, chunk=64):
loss, dh, dW, peak = 0.0, np.zeros_like(h), np.zeros_like(W), 0
for s in range(0, len(y), chunk):
z = h[s:s + chunk] @ W; peak = max(peak, z.size) # only [chunk, V] alive at a time
lse = z.max(1) + np.log(np.exp(z - z.max(1, keepdims=True)).sum(1))
yc = y[s:s + chunk]; loss += (lse - z[np.arange(len(yc)), yc]).sum() / len(y)
g = np.exp(z - lse[:, None]); g[np.arange(len(yc)), yc] -= 1; g /= len(y)
dh[s:s + chunk] = g @ W.T; dW += h[s:s + chunk].T @ g # grads per chunk; dW accumulated
return loss, dh, dW, peak
L1, dh1, dW1, n1 = ce_full(h, W, y); L2, dh2, dW2, n2 = ce_chunked(h, W, y)
print(f"\nfused linear-CE: |dloss|={abs(L1 - L2):.1e} |d dh|={np.abs(dh1 - dh2).max():.1e} "
f"|d dW|={np.abs(dW1 - dW2).max():.1e}; peak logits {n2:,} vs {n1:,} floats ({n1 // n2}x less)")import torch
import torch.nn.functional as F
from torch.nn.attention import sdpa_kernel, SDPBackend # torch >= 2.3
B, H, N, d = 2, 16, 4096, 128
q, k, v = (torch.randn(B, H, N, d, device="cuda", dtype=torch.bfloat16) for _ in range(3))
def run(backend, *xs):
torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
with sdpa_kernel(backend):
o = F.scaled_dot_product_attention(*xs, is_causal=True)
torch.cuda.synchronize()
return o, (torch.cuda.max_memory_allocated() - base) / 2**20
o_flash, mem_flash = run(SDPBackend.FLASH_ATTENTION, q, k, v)
o_math, mem_math = run(SDPBackend.MATH, q.float(), k.float(), v.float()) # materialises B*H*N*N scores
print(f"max |flash - math(fp32)| = {(o_flash.float() - o_math).abs().max().item():.3e}")
print(f"extra memory: flash {mem_flash:.0f} MiB vs math {mem_math:.0f} MiB")
# Decode shape: one query per sequence against a long cache. SDPA picks a kernel; dedicated decode
# kernels (flash_attn_with_kvcache, FlashInfer) add split-KV and paged block tables.
qd = torch.randn(B, H, 1, d, device="cuda", dtype=torch.bfloat16)
od = F.scaled_dot_product_attention(qd, k, v) # no causal mask needed for the last position
print(od.shape)FA4는 running max가 (log2 단위로) 8보다 많이 커지지 않으면 누산기 rescale을 건너뛴다. 그래도 최종 출력이 정확한 이유는?
와 은 같은 을 기준으로 정의된다. 공통의 이 무엇이든 은 같다. 을 갱신하는 것은 지수값을 범위 안에 두기 위해서일 뿐이다. 낡은 이면 이 1을 넘을 수 있지만, rescale이 강제되기 전까지 많아야 배다. NumPy 블록이 확인한다. 수백 번 대신 9번 rescale하고 오차는 기계 정밀도다.
Flash-Decoding(KV 시퀀스 방향 분할)이 가장 도움이 되는 decode 작업은?
split-KV는 (배치 × KV head)가 SM 수보다 훨씬 작고 각 시퀀스가 나눌 만큼 길 때 효과가 있다. 배치 1 × head 8 = SM 132개 위의 thread block 8개다. 16으로 나누면 GPU가 찬다. 배치 64 × head 64면 격자가 이미 차 있어 분할은 combine 단계만 더한다. prefill은 query 블록이 많아 분할이 필요 없다.
정리
- naive attention은 score를 HBM으로 왕복시키므로 memory-bound다().
- online softmax는 위의 결합 연산이다. 어떤 블록 분할과 순서에서도 정확하므로 tiling, split-KV, chunk cross-entropy를 가능하게 한다.
- FlashAttention: HBM 접근 (최적). 역전파는 저장한 LSE로부터 재계산한다.
- FA2는 비행렬곱 FLOPs와 occupancy와 싸웠고, FA3는 Hopper의 비동기성으로 지수함수를 숨겼다(3.9 대 989 TFLOP/s). FA4는 에서 score당 exp가 MMA만큼 비싼 Blackwell을 상대로 소프트웨어 exp2와 조건부 rescaling으로 답한다.
- decode attention에는 key 방향 병렬화(Flash-Decoding)와 GQA packing이 필요하고, paged kernel은 block table gather를 더한다.
- logit 크기의 tensor는 LM head에서의 같은 문제다. fused linear cross-entropy는 그것을 만들지 않는다.
더 읽을거리Further reading
- Dao, Fu, Ermon, Rudra, Ré, FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (NeurIPS 2022) — tiling·재계산과 IO 복잡도 Θ(N²d²/M), 그리고 그 하한.Tiling and recomputation, the IO complexity Θ(N²d²/M), and its lower bound.
- Dao, FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning (2023) — 비행렬곱 FLOPs 줄이기, 시퀀스 방향 병렬화, warp 간 Q 분할.Fewer non-matmul FLOPs, parallelism along the sequence, splitting Q across warps.
- Shah et al., FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision (2024) — Hopper의 TMA·WGMMA 비동기성으로 softmax와 GEMM을 겹치기, FP8 block 양자화와 incoherent processing.Overlapping softmax with GEMMs using Hopper's asynchronous TMA and WGMMA; FP8 block quantisation and incoherent processing.
- Zadouri et al., FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling (2026) — Blackwell에서 tensor core만 두 배가 된 비대칭을, 소프트웨어 exp와 조건부 rescaling으로 메운다. 저자 블로그(tridao.me/blog/2026/flash4)도 함께.Closes Blackwell's asymmetry (only the tensor cores doubled) with software exponentials and conditional rescaling. Read with the author's blog (tridao.me/blog/2026/flash4).
- Dao, Haziza, Massa, Sizov, Flash-Decoding for long-context inference (Stanford CRFM blog, 2023) — KV 시퀀스 방향으로 나누고 log-sum-exp로 합치는 decode kernel.The decode kernel that splits along the KV sequence and merges with the log-sum-exp.
- Ye et al., FlashInfer: Efficient and Customizable Attention Engine for LLM Inference Serving (MLSys 2025) — paged·ragged·prefix 공유 KV를 block-sparse 형식 하나로 다루는 서빙용 attention 엔진.A serving attention engine that handles paged, ragged and prefix-shared KV with one block-sparse format.
- Hsu et al., Liger Kernel: Efficient Triton Kernels for LLM Training (2024) — logits를 만들지 않는 fused linear cross-entropy(§3.2)와 fused RMSNorm·RoPE·SwiGLU.Fused linear cross-entropy that never materialises the logits (§3.2), plus fused RMSNorm, RoPE and SwiGLU.