Module contents
Lesson 27 of 28Core 105 min

Knowledge distillation I: temperature, dark knowledge and compact students

Transfer a teacher's softened probabilities to a compact student. Derive the temperature loss and its high-temperature limit, study intermediate features and capacity gaps, and compare distillation with supervised baselines in NumPy and a local CNN experiment.

After this lesson you can

  • Derive the temperature-distillation loss gradient and justify the T² factor.
  • Show that high-temperature distillation approaches centered-logit matching.
  • Implement output and intermediate-feature distillation and compare with a well-trained baseline.
  • Explain dark knowledge and its relation to label smoothing.
  • Design a fair distillation protocol with temperature and mixture sweeps and multiple seeds.

Before you start

Learning from a distribution

Knowledge distillation trains a student to reproduce part of a teacher’s behavior. A label indicates the observed class; the teacher’s distribution also assigns probabilities to alternatives. A compact student can learn from those probabilities without running the teacher at deployment. Hinton, Vinyals and Dean present transfer from a model or ensemble to a simpler model.

InteractiveTemperature of a real teacher

ResNet20 teacher: test image 0, cat label; the first image whose top result is cat and second is dog was selected.

airplane3.3 %
car3.3 %
bird3.9 %
cat67.7 %
deer3.3 %
dog5.7 %
frog3.4 %
horse3.4 %
ship2.6 %
truck3.4 %

Gradient norm: blue unscaled; orange with T². Discrete temperatures are evenly spaced.

12485.40

The shown gradient is with respect to student logits, with unscaled KL and with T², for this single example. It is not a training curve.

3
Temperature8
KL gradient norm0.0760
Norm with T²4.8671
ResNet20 probabilities for a CIFAR-10 image and gradient norm of a uniform student.

Probabilities come from Chen’s ResNet20, checkpoint cifar10_resnet20-4118986f.pt (SHA-256 4118986f0df73003d572b0e397f0ac7b3f60af1f31aff3d2da164536e36f6ec8), with the lab’s normalization. The image is the first among the first 1000 test images labeled cat for which the teacher ranks cat first and dog second. This illustrative selection does not represent the frequency of that pattern.

The teacher remains fixed during distillation in this lesson. Let v∈RKv\in\R^K be its logit vector, z∈RKz\in\R^K the student’s, pT=softmax⁡(v/T)p_T=\operatorname{softmax}(v/T) and qT=softmax⁡(z/T)q_T=\operatorname{softmax}(z/T). For temperature T>0T>0 and mixture α∈[0,1]\alpha\in[0,1], a common loss is

L=(1−α)CE⁡(y,q1)+αT2KL⁡(pT∥qT).L=(1-\alpha)\operatorname{CE}(y,q_1)+\alpha T^2\operatorname{KL}(p_T\|q_T).

Label yy is used at temperature one and KL has the teacher as its first argument. Reversing KL changes loss and gradient. Since the teacher is fixed, replacing KL with cross-entropy CE⁡(pT,qT)\operatorname{CE}(p_T,q_T) changes the loss by a constant with respect to the student, not its gradient.

What a prediction transfers

A hard cat label produces the same target for every image with that label. The teacher may instead assign different proportions to dog, bird or car depending on each image’s content. Those differences add many constraints to each update: they indicate not only which class should rise but which should remain relatively close or far apart. The information is still a prediction, not a second human annotation. If an image contains a dog and is mistakenly labeled cat, the teacher might correct or reproduce the error; both cases need independent review.

Compressing an ensemble’s function into a smaller model was already studied in Model Compression. A teacher may be one network, an ensemble or a more expensive model. An ensemble’s outputs can be combined in several ways: averaging probabilities and logits are not equivalent because softmax is nonlinear. The NumPy lab explicitly averages logits. With equal resources, an ensemble can supply targets different from its members’, but training and querying costs must be counted. An inference advantage appears only when deploying the student alone and measuring it on the relevant hardware and batch.

Label loss anchors the student to the supervised task, while KL moves it toward the teacher. With α=0\alpha=0 this recovers hard-label training; with α=1\alpha=1 the label’s direct contribution disappears. If the teacher makes systematic errors, increasing α\alpha can reinforce them. Values of α\alpha are also not comparable between implementations that sum instead of averaging across batch or classes: the effective scale of each term changes. Print both losses and their gradient norms before interpreting a mixture.

