Pidoku

Softmax and Numerical Stability

Module 10 Lesson 10.g 1h 15m Difficulty 3/5

Prerequisites 10.a, 10.c

The “online softmax” trick in section 5 is the mathematical core of FlashAttention. Understand it here and 13.l will be easy.


Before you start: four words#

WordPlain meaning
exp(x)e (≈ 2.718) raised to the power x. Always positive; grows extremely fast: exp(10) ≈ 22,000, exp(100) ≈ 2.7 × 10⁴³.
OverflowA result too large for the number format, which becomes Inf (infinity).
UnderflowA result too small to represent, which becomes 0.
NaN“Not a number”: the result of undefined arithmetic such as Inf / Inf or 0 / 0. Once it appears, it spreads through every later calculation.

1. What is it?#

Softmax turns a list of arbitrary scores into probabilities:

softmax(x)_i = exp(x_i) / sum_j exp(x_j)

Every output is between 0 and 1, and together they add up to 1. Softmax appears twice in every language model:

  1. Inside attention, to turn “how relevant is each earlier token?” scores into weights (10.h).
  2. At the output, to turn one score per vocabulary token into probabilities for choosing the next token (12.o).

2. Why does it exist?#

You have scores and you need probabilities with three properties:

  1. All positive — exp guarantees it.
  2. Adding up to 1 — dividing by the sum guarantees it.
  3. Smooth and order-preserving — a bigger score always gets a bigger probability.

The exponential also makes differences count multiplicatively: a score gap of 2 always means a probability ratio of e² ≈ 7.4, whatever the absolute values. That is why it is called soft max: a smooth version of “pick the largest”.


3. Simple analogy#

Turning enthusiasm scores into vote shares.

Three candidates score 8, 6 and 2. Dividing each by the total (8/16, 6/16, 2/16) breaks down for zero or negative scores. Softmax exponentiates first — e⁸, e⁶, e² — giving 88%, 12% and 0.2%. The exponential sharpens the difference; the leader wins decisively.

Temperature (12.o) is the dial on that sharpness: divide the scores by T before exponentiating. A high T flattens the distribution (more random choices); a low T sharpens it (more predictable).


4. Tiny example#

Go
package main

import (
	"fmt"
	"math"
)

func softmaxNaive(x []float64) []float64 {
	out, sum := make([]float64, len(x)), 0.0
	for i, v := range x {
		out[i] = math.Exp(v) // [7.389, 2.718, 1.105]
		sum += out[i]
	}
	for i := range out {
		out[i] /= sum
	}
	return out
}

func main() {
	fmt.Printf("%.3f\n", softmaxNaive([]float64{2.0, 1.0, 0.1})) // [0.659 0.242 0.099], sums to 1 ✓
}

By hand: exp(2) = 7.389, exp(1) = 2.718, exp(0.1) = 1.105; the sum is 11.212; so the probabilities are 7.389/11.212 = 0.659, and so on.

Now break it:

Go
fmt.Println(softmaxNaive([]float64{1000, 999, 998}))
// math.Exp(1000) = +Inf, and Inf/Inf = NaN:
// [NaN NaN NaN]        ← OVERFLOW

The correct answer is the same as for [2, 1, 0] — [0.665, 0.245, 0.090] — because softmax depends only on the differences between scores. But the naive calculation produces NaN.

The fix is to subtract the largest score first:

Go
func softmaxStable(x []float64) []float64 {
	m := slices.Max(x) // subtract the max: the largest becomes 0, so max(exp) = 1
	out, sum := make([]float64, len(x)), 0.0
	for i, v := range x {
		out[i] = math.Exp(v - m)
		sum += out[i]
	}
	for i := range out {
		out[i] /= sum
	}
	return out
}

// softmaxStable([]float64{1000, 999, 998})
// [0.665 0.245 0.090]        ✓

Why this is exactly right, not an approximation:

exp(x_i - c) / Σ exp(x_j - c) = [exp(x_i)·exp(-c)] / [exp(-c)·Σ exp(x_j)]
                              = exp(x_i) / Σ exp(x_j)

