The Teacher's Softened Opinion

Deep Learning in the Real WorldMedium+20 XP+20

The Teacher's Softened Opinion

In distillation the student learns from the teacher's whole spread of probabilities, not just the right answer: cat, but dog was a close second. There's a catch at an ordinary softmax. A confident teacher puts almost all its probability on one class, and the close-second information nearly disappears. So both models' scores are first softened with a temperature TTT:

pi=ezi/T∑jezj/Tp_i = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}pi​=∑j​ezj​/Tezi​/T​

At T=1T = 1T=1 this is the ordinary softmax. A larger TTT spreads the probabilities out more evenly.

The loss for one example blends two parts.

  • Soft part. Soften the teacher's scores into ppp and the student's scores into qqq, both at the same TTT. Measure how far qqq is from ppp with the KL divergence (natural log), then multiply by T2T^2T2:
soft=T2∑ipiln⁡piqi\text{soft} = T^2 \sum_i p_i \ln\frac{p_i}{q_i}soft=T2i∑​pi​lnqi​pi​​
  • Hard part. Ordinary cross-entropy against the true label yyy, using the student's probabilities at temperature 1:  hard=−ln⁡qy(1)\ \text{hard} = -\ln q^{(1)}_y hard=−lnqy(1)​.
loss=α⋅soft+(1−α)⋅hard\text{loss} = \alpha \cdot \text{soft} + (1 - \alpha)\cdot \text{hard}loss=α⋅soft+(1−α)⋅hard

The T2T^2T2 is there because softening shrinks the soft part's gradients by roughly a factor of T2T^2T2. Multiplying it back keeps the two parts on a comparable scale whatever temperature you pick.

Task: write distillation_loss(student, teacher, labels, T, alpha).

  • student and teacher are lists of score lists, one per example.
  • labels holds each example's correct class index.

Average the soft part over the batch, and average the hard part over the batch. Return a tuple (soft, hard, loss): the average soft part, the average hard part, and their blend. Round each to 4 decimal places, only at the end: blend the unrounded averages.

Examples

student = [[2.0, 1.0, -1.0]]
teacher = [[3.0, 2.0, -2.0]]
labels = [0]
T = 1.0
alpha = 0.5
returns (0.021, 0.349, 0.185)
student = [[2.0, 1.0, -1.0]]
teacher = [[3.0, 2.0, -2.0]]
labels = [0]
T = 4.0
alpha = 0.8
returns (0.2689, 0.349, 0.285)

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run