A Gradient That Should Be Zero
A Fix for Softmax and Cross-Entropy studies the soft-target cross-entropy L(zS,zT)=−∑kpklogsoftmax(zS)k with p=softmax(zT). Its exact gradient is q−p with q=softmax(zS), so a student that matches the teacher (zS=zT) should receive a gradient of exactly zero. In floating point it does not, because the forward pass and the backward pass reach q and p by different arithmetic routes. Build the probe that measures this residual.
soft_target_grad_standard(z_S, z_T, dtype)
z_S and z_T are 1-D logit arrays of the same length; dtype is np.float64, np.float32 or np.float16. Cast both inputs to dtype first and keep every intermediate in dtype (no float64 anywhere inside).
- Teacher probabilities take the forward softmax route: shift by the maximum, exponentiate, divide by the sum.
- The student side follows what autodiff does with the standard loss. The forward pass computes the log-softmax ℓk=z~k−log∑jez~j with z~=zS−maxzS. The backward pass of −∑kpkℓk re-exponentiates it, so the gradient is
gk=eℓki∑pi−pk
- Keep the factor ∑ipi (it is not exactly 1 in floating point). Return
g as an array of dtype.
residual_at_equality(z_T, dtype)
- Return the L2 norm of
soft_target_grad_standard(z_T, z_T, dtype) as a Python float (take the norm in float64 after the gradient has been computed in dtype).
Float16 stands in for bfloat16 (numpy has no bf16); it has an 11-bit significand instead of 8, so its residuals are a little smaller than the paper's 10−3 but far above float32's.
Hints
np.asarray(z, dtype=dtype) and arithmetic between dtype arrays stay in dtype; a stray Python float in a multiplication is fine, but np.float64 scalars from np.sum on a float64 array are not.
- eℓk and ez~k/∑jez~j are the same number on paper and differ by about one unit in the last place in practice. That difference is the whole point.
- A test checks the order of magnitude of the residual in each precision, not its last digits.