ELLMEngineering Large
Language Models
Download PDF

Chapter 31

Softmax, Normalization, Top-K, and Sampling

On this page

These kernels are small relative to GEMM in FLOPs and large in system importance. They are often bandwidth- or launch-bound, numerically sensitive, and excellent fusion candidates.

The collectives from the previous section become transformer epilogues here. Softmax is two reductions plus a normalize pass. LayerNorm and RMSNorm are statistics plus an affine map. Top-k and sampling sit at the end of a decode step. In the running example, these kernels rarely dominate FLOPs, but they dominate launch count, numerical edge cases, and fusion decisions around attention and logits.

Stable softmax

For a row x, softmax is:

p_i = exp(x_i - m) / sum_j exp(x_j - m), where m = max_j x_j

Subtracting the row maximum prevents overflow. A basic row kernel has three logical phases:

  1. reduce to the row maximum;
  2. reduce the shifted exponentials to the denominator;
  3. normalize and write outputs.

Example status: CUDA excerpt; not compiled or benchmarked.

__shared__ float row_stats[2];
float local_max = -INFINITY;
for (int i = threadIdx.x; i < cols; i += blockDim.x) {
  local_max = max(local_max, x[row * cols + i]);
}
float max_at_thread_zero = block_max(local_max);
if (threadIdx.x == 0) row_stats[0] = max_at_thread_zero;
__syncthreads();
float row_max = row_stats[0];

float local_sum = 0.0f;
for (int i = threadIdx.x; i < cols; i += blockDim.x) {
  local_sum += expf(x[row * cols + i] - row_max);
}
float sum_at_thread_zero = block_sum(local_sum);
if (threadIdx.x == 0) row_stats[1] = sum_at_thread_zero;
__syncthreads();
float row_sum = row_stats[1];

for (int i = threadIdx.x; i < cols; i += blockDim.x) {
  y[row * cols + i] = expf(x[row * cols + i] - row_max) / row_sum;
}

Here one block owns one row, cols > 0, inputs are finite, and the full-warp launch contract from block_sum applies. block_max is the analogous reduction with maximum and negative infinity as the identity; it also returns its result only in thread zero. Both row statistics are explicitly broadcast before other threads consume them. Masked rows need the policy below before this arithmetic runs.

The code recomputes exponentials in the final loop. Keeping every value in registers can be faster for narrow rows but creates spills for wide rows. Recompute spends special-function arithmetic to avoid HBM or local-memory traffic.

For attention in the running example, a softmax row length equals the attended context. Prefill rows can be length 2048; decode rows can be length 4096. Materializing those scores in HBM is the problem FlashAttention later removes. The reduction structure remains the same.

Online softmax derivation

Suppose a processed prefix has maximum m_a and exponential sum l_a = sum exp(x - m_a). A new tile has maximum m_b and local sum l_b = sum exp(x - m_b). The combined maximum is:

2026-10-12T12:02:55.707192 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Rescale each partial into the new reference frame:

2026-10-12T12:02:55.711667 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

This state (m, l) is associative up to floating-point order. Adding an output accumulator produces the recurrence used in tiled attention.

Represent an empty or fully masked tile by zero mass and handle it as a neutral state before evaluating exponentials. Merging two empty states by blindly subtracting their negative-infinity maxima produces NaNs. The same guard is needed for attention's weighted-output state.

Two tiles keep compact state instead of the full score vector. Merging rescales both sides into one maximum, then adds denominators and weighted outputs.
Open full diagram ↗

Two tiles keep compact state instead of the full score vector. Merging rescales both sides into one maximum, then adds denominators and weighted outputs.

Masking and edge cases

A masked element contributes negative infinity before the maximum. A fully masked row is a policy decision: produce zeros, NaNs, or a declared fallback. Silently evaluating exp(-inf - -inf) produces invalid arithmetic.