The exp(-c) cancels. Any c works; c = max(x) is chosen because it makes the largest term exp(0) = 1, so nothing can overflow.


5. Technical explanation#

How far each format can go#

FP32:  largest ≈ 3.4 × 10^38   → exp overflows for x > ~88
FP16:  largest ≈ 65,504        → exp overflows for x > ~11.1
BF16:  largest ≈ 3.4 × 10^38   → same range as FP32 (with far fewer digits, 10.k)

In FP16, exp overflows above about 11. Attention scores routinely exceed that at long context. That is why:

  • attention softmax is computed in FP32 even inside FP16 or BF16 models, and
  • BF16 is the default format for serving: its FP32-sized range removes a whole class of overflow bugs, at the cost of precision that is rarely needed.

Underflow#

exp(-100) ≈ 3.7 × 10^-44   → a tiny "subnormal" in FP32, exactly 0 in FP16

Underflow to zero is usually harmless in softmax — that token had negligible probability anyway. It matters when you then take a logarithm: log(0) = −Inf. Compute log-probabilities with the log-sum-exp form instead:

Go
func logSoftmax(x []float64) []float64 {
	c, sum := slices.Max(x), 0.0
	for _, v := range x {
		sum += math.Exp(v - c)
	}
	out := make([]float64, len(x))
	for i, v := range x {
		out[i] = v - c - math.Log(sum)
	}
	return out
}

Always use log_softmax(x) rather than log(softmax(x)).

Softmax inside attention#

scores = (q @ k.T) / sqrt(d_head)      # (S_q, S_k): one score per query–key pair
scores = scores + causal_mask          # positions a token may not see get -inf
attn   = softmax(scores, dim=-1)       # over the KEYS
out    = attn @ v

Three subtleties:

1. The mask. A token must not attend to tokens after it. Use -inf where possible so exp(-inf) = 0 exactly. -1e9 overflows to -inf in FP16 (fine), while -1e4 does not fully mask. A row that is entirely masked gives 0 / 0 = NaN — a classic bug with some padding and sliding-window schemes.

2. The scale. 1/√d_head keeps the scores at a typical size of about 1 whatever the head size (10.a). Without it, softmax puts almost all weight on one key.

3. The axis. Softmax runs over the key axis (the last one). The wrong axis gives a valid shape and nonsense values.

A modern variation — attention sinks. Softmax forces the weights to add up to 1, so a head that has “nothing useful to attend to” must still put its weight somewhere; trained models learn to dump it on the first token. Some recent models (gpt-oss, for example) add a learned extra term to the denominator — a “sink” — so a head can attend to nothing. Engines have to support it in their attention kernels; it changes nothing else in this lesson.

Online (streaming) softmax — the core of FlashAttention#

The problem: an ordinary softmax needs the whole score row in memory to find the maximum and the sum. With 128,000 keys that row is large, and for every query you would have to store it.

The insight: you can compute softmax incrementally, keeping a running maximum and a running sum as blocks of scores arrive:

Process the keys in blocks. Keep:
    m = running maximum
    l = running sum of exp(x - m)
    o = running weighted output