Temperature and gradient

Distillation temperature divides logits before softmax. As TT increases, the distribution approaches uniform; differences among less likely alternatives become more visible. It does not alter the true label or guarantee better calibration: distillation temperature is chosen to transfer signals, while calibration temperature is tuned for another objective.

Proof

The derivative of log⁡qT,j\log q_{T,j} with respect to ziz_i is (1i=j−qT,i)/T(\mathbf 1_{i=j}-q_{T,i})/T. In KL only the term −∑jpT,jlog⁡qT,j-\sum_jp_{T,j}\log q_{T,j} depends on zz. Summing and using ∑jpT,j=1\sum_jp_{T,j}=1 gives (qT,i−pT,i)/T(q_{T,i}-p_{T,i})/T. Multiplying KL by T2T^2 multiplies that gradient by T2T^2; it does not change the minimum of that loss in isolation.

∎

For fixed logits and high temperatures, qT−pTq_T-p_T is typically order 1/T1/T, so the uncorrected gradient is order 1/T21/T^2. The T2T^2 factor maintains a comparable scale in that limit. In the figure teacher logits are large and the corrected norm still changes between T = 1 and T = 8: stability is an asymptotic property, not a promise for those four points. It does not guarantee identical magnitude for every temperature or remove the need to tune α\alpha, optimizer and learning rate. If logits depend on TT or the distribution has other transformations, revisit the scale.

Dark knowledge and uniform smoothing

Dark knowledge is the structure of probabilities the teacher assigns to classes not chosen as the main answer. For a particular image it may regard a visually similar class as more plausible than a very different one. This signal is conditioned on input and teacher; a small probability is not automatically reliable knowledge.

InteractiveMean probabilities by class

Rows: true label. Columns: target class. Each row sums to one; for the teacher these are means, not an accuracy matrix.

aircarbircatdeedogfrohorshitru
airplane82133111151
car19000000015
bird20832244110
cat104783102101
deer10228931100
dog10282851200
frog11241188000
horse10122209101
ship41000010931
truck14010001389

Values in percent. For the teacher rows contain between 86 and 112 images; the pattern reflects this sample. One-hot and smoothed targets are image-independent; smoothing mixes 90% label and 10% uniform.

1
0
Targetteacher
Teacher temperature2
Test images1000
Teacher accuracy, T = 192.5 %
Compare ResNet20 averages on the first 1000 CIFAR-10 test images with one-hot and uniform smoothing.

Label smoothing distributes a fixed portion of mass among classes, usually uniformly. It is equivalent to mixing the hard label with a uniform target, but does not reproduce image-dependent relationships a teacher can encode. Müller and colleagues observed that a teacher trained with strong smoothing could transfer less information in their experiments; this does not show that every use of smoothing harms all distillation.

A map averaging probabilities by true class summarizes dataset trends and hides per-image variation. Its diagonal often dominates because the teacher recognizes many inputs; also examine mass among incorrect classes and the teacher’s own errors. The matrix depends on dataset, temperature and preprocessing protocol; it is not a causal similarity matrix.

Reading the matrix carefully

For a row labeled cat, the dog cell is average dog probability on images whose true label is cat. It does not mean all cats resemble all dogs or that the teacher is correct at the same rate: mean probability and argmax frequency measure different things. Temperature changes each example’s distribution before averaging; applying softmax to average logits would yield another result. Rows contain different numbers of images, so their uncertainty differs too.

If the student already has correct labels, additional information about incorrect classes can act as regularization. However, the teacher can also have acquisition biases, subgroup errors or excessive out-of-distribution confidence. Detect these by comparing by class and relevant subgroup, not only the overall average. Uniform smoothing is a cheap baseline for asking whether teacher-specific information improves results or avoiding overly concentrated targets suffices.

The high-temperature limit

The logit-matching limit is obtained after removing their common component. Define z~i=zi−zˉ\tilde z_i=z_i-\bar z and v~i=vi−vˉ\tilde v_i=v_i-\bar v. Softmax does not change when a constant is added to all logits; thus matching uncentered logits introduces a constraint that probability distillation does not impose.

