L2 Intermediate · Module 5: Parallel patterns
5.7Softmax: three kernels, then one fused kernel
Softmax is two reductions and a map, the patterns of this module put to work in one of the most-run operations in an LLM. This chapter writes it as three kernels, fuses it into one, derives the online softmax that FlashAttention is built on, and measures five versions on three row shapes, finding that the right kernel depends on how long the rows are.
By the end you will be able to
- ✓Explain why softmax subtracts the row max, and show the overflow it prevents
- ✓Count the memory traffic of a three-kernel softmax and of fused versions, and predict their speed
- ✓Derive the online softmax update that computes max and sum in one pass
- ✓Choose a block-per-row, warp-per-row or split-row layout from the row length
Softmax turns a row of scores into probabilities. It runs over every row of attention scores in every layer (1.3), and over the logits at the end of every decode step (1.4):
In terms of this module’s patterns, it is a max reduction (5.1), then a sum reduction of exponentials, then an elementwise map.
Why subtract the max
Mathematically, subtracting changes nothing: it multiplies the top and bottom of the fraction by . Numerically, it is essential. FP32 overflows at about , and logits of 90 or more are entirely normal:
Logits 90 ... 100: exp(x) / sum nan nan nan nan nan nan nan nan exp(x - max) / sum 0.0000 0.0002 0.0016 0.0116 0.0316 0.0860 0.2337 0.6353Without the max, becomes inf, inf / inf is NaN, and the whole row is lost. With it, the largest exponent is , and
nothing can overflow. In FP16, which overflows at 65,504 ≈ , this matters even more.
Version 1: three kernels
The direct translation launches one kernel per step:
k_row_max <<<rows, 256>>>(x, m, cols); // m[r] = max of row rk_exp_sum <<<rows, 256>>>(x, m, y, s, cols); // y = exp(x - m[r]), s[r] = sum of yk_normalize<<<rows, 256>>>(y, s, cols); // y /= s[r]Count the trips through memory. Kernel 1 reads the row. Kernel 2 reads it again and writes y. Kernel 3 reads y and writes it
again. That is 3 reads and 2 writes, plus 3 launches. The minimum is 1 read and 1 write.
Version 2: fuse into one kernel
Give each row to one block, which does all three steps. The max and sum are block reductions with warp shuffles
(5.2), and every thread needs the results, so they use the xor butterfly:
// labs/m05/5.7/softmax.cu, k_fused3float v = -FLT_MAX;for (int c = threadIdx.x; c < cols; c += BLOCK) v = fmaxf(v, row[c]);float mx = block_reduce_max(v); // pass 1: maxfloat s = 0.0f;for (int c = threadIdx.x; c < cols; c += BLOCK) s += expf(row[c] - mx);float inv = 1.0f / block_reduce_sum(s); // pass 2: sumfor (int c = threadIdx.x; c < cols; c += BLOCK) out[c] = expf(row[c] - mx) * inv; // pass 3: writeThis still reads the row three times, but the intermediate y is never written, and if the row is short, the second and third reads come
from cache.
Version 3: online softmax, one pass for max and sum
Can the max and the sum be computed in a single pass? The problem is that the sum needs the max, which isn’t known until the end. The trick (Milakov and Gimelshein, 2018) is to keep a running max and a running sum of , and rescale whenever the max changes:
If a new element is larger than everything so far, the old sum was relative to the wrong max, and multiplying by corrects it. Two partial results and merge the same way, so the per-thread states combine with an ordinary shuffle tree:
That makes 2 reads (one for , one to write the outputs) and 1 write.
Version 4 and 5: keep the row on chip
If the row fits in registers, load it once, compute max and sum from the registers, and write once: the minimum traffic. With 256 threads,
a 1,024-element row is just 4 floats per thread (k_registers).
For short rows, a whole block per row wastes threads. A 64-element row gives a 256-thread block only 64 elements to work on. Instead,
give each row to one warp: 2 values per lane, reductions purely by shuffles, no shared memory and no __syncthreads (k_warp_row).
Measured
“GB/s” counts only the minimum traffic, 1 read and 1 write, so it shows how close each kernel comes to a perfect one. In this run a plain copy reached about 125 GB/s (the memory was below its top clock; see 5.1).
attention: 16384 rows x 1024 (67 MB) 3 kernels 2.725 ms 49.3 GB/s PASS fused 3-pass 1.107 ms 121.2 GB/s PASS online 1.130 ms 118.7 GB/s PASS registers 1.086 ms 123.5 GB/s PASS warp/row 1.089 ms 123.3 GB/s PASS
vocab: 64 rows x 128256 (33 MB) 3 kernels 1.347 ms 48.8 GB/s PASS fused 3-pass 1.056 ms 62.2 GB/s PASS online 0.801 ms 82.0 GB/s PASS
short: 262144 rows x 64 (67 MB) 3 kernels 6.624 ms 20.3 GB/s PASS fused 3-pass 3.995 ms 33.6 GB/s PASS online 6.734 ms 19.9 GB/s PASS warp/row 1.096 ms 122.5 GB/s PASSAttention-shaped rows (1,024 wide). Fusion gives 2.5×. After that, every fused version is at the bandwidth limit. A 4 KB row is still in L1 when the second and third passes read it, so in practice even the 3-pass kernel reads DRAM only once.
Vocabulary rows (128,256 wide, a decode batch of 64). Each row is 513 KB, far too big for L1, and 64 of them exceed the 2 MB L2. Now every extra pass really goes to DRAM, so online beats 3-pass by 1.3×, reading 2 rows instead of 3. Even online softmax reaches only 82 GB/s, because there are only 64 blocks for 20 SMs. Production kernels split long rows across several blocks and merge their pairs with the rule above, as in 5.3’s last-block pattern.
Short rows (64 wide). Block-per-row kernels waste three quarters of their threads and spend most of their time in barriers. The online
version is even slower than 3-pass here. Most likely, with at most one element per thread, the two extra expf in each merge step cost
more than the memory pass they save. Warp-per-row is 3.6× faster than the best block kernel and runs at full bandwidth.
And then, fuse it away
The fastest softmax is one that never runs as its own kernel:
- Attention fuses softmax into the attention kernel (FlashAttention), so the scores never reach memory at all.
- Sampling fuses temperature scaling, softmax and top-k/top-p into one sampling kernel (11.1). Greedy decoding doesn’t need the softmax at all, only the argmax.
- Training fuses softmax with the cross-entropy loss, which is beyond this course.
Lab: five softmaxes, three shapes 🔴
cd labs/m05/5.7 && nvcc -O2 -arch=native softmax.cu -o softmax && ./softmaxSources
Check your understanding
0 / 4 answered1.Why does softmax subtract the row max before exponentiating?
2.How many times does the three-kernel softmax move each row through memory?
3.Online softmax has seen max m = 5 and sum d = 2 (relative to 5). The next element is 7. What are m and d now?
4.For 64-element rows, warp-per-row was 3.6× faster than the best block-per-row kernel. Why?