For a new block whose maximum is m_new:
    m'   = max(m, m_new)
    l'   = l · exp(m - m') + Σ exp(x - m')
    o'   = o · exp(m - m') + Σ exp(x - m') · v

The factor exp(m − m') rescales everything computed so far to the new maximum. After the last block, divide o by l and you have exactly the same answer as the full softmax.

Worked with two blocks:

Block 1: x = [2, 1]     → m = 2,  l = e⁰ + e⁻¹ = 1.368
Block 2: x = [5, 0]     → m_new = 5, so m' = 5
         rescale: l = 1.368 · e^(2-5) = 1.368 · 0.0498 = 0.0681
         add:     l += e⁰ + e⁻⁵ = 1.0067   →   l = 1.0748

Full softmax denominator for [2, 1, 5, 0] with max 5:
         e⁻³ + e⁻⁴ + e⁰ + e⁻⁵ = 0.0498 + 0.0183 + 1 + 0.0067 = 1.0748   ✓ exact

This is not an approximation. It means attention never needs the full (S, S) score matrix in memory. That is FlashAttention (13.l), and it is why 128k-token contexts are feasible.

The same trick lets you merge partial results: if two GPUs each compute attention over half of the keys and return their (m, l, o) — or, equivalently, the output plus its log-sum-exp — the two halves combine exactly. Context parallelism (14.f) and shared-prefix attention kernels rely on this.


6. Under the hood#

A naive softmax kernel makes three passes over the data:

pass 1: find the max
pass 2: compute exp and the sum
pass 3: divide
→ 3 reads + 1 write of the whole tensor

A fused “online” kernel makes one pass, with the running max and sum kept in registers:

one pass: running max and sum, then normalise
→ 1 read + 1 write (or 2 reads if it re-reads to normalise)

For the output softmax over V = 128,256 at batch 64, that is roughly 65 MB versus 16 MB of traffic per step — modest but real. For attention it is the difference between storing (B, h, S, S) in HBM and never storing it — between running out of memory and working.


7. Performance implications#

  • Softmax is memory-bound: about 5 FLOPs per element against 4–8 bytes moved.
  • Fusing softmax into the attention kernel is the single largest attention optimisation.
  • Accumulating the sum in FP32 costs nothing meaningful (one number per row) and buys stability.
  • The output softmax over a large vocabulary is a (B, 128256) reduction every step. Fuse it with sampling (12.o).

8. Production implications#

  • Serve in BF16 rather than FP16 where possible; the range removes a class of overflow bugs, especially at long context.
  • Compute attention softmax with FP32 accumulation, even in a BF16 or FP8 model.
  • Watch for NaN. In production it usually traces to a fully masked attention row, an FP16 overflow in attention scores, or a division by a zero sum. Keep a debug mode that checks for NaN after each layer.
  • Use log_softmax for log-probabilities. Never log(softmax(x)).
  • Temperature 0 is not softmax with T = 0 (a division by zero). Implement it as argmax.

9. Common mistakes#

Naive softmax without subtracting the max. Overflows immediately in FP16.

log(softmax(x)) instead of log_softmax(x). Underflow → −Inf → NaN later.

The wrong axis. Softmax over queries instead of keys: valid shape, garbage values.

A weak mask value. -1e4 does not mask properly.

Fully masked rows. All keys masked → sum = 0 → NaN.

Forgetting 1/√d_head. Attention collapses onto single keys.

Computing softmax in FP16 “to save memory”. The saving is negligible; the risk is not.


10. Hands-on exercise#

A. Break and fix. Implement naive and stable softmax. Find inputs that make the naive version give Inf or NaN in FP32 and in FP16, and show the stable version handles them.

B. Online softmax. Write a function that computes softmax over a long vector in blocks of 128, keeping a running max and sum. Check that it matches scipy.special.softmax to floating-point precision. Keep this code — it is the heart of Project 04.

C. Extend it to attention. Compute softmax(QKᵀ/√d) @ V block by block without ever storing the full score matrix. Check against the naive version and measure peak memory for both at S = 4,096. You have now implemented the core of FlashAttention.

D. Range experiment. For d_head ∈ {64, 128, 256}, draw random q and k with entries from a normal distribution and measure the spread of q · k with and without the 1/√d scale. At which d_head does unscaled attention overflow FP16?

E. Merge two halves. Split the keys of exercise C into two halves, compute each half’s output and log-sum-exp separately, and combine them. Check that the result matches the full computation.

F. NaN hunt. Build an attention input with a fully masked row, observe the NaN, and fix it.


11. Interview questions#

  1. Why does softmax subtract the maximum? Prove it does not change the result.
  2. At what value does exp overflow in FP16, and why does that matter for attention?
  3. What is online softmax, and why does FlashAttention need it?
  4. How can two partial attention results over disjoint key sets be combined exactly?
  5. Why is BF16 preferred over FP16 for serving?
  6. Your model produces NaN after 3,000 tokens. Give four hypotheses.
  7. Why is log_softmax preferred to log(softmax(x))?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in