Proof

Expanding the exponential gives qT,i=1/K+z~i/(KT)+O(T−2)q_{T,i}=1/K+\tilde z_i/(KT)+O(T^{-2}) and an analogous expression for pTp_T. Near the uniform distribution, the second-order KL expansion is K2∑i(pT,i−qT,i)2+O(T−3)\tfrac K2\sum_i(p_{T,i}-q_{T,i})^2+O(T^{-3}). Substituting first-order differences and multiplying by T2T^2 gives the result. The expansion requires finite logits and a fixed number of classes; the error vanishes in the limit.

∎

The corresponding derivative is approximately (z~i−v~i)/(KT2)(\tilde z_i-\tilde v_i)/(KT^2) before multiplying by T2T^2. This limit connects with learning logits studied by Ba and Caruana. At finite temperature the distributions are not necessarily close to uniform and equivalence is only approximate.

Features, assistants and self-distillation

Feature distillation adds a loss on intermediate representations. If the student produces hsh_s and teacher hth_t, a learnable projection PP can align dimensions and use ∥Phs−ht∥2\|Ph_s-h_t\|^2. Choose layers with compatible resolution and meaning, decide normalization and balance this loss against output loss. FitNets studies intermediate-layer hints; other methods transfer attention maps or additional targets. DistilBERT combines pretraining and distillation signals; it is not simply a small CNN with KL.

TinyBERT transfers Transformer signals in both pretraining and a task-specific stage. Matching layers, attention and representations requires different choices from this lab’s CNN projection. Copying a loss coefficient between architectures is insufficient.

A teacher may also have privileged information during training that the student will not have at deployment, such as expensive data available only offline. Generalized distillation studies that relationship. The student does not magically receive the variable in production: it learns only an approximation to what its own inputs allow it to predict. Averaging several teachers can reduce some target variation when their errors are not perfectly correlated, but may also retain shared biases. Variance reduction is a procedure-dependent hypothesis, not a guarantee for all distillation.

For example, for a fixed prediction coordinate, if MM teachers have variance σ2\sigma^2 and common correlation ρ\rho, their average has variance

Var⁡ ⁣(1M∑j=1Mfj)=σ2M+M−1Mρσ2.\operatorname{Var}\!\left(\frac1M\sum_{j=1}^{M}f_j\right)=\frac{\sigma^2}{M}+\frac{M-1}{M}\rho\sigma^2.

This follows by summing MM variances and M(M−1)M(M-1) covariances and dividing by M2M^2. When ρ=0\rho=0 it becomes σ2/M\sigma^2/M; if ρ\rho is positive the correlated term persists. This calculation concerns random predictions under specific assumptions and does not directly measure the trained student’s variance or correct shared bias.

Self-distillation uses a teacher related to the student, such as another previously trained instance of the same architecture. Born Again Networks shows improvements in some settings even without a larger teacher. The soft signal can regularize or reduce variation in certain problems, but the direction and magnitude of improvement are empirical. A mistaken teacher can also transmit its errors.

The capacity gap arises when the student cannot approximate a complex distribution well. Teacher Assistant KD studies introducing an intermediate model in some scenarios. It is not a law that a larger teacher is always worse: a different architecture, recipe, task or duration can change the result.

InteractiveA capacity comparison

Direct and assistant student accuracy, three seeds per point.

481632640.71.0

Blue: direct; orange: assistant. Synthetic data with 256 test examples. Width does not guarantee a better teacher and these results do not establish a general rule.

2
Teacher width16
Individual teachers, mean0.803
Direct student, mean0.786
Student with assistant, mean0.781
Explore a measured synthetic experiment with direct and assistant-based students; each point summarizes three student seeds.

The figure comes from a synthetic four-class problem with 256 training and 256 test examples. Each teacher is an average of logits from three equally wide MLPs; the assistant has width 8, the student width 5, with T=2T=2 and α=0.5\alpha=0.5. Teachers trained for 400 steps with seeds 100, 101 and 102; assistant and students for 300 steps with seeds 222 and 1, 2, 3 respectively. The lab below uses fewer steps to run quickly, so it does not reproduce the figure exactly without adjusting that budget. Means of three student initializations are shown without confidence intervals and on one dataset. Teachers do not improve monotonically with width and the figure does not show that an assistant generally helps.

