Stable attention softmax
Quick answer
Stable softmax subtracts the maximum allowed score before exponentiation. Masked positions receive exactly zero weight, and rows with no allowed positions need an explicit policy. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Stable masked row
import maths=[1000.,1000.,9999.];allow=[1,1,0]m=max(x for x,a in zip(s,allow) if a)e=[math.exp(x-m) if a else 0. for x,a in zip(s,allow)]print([x/sum(e) for x in e])Expected output (locally tested): [0.5, 0.5, 0.0]. The blocked huge score is not included in the maximum.
How it works
For finite allowed logits s_j, let m=max(s_j) over allowed keys. Set w_j=exp(s_j-m)/sum_allowed exp(s_k-m) for allowed positions, and zero elsewhere. At least one exponent equals one, so the denominator is positive and no allowed exponent exceeds one. Adding a constant to all allowed logits leaves weights unchanged in exact arithmetic; finite precision can still lose small differences when numbers are extreme. Exclude masked scores before computing the maximum, not just after exponentiation. For a row with no allowed keys this expression has no denominator; this lesson rejects it explicitly. A production model may instead define a zero-output policy and must test it. Softmax operates over the key axis independently for every query/head. With no dropout, a weighted sum is a convex combination of values. Compute in sufficient precision and avoid softmax on all negative infinity. Do not expect the same output bit-for-bit across kernels or dtypes.
Shift invariance
import torchx=torch.tensor([[1000.,1001.],[0.,1.]],dtype=torch.float64)y=x.softmax(-1)print(y[0].round(decimals=6).tolist(),bool(torch.allclose(y[0],y[1])))Expected output (locally tested): [0.268941, 0.731059] True. Each row is independently normalized over keys.
Common mistakes
Do not exponentiate raw logits such as 1000, include masked logits in the maximum, normalize across queries, or silently assign uniform probability to an entirely masked row.
Practice and next steps
Calculate softmax of [1000,1000,9999] with the third position blocked. Then add 500 to the first two values and verify the same result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Stable attention softmax — knowledge check
Apply stable attention softmax to small examples and debugging scenarios.
Why subtract the maximum?
Which axis should attention softmax use?
What is the hand implementation policy for no allowed keys?
What is a blocked weight?
Does a constant shift change exact softmax?