Track VIII · Inference & Optimisation · 02/09

Attention kernelAttention kernels

online softmax를 유도하고 그 결합 연산 하나로 FlashAttention의 tiling, 역전파 재계산, Flash-Decoding의 split-KV, fused linear cross-entropy를 모두 설명한다. IO 복잡도를 세고, FA2·FA3·FA4가 각각 어떤 하드웨어 병목(비행렬곱 FLOPs, 비동기성, 지수함수 처리량) 때문에 바뀌었는지 사이클 단위로 계산한다.Derive online softmax and use its single merge operation to explain FlashAttention's tiling and backward recomputation, Flash-Decoding's split-KV and fused linear cross-entropy. Count the IO complexity, and work out cycle by cycle which hardware bottleneck (non-matmul FLOPs, asynchrony, exponential throughput) drove FA2, FA3 and FA4.

50 분min attention · FlashAttention · online softmax · IO complexity · Flash-Decoding · split-KV · Hopper · Blackwell · paged attention · fused cross-entropy 먼저 볼 것:Before this: Roofline과 추론 지표The roofline and inference metrics, Attention: query·key·valueAttention: query, key, value

The roofline lesson placed prefill attention far to the right of the ridge: O(N2d)O(N^2 d) FLOPs on O(Nd)O(Nd) 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 Q,K,V∈RN×dQ, K, V \in \mathbb{R}^{N \times d}:

S=QK⊤/d∈RN×N,P=softmaxrow(S),O=PV.S = QK^\top/\sqrt{d} \in \mathbb{R}^{N\times N}, \qquad P = \mathrm{softmax}_{\text{row}}(S), \qquad O = PV.

The textbook implementation writes SS to HBM, reads it back for the softmax, writes PP, and reads PP again for the second GEMM: Θ(Nd+N2)\Theta(Nd + N^2) HBM accesses (FlashAttention, Theorem 2). With N=8192N = 8192 and bf16, SS alone is 128 MiB per head per sequence. Intensity: 4N2d4N^2 d FLOPs over roughly 4N2⋅24N^2 \cdot 2 bytes gives I≈d/2=64I \approx d/2 = 64 for d=128d = 128 — below the H100 ridge of ~295, so the “compute-bound” operation runs memory-bound. The fix is to never let SS or PP 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 J\mathcal{J} by three things: the running max, the running denominator, and an unnormalised output,

m=max⁡j∈Jsj,ℓ=∑j∈Jesj−m,o~=∑j∈Jesj−m vj.m = \max_{j\in\mathcal J} s_j, \qquad \ell = \sum_{j\in\mathcal J} e^{s_j - m}, \qquad \tilde o = \sum_{j\in\mathcal J} e^{s_j - m}\, v_j .

Two partial states over disjoint key sets combine exactly:

(ma,ℓa,o~a)⊕(mb,ℓb,o~b)=(m,  ema−mℓa+emb−mℓb,  ema−mo~a+emb−mo~b),m=max⁡(ma,mb),(m_a,\ell_a,\tilde o_a) \oplus (m_b,\ell_b,\tilde o_b) = \big(m,\; e^{m_a - m}\ell_a + e^{m_b - m}\ell_b,\; e^{m_a - m}\tilde o_a + e^{m_b - m}\tilde o_b\big),\quad m = \max(m_a, m_b),

and the answer is o=o~/ℓo = \tilde o / \ell, with LSE=m+log⁡ℓ\text{LSE} = m + \log \ell. Check: every term esj−mae^{s_j - m_a} multiplied by ema−me^{m_a - m} becomes esj−me^{s_j - m}, so the merged state is the state you would have computed in one pass. ⊕\oplus 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 BrB_r queries on chip, stream K,VK, V through in tiles of BcB_c keys, and fold each tile into (m,ℓ,o~)(m, \ell, \tilde o) with ⊕\oplus. SS and PP exist only as a Br×BcB_r \times B_c tile in SRAM. With SRAM of MM elements the paper picks Bc=⌈M/4d⌉B_c = \lceil M/4d \rceil, Br=min⁡(⌈M/4d⌉,d)B_r = \min(\lceil M/4d\rceil, d).

