Knowledge Distillation Loss and Gradient

Quick Overview

Implement a knowledge distillation loss that blends temperature-scaled KL divergence from teacher to student with hard-label cross-entropy, plus its gradient with respect to the student logits. Tests stable log-softmax computation, the chain rule through the temperature, and how the soft-term weight interacts with the gradient.

Knowledge Distillation Loss and Gradient

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given student logits `s` and teacher logits `t` of shape `(N, K)` and integer `labels` of shape `(N,)`, implement `distillation_loss` (returns a Python `float`) and `distillation_loss_grad` (returns the gradient with respect to `student_logits`, shape `(N, K)`). Both take `(student_logits, teacher_logits, labels, temperature=2.0, alpha=0.5)`, and `T` below is `temperature`. The loss averages per-sample terms over the batch: ```text p_T = softmax(t / T) # teacher, row-wise q_T = softmax(s / T) # student, row-wise KL = sum_k p_T * (log p_T - log q_T) # KL(teacher || student) CE = -log softmax(s)[label] # unscaled student logits loss = alpha * T**2 * mean(KL) + (1 - alpha) * mean(CE) ``` Example: ```python s = [[0.0, 0.0]] t = [[2 * np.log(3), 0.0]] labels = [0] temperature, alpha = 2.0, 1.0 # p_T = [0.75, 0.25], q_T = [0.5, 0.5] distillation_loss(s, t, labels, temperature, alpha) # -> 0.523248 (4 * KL) distillation_loss_grad(s, t, labels, temperature, alpha) # -> [[-0.5, 0.5]] ``` ```hint Extreme logits Every softmax in this loss, including the ones at temperature, can be computed as a log-softmax after a per-row shift. Stay in log-probabilities until you need probabilities. ``` ```hint Chain rule through the temperature Find the gradient of the KL term with respect to `s / T` first, then account for the division by `T` and for the weight on the soft term. ``` ### Constraints & Assumptions - `1 <= N`, `2 <= K`, and `0 <= labels[i] < K`. - `temperature > 0` and `0 <= alpha <= 1`. - Logits may be extreme (for example ±1000): the loss and the gradient must stay finite and accurate. - Inputs may be lists or arrays. The gradient must match finite differences of the loss. ### What a Strong Answer Covers - The blended loss assembled exactly as specified: both distributions softened by `T`, the KL taken from teacher to student, the hard cross-entropy on unscaled student logits, batch averaging, and the weight on the soft term. - Numerical stability for logits around ±1000, with no overflow or NaN in the loss or the gradient. - A gradient derived through the temperature scaling, with every factor of `T` accounted for. - Verification against the example and against finite differences, including the sum of each gradient row. ### Follow-up Questions - Why multiply the soft term by `T**2`? - What does the gradient look like, and why do its rows sum to zero? - How would you distill when teacher and student vocabularies or label spaces differ?

Overview: Implement a knowledge distillation loss that blends temperature-scaled KL divergence from teacher to student with hard-label cross-entropy, plus its gradient with respect to the student logits. Tests stable log-softmax computation, the chain rule through the temperature, and how the soft-term weight interacts with the gradient.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Given student logits s and teacher logits t of shape (N, K) and integer labels of shape (N,), implement distillation_loss (returns a Python float) and distillation_loss_grad (returns the gradient with respect to student_logits, shape (N, K)). Both take (student_logits, teacher_logits, labels, temperature=2.0, alpha=0.5), and T below is temperature. The loss averages per-sample terms over the batch:

p_T = softmax(t / T)   # teacher, row-wise
q_T = softmax(s / T)   # student, row-wise
KL  = sum_k p_T * (log p_T - log q_T)          # KL(teacher || student)
CE  = -log softmax(s)[label]                    # unscaled student logits
loss = alpha * T**2 * mean(KL) + (1 - alpha) * mean(CE)

Example:

s = [[0.0, 0.0]]
t = [[2 * np.log(3), 0.0]]
labels = [0]
temperature, alpha = 2.0, 1.0
# p_T = [0.75, 0.25], q_T = [0.5, 0.5]
distillation_loss(s, t, labels, temperature, alpha)       # -> 0.523248  (4 * KL)
distillation_loss_grad(s, t, labels, temperature, alpha)  # -> [[-0.5, 0.5]]

Constraints & Assumptions

  • 1 <= N , 2 <= K , and 0 <= labels[i] < K .
  • temperature > 0 and 0 <= alpha <= 1 .
  • Logits may be extreme (for example ±1000): the loss and the gradient must stay finite and accurate.
  • Inputs may be lists or arrays. The gradient must match finite differences of the loss.

What a Strong Answer Covers Guidance

  • The blended loss assembled exactly as specified: both distributions softened by T , the KL taken from teacher to student, the hard cross-entropy on unscaled student logits, batch averaging, and the weight on the soft term.
  • Numerical stability for logits around ±1000, with no overflow or NaN in the loss or the gradient.
  • A gradient derived through the temperature scaling, with every factor of T accounted for.
  • Verification against the example and against finite differences, including the sum of each gradient row.

Follow-up Questions Guidance

  • Why multiply the soft term by T**2 ?
  • What does the gradient look like, and why do its rows sum to zero?
  • How would you distill when teacher and student vocabularies or label spaces differ?