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 NoneInspect 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