IO count. QQ is read once and OO written once (2Nd2Nd). KK and VV are re-streamed once per resident block; with blocks of size Θ(M/d)\Theta(M/d) there are Θ(Nd/M)\Theta(Nd/M) of them:

HBM accesses=Θ ⁣(Nd+Nd⋅NdM)=Θ ⁣(N2d2M).\text{HBM accesses} = \Theta\!\Big(Nd + Nd \cdot \frac{Nd}{M}\Big) = \Theta\!\Big(\frac{N^2 d^2}{M}\Big).

For d2≪Md^2 \ll M this is far below N2N^2, and Proposition 3 of the paper shows no exact algorithm does asymptotically better for all M∈[d,Nd]M \in [d, Nd]. The paper reports up to 9× fewer HBM accesses and up to 7.6× faster attention on GPT-2.

Backward. Storing PP for the backward pass would bring back the N2N^2 term. FlashAttention stores only the per-row LSE (NN floats per head) and recomputes SS and PP 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의 한참 오른쪽에 놓았다. 입력 O(Nd)O(Nd)에 FLOPs O(N2d)O(N^2 d)이다. 이것은 수식에 대해서는 맞다. 그런데 곧이곧대로 구현하면 memory-bound가 된다. 2022년 이후 attention kernel의 역사는 이 간극을 메우는 이야기다. 처음엔 HBM 트래픽, 그다음엔 tensor core가 아닌 GPU 부품들. 레슨 전체를 끌고 가는 대수적 사실은 하나다. softmax 가중합은 조각으로 계산해 합칠 수 있다.

표준 attention이 옮기는 것

head 하나, Q,K,V∈RN×dQ, K, V \in \mathbb{R}^{N \times d}에 대해

S=QK⊤/d∈RN×N,P=softmaxrow(S),O=PVS = QK^\top/\sqrt{d} \in \mathbb{R}^{N\times N}, \qquad P = \mathrm{softmax}_{\text{row}}(S), \qquad O = PV

교과서식 구현은 SS를 HBM에 쓰고, softmax를 위해 다시 읽고, PP를 쓰고, 두 번째 GEMM을 위해 PP를 또 읽는다. HBM 접근이 Θ(Nd+N2)\Theta(Nd + N^2)이다(FlashAttention, Theorem 2). N=8192N = 8192, bf16이면 SS만 시퀀스·head당 128 MiB다. 산술 강도는 4N2d4N^2 d FLOPs ÷ 약 4N2⋅24N^2 \cdot 2바이트로 d=128d = 128일 때 I≈d/2=64I \approx d/2 = 64. H100 ridge ~295보다 낮다. “compute-bound” 연산이 memory-bound로 돈다. 해법은 SS와 PP가 칩 안 SRAM을 떠나지 않게 하는 것이다.

Online softmax: 결합 연산

행을 정규화하려면 최댓값(안정성)과 합이 필요하다. 둘 다 흘려보내며 유지할 수 있다. key 집합 J\mathcal{J}에 대한 부분 결과를 세 가지로 나타낸다. running max, running 분모, 그리고 정규화하지 않은 출력.

m=max⁡j∈Jsj,ℓ=∑j∈Jesj−m,o~=∑j∈Jesj−m vjm = \max_{j\in\mathcal J} s_j, \qquad \ell = \sum_{j\in\mathcal J} e^{s_j - m}, \qquad \tilde o = \sum_{j\in\mathcal J} e^{s_j - m}\, v_j

서로소인 key 집합에 대한 두 부분 상태는 정확히 합쳐진다.

