Knowledge distillation loss with temperature (Hinton et al., 2015)
"Distilling the Knowledge in a Neural Network" (Hinton, Vinyals and Dean, 2015) trains a small student to match a large teacher's softened output distribution. Dividing logits by a temperature T > 1 reveals how the teacher ranks the wrong classes. Because the soft-target gradients shrink by about 1 / T^2, the paper multiplies the soft term by T^2 so it stays balanced with the hard-label term.
Write distill_loss(student_logits, teacher_logits, labels, T, alpha). Logits have shape (n, C), labels has length n.
- p_t = softmax(teacher_logits / T), p_s = softmax(student_logits / T), per row
- soft = T^2 * mean over rows of KL(p_t || p_s) = sum p_t * (log p_t - log p_s)
- hard = mean cross-entropy of softmax(student_logits) (temperature 1) against labels
- total = alpha * soft + (1 - alpha) * hard
Use a numerically stable log-softmax. Return (total, soft, hard) as floats.
def distill_loss(student_logits, teacher_logits, labels, T, alpha)Understand the idea
Distillation trains a small student to copy a big teacher. Dividing logits by a temperature T > 1 softens both distributions, which reveals how the teacher ranks the wrong classes, useful hints a hard label hides. The soft part is a KL divergence, multiplied by T^2 so its size stays comparable to the normal label loss. Worked example: T = 2, teacher logits [2, 0] become [1, 0], softmax [0.7311, 0.2689]; student logits [0, 0] give [0.5, 0.5]. KL = 0.7311 * ln(0.7311 / 0.5) + 0.2689 * ln(0.2689 / 0.5) = 0.2778 - 0.1668 = 0.1109. soft = 4 * 0.1109 = 0.4438. hard: student softmax at T = 1 is [0.5, 0.5] with label 0, so -ln 0.5 = 0.6931. With alpha = 0.5, total = 0.2219 + 0.3466 = 0.5685. Rule: soft = T^2 * mean of sum p_t * (log p_t - log p_s); hard = mean cross-entropy at temperature 1; total = alpha * soft + (1 - alpha) * hard. This is how many small production models are trained from larger ones.