advanced25 min studyLesson 476 in Engineering

Stable softmax: keep the normalizer consistent as tiles arrive

Derive max-shifted softmax, combine online block summaries, and connect numerical state reuse to attention without materializing every score.

On this page

What you’ll understand

  • Compute softmax after a common maximum shift.
  • Combine block maxima and shifted sums with a shared normalization scale.
  • Identify masked-row, nonfinite, accumulation, and storage assumptions in a fused softmax or attention kernel.

Softmax turns logits into normalized positive weights, but exponentiating large logits directly can overflow before normalization cancels their common scale. Subtracting a common maximum avoids that failure for finite inputs. Tiled implementations add another obligation: every partial sum and weighted value must be expressed on the same scale when a later block introduces a larger maximum.

A common shift preserves the mathematical probabilities

For a nonempty finite row, subtract its largest logit before exponentiation. The maximum shifted logit is zero, so no shifted exponential exceeds one in real arithmetic. The normalizer remains positive because at least one term is one. Very small shifted terms can still underflow in a finite representation, and approximate exponential instructions introduce their own error. The transformation improves stability; it does not make a floating-point implementation exact. Logits here are dimensionless, as required for the exponential.

Masks need a defined semantic contract. Invalid tail lanes can use an appropriate exclusion value for a maximum and exponential reduction, but a row with every position masked cannot blindly compute negative infinity minus negative infinity. Positive infinity, NaN, and empty rows also need an explicit API policy or supported reference behavior. Choose the accumulator type and final output conversion separately from the input type. Check normalization and selected probability errors against a trusted reference rather than only checking that the kernel returned finite values.

m=max⁡jxj,pi=exi−mℓ,ℓ=∑jexj−mm=\max_j x_j,\qquad p_i=\frac{e^{x_i-m}}{\ell},\qquad \ell=\sum_j e^{x_j-m}
The row is nonempty with finite real dimensionless logits x_j, so ℓ is positive. This is the exact mathematical shifted softmax; finite precision, approximate exponentials, masking, and nonfinite policies need additional handling.↔ Scroll wide equations horizontally.

Online summaries must be rescaled when maxima change

Summarize a block by its maximum and the sum of exponentials shifted by that maximum. To merge two blocks, choose the larger maximum and rescale both sums to it before adding. Adding the original shifted sums directly is wrong when their maxima differ. A weighted-value accumulator can be rescaled the same way, allowing the normalized weighted result to be formed after processing more blocks. The summaries refer to represented logits and the chosen arithmetic; their mathematical combination is associative in real arithmetic, while floating-point grouping can still differ.

Online normalization is one mechanism enabling attention algorithms to avoid storing the entire score or probability matrix in external memory. FlashAttention combines tiling, online softmax, and careful data movement; it is not a claim that attention performs no quadratic arithmetic or that every sequence length benefits equally. Causal masks, head dimensions, dropout, and backward computation add further contracts. Distinguish exact attention as a mathematical operation from bitwise equivalence to a particular materialized implementation. Different rounding and accumulation schedules require tolerance-based validation.

m=max⁡(mA,mB),ℓ=emA−mℓA+emB−mℓB,r=emA−mrA+emB−mrBm=\max(m_A,m_B),\qquad \ell=e^{m_A-m}\ell_A+e^{m_B-m}\ell_B,\qquad r=e^{m_A-m}r_A+e^{m_B-m}r_B
For two nonempty finite blocks, ℓ terms are shifted exponential sums and r terms are correspondingly shifted sums of exponentials times value vectors. r/ℓ gives the combined weighted value. All block summaries must use the stated maxima; empty or fully masked blocks require explicit identity handling.↔ Scroll wide equations horizontally.

Reuse saves traffic only within a feasible resource budget

A fused row softmax can load a row, compute its maximum and sum, and write normalized results without round-tripping several intermediates through device memory. Large rows may not fit the chosen register or shared-memory budget, requiring multiple stages or a different partition. More retained values can cause spills or reduce parallelism. Include any rereads and temporary storage in the actual traffic boundary. A small illustrative tutorial's in-row fusion strategy is not a universal implementation for arbitrary shapes and hardware.

The network lab shows exactly the two-logit softmax family [0,z] through p=σ(z), where z=wx−0.5. Reset, set x=1 and w=1, predict p≈0.622, then Play or Step. Separately Reset, set x=1 and w=3, predict p≈0.924, then Play or Step. The complement is the probability for the zero logit. The instrument does not expose arbitrary rows, large-logit arithmetic, masks, or online block merging. Use the hand example to verify rescaling and the lab to inspect only this fixed binary normalization family.

Normalize large logits and merge their blocks

Compute softmax for finite logits [1,000,1,001,1,002]. Treat the first two logits as block A and the last as block B.

  1. The row maximum is 1,002, giving shifted exponentials [e⁻²,e⁻¹,1]. Their sum is approximately 1.503214724, so probabilities are approximately [0.090031,0.244728,0.665241].

  2. Block A has maximum 1,001 and shifted sum 1+e⁻¹≈1.367879441. Block B has maximum 1,002 and sum one.

  3. Merge on maximum 1,002: multiply A's sum by e⁻¹ and add B's one, yielding the same 1.503214724 normalizer. Adding 1.367879441+1 without rescaling would use incompatible exponential scales.

The result

The common shift avoids direct huge exponentials, and rescaled block merging recovers the same real-arithmetic normalizer.

Explore the model

Interactive lab

Interactive lab · network

Inspect a fixed binary softmax

The graph computes σ(wx−0.5), equal to the second probability of logits [0,wx−0.5]. Reset, set x=1 and w=1, predict about 0.622, then Play or Step. Separately Reset, set x=1 and w=3, predict about 0.924, then Play or Step. It does not implement arbitrary softmax rows, online merging, masking, or GPU execution.

Inspect a fixed binary softmaxOne inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Current readings: Product · wx: 1.2; Logit · wx − 0.5: 0.7; Sigmoid output: 0.6682. All parameters are adjustable with the labeled controls below.One input. One weight. One sigmoid.x1.20× w1.20+ b0.70σ0.668output0.668w = 1.00b = −0.50σ(z) = 1 / (1 + exp(−z))
Computation graphSignal trace
Product · wx
1.2
Logit · wx − 0.5
0.7
Sigmoid output
0.6682
t = 0 s

One inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA fixed two-logit model supports binary normalization intuition; stable tiled rows need the separate rescaling derivation.

Check your understanding

Why cannot two blocks' shifted exponential sums always be added directly?

Try it yourself

Block A has maximum 2 and shifted sum 3. Block B has maximum 4 and shifted sum 2. Find the combined maximum and shifted sum, leaving an exact expression and a decimal approximation.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Rescale A by exp(2−4); B already uses the combined maximum.

Compare with the solution

The combined maximum is four. The combined shifted sum is 3e⁻²+2≈2.40600585. Directly adding three and two would give five on incompatible scales. If weighted value accumulators are present, they require the same respective rescaling before the final division.

Take it with you

  • A common maximum shift stabilizes finite-row softmax without making floating point exact.
  • Online block summaries require consistent rescaling of sums and weighted values.
  • Fusion and attention tiling must fit resource, masking, and numerical contracts.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.