Compatible hints and limits

A teacher convolutional layer may produce a larger and wider spatial tensor than the student’s. A 1×1 projection adjusts channels but does not guarantee positions represent the same thing; changing resolution and choosing comparable layers may also be necessary. The lab simplifies the problem with spatial averaging and a linear projection from 32 to 64 components. Normalizing each vector before squared error makes the hint focus on direction; this discards norm information and changes the objective relative to unnormalized error.

Hint weight is expressed on the chosen error’s scale. A mean over 64 coordinates and a sum produce different magnitudes; copying the same numerical coefficient between them does not preserve balance. A useful diagnostic is to record each term separately and check the projection receives a gradient. Accidentally unfreezing the teacher during training also changes the target, so the experiment no longer has a fixed teacher. eval() fixes batch normalization and dropout behavior, while no_grad() avoids building its graph; the two operations serve different roles.

An assistant adds another stage and cost, as well as another error source. The hypothesis is that a sequence of targets can ease approximation when the gap is large, but an extra stage can lose information or overfit. In the figure assistant width is 8: when teacher width is 4 it is not an intermediate capacity step. That point therefore compares two paths, not a demonstration of a strict hierarchy. Means over three initializations also cannot establish a full distribution of results.

A fair protocol

Compare a well-tuned undistilled student with the same student, data, architecture, budget and augmentations. If teacher and student receive different views of an augmented image, the teacher’s distribution may describe content the student does not see. A consistent recipe uses the same view for both; Beyer and colleagues examine duration and consistency as important choices. Not every augmentation and task combination must follow the same recipe without evaluation.

Separate training, validation for choosing TT, α\alpha and hint weights, and test for final evaluation. Repeat seeds and report dispersion and teacher, storage, training and deployment costs. Measure accuracy against labels and fidelity to the teacher separately: a student can disagree with its teacher and still get more test labels right. If test is used to select the recipe, the result is no longer an independent estimate.

Costs and selection

A fair comparison begins by fixing the resource of interest: parameters, memory, latency, energy or training cost. A student with fewer parameters may be slower if its operations do not exploit the device; measuring one isolated pass does not necessarily characterize a service with variable batches. The teacher has initial training and target-generation costs; storing all logits saves repeated queries but takes space and can prevent applying consistent new random views. The two storage exercises quantify this tradeoff and show that saving only the top ten classes discards part of the distribution.

Select hyperparameters on validation equivalently for baseline and KD. For example, a sweep of three temperatures and three mixtures consumes nine trials per seed, while one weak baseline trial cannot attribute a difference to teacher signal. After choosing the recipe, run predefined seeds and present individual results or mean and dispersion. Hold test until the end; if selection is repeated after viewing test, describe that adaptation and obtain another independent evaluation before a general claim.

Fidelity can be measured as argmax agreement or divergence between distributions, stating temperature and dataset. Stanton and colleagues observed discrepancies between student and teacher distributions even where the student had capacity to match it; that observation calls for measuring fidelity, not assuming it. Accuracy uses labels. These are different questions: if the teacher predicts dog for a cat and the student predicts cat, the student is correct but loses agreement. Sensitive applications also require attention to rare classes and specific errors, which averages can hide. Higher fidelity does not demonstrate better safety, calibration or robustness.

NumPy lab

The experiment uses a synthetic four-class dataset with 256 training and 256 test examples; some training labels are randomly replaced. Three MLPs form a teacher by averaging logits. The gradient is checked with finite differences, temperatures and mixtures are swept over three student seeds, and a feature projection from the first teacher is tested. These are small samples and budgets, useful for checking the procedure, not evidence of general improvement.

[ ]Gradient, temperature and compact studentBrowser
import numpy as np
rng=np.random.default_rng(27)
def softmax(z,T=1.):
    s=z/T; s=s-s.max(axis=-1,keepdims=True);p=np.exp(s);return p/p.sum(axis=-1,keepdims=True)