(ma,ℓa,o~a)⊕(mb,ℓb,o~b)=(m,  ema−mℓa+emb−mℓb,  ema−mo~a+emb−mo~b),m=max⁡(ma,mb)(m_a,\ell_a,\tilde o_a) \oplus (m_b,\ell_b,\tilde o_b) = \big(m,\; e^{m_a - m}\ell_a + e^{m_b - m}\ell_b,\; e^{m_a - m}\tilde o_a + e^{m_b - m}\tilde o_b\big),\quad m = \max(m_a, m_b)

답은 o=o~/ℓo = \tilde o / \ell, LSE=m+log⁡ℓ\text{LSE} = m + \log \ell이다. 확인: 항 esj−mae^{s_j - m_a}에 ema−me^{m_a - m}을 곱하면 esj−me^{s_j - m}이 되므로, 합친 상태는 한 번에 계산했을 상태와 같다. ⊕\oplus는 결합법칙과 교환법칙을 만족한다. 즉 어떻게 블록을 나누든, 어떤 순서로 reduce하든 정확한 답이 나온다(부동소수점 반올림을 빼면). FlashAttention은 K/V tile을 하나씩 접어 넣고, Flash-Decoding은 key를 thread block들에 나눠 끝에 합치며, 아래의 fused cross-entropy는 토큰 chunk에 대해 같은 LSE 장부를 쓴다.

FlashAttention: tiling과 재계산

query BrB_r개짜리 tile을 칩에 두고, K,VK, V를 key BcB_c개짜리 tile로 흘려보내며 각 tile을 ⊕\oplus로 (m,ℓ,o~)(m, \ell, \tilde o)에 접어 넣는다. SS와 PP는 SRAM 안의 Br×BcB_r \times B_c tile로만 존재한다. SRAM이 원소 MM개라면 논문은 Bc=⌈M/4d⌉B_c = \lceil M/4d \rceil, Br=min⁡(⌈M/4d⌉,d)B_r = \min(\lceil M/4d\rceil, d)를 고른다.

IO 세기. QQ는 한 번 읽고 OO는 한 번 쓴다(2Nd2Nd). KK와 VV는 칩에 상주하는 블록마다 한 번씩 다시 흘러가는데, 블록 크기가 Θ(M/d)\Theta(M/d)이면 블록이 Θ(Nd/M)\Theta(Nd/M)개다.

HBM 접근=Θ ⁣(Nd+Nd⋅NdM)=Θ ⁣(N2d2M)\text{HBM 접근} = \Theta\!\Big(Nd + Nd \cdot \frac{Nd}{M}\Big) = \Theta\!\Big(\frac{N^2 d^2}{M}\Big)

d2≪Md^2 \ll M이면 N2N^2보다 훨씬 작고, 논문의 Proposition 3은 모든 M∈[d,Nd]M \in [d, Nd]에 대해 점근적으로 이보다 나은 정확한 알고리즘이 없음을 보인다. 논문은 HBM 접근이 최대 9배 줄고 GPT-2의 attention이 최대 7.6배 빨라졌다고 보고한다.

역전파. 역전파를 위해 PP를 저장하면 N2N^2 항이 돌아온다. FlashAttention은 행마다 LSE(NN개 float/head)만 저장하고 역전파에서 SS와 PP를 tile 단위로 다시 계산한다. FLOPs는 늘고 바이트는 준다. ridge 아래에 있을 때 옳은 거래다.

