REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Distill a detached teacher with temperature scaling

Soft teacher distributions contain relative class information that hard labels discard.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Distill a detached teacher with temperature scaling →

Your task

Compute (1-alpha)*cross_entropy(student,labels) + alpha*T*T*KL(softmax(teacher.detach()/T) || softmax(student/T)). Use KL batchmean, not an elementwise mean. Inputs are finite aligned [N,C] tensors, integer labels [N], C>=2, T>0 and alpha in [0,1]. Return a differentiable scalar. Teacher logits must receive no gradient.

Starter

import torch


def distillation_loss(student, teacher, labels, temperature, alpha):
    return None
Inspect the worked answer
import math
import torch
from torch.nn import functional as F


def distillation_loss(student, teacher, labels, temperature, alpha):
    if not math.isfinite(temperature) or temperature <= 0 or not math.isfinite(alpha) or not 0 <= alpha <= 1:
        raise ValueError('positive temperature and mixture in 0..1 required')
    if student.ndim != 2 or student.shape != teacher.shape or student.shape[0] == 0 or student.shape[1] < 2:
        raise ValueError('aligned nonempty multiclass logits required')
    if labels.shape != student.shape[:1] or labels.dtype != torch.long:
        raise ValueError('one integer target per observation required')
    if not bool(torch.isfinite(student).all()) or not bool(torch.isfinite(teacher).all()):
        raise ValueError('finite logits required')
    hard = F.cross_entropy(student, labels)
    target = F.softmax(teacher.detach() / temperature, dim=-1)
    soft = F.kl_div(F.log_softmax(student / temperature, dim=-1), target, reduction='batchmean')
    return (1 - alpha) * hard + alpha * temperature ** 2 * soft

About this algorithm

How Distill a detached teacher with temperature scaling works

The idea

Knowledge distillation trains a small student network to imitate a large teacher. A hard label says only which class is right. The teacher's full output also says how likely it finds each wrong class, which tells the student which classes resemble each other.

Dividing logits by a temperature above 1 flattens both distributions so those small probabilities carry weight. The soft loss is the KL divergence from the teacher's softened distribution to the student's, multiplied by temperature ** 2 to keep its gradients on the same scale as the hard loss. alpha blends it with ordinary cross entropy on the labels. The teacher is detached, so only the student learns.

How it works

  1. Check that both logits are finite, aligned [N, C] tensors, that temperature > 0 and that alpha is in 0..1.
  2. Compute the hard loss with F.cross_entropy(student, labels).
  3. Build the soft target as the softmax of teacher.detach() / temperature.
  4. Take the log-softmax of student / temperature and its KL divergence from the target with reduction='batchmean'.
  5. Return (1 - alpha) * hard + alpha * temperature ** 2 * soft, a scalar that backpropagates into the student only.

What it costs

Per batch
O(N·C)
Memory
O(N·C)
Scales with
batch N, classes C

Each softmax and the KL sum read every one of the N by C logits once, and in real training the costly part is the extra teacher forward pass, which happens outside this function.

Where it is used

  • DistilBERT was distilled from BERT and is 40% smaller and 60% faster while keeping about 97% of its language understanding scores.
  • Hinton, Vinyals and Dean introduced this temperature recipe in 2015 to compress an ensemble of speech recognition models into one network.
  • MobileBERT was trained from a larger BERT-style teacher so that the model fits on phones.

Watch out for

  • Forgetting teacher.detach(): gradients flow back into the teacher's graph, which wastes memory and can change the teacher.
  • Using reduction='mean' in F.kl_div: it divides by N times C instead of N, so the soft term comes out C times too small.
  • Passing probabilities as the first argument of F.kl_div: it expects the student's log-probabilities and the teacher's plain probabilities.