def logsoftmax(z,T=1.):
    s=z/T; s=s-s.max(axis=-1,keepdims=True);return s-np.log(np.exp(s).sum(axis=-1,keepdims=True))
def kd_loss(z,v,labels,T,alpha):
    n,k=z.shape;lp=logsoftmax(v,T);lq=logsoftmax(z,T);lhard=logsoftmax(z);p=np.exp(lp);q=np.exp(lq);hard=np.exp(lhard)
    loss=(1-alpha)*(-lhard[np.arange(n),labels].mean())+alpha*T*T*np.sum(p*(lp-lq))/n
    grad=(1-alpha)*hard+alpha*T*(q-p)
    grad[np.arange(n),labels]-=(1-alpha)
    return loss,grad/n
z=rng.normal(size=(4,4));v=rng.normal(size=(4,4));labels=np.array([0,1,2,3]);loss,g=kd_loss(z,v,labels,3.,.7)
eps=1e-5;numeric=np.zeros_like(z)
for i in range(4):
    for j in range(4):
        perturb=np.zeros_like(z);perturb[i,j]=eps
        numeric[i,j]=(kd_loss(z+perturb,v,labels,3.,.7)[0]-kd_loss(z-perturb,v,labels,3.,.7)[0])/(2*eps)
print('diferencia gradiente finito:',np.max(np.abs(numeric-g)))
assert np.allclose(numeric,g,atol=1e-8)
for T in (1.,2.,4.,16.,128.):
    plain=(softmax(z,T)-softmax(v,T))/T
    centered=(z-z.mean(axis=1,keepdims=True))-(v-v.mean(axis=1,keepdims=True))
    approx=centered/(z.shape[1]*T*T)
    print('T',T,'norma sin y con T²',round(np.linalg.norm(plain),7),round(np.linalg.norm(T*T*plain),7),
          'diferencia límite escalada',round(np.linalg.norm(T*T*(plain-approx)),7))

# Problema sintético: clases producidas por una regla no lineal, etiquetas de entrenamiento con ruido.
X=rng.normal(size=(512,6));oracle1=rng.normal(size=(6,12));oracle2=rng.normal(size=(12,4))
y=np.argmax(np.tanh(X@oracle1)@oracle2,axis=1);xt,xe=X[:256],X[256:];yt,ye=y[:256].copy(),y[256:]
noise=rng.random(len(yt))<.12;yt[noise]=rng.integers(0,4,size=noise.sum())
def init(seed,width):
    r=np.random.default_rng(seed)
    return [r.normal(size=(6,width))*.3,np.zeros(width),r.normal(size=(width,4))*.3,np.zeros(4)]
def forward(params,x):
    h=np.tanh(x@params[0]+params[1]);return h,h@params[2]+params[3]
def fit(seed,width,steps,teacher_logits=None,T=2.,alpha=0.,teacher_features=None):
    p=init(seed,width);r=np.random.default_rng(seed+1000)
    P=r.normal(size=(width,16))*.05 if teacher_features is not None else None
    for step in range(steps):
        h,z=forward(p,xt)
        v=z if teacher_logits is None else teacher_logits
        _,gz=kd_loss(z,v,yt,T,alpha)
        g2=h.T@gz;gb2=gz.sum(axis=0);gh=gz@p[2].T
        if P is not None:
            difference=h@P-teacher_features
            gp=h.T@(2*difference/difference.size)
            gh+=.2*(2*difference/difference.size)@P.T
        pre=gh*(1-h*h);g1=xt.T@pre;gb1=pre.sum(axis=0)
        for param,grad in zip(p,(g1,gb1,g2,gb2)):param-=.25*grad
        if P is not None:P-=.25*.2*gp
    return p
def accuracy(p):return float(np.mean(forward(p,xe)[1].argmax(axis=1)==ye))
teachers=[fit(100+i,16,300) for i in range(3)]
teacher_features=forward(teachers[0],xt)[0]
teacher_logits=np.mean([forward(p,xt)[1] for p in teachers],axis=0)
print('maestros accuracy test:',[round(accuracy(p),3) for p in teachers])
# Con alpha cero la temperatura no afecta a la CE dura; reutiliza la misma línea base.
baseline=[accuracy(fit(seed,5,200,teacher_logits,1.,0.)) for seed in (1,2,3)]
for T in (1.,2.,4.):
    for alpha in (0.,.5,1.):
        results=baseline if alpha==0. else [accuracy(fit(seed,5,200,teacher_logits,T,alpha)) for seed in (1,2,3)]
        print('T',T,'alpha',alpha,'accuracy por semilla',np.round(results,3),'media',round(np.mean(results),3))
