Compute the Difference, Not the Two Numbers
The previous probe showed that the standard soft-target gradient q−p is a difference of two nearly equal numbers computed by two different routes, so it carries a residual of the size of the rounding unit. A Fix for Softmax and Cross-Entropy rewrites the gradient in terms of the logit difference δ=zS−zT, so that the subtraction happens in log space where it is exact, and the only exponentials and logarithms are of quantities near zero, handled by expm1 and log1p. Implement it.
soft_target_grad_fixed(z_S, z_T, remove_drift=True)
z_S and z_T are 1-D arrays of the same length and the same floating dtype (float64, float32 or float16). Do all arithmetic in that dtype and return an array of it.
- p=softmax(zT) and q=softmax(zS) by the usual shift-exp-normalise route, δ=zS−zT, then
dk=δk−i∑piδi,sk=dk−log1p(i∑piexpm1(di)),uk=pkexpm1(sk)
gk=uk−qki∑ui
- With
remove_drift=True return g. With remove_drift=False return u, the gradient before the drift-removal term.
- At zS=zT the result must be exactly zero in every entry, in every dtype.
Hints
- expm1(x)=ex−1 and log1p(x)=log(1+x) evaluated without ever forming 1+x;
np.expm1 and np.log1p keep their precision for ∣x∣≪1, where np.exp(x) - 1 returns zero or a multiple of the rounding unit.
- ∑ipiexpm1(di) is ∑ipiedi−1 because p sums to one, so sk is dk minus the log of a weighted mean of ed.
- In exact arithmetic ∑kuk=0; the last line removes whatever rounding leaves behind so that ∑kgk=0 holds the way it does for the hard-target fix.