Left: the 16×16 score matrix S = QKᵀ/√d (darker = larger). Tiles already folded into the output are shaded; the current tile is outlined in red. Right: for each row of the current Q tile, the running max m (dot), the rescale factor α = emold−mnew applied at this step, and the error of the partial output acc/ℓ against exact attention. Step through a Q tile: when a tile contains a new maximum, α drops below 1 and the old accumulator is shrunk; when the last K/V tile is folded in, every error bar hits zero — the result is exact, not an approximation. Larger tiles mean fewer K/V reloads, and causal skips whole tiles: the HBM readouts count the visited tiles, with reads and writes listed separately for both FlashAttention and the naive kernel (which writes and re-reads the full S and P). 왼쪽: 16×16 score 행렬 S = QKᵀ/√d(진할수록 큼). 이미 출력에 접혀 들어간 tile은 음영, 현재 tile은 빨간 테두리. 오른쪽: 현재 Q tile의 각 행에 대해 running max m(점), 이번 step에 곱한 rescale 계수 α = emold−mnew, 부분 출력 acc/ℓ과 정확한 attention의 오차. Q tile 하나를 한 step씩 넘겨 보면 새 최댓값이 든 tile에서 α가 1보다 작아져 이전 누적값이 줄어들고, 마지막 K/V tile이 접히면 모든 오차 막대가 0이 된다. 근사가 아니라 정확한 결과다. tile이 클수록 K/V를 다시 읽는 횟수가 줄고, causal은 tile을 통째로 건너뛴다. 아래 HBM 수치는 실제로 방문한 tile을 세며, FlashAttention과 naive kernel(전체 S와 P를 쓰고 다시 읽는다) 모두 읽기와 쓰기를 따로 보인다.

Step through the first Q tile with Bc=4B_c = 4: the key columns 5, 11 and 14 hold large scores, and when such a tile arrives α\alpha turns red — the old accumulator is shrunk by emold−mnewe^{m_{\text{old}} - m_{\text{new}}}. 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 Br=Bc=4B_r = B_c = 4 the kernel visits 10 of the 16 tiles, so K/V reads fall from 512 to 320 elements (plus 64 for QQ: 576 → 384 reads in total); the diagonal tiles are still visited, so the saving approaches 2× only when the tiles are small relative to NN. The naive kernel in the readout materialises the full SS and PP either way: 704 reads and 576 writes against FlashAttention’s 64 writes of OO.

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 o~\tilde o 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 4d4d FLOPs and the softmax one exponential, so at d=128d = 128

texp⁡tMMA=1/3.9T512/989T≈0.5.\frac{t_{\exp}}{t_{\text{MMA}}} = \frac{1/3.9\text{T}}{512/989\text{T}} \approx 0.5 .

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 QQ and KK by a random orthogonal matrix, which leaves QK⊤QK^\top 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 d=128d = 128: the MMA takes 512/8192=1/16512/8192 = 1/16 clock per score and the exponential 1/161/16 clock. The exponentials now cost as much as the matmuls; even perfect overlap leaves no slack, and at d=64d = 64 the exponentials dominate. FA4’s answers:

  • Software exponential. Compute 2x2^x on the FMA pipe as well as on the MUFU: Cody–Waite range reduction to 2⌊x⌋⋅2f2^{\lfloor x\rfloor} \cdot 2^{f}, a degree-3 polynomial for 2f2^f, 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 (ℓ,o~)(\ell, \tilde o) only when the running max grows by more than τ=log⁡2256=8\tau = \log_2 256 = 8. Skipping a rescale is exact: ℓ\ell and o~\tilde o keep the same stale reference max, so their ratio is unchanged; the stale max only lets entries of PP exceed 1 by at most 282^8, harmless in FP32 accumulators.
  • Blackwell plumbing. Accumulators live in tensor memory (TMEM, 256 KB per SM) and tcgen05.mma is 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.

Bc=4B_c = 4로 첫 Q tile을 한 step씩 넘겨 보라. key 열 5, 11, 14에 큰 score가 있고, 그런 tile이 오면 α\alpha가 빨개진다. 이전 누적값이 emold−mnewe^{m_{\text{old}} - m_{\text{new}}}배로 줄어든다. 행 블록의 마지막 tile이 지나면 모든 오차 막대가 정확히 0이 된다. causal을 켜면 대각선 위의 tile은 통째로 건너뛴다. kernel에서 causal attention의 2배 절감은 여기서 나온다. Br=Bc=4B_r = B_c = 4이면 kernel은 16개 tile 중 10개만 방문하므로 K/V 읽기가 512에서 320원소로 준다(QQ의 64를 더하면 읽기 전체가 576 → 384). 대각선 tile은 여전히 방문하므로 2배 절감에 가까워지는 것은 tile이 NN에 비해 작을 때다. 수치의 naive kernel은 어느 쪽이든 전체 SS와 PP를 만든다. 읽기 704, 쓰기 576으로, FlashAttention이 OO를 쓰는 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) o~\tilde o의 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 두 개가 4d4d FLOPs, softmax가 지수함수 하나이므로 d=128d = 128에서