hint=[accuracy(fit(seed,5,200,teacher_logits,2.,.5,teacher_features)) for seed in (1,2,3)]
print('con proyección de características y KD, tres semillas:',np.round(hint,3))

Local vision lab

The following cell reproduces a local CIFAR-10 trial. It downloads the official dataset and published weights if uncached; it needs PyTorch and torchvision. The teacher has 272,474 parameters and the student 16,938 including the hint projection. Random crop and flip are shared by teacher and student, and architecture, initialization by seed and budget are the same for hard, kd and hint. patient doubles epochs and therefore costs more: it is not an equal-budget comparison. Accuracy per seed is shown on 1000 validation and 512 test images, using the first 2048 student-training images; the pretrained teacher saw all CIFAR-10 training data, including that validation. Test evaluation is separate, though small. The pilot and figure use part of test; if you change the recipe after seeing them, reserve another unseen section for independent evaluation.

In an RTX 3060 run, training was extended to 30 epochs per recipe, and 60 for patient, with cosine decay. A total of 2048 images were retained for training and 1000 to choose the epoch; test was shifted to indices 1512 through 2023 to avoid reusing the first 1512 images already examined in pilots and figures. Each series shows seeds 0, 1 and 2 in that order. The teacher achieved 0.922 accuracy on that section. Values are fractions, not percentages.

  • Labels (30 epochs): best epoch 26 / 29 / 30; validation 0.542 / 0.553 / 0.555; test 0.527 / 0.533 / 0.553; agreement 0.531 / 0.535 / 0.551.
  • KD (30 epochs): best epoch 28 / 30 / 29; validation 0.568 / 0.577 / 0.552; test 0.541 / 0.551 / 0.545; agreement 0.541 / 0.547 / 0.539.
  • KD with hints (30 epochs): best epoch 30 / 27 / 25; validation 0.557 / 0.550 / 0.565; test 0.549 / 0.561 / 0.529; agreement 0.549 / 0.549 / 0.531.
  • Patient (60 epochs): best epoch 54 / 53 / 58; validation 0.598 / 0.618 / 0.597; test 0.598 / 0.598 / 0.611; agreement 0.602 / 0.598 / 0.607.

The 30-epoch comparison holds architecture, views and budget fixed but is not an exhaustive hyperparameter sweep. The patient variant uses twice as many epochs and another learning-rate schedule; its difference does not by itself identify the cause. Several curves still improve near the end, so convergence or generalization to all CIFAR-10 is not assured. The test sample has 512 images, the teacher saw the full training set and results may vary with device. To reproduce this setup, set KD_EPOCHS=30 and KD_TEST_START=1512 before running the cell; patient automatically doubles duration.

Choose each run’s best epoch by validation before test evaluation; validation curves are retained to check whether training is still progressing. Test reports accuracy against labels and argmax agreement with the teacher separately. Comparing one recipe’s final model with another’s best would introduce asymmetry.

By default this is a three-epoch pilot, not a well-tuned baseline; cosine learning-rate decay adapts to each variant’s duration. For a conclusive comparison, increase KD_TRAIN_LIMIT and KD_EPOCHS, reserve validation to tune all recipes and evaluate once on full test; also report compute costs. CIFAR_ROOT, TEACHER_PATH and CIFAR_LOCAL_ONLY=1 allow already downloaded files to be used. KD_TEST_START shifts the test section without changing training or validation. Normalization follows the author’s CIFAR recipe; the teacher remains in evaluation mode and without gradients. The hint matches normalized global vectors using a learned projection: it is a FitNets-inspired variant, not a reproduction of its architecture or recipe.

[ ]CNN student with labels, KD and hintsLocal GPU
import os, time, json, random
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms

