#281Knowledge-Distillation LossMediumML System DesignLoss FunctionsFine TuningAsked atGoogle · Meta · Microsoft
Knowledge-Distillation Loss
Background
Knowledge Distillation (Hinton et al.) trains a small student to match a large teacher's softened logits, plus a small CE term on the hard ground-truth labels. Temperature softens both softmaxes so the student picks up dark knowledge about non-target classes.
Problem statement
Implement kd_loss(student_logits, teacher_logits, labels, T=4.0, alpha=0.9):
where and the factor restores gradient scale.
Input
student_logits—np.ndarrayshape .teacher_logits—np.ndarrayshape .labels— sequence ofint, length , in .T—float > 0, temperature (default4.0).alpha—floatin , KD weight (default0.9).
Output
Returns a Python float >= 0.
Examples
Example 1 — identical logits with alpha=1 → KL=0 → loss=0
Input: student==teacher, alpha=1.0
Output: ≈ 0
Example 2 — alpha=0 reduces to plain cross-entropy on hard labels
Input: perfect student logits (correct class very high), alpha=0
Output: near 0
Example 3 — returns plain Python float
Input: any valid logits, labels
Output: isinstance(result, float)
Constraints
student_logitsandteacher_logitsmust agree in shape.labelslength matches batch dimension.- Use a numerically stable softmax (subtract max before exp).
Notes
- Why . Soft targets shrink gradient magnitude by ; the multiplier brings it back so the KD term doesn't get drowned out by the CE term at high .
- vs DistilBERT-style. Adds a hidden-state MSE term that pushes the student's intermediate representations to match the teacher — out of scope here.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Identical logits alpha=1 example -> zero loss
- •Reference random batch matches formula
- •Sample alpha=0 reduces to cross-entropy