texp⁡tMMA=1/3.9T512/989T≈0.5\frac{t_{\exp}}{t_{\text{MMA}}} = \frac{1/3.9\text{T}}{512/989\text{T}} \approx 0.5

이다. 직렬로 돌리면 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을 더한다. QQ와 KK에 같은 무작위 직교행렬을 곱하면 QK⊤QK^\top은 그대로이고 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)은 그대로다. d=128d = 128에서 SM·clock 단위로 비를 다시 계산하면, MMA는 score당 512/8192=1/16512/8192 = 1/16 clock, 지수함수도 1/161/16 clock이다. 이제 지수함수가 행렬곱만큼 비싸다. 완벽하게 겹쳐도 여유가 없고, d=64d = 64에서는 지수함수가 지배한다. FA4의 답:

  • 소프트웨어 지수함수. 2x2^x를 MUFU뿐 아니라 FMA 파이프에서도 계산한다. Cody–Waite range reduction으로 2⌊x⌋⋅2f2^{\lfloor x\rfloor} \cdot 2^{f}로 나누고, 2f2^f는 3차 다항식으로, 정수부는 float의 지수 비트에 바로 넣는다. 행마다 일부(10–25%)만 에뮬레이트해서 두 파이프가 부하를 나눈다.
  • 조건부 rescaling. running max가 τ=log⁡2256=8\tau = \log_2 256 = 8보다 많이 커질 때만 (ℓ,o~)(\ell, \tilde o)를 rescale한다. rescale을 건너뛰어도 정확하다. ℓ\ell과 o~\tilde o가 같은 낡은 기준 max를 쓰므로 둘의 비는 변하지 않는다. 낡은 max 때문에 PP의 원소가 1을 넘을 수 있지만 많아야 282^8배라서 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배.

Clock cycles one SM spends on a 128×128 tile of scores: the two GEMMs (QKᵀ and PV, 4·128·128·d FLOPs) on the tensor cores, 128·128 exponentials on the MUFU, and the FMA-pipe work. Switch Hopper → Blackwell: the MMA bar halves but the exp bar does not, so at d = 128 the exponentials alone take as long as the matmuls. Turn off overlap to see why FA3 interleaves softmax with GEMMs. Then move part of the exps to the FMA pipe (FA4 emulates 10–25%): the two exp pipes run in parallel and the tensor cores become the bottleneck again. SM 하나가 128×128 score tile 하나에 쓰는 clock cycle: tensor core의 GEMM 두 개(QKᵀ와 PV, 4·128·128·d FLOPs), MUFU의 지수함수 128·128개, FMA 파이프 작업. Hopper → Blackwell로 바꾸면 MMA 막대는 절반이 되는데 exp 막대는 그대로라서, d = 128에서는 지수함수만으로 행렬곱만큼 시간이 걸린다. overlap을 끄면 FA3가 왜 softmax와 GEMM을 엇갈려 돌리는지 보인다. 그다음 exp 일부를 FMA 파이프로 옮기면(FA4는 10–25%를 에뮬레이트한다) 두 exp 파이프가 병렬로 돌아 다시 tensor core가 병목이 된다.

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 d=128d = 128 and a 50% ceiling at d=64d = 64. 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 (I=2g/bkvI = 2g/b_{kv}), so this is a direct loss.

