A Fix for Softmax and Cross-Entropy describes a second bug, separate from softmax collapse. For a soft target and student logits , the loss has gradient with . When the student is close to the teacher this is a difference of nearly equal numbers computed along two different paths, so even at the gradient is not zero but rounding noise of about in float32. Adam normalises that noise into full-size steps, and a student initialised at its teacher drifts away. The paper's fix evaluates the gradient from the logit difference with expm1 and log1p, so no one is added to or subtracted from a number close to it. Implement the loss with the standard forward and the fixed backward.
FixedSoftTargetCE(torch.autograd.Function) and fixed_soft_target_ce(z_S, z_T)
z_S and z_T are float tensors of shape (B, K), the same dtype (float32 or float64), on the CPU. fixed_soft_target_ce applies the Function and returns a scalar tensor.torch.log_softmax and torch.softmax so the loss value is unchanged from the usual implementation.z_S is the incoming scalar gradient times (the of the batch mean). Return None for z_T: the teacher receives no gradient.torch.expm1 and torch.log1p for the two bracketed terms; exp(x) - 1 and log(1 + x) written out reintroduce the cancellation the problem is about. No torch.func, no torch.compile, CPU only.z_S and z_T with ctx.save_for_backward and recompute and in backward; the Function's forward runs without gradient tracking, so nothing else is needed.