The derivative of Boolean-masked softmax #
The mask is fixed while the scores vary. A row with an allowed key is a normalized sum of exponentials over those keys; a row without one is the constant zero function. These are separate cases of the same derivative formula, because a blocked key has exactly zero weight.
The implementation subtracts a maximum before exponentiating. We first cancel that common factor over the reals, then differentiate the resulting quotient. In particular, ties for the maximum do not require a hypothesis: the maximum is an implementation detail of the stable evaluation, and the function being differentiated is smooth even where that maximum changes.
An allowed logit contributes its exponential; a blocked logit contributes zero.
Instances For
The sum is positive exactly when the fixed mask has an allowed key.
Instances For
The real formula for the weights, including the zero row when every key is blocked.
Instances For
Removing the stable shift gives the ordinary exponential quotient on the allowed keys.
The implementation and the smooth real presentation have the same vector coordinates.
Reading one coordinate exposes the weighted centering performed by the spec JVP and VJP.
Hard-masked softmax is differentiable for every score vector and every fixed Boolean mask.
An all-false row is handled before applying the quotient rule. Consequently the proof neither divides by its zero denominator nor invents a derivative at a masked infinity.
This derivative theorem is about the actual stable tensor implementation.
The implementation's weighted-centering helper evaluates the derivative itself.
The row derivative is self-adjoint, including rows whose weights are all zero.
The concrete backward helper is the adjoint of the derivative of the concrete forward.
This is stronger than an algebraic JVP/VJP pairing: hasFDerivAt_spec supplies the analytic
derivative, and the equality below identifies the helper called by attention with its adjoint.