Flash-Decoding adds a parallel dimension along the keys: split the KV sequence into SS chunks, let each thread block compute a partial (m,ℓ,o~)(m, \ell, \tilde o) — written out as a normalised output and its LSE — and merge them with ⊕\oplus 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 gg query heads that share a KV head in the same block, turning gg matrix–vector products into one small matrix–matrix product over the same KV bytes — and choosing SS 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을 해도 d=128d = 128에서 여유가 0이고 d=64d = 64에서는 상한이 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은 순수한 대역폭 문제(I=2g/bkvI = 2g/b_{kv})이므로 이것은 그대로 손실이다.

Flash-Decoding은 key 방향으로 병렬 차원을 하나 더한다. KV 시퀀스를 SS개 chunk로 나누고, thread block마다 부분 (m,ℓ,o~)(m, \ell, \tilde o)를 정규화된 출력과 LSE 형태로 써낸 뒤, 작은 두 번째 kernel에서 ⊕\oplus로 합친다. 저자들은 CodeLlama-34B에서 아주 긴 시퀀스의 생성이 최대 8배, attention 자체는 FlashAttention보다 최대 50배 빨라졌다고 보고한다. 실전에서는 두 가지가 중요하다. GQA packing: KV head 하나를 공유하는 query head gg개를 같은 블록에서 처리해, 같은 KV 바이트에 대해 행렬–벡터 곱 gg개를 작은 행렬–행렬 곱 하나로 바꾼다. 그리고 격자가 GPU를 딱 채우도록 배치에 따라 SS를 고른다.

Left: the GPU's SMs; a coloured square is busy in the first wave of the decode-attention kernel (one CTA per sequence × KV head × split). Right: modelled time of one layer's decode attention against the number of splits S (bf16, dh = 128, each busy SM streams at its 1/nSM share of HBM bandwidth; the combine pass is charged 3 µs plus its traffic — our assumptions). At batch 1 with 8 KV heads and S = 1, 8 of 132 SMs work and the kernel reaches ~6% of HBM bandwidth. Raise S until the grid fills: time drops by an order of magnitude. Raise the batch instead and the split stops mattering — large-batch decode already fills the GPU. 왼쪽: GPU의 SM들. 색칠된 칸은 decode attention kernel의 첫 wave에서 일하는 SM이다(시퀀스 × KV head × split마다 CTA 하나). 오른쪽: 층 하나의 decode attention 시간을 분할 수 S에 대해 모델링한 것(bf16, dh = 128, 일하는 SM은 HBM 대역폭의 1/nSM씩 끌어온다고 보고, combine 단계에는 3 µs와 그 트래픽을 매겼다. 우리의 가정이다). 배치 1, KV head 8, S = 1이면 SM 132개 중 8개만 일하고 HBM 대역폭의 ~6%만 쓴다. 격자가 찰 때까지 S를 올리면 시간이 한 자릿수 줄어든다. 대신 배치를 올리면 분할이 무의미해진다. 큰 배치 decode는 이미 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 KK: 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 N×N \times(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 x=W⊤hx = W^\top h, the per-row LSE and loss, and the gradient ∂L/∂x=softmax(x)−1y\partial L/\partial x = \mathrm{softmax}(x) - \mathbf{1}_y in place; it then forms ∇h=W ∂L/∂x\nabla_h = W\,\partial L/\partial x for the chunk and accumulates ∇W+=h (∂L/∂x)⊤\nabla_W \mathrel{+}= h\,(\partial L/\partial x)^\top. Only a chunk × VV tile is ever alive. This is exactly what an RL trainer computes for every rollout token — the log-probabilities log⁡πθ(yt∣⋅)\log \pi_\theta(y_t \mid \cdot) — 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).

NumPy Online softmax, FlashAttention, lazy rescaling, split-KV and fused linear-CE
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)")
 
PyTorch PyTorch: SDPA's flash backend vs the math backend 로컬에서 실행run locally (pip install torch)
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)
 