# Arquitectura compatible con los pesos publicados por chenyaofo/pytorch-cifar-models.
class Block(nn.Module):
    def __init__(self, inp, out, stride=1):
        super().__init__()
        self.conv1 = nn.Conv2d(inp, out, 3, stride, 1, bias=False)
        self.bn1 = nn.BatchNorm2d(out)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(out, out, 3, 1, 1, bias=False)
        self.bn2 = nn.BatchNorm2d(out)
        self.downsample = (nn.Sequential(nn.Conv2d(inp, out, 1, stride, bias=False),
                                         nn.BatchNorm2d(out)) if stride != 1 or inp != out else None)
    def forward(self, x):
        skip = x if self.downsample is None else self.downsample(x)
        return self.relu(self.bn2(self.conv2(self.relu(self.bn1(self.conv1(x))))) + skip)

class Teacher(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 16, 3, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(16)
        self.relu = nn.ReLU(inplace=True)
        self.layer1 = nn.Sequential(Block(16,16), Block(16,16), Block(16,16))
        self.layer2 = nn.Sequential(Block(16,32,2), Block(32,32), Block(32,32))
        self.layer3 = nn.Sequential(Block(32,64,2), Block(64,64), Block(64,64))
        self.avgpool = nn.AdaptiveAvgPool2d((1,1))
        self.fc = nn.Linear(64,10)
    def forward(self, x):
        x = self.relu(self.bn1(self.conv1(x)))
        x = self.layer3(self.layer2(self.layer1(x)))
        features = self.avgpool(x).flatten(1)
        return self.fc(features), features

class Student(nn.Module):
    def __init__(self):
        super().__init__()
        self.body = nn.Sequential(nn.Conv2d(3,16,3,padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(2),
                                  nn.Conv2d(16,32,3,padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2),
                                  nn.Conv2d(32,32,3,padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.AdaptiveAvgPool2d(1))
        self.fc = nn.Linear(32,10)
        self.hint = nn.Linear(32,64)
    def forward(self, x):
        h = self.body(x).flatten(1)
        return self.fc(h), h

URL = 'https://github.com/chenyaofo/pytorch-cifar-models/releases/download/resnet/cifar10_resnet20-4118986f.pt'
ROOT = os.environ.get('CIFAR_ROOT', './data/cifar10')
PATH = os.environ.get('TEACHER_PATH')
LIMIT = int(os.environ.get('KD_TRAIN_LIMIT', '2048'))
EVAL = int(os.environ.get('KD_EVAL_LIMIT', '512'))
TEST_START = int(os.environ.get('KD_TEST_START', '0'))
EPOCHS = int(os.environ.get('KD_EPOCHS', '3'))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
MEAN = (0.4914, 0.4822, 0.4465)
STD = (0.2023, 0.1994, 0.2010)
assert 0 < LIMIT <= 49000 and 0 < EVAL and 0 <= TEST_START and TEST_START + EVAL <= 10000 and EPOCHS > 0
random.seed(19); np.random.seed(19); torch.manual_seed(19)
torch.set_num_threads(4)
normal = transforms.Compose([transforms.ToTensor(), transforms.Normalize(MEAN, STD)])
augmented = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(),
                                transforms.ToTensor(), transforms.Normalize(MEAN, STD)])
train_data = datasets.CIFAR10(ROOT, train=True, transform=augmented, download=not bool(os.environ.get('CIFAR_LOCAL_ONLY')))
val_data = datasets.CIFAR10(ROOT, train=True, transform=normal, download=False)
test_data = datasets.CIFAR10(ROOT, train=False, transform=normal, download=False)
train = Subset(train_data, range(LIMIT))
val = Subset(val_data, range(49000,50000))
test = Subset(test_data, range(TEST_START, TEST_START + EVAL))
val_loader = DataLoader(val, batch_size=128, shuffle=False)
test_loader = DataLoader(test, batch_size=128, shuffle=False)
teacher = Teacher().to(DEVICE)
state = torch.load(PATH, map_location='cpu', weights_only=True) if PATH else torch.hub.load_state_dict_from_url(URL, map_location='cpu', check_hash=True)
teacher.load_state_dict(state, strict=True)
teacher.eval()
for p in teacher.parameters(): p.requires_grad_(False)

def accuracy(model, loader):
    correct = total = 0
    model.eval()
    with torch.no_grad():
        for x,y in loader:
            logits,_ = model(x.to(DEVICE))
            correct += (logits.argmax(1).cpu() == y).sum().item(); total += len(y)
    return correct / total

def evaluate_student(model, loader):
    model.eval(); correct = agreement = total = 0
    with torch.no_grad():
        for x,y in loader:
            x = x.to(DEVICE)
            pred = model(x)[0].argmax(1).cpu()
            teacher_pred = teacher(x)[0].argmax(1).cpu()
            correct += (pred == y).sum().item()
            agreement += (pred == teacher_pred).sum().item()
            total += len(y)
    return correct/total, agreement/total

print('device', DEVICE, 'teacher test', accuracy(teacher, test_loader), flush=True)
print('parameters teacher/student', sum(p.numel() for p in teacher.parameters()), sum(p.numel() for p in Student().parameters()), flush=True)
results = {}
for mode in ['hard', 'kd', 'hint', 'patient']:
    rows = []
    for seed in [0, 1, 2]:
        random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
        student = Student().to(DEVICE)
        opt = torch.optim.SGD(student.parameters(), lr=0.05, momentum=0.9, weight_decay=5e-4)
        epochs = EPOCHS * (2 if mode == 'patient' else 1)
        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
        generator = torch.Generator().manual_seed(seed)
        loader = DataLoader(train, batch_size=64, shuffle=True, generator=generator, num_workers=0)
        start = time.perf_counter()
        best_val, best_epoch, best_state = -1., 0, None
        val_history = []
        for epoch in range(epochs):
            student.train()
            for x,y in loader:
                x,y = x.to(DEVICE),y.to(DEVICE)
                z,h = student(x)
                loss = F.cross_entropy(z,y)
                if mode != 'hard':
                    with torch.no_grad(): v, target = teacher(x)
                    T = 4.0
                    kl = F.kl_div(F.log_softmax(z/T,dim=1), F.softmax(v/T,dim=1), reduction='batchmean') * T*T
                    loss = 0.5*loss + 0.5*kl
                    if mode == 'hint':
                        loss = loss + F.mse_loss(F.normalize(student.hint(h),dim=1), F.normalize(target,dim=1))
                opt.zero_grad(); loss.backward(); opt.step()
            val_acc = accuracy(student, val_loader)
            val_history.append(val_acc)
            if val_acc > best_val:
                best_val, best_epoch = val_acc, epoch+1
                best_state = {k: v.detach().cpu().clone() for k,v in student.state_dict().items()}
            scheduler.step()
        student.load_state_dict(best_state)
        test_acc, fidelity = evaluate_student(student, test_loader)
        row = {'seed':seed,'epochs':epochs,'best_epoch':best_epoch,'val':best_val,'val_history':val_history,'test':test_acc,'agreement':fidelity,'seconds':round(time.perf_counter()-start,1)}
        print(mode, row, flush=True); rows.append(row)
    results[mode] = rows
print('results', json.dumps(results), flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
For logits (5, 2, 1, −1) and T = 1, what is the entropy in nats?
Numeric
For the same logits and T = 4, what is the entropy in nats?
Numeric
One million examples have 1000 FP16 logits each. How many decimal GB do they occupy, excluding metadata?
Numeric
If 10 FP16 logits and 10 uint16 indices are saved per example, how many decimal MB do one million examples occupy, excluding metadata?
Proof
Prove: Derive the KL gradient and its behavior for large T.
0
The teacher is fixed and q = softmax(z/T).

Step 1 of 2. What is the derivative with respect to zᵢ?

Quiz
Which statement best describes when distillation can help?
Code
Implement kd_loss(z, v, labels, T, alpha) returning mean loss and gradient with respect to z, with hard CE and T² KL(teacher || student).
import numpy as np
def kd_loss(z, v, labels, T, alpha):
  pass
Shift+Enter to run
Key idea
Distillation transfers a signal dependent on teacher and input; evaluating its usefulness requires controlling temperature, views, capacity and a strong baseline.