Recompute probabilities and differentiate the normalized row
Derive softmax row gradients, saved normalization state, and the conditions for consistent backward recomputation.
On this page
The question for today
What you’ll understand
- Derive the coupled softmax score gradient.
- Explain how saved LSE reconstructs tile probabilities.
- Check masks, dropout replay, scales, and shared-head gradient accumulation.
Saving every forward probability makes backward differentiation straightforward but retains a quadratic matrix. A tiled backward pass can instead reconstruct each needed probability tile from the original Q and K plus the row normalization statistic saved during forward. It then accumulates gradients and discards the tile. This performs extra arithmetic in exchange for less saved state and memory traffic. The mathematical gradient is unchanged only when recomputation uses the same scale, allowed positions, and stochastic choices as the forward operation; a similar-looking softmax from different inputs differentiates a different computation.
The gradient couples the whole row
For one row, the derivative of the output with respect to a probability is the upstream output gradient dotted with that key’s value. Softmax then subtracts a probability-weighted row mean from each of these derivatives. This subtraction captures the denominator’s dependence on every score. Ignoring it treats probabilities as independent exponentials and produces gradients whose sum generally fails the score-shift invariance check.
The weighted mean can also be computed by dotting the upstream gradient with the forward output, because the output is the probability-weighted sum of values. This identity avoids another materialized row reduction in suitable tiled schedules. The formulas here omit dropout and use one row with finite allowed logits. Masked scores contribute zero probability and gradient under a fixed mask; an entirely masked row follows the separately declared extension rather than an undefined normalized distribution.
Reconstruct a tile from a saved row statistic
Saving LSE equal to the logarithm of the row’s exponential sum lets backward reconstruct each probability as exp(score−LSE). The score tile is recomputed from Q and K using the forward scaling and bias rules. This is not another independently normalized local softmax: its denominator belongs to the entire original row. After obtaining score gradients, the usual matrix products form gradients with respect to Q, K, and V, including the score scale in both Q and K derivatives.
Tiled accumulation must include contributions from every tile that shares an input. One query receives gradient contributions from many key tiles, and a key/value can receive contributions from many query tiles. GQA adds another sharing axis because several query heads use the same KV head, requiring their gradient contributions to sum. Race-free accumulation, numerical precision, and deterministic reduction choices are implementation concerns that can change performance without changing the required mathematical derivative.
Replay stochastic behavior deliberately
Attention dropout modifies probabilities after softmax in common training formulations. Recomputing backward needs the same logical dropout mask and scaling as forward, often regenerated from a saved random state and a stable mapping from logical indices to random values. A different tile schedule must not silently assign different draws to the same logical operation if exact replay is required. Disable dropout for the first deterministic correctness tests, then test the stochastic contract separately.
An exact algorithm can still have finite-precision differences because the reduction order changes between the materialized and tiled versions. Compare gradients against a higher-precision reference and use small finite-difference tests on selected smooth inputs. Include large score ranges, unusual lengths, shared heads, and masked rows. Extra recomputation is worthwhile when saved traffic and memory dominate its cost, but neither the memory reduction nor the algebra proves that every shape runs faster on every accelerator.
Work it through
Differentiate a two-key weighted average
Use one query, scalar values v=(2,6), scores s=(0,ln3), and upstream derivative gO=1. There is no dropout or mask, and score scale τ=1. Compute the forward output and derivatives with respect to scores and values.
The exponential weights are (1,3), so probabilities are (1/4,3/4), LSE=ln4, and output is (1/4)2+(3/4)6=5. Recomputing exp(s−ln4) recovers the same probabilities without a saved P array.
The probability derivatives are gP=(2,6). Their weighted mean is δ=5, also equal to gO×o. Thus score derivatives are ((1/4)(2−5),(3/4)(6−5))=(−0.75,0.75).
Value derivatives are p×gO=(0.25,0.75). The score derivatives sum to zero, matching invariance to a common score shift. If scalar q=1 and keys are (0,ln3), the query derivative is 0.75ln3≈0.823959.
The global normalizer creates the subtraction by 5. Recomputing probabilities preserves that coupling; differentiating two independent unnormalized exponentials would not.
The living notebook
Explore the model
Interactive lab · function
Check an analytic derivative on a smaller computation
Reset, set Coefficient a to 0.5 and Position x to 2. Predict y=2 and tangent slope 2 before Step. Reset, set a to 0.5 and x to 1; predict y=0.5 and slope 1 before Step. This instrument differentiates y=ax² exactly. It is a local derivative-check analogy, not attention backward or a memory-recomputation implementation.
- y at chosen x
- 0.608
- Tangent slope · 2ax
- 1.35
- Signed area · ax³/3
- 0.182
This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. 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 derivative should be checked against the operation actually computed, with all coefficients included.
Pause & reason
Check your understanding
Your turn
Try it yourself
For equal scores (0,0), scalar values (1,3), and gO=1, find output, score derivatives, and value derivatives without dropout.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
The probabilities are one half each, and δ equals the forward output.
Compare with the solution
Output is 0.5×1+0.5×3=2. The score gradient is (0.5(1−2),0.5(3−2))=(−0.5,0.5), whose sum is zero. Value gradients are (0.5,0.5). These use the coupled softmax denominator; omitting δ would incorrectly produce positive score derivatives (0.5,1.5).
Keep the idea
Take it with you
- Recompute probability tiles with the original full-row normalization.
- Softmax score gradients subtract a weighted row mean.
- Masks, stochastic replay, scales, and shared-input sums belong to backward correctness.
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.