Causal masks can avoid loading disallowed tiles. Arbitrary masks may add branches or extra memory traffic. Packed ragged sequences require per-row lengths and careful prevention of cross-sequence reads.

Softmax backward

Given output p and upstream gradient g, the gradient with respect to logits is:

2026-10-12T12:02:55.719388 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

This needs one dot-product reduction followed by an elementwise pass. Fusing the reduction and output when the row fits on chip avoids an intermediate. Accumulate the dot product in higher precision for low-precision inputs.

LayerNorm

LayerNorm over a row computes:

2026-10-12T12:02:55.724598 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.731385 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.739792 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

A one-pass Welford state (count, mean, M2) is numerically stable and mergeable across lanes. A two-pass mean-then-variance kernel can be competitive when rows are moderate and input rereads hit cache.

In the running example, normalization rows have length D = 4096. That fits a block-strided reduction comfortably. The dominant cost is usually reading and writing the activation tensor, which is why residual-plus-norm fusion matters.

LayerNorm backward reduces both sum(dy times gamma) and sum(dy times gamma times x_hat) for each row, then applies the closed-form gradient. Gradients for gamma and beta reduce across rows and may require a second dimension of parallelism.

RMSNorm

RMSNorm omits mean subtraction:

2026-10-12T12:02:55.748928 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.755459 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

It needs one reduction and is simpler to fuse. Accumulate squares in FP32 when inputs are FP16 or BF16. Extremely large values can still overflow before accumulation if conversion or scaling is wrong.

Derive normalization backward and its reduction axes

Let g_i = dy_i*gamma_i, r=(mean(x_i^2)+epsilon)^(-1/2), and a=mean(g_i*x_i) for one RMSNorm row. Differentiating r gives dr/dx_j = -x_j*r^3/N, hence dx_i = r*g_i - x_i*r^3*a. The correction couples every column through one scalar reduction; independently differentiating each element while holding r fixed drops that term.

For LayerNorm define h_i=(x_i-mean(x))*r, where now r=(variance+epsilon)^(-1/2). The derivative is dx_i = r*(g_i-mean(g)-h_i*mean(g*h)). This requires two row reductions after the forward statistics are known. Epsilon remains inside the saved inverse square root; replacing mean(h*h) with exactly one in a derivation is wrong when epsilon is nonzero.

Across rows t, dgamma_i=sum_t(dy_ti*h_ti) and dbeta_i=sum_t(dy_ti) for LayerNorm. For RMSNorm replace h_ti by x_ti*r_t. These are column reductions, so the best ownership scheme can differ from the rowwise dx kernel. One strategy writes per-block parameter-gradient partials and launches a second reduction; another uses atomics with a documented numerical nondeterminism policy. Include those partial buffers and their traffic in any backward benchmark.

The companion examples/kernel_algebra.py checks both input-gradient formulas against central finite differences, including width one and nonzero epsilon. This verifies the algebra in double-precision host arithmetic; it does not validate a CUDA reduction implementation.

Residual and normalization fusion

A common transformer sequence is:

2026-10-12T12:02:55.761232 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.768275 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Fusing residual addition, optional bias, normalization, and perhaps quantization can eliminate one or more full-tensor round trips. The kernel must still expose the updated residual if a later branch needs it.

Fusion tradeoffs include:

  • saved HBM bytes and launches;
  • extra live values and register pressure;
  • more output tensors;
  • dropout or RNG semantics;
  • backward-save requirements;
  • variant count across dtype and hidden size.

For one residual stream of shape [tokens, D] in FP16, a separate residual add performs two tensor reads and one intermediate write. RMSNorm must then read that intermediate to compute statistics, read it again to apply the scale unless the row remains on chip, and write the output. The unfused lower bound is therefore five full activation-tensor transfers and the common two-pass case is six, before counting gamma. If the residual is not needed later, fusion can reduce this to two input reads and one normalized-output write. If a later layer needs the updated residual, its write remains: fusion saves the norm reread, or two rereads for the two-pass case. At prefill with tokens = 2048 and D = 4096, each FP16 tensor is 16 MiB, so one eliminated transfer saves 16 MiB. At decode with tokens = 8, the absolute byte saving is small, but avoiding a launch can still matter. These are logical transfer counts; measured HBM savings also depend on cache reuse.