확인 문제Check yourself

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 o~=∑esj−mvj\tilde o = \sum e^{s_j - m}v_j and ℓ=∑esj−m\ell = \sum e^{s_j - m} are defined relative to the same mm; any common mm gives the same o~/ℓ\tilde o/\ell. Updating mm only matters to keep the exponentials in range: with a stale mm, esj−me^{s_j - m} can exceed 1, by at most 2τ=2562^\tau = 256 before a rescale is forced. The NumPy block confirms: 9 rescales instead of hundreds, error at machine precision.

확인 문제Check yourself

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 (I≈d/2I \approx d/2) because it round-trips the N×NN \times N scores through HBM.
  • Online softmax is a merge operator on (m,ℓ,o~)(m, \ell, \tilde o); it is exact in any blocking and order, which enables tiling, split-KV and chunked cross-entropy.
  • FlashAttention: Θ(N2d2/M)\Theta(N^2 d^2 / M) 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 d=128d = 128, 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은 KK가 연속이라고 가정할 수 없다. 시퀀스마다 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의 또 다른 N×N \times(거대한 무엇) 행렬은 logits, 즉 토큰 × 어휘다. Liger Kernel의 예: Gemma의 256K 어휘에 배치 8, 길이 4096이면 bf16 logit tensor가 16.8 GB다. fused linear cross-entropy는 펼친 hidden state를 chunk로 나누고, chunk마다 logits x=W⊤hx = W^\top h, 행별 LSE와 loss, 기울기 ∂L/∂x=softmax(x)−1y\partial L/\partial x = \mathrm{softmax}(x) - \mathbf{1}_y를 그 자리에서 계산한다. 그다음 그 chunk의 ∇h=W ∂L/∂x\nabla_h = W\,\partial L/\partial x를 만들고 ∇W+=h (∂L/∂x)⊤\nabla_W \mathrel{+}= h\,(\partial L/\partial x)^\top를 누적한다. 살아 있는 것은 chunk × VV tile 하나뿐이다. RL trainer가 rollout 토큰마다 계산하는 것, 즉 log-probability log⁡πθ(yt∣⋅)\log \pi_\theta(y_t \mid \cdot)가 정확히 이것이므로, 긴 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와 두 기울기).

NumPy Online softmax, FlashAttention, lazy rescaling, split-KV, fused linear-CE
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)")
 
PyTorch PyTorch: SDPA flash backend와 math backend 비교 로컬에서 실행run locally (pip install torch)
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)
 
확인 문제Check yourself

FA4는 running max가 (log2 단위로) 8보다 많이 커지지 않으면 누산기 rescale을 건너뛴다. 그래도 최종 출력이 정확한 이유는?

o~=∑esj−mvj\tilde o = \sum e^{s_j - m}v_j와 ℓ=∑esj−m\ell = \sum e^{s_j - m}은 같은 mm을 기준으로 정의된다. 공통의 mm이 무엇이든 o~/ℓ\tilde o/\ell은 같다. mm을 갱신하는 것은 지수값을 범위 안에 두기 위해서일 뿐이다. 낡은 mm이면 esj−me^{s_j - m}이 1을 넘을 수 있지만, rescale이 강제되기 전까지 많아야 2τ=2562^\tau = 256배다. NumPy 블록이 확인한다. 수백 번 대신 9번 rescale하고 오차는 기계 정밀도다.

확인 문제Check yourself

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은 N×NN \times N score를 HBM으로 왕복시키므로 memory-bound다(I≈d/2I \approx d/2).
  • online softmax는 (m,ℓ,o~)(m, \ell, \tilde o) 위의 결합 연산이다. 어떤 블록 분할과 순서에서도 정확하므로 tiling, split-KV, chunk cross-entropy를 가능하게 한다.
  • FlashAttention: HBM 접근 Θ(N2d2/M)\Theta(N^2 d^2 / M)(최적). 역전파는 저장한 LSE로부터 재계산한다.
  • FA2는 비행렬곱 FLOPs와 occupancy와 싸웠고, FA3는 Hopper의 비동기성으로 지수함수를 숨겼다(3.9 대 989 TFLOP/s). FA4는 d=128d = 128에서 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