Numerically stable definition

Subtracting the max is needed for stability as overflows FP32 above , and attention logits can often exceed that.

Pass structure

VersionPasses over rowHBM traffic
Three-pass (max, sum, normalize)3 reads + 1 write elements
Two-pass (fused max+sum via online)1 read + 1 read + 1 write
One-pass (row fits in registers/shared)1 read + 1 write

A row that fits on-chip should always be one-pass: load once, keep in registers, reduce, write. Lower bound is , softmax can never do better, so its arithmetic intensity is and it is always memory-bound.

Online (streaming) softmax

Process the row in blocks, maintaining a running max and running sum . On a new block with local max and local sum :

The correction factor retroactively rescales everything accumulated so far. This makes max and sum computable in a single pass, and the operator is associative, so it also parallelizes as a tree reduction over pairs (Reduction Kernels).

# one block of a Triton softmax row
m_new = tl.maximum(m, tl.max(x, 0))
alpha = tl.exp(m - m_new)
l     = l * alpha + tl.sum(tl.exp(x - m_new), 0)
acc   = acc * alpha + ...      # any accumulator must be rescaled too
m     = m_new

Why this matters for attention

FlashAttention never materializes the score matrix. It walks K/V tiles, and for each tile it needs softmax over scores it has not finished seeing. Online softmax lets it rescale the running output accumulator by the same :

with the single division by deferred to the end. Memory drops from to , turning attention from HBM-bound to compute-bound.

Implementation notes

  • One row per CTA (or per warp for short rows); use __shfl_down_sync for the intra-warp max/sum.
  • Fuse whatever surrounds it: mask, scale, dropout, top-k: every fused elementwise op is bytes saved (Kernel Fusion).
  • Vocabulary-sized softmax (e.g. 128K logits) at decode is a real cost; fuse it with the sampling/top-k step.
  • exp2f is cheaper than expf; fold into the scale factor so you compute .

Tip

Any “reduce then normalize” pattern (softmax, layernorm, RMSNorm, logsumexp) has an online single-pass form. Knowing the rescaling identity is the standard attention-kernel interview question.

FlashAttention · Reduction Kernels · Kernel Fusion · Arithmetic Intensity · Triton Programming Model