Top-k selection

Full sorting is unnecessary for small k. A common hierarchy is:

  1. each thread scans a strided subset and keeps local candidates;
  2. lanes merge candidates within a warp;
  3. warps merge through shared memory;
  4. the block emits k values and indices.

For very small k, register insertion networks or compare-exchange sequences work well. For larger k, radix selection, heap-like structures, or partial sorting may win. The best method depends on vocabulary size, k, dtype, and batch.

Distributed vocabulary top-k

If logits are sharded across P ranks, each rank computes its local top-k with global token IDs. The global top-k must lie in the union of P * k candidates, so ranks can all-gather candidates and select again.

Communication is small relative to gathering the full vocabulary. For top-p, local top-k may not include enough mass; use a larger candidate bound, histogram/bucket thresholding, or an exact distributed algorithm with additional rounds.

Sampling pipeline

A sampling kernel may apply temperature, repetition or presence penalties, forbidden-token masks, top-k, top-p, normalization, and RNG. Fusing the pipeline reduces launches but complicates exact semantics and variant coverage.

Counter-based RNG maps request, sequence position, and sample index to deterministic random bits without mutable per-thread generator state. Reordering requests must not change a user's random stream unless the product contract permits it.

Design Exercises

  1. Why is stable softmax logically a maximum reduction and a sum reduction?
  2. Derive the online-softmax merge rule.
  3. When is recomputing exp cheaper than storing it?
  4. Compare LayerNorm and RMSNorm kernel structure.
  5. How would you implement distributed vocabulary top-k?
  6. What can go wrong when fusing sampling operations?

Worked Solutions

1. Two reductions

The maximum establishes a safe numerical reference so shifted exponentials cannot overflow. The denominator is then a sum over those shifted exponentials. The second reduction depends on the first result, so they are logically sequential even if each reduction is parallel. Omitting the max risks overflow; using a local max without global row combination gives the wrong distribution.

2. Online merge

For partial states (m_a, l_a) and (m_b, l_b), choose m = max(m_a, m_b). Because l_a was measured relative to m_a, convert it by multiplying with exp(m_a - m); do the analogous conversion for l_b; then add. This maintains l = sum exp(x - m) for the union. The same rescaling applies to a weighted output accumulator.

3. Recompute versus store

Recompute wins when storing exponentials would spill registers or create a global/local-memory round trip whose latency and bandwidth cost exceeds another exp. It is especially attractive on compute-rich GPUs for moderate rows. Storing wins when values already fit in registers, exp throughput is the bottleneck, or the values are needed by several later operations.

4. LayerNorm versus RMSNorm

LayerNorm needs mean and variance, usually Welford or two reductions, then scale and bias. RMSNorm needs only mean square, inverse RMS, and scale. Both are often bandwidth-bound and benefit from residual fusion. LayerNorm backward has two rowwise statistics; RMSNorm backward is simpler. Both should accumulate statistics in higher precision for low-precision inputs.

5. Distributed top-k

Each rank selects local top-k pairs (score, global_token_id). All-gather the P * k pairs and perform a second top-k. This is exact because an item outside a rank's local top-k has at least k better items on that rank and therefore cannot enter the global top-k. Define tie-breaking and NaN handling consistently.

6. Fused sampling risks

Fusion can change operation order, numerical rounding, tie behavior, RNG indexing, and top-p truncation semantics. It can also create high register pressure and too many variants. Validate outputs statistically and, where exact reproducibility is promised, bitwise against the reference for every policy combination. Preserve request-specific RNG under batching and reordering.