Knowledge Distillation

A hard label says cat 1, dog 0. A teacher says cat 0.971, dog 0.018, car 0.011, and the small gaps hold what it knows. Distillation hands them to a tiny student.

Learn how a big network trains a small one, what the student can be asked to copy, and why a tiny model needs this help.

Pick what the student learns from, then press Train. Watch the dog to car odds. The teacher says 1.65 to 1. Then we build, piece by piece, the temperature, the loss, the six things to match, self and online teachers, the task recipes and network augmentation.

You need a little probability (numbers that add to 1) and a little Python for the code. We build the rest from zero.

Based on Lecture 9 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. The lecture slides are linked from the course page. Every idea is re-taught here in our own words and devices. It follows Lecture 8, Neural Architecture Search II and leads into Lecture 10, MCUNet.

Teach the student

Illustrative: one image, three classes, teacher logits cat 5, dog 1, car 0.5 (cat 5 and dog 1 are the lecture's example). The student is three free logits trained by gradient descent with learning rate 1.2. The probability axis is logarithmic so the small bars stay visible.

Chapter 0

A Tiny Model Cannot Even Fit Its Own Training Data

See the hardware gap that forces models to shrink, and see why a shrunken model needs more than ordinary tricks to train

You have a camera that must tell a cat from a dog. Its chip has 256 kB of memory. A model that does this well in a data center does not come close to fitting.

Slides 3 and 4Cloud AI (NVIDIA B300)Tiny AI
Computation, 32-bit75 TFLOPS (trillion operations per second)MFLOPs (millions)
Memory288 GB256 kB
Example networksResNet, ViT-LargeMCUNet, MobileNetV2-Tiny

Divide the memory: 288 GB over 256 kB is about 1.1 million. ResNet50 costs 4.1G MACs per image (a MAC is one multiply and one add). MobileNetV2-Tiny costs 23.5M MACs, about 175 times fewer.

Tiny models underfit

The usual worry is overfitting: high accuracy on training data, low accuracy on new data. Slide 5 shows the opposite problem. A tiny model underfits: it cannot reach high accuracy even on the data it trains on.

Compare two training runs

Pick a model, then drag the epoch. The blue line is training accuracy. The warm line is validation accuracy, measured on images the model never trained on.

100%

Illustrative curve shapes. End points read from the slide 5 plots and rounded. ResNet50: about 82 train and 77 validation at epoch 100. MobileNetV2-Tiny: about 52 and 48 at epoch 150. The slider shows how far through the plotted window training has run.

ResNet50 ends near 82 percent on training data and 77 on validation. MobileNetV2-Tiny ends near 52 and 48. Both of its lines are low and close together. The data is not too hard. The model is too small to use it.

The failure, and the fix

Symptom: a tiny model scores badly. Measure: compare training accuracy with validation accuracy. If both are low and close, the model underfits. If training is high and validation is low, it overfits.

pythondef diagnose(train_acc, val_acc, low=0.6, gap=0.08):
    # acc values are fractions in [0, 1]
    if train_acc < low and train_acc - val_acc < gap:
        return "underfit: add supervision, not regularization"
    if train_acc - val_acc >= gap:
        return "overfit: regularize or add data"
    return "fine"

The thresholds are our toy values, not the lecture's. The lecture's fix is extra supervision: more signal for each training image than one label gives. Chapters 1 to 8 take it from a big teacher. Chapter 9 takes it from a wider copy of the student.

  1. A teacher and a student: the setup, and why soft answers carry more.
  2. Temperature: a dial that makes small probabilities visible.
  3. The distillation loss: the number the student minimizes, and the T squared factor.
  4. What to match, part one: logits and intermediate layers.
  5. Features and attention: matching what the layers see.
  6. Sparsity and relations: matching on and off patterns and distances between examples.
  7. Self and online distillation: no fixed teacher needed.
  8. Distillation for different tasks: detection, segmentation, GANs, NLP and LLMs.
  9. Network augmentation: the tiny model as a part of a wider one.
  10. The field guide: numbers, code and where to go next.
A tiny model reaches 52 percent on its training data and 48 percent on validation data. What is its main problem?

Chapter 1

A Student Learns From the Teacher's Probabilities

Follow one cat photo through a teacher and a student, and measure how far apart their answers are

A teacher who says only "wrong" teaches less than one who says what was close and what was far off. A network can teach the second way.

The setup

Slide 6 feeds one input to two networks. The teacher is large and already trained. The student is small. The slide draws it as the teacher after pruning, but any pair works.

Each network outputs one raw score for each class, its logits: B × C for a batch of B images and C classes. A distillation loss compares the student's logits with the teacher's. A classification loss compares them with the true label. The teacher is frozen.

The softmax turns logits into probabilities (Chapter 2 writes it out). Teacher logits cat 5 and dog 1 give cat 0.982 and dog 0.018. Student logits cat 3 and dog 2 give 0.731 and 0.269. The student is less confident.

Scoring the gap

Call the teacher's probability for class i pt,i and the student's ps,i. The KL divergence scores the gap between the two lists.

Say it aloud

KL of p-t parallel p-s equals the sum over i of p-t-i times the log of p-t-i over p-s-i.

KL(pt ‖ ps)
KL of p-t parallel p-s the gap from the teacher's answer to the student's. It is 0 for a perfect match and grows as they drift apart.
∑i
the sum over i add one term for each class: here cat and dog.
pt,i
p-t-i the teacher's probability for class i, between 0 and 1.
log
the log of the natural log. It is positive when the teacher gives a class more than the student does.
ps,i
p-s-i the student's probability for class i.
In plain words

For each class, divide p-t-i by p-s-i and take the log. Weight it by p-t-i, so the classes the teacher believes in count most. Add the terms.

With numbers

Slide 7's numbers: cat gives 0.982 × ln(0.982 / 0.731) = 0.290. Dog gives 0.018 × ln(0.018 / 0.269) = −0.049. KL = 0.24. Most of it is the cat term: the student is not sure enough.

Close the gap to the teacher

The teacher is fixed at cat 5, dog 1. Drag the student's two logits. Start from the slide's values, 3 and 2, and try to bring the gap to zero.

3.0
2.0

The teacher's logits (5 and 1) and the student's starting logits (3 and 2) are the lecture's slide 7 example, with two classes. Probabilities are computed live. Only the difference between the two student logits matters to the probabilities, so you can reach a match with many different pairs.

Only the difference between the logits matters. The teacher's is 5 − 1 = 4 and the student's is 3 − 2 = 1. To match, the student must grow its difference to 4.

Why a soft answer carries more

Add car as a third class. The teacher says cat 0.971, dog 0.018, car 0.011: a cat looks more like a dog than a car. Hinton called this dark knowledge. A hard label sets it to zero.

The failure. A hard label pushes dog and car down in proportion to their current probabilities. If they start equal, they stay equal at odds of 1.00 to 1, while the teacher says 1.65 to 1. Fix: add the teacher's probabilities as a second signal, as the hero shows.

pythonimport torch, torch.nn.functional as F
logits_t = torch.tensor([5.0, 1.0])        # teacher: cat, dog
logits_s = torch.tensor([3.0, 2.0])        # student
p_t = F.softmax(logits_t, dim=0)               # [0.982, 0.018]
log_p_s = F.log_softmax(logits_s, dim=0)       # [-0.313, -1.313]
gap = F.kl_div(log_p_s, p_t, reduction="sum")   # KL(p_t || p_s), about 0.24
A teacher gives cat 0.982 and dog 0.018. A student gives cat 0.731 and dog 0.269. What does the distillation loss ask the student to do?

Chapter 2

Temperature Turns Up the Small Probabilities

Divide the logits by T before the softmax, and see how a confident answer opens up

A confident teacher hides its small answers. Its dog probability of 0.018 is too faint to push a student. A dial called temperature turns the faint answers up.

Call the logit of class i zi and the number of classes C. Before the softmax, divide every logit by one number, the temperature T. Slide 10 writes it this way:

Say it aloud

P of z-i and T equals e to the z-i over T, divided by the sum over j of e to the z-j over T.

p(zi, T)
p of z-i and T the probability of class i at temperature T, between 0 and 1.
exp
e to the raise e to a power. It makes every share positive.
zi
z-i the logit of class i: any real number.
T
T the temperature. T = 1 is the ordinary softmax. A larger T smooths the answer, a smaller T sharpens it.
∑j
the sum over j add one term for every class j, from 0 to C − 1, so the probabilities add to 1.
In plain words

Divide each logit z-i by T. Raise e to each result. Divide each by the total over all classes j. The order of the classes never changes. Only the gaps shrink as T grows.

With numbers

Slide 9's logits are cat 5 and dog 1. At T = 10 they become 0.5 and 0.1. Then e gives 1.649 and 1.105, a total of 2.754. So cat is 0.599 and dog is 0.401. At T = 1 the dog had 0.018. It rose from 2 percent to 40 percent.

Dim the lamp

The bars show the teacher's probabilities. The faint line marks each class at T = 1. Drag T up and watch the small classes rise. Add the car class to see three at once.

1.0

Logits cat 5 and dog 1 are the lecture's example. The car logit of 0.5 is an illustrative third class. At T = 10 with two classes the device gives 0.599 and 0.401, the numbers on slide 9.

Two logits 4 apart give shares e4 = 55 times apart. Divide both by 10 and they are 0.4 apart, so the shares are only e0.4 = 1.5 times apart. Drag T below 1 and the cat takes everything. Drag it to 30 and the bars are nearly equal.

Three classes at T = 4

Add car with logit 0.5. At T = 1 the answer is cat 0.971, dog 0.018, car 0.011, and dog and car look the same. At T = 4:

  1. Divide by 4: (1.25, 0.25, 0.125).
  2. Exponentiate: (3.490, 1.284, 1.133).
  3. Sum: 5.907.
  4. Divide: cat 0.591, dog 0.217, car 0.192.

Now the student can see that dog leads car. Cat is still on top. Temperature adds no facts. It turns up the quiet ones.

The failure: too hot or too cold. Symptom: distillation gives no gain. Measure: print the teacher's probabilities at your T. If the top class still holds 0.97 or more, T is too low. If all classes sit within a few percent of each other, T is too high. Many recipes start between 2 and 5.

Teacher and student use the same T in training. The shipped student runs at T = 1.

pythonimport torch.nn.functional as F
def soft(logits, T):          # logits: (B, C)
    return F.softmax(logits / T, dim=-1)   # (B, C), rows sum to 1
The teacher's logits are cat 5 and dog 1. What happens to the dog's probability when T goes from 1 to 10?

Chapter 3

The Distillation Loss Has Two Terms and a T Squared

Write the one number the student minimizes, work it by hand, and see why the soft term needs a factor of T squared

The answer key says "cat". The teacher says "mostly cat, a little dog", and it can be wrong. One loss must let both pull.

Slide 10 states the goal: align the two networks' class probabilities. The Hinton paper adds what the slides leave out: a mixing weight and a factor of T squared.

Call the softened probabilities at temperature T ptT for the teacher and psT for the student. Call the student's logits zs, the true label y, and the weight that splits the trust α.

Say it aloud

L equals alpha times T squared times the KL of p-t-T parallel p-s-T, plus one minus alpha times the cross-entropy of z-s and y.

L
L the one number the student minimizes.
α
alpha the trust in the teacher, from 0 to 1. One minus alpha goes to the label.
T2
T squared a rescaling factor for the soft term. The next section derives it.
KL(ptT ‖ psT)
KL of p-t-T parallel p-s-T the gap between the softened teacher and student answers, as in Chapter 1.
CE(zs, y)
cross-entropy of z-s and y minus the log of the student's probability for the true class y, at T = 1.
In plain words

Soften both answers with T and score their gap with KL. Multiply it by T squared and by alpha. Score the student's ordinary answer against y, weight it by one minus alpha, and add the two.

With numbers

With made-up numbers: teacher logits (3, 1, 0.5), an untrained student at (1, 1, 1), label cat, T = 2, alpha = 0.5. Softened, the teacher says (0.604, 0.222, 0.173) and the student (0.333, 0.333, 0.333), so KL = 0.156. CE = −ln 0.333 = 1.099. L = 0.5 × 4 × 0.156 + 0.5 × 1.099 = 0.862.

Why T squared

The soft term pushes student logit i by (ps,i − pt,i) / T. At a large T, each probability is close to 1/C plus a small part, about zi / (C T) for logits with mean zero. Put that in, and the push on logit i becomes:

push on logit i ≈ (zs,i − zt,i) / (C T2)

The push shrinks like 1 / T2. At T = 4 that is a factor of 16, and the label term drowns out the teacher. Multiplying the soft term by T2 keeps the two terms level as you change T.

Watch the gradient shrink

The student is untrained: all logits are 0. The curves show the size of the soft term's gradient as T grows. Drag T, and turn the T squared factor on and off.

4.0

Illustrative: teacher logits cat 5, dog 1, car 0.5, a student with all logits 0, true label cat. Gradient size is the length of the vector of pushes on the three student logits. The shape of the curves, not the exact values, is the point.

pythonimport torch, torch.nn.functional as F

def kd_loss(zs, zt, y, T=4.0, alpha=0.5):
    # zs, zt: (B, C) logits   y: (B,) class ids
    log_ps = F.log_softmax(zs / T, dim=-1)      # student, softened, log form
    pt     = F.softmax(zt / T, dim=-1)          # teacher, softened
    soft   = F.kl_div(log_ps, pt, reduction="batchmean") * T * T
    hard   = F.cross_entropy(zs, y)                    # label term at T = 1
    return alpha * soft + (1 - alpha) * hard

def step(student, teacher, x, y, opt):
    with torch.no_grad():
        zt = teacher(x)                                # frozen
    loss = kd_loss(student(x), zt, y)
    opt.zero_grad(); loss.backward(); opt.step()
    return loss.item()

The batchmean setting divides by the batch size, which gives the true KL. The default mean divides by B times C and gives a number far too small.

The failure: forgetting T squared. Symptom: raising T makes the soft term useless. Measure: print both gradient norms. Without the factor, the device's soft push falls from 0.78 at T = 1 to 0.08 at T = 4. Fix: multiply by T squared.

You raise T from 1 to 4 and leave the soft term unscaled. What happens to the soft term's gradient, and what fixes it?

Chapter 4

Six Things a Student Can Match, Starting With Outputs and Hints

List what a student can be asked to copy, then compare two ways to score an output match and see how a hint layer is wired

A teacher holds more than its final answer. Slide 12 lists six things to match: output logits, intermediate weights, intermediate features, gradients, sparsity patterns and relational information. Chapters 4 to 6 take them in order.

One, output logits

Slide 13 gives two scores for the logits. Cross-entropy is −pt log ps. L2 is the squared distance ‖pt − ps‖2. They differ when the student is badly wrong.

For cross-entropy, the push on the student's logit is ps − pt. L2 adds a factor ps(1 − ps) from the softmax, and that factor is near 0 when the student is sure and wrong. This derivation is ours, not the slide's.

Compare the two scores

Two classes. Set the teacher's cat probability, then drag the student's. The curves show the size of the push on the student's logit from each score.

0.90
0.02

Illustrative two-class case. The push is the derivative of the score with respect to the student's logit difference. Cross-entropy gives ps minus pt. L2 on the two probabilities gives 2 times (ps minus pt) times 2 ps (1 minus ps).

At teacher 0.90 and student 0.02, cross-entropy pushes with 0.88. L2 pushes with 2 × 0.88 × 2 × 0.02 × 0.98 = 0.07. It stops just where the student needs help.

Two, intermediate weights (hints)

Slides 15 and 16 move the loss to the middle. They add an L2 loss between teacher and student weights, with a linear map to match the sizes. In the FitNets paper the matched values are the outputs of a teacher layer, the hint. The small map is the regressor.

Call the student's middle-layer output Fs, the teacher's hint Ft, and the regressor r.

Say it aloud

L-hint equals the squared norm of r of F-s minus F-t.

Lhint
L-hint the hint loss, added to the other losses.
r(Fs)
r of F-s the student's output, B × 32 × H × W, after the regressor. Here r is a 1 × 1 convolution with 32 × 64 = 2,048 weights. Its output is B × 64 × H × W.
Ft
F-t the teacher's hint output, B × 64 × H × W. It is frozen. The channel counts are our illustration.
‖ … ‖2
the squared norm of square every difference and add them all.
In plain words

Map F-s to the teacher's width with r. Subtract F-t, number by number. Square the differences and add them. The code's mse_loss also divides by the count.

With numbers

With made-up numbers at one position and three channels: r(F-s) = (0.5, 1.0, 2.0) and F-t = (1.0, 1.0, 1.0). The differences are (−0.5, 0, 1.0), so L-hint = 0.25 + 0 + 1.00 = 1.25. The third channel holds most of the gap.

FitNets trains in two stages: the student's lower layers match the hint, then ordinary distillation trains the whole student. Then you drop the regressor, so the shipped student costs nothing extra.

pythonimport torch.nn as nn, torch.nn.functional as F

regressor = nn.Conv2d(32, 64, kernel_size=1)   # student width 32 -> teacher width 64

def hint_loss(f_student, f_teacher):
    # f_student: (B, 32, H, W)   f_teacher: (B, 64, H, W), frozen
    return F.mse_loss(regressor(f_student), f_teacher.detach())

The failure: shapes that do not meet. Symptom: a size-mismatch crash, or silent broadcasting that trains on nonsense. Measure: print both shapes before the loss. Fix: a regressor for the channels, and matching strides or a resize for H × W.

The teacher's hint layer has 64 channels and the student's guided layer has 32. How do you apply an L2 hint loss?

Chapter 5

Match What the Layers See: Feature Maps and Attention

Compare two networks by where their layers look, and measure how far a student's focus has drifted

Two students both write 42, but only one shows the working. Items three and four ask the student network to copy the working.

Three, intermediate features

A feature map is one layer's output for one image: C × H × W, C channels of H by W. Slide 18: teacher and student should have similar feature distributions, not only similar outputs. It minimizes the maximum mean discrepancy (MMD) between feature maps.

MMD describes each activation with a kernel, then compares the group averages. Teacher activations 1 and 3 and student activations 2 and 2 share the mean 2. Squared, they average 5 and 4, so the kernel sees the spread.

Four, gradients: attention maps

Slide 20 defines the attention of a feature map x as ∂L / ∂x, the change in the objective L for a nudge to x. A large value at (i, j) means the network attends there. Strong models agree (slide 21): ResNet34 (73 percent) and ResNet101 (77 percent) have similar maps, Network-in-Network (62 percent) does not.

The practical form sums the squared activations over the channels at each position. Call that map, flattened, Qs for the student and Qt for the teacher.

Say it aloud

L-A-T equals the norm of Q-s over the norm of Q-s, minus Q-t over the norm of Q-t.

LAT
L-A-T the attention transfer loss: 0 for the same map, 2 at most.
Qs
Q-s the student's attention map: for each of the H × W positions, the sum over channels of the squared activation.
Qt
Q-t the teacher's map, at the same H × W. Its channel count can differ.
‖ … ‖
the norm of the length of a vector: the square root of the sum of squares. Dividing by it scales a map to length 1.
In plain words

Collapse each feature map over its channels into Q. Divide each Q by its own length, so only the shape counts. Subtract Q-t from Q-s and take the length of the difference.

With numbers

With made-up maps of two positions: Q-t = (3, 4) has length 5 and becomes (0.6, 0.8). Q-s = (4, 3) becomes (0.8, 0.6). The difference is (0.2, −0.2), so L-A-T = 0.28. The student looks at the right places in the wrong amounts.

No channel axis is left, so a 64-channel teacher layer pairs with a 32-channel student layer and needs no regressor.

Measure the drift of attention

A toy feature map with 4 channels on a 7 by 7 grid. Choose how channels are combined, then slide the student's focus away from the teacher's.

1.5 cells

Illustrative: both feature maps are synthetic blobs, not real network features. The loss is the distance between the two maps, each scaled to length 1. It runs from 0 (identical) to 2 at most.

At shift 0 the loss is 0. Past about 3 cells it flattens, because the two blobs no longer overlap.

pythonimport torch, torch.nn.functional as F

def attention(f, p=2):
    # f: (B, C, H, W)  ->  (B, H*W), each row of length 1
    a = f.abs().pow(p).sum(dim=1)            # (B, H, W) sum over channels
    return F.normalize(a.flatten(1), dim=1)

def at_loss(f_student, f_teacher):
    # H, W must match; C may differ
    return (attention(f_student) - attention(f_teacher.detach())).pow(2).mean()

The code averages the squared difference, a common variant that also grows as the maps part.

The failure: different spatial sizes. Symptom: a shape error, or a loss over unrelated positions. Measure: print each pair's H × W. A stride of 2 where the teacher has 1 halves the map. Fix: pair layers at the same resolution, or resize.

Why can an attention-map loss pair a 64-channel teacher layer with a 32-channel student layer without a regressor?

Chapter 6

Match On-Off Patterns and the Relations Between Examples

Copy which neurons fire, not how strongly, and copy how examples sit relative to each other

A loud choir and a quiet choir sing the same notes. Items five and six copy the notes, not the volume.

Five, sparsity patterns

A ReLU keeps positive numbers and zeroes negative ones. Slide 24 marks an activated neuron with rho of x, ρ(x) = 1[x > 0]: 1 if x is above zero, else 0. The activated set is the sparsity pattern. Matching it copies where the teacher's switches flip.

The indicator has no gradient, so training needs a smooth stand-in. The device only measures agreement.

Compare pattern and value

Twelve neurons before the ReLU. The top row is the teacher. The bottom row is the student. Filled means activated. Shrink the student, then add noise.

0.30
0.00

Illustrative: twelve made-up values for the teacher, and a student that equals the teacher times the scale plus fixed pseudo-random noise times the noise slider. The value distance is the plain L2 distance between the two rows of values.

At scale 0.3 the value distance is large, yet all twelve patterns agree. Noise flips the neurons near zero first.

Six, relational information

Between layers (slide 26): take the inner product of two layers' feature maps over all positions. It gives a Cin × Cout matrix of how channels fire together, and an L2 loss matches the two networks' matrices.

Between samples (slides 27 and 28): relational knowledge distillation, RKD, matches the distances between examples. Call the student's feature vectors for n examples s1 to sn.

Say it aloud

Psi of s-1 to s-n equals the list of squared distances: s-1 to s-2, s-1 to s-3, and on to s-n-minus-1 to s-n.

ψ
psi the relation vector: every pairwise squared distance, n(n − 1)/2 numbers.
s1, …, sn
s-1 to s-n the student's feature vectors for n examples. The teacher's are t-1 to t-n.
‖sa − sb‖2
the squared distance from s-a to s-b subtract the vectors, square each entry, add.
n
n the number of examples. 5 examples give 10 distances. A batch of 64 gives 2,016.
In plain words

List the squared distance between every pair of student features. List the teacher's from t-1 to t-n. Divide each list by its own mean and train until the lists match.

With numbers

With made-up 2D features: teacher (0, 0), (6, 0), (0, 8) gives (36, 64, 100). A student at half size gives (9, 16, 25). Divided by their means, 66.7 and 16.7, both become (0.54, 0.96, 1.50). The loss is 0.

Compare point and relation

Five examples in two dimensions. The blue points are the teacher's. The warm points are the student's. Rotate and shrink the student, then bend one point out of place.

60°
0.60
0.00

Illustrative: five made-up points. The relational loss divides each set of distances by its own mean, as the RKD paper does, so a global scale does not count. The point loss is the mean squared distance between matching points.

At rotation 60 and scale 0.6 the point loss is large and the relational loss is 0. Move one point and it rises: it sees structure, not frame.

The failure: matching what does not carry over. Symptom: a student stuck on a raw-value match. Measure: does the value's scale or frame differ between the networks? Fix: match on-off patterns or normalized distances.

The student's embeddings are the teacher's rotated by 60 degrees and shrunk to half size. Which loss calls them a perfect match?

Chapter 7

A Student Can Teach Itself, or Teach a Partner

Drop the fixed big teacher, and see three ways networks improve each other during training

A study group with no professor still improves. Slide 31 asks: do we need a fixed large teacher? It costs a full training run first, and some tasks have no good large model.

Self-distillation: born-again networks

The Born-Again Network (BAN, slides 32 and 33) trains model T from the labels. Each next model has the same architecture and a new random seed, and learns from the labels and the model before it. The architectures are equal, T = S1 = … = Sk, but accuracy climbs, T < S1 < … < Sk. An ensemble of the generations gains more.

Online distillation: deep mutual learning

Deep mutual learning (DML, slides 35 and 36) trains two networks from scratch at the same time. Each is the other's teacher at every step, and they need not share an architecture. Take one network S, its peer T, an image I and its label y.

Say it aloud

L of S equals the cross-entropy of S of I and y, plus the KL of S of I and T of I.

L(S)
L of S the loss for network S. Network T gets the same loss with the roles swapped.
CrossEntropy
the cross-entropy of minus the log of the probability that S gives the true class.
S(I)
S of I the class probabilities that S predicts for image I. T(I) is the peer's.
y
y the true label.
KL(S(I), T(I))
the KL of S of I and T of I the gap between the two predictions. The code measures it from T's answer to S's and holds T's answer fixed for the step.
In plain words

Score S against the label y. Score how far S's prediction sits from its peer's. Add the two. Do the same for T with S as its peer, then update both.

With numbers

With made-up numbers, two classes, label cat: S says cat 0.6 and T says cat 0.8. Cross-entropy = −ln 0.6 = 0.511. KL = 0.8 ln(0.8 / 0.6) + 0.2 ln(0.2 / 0.4) = 0.092. L(S) = 0.602. The peer pulls S toward a surer cat.

CIFAR-100, slide 36Trained aloneTrained with DML
ResNet-32 and ResNet-3268.99 and 68.9971.19 and 70.75
WRN-28-10 and MobileNet78.69 and 73.6580.28 and 77.39

The big WRN-28-10 gains 1.59 points too. In DML the "teacher" learns from the "student".

Combined: be your own teacher

Slides 38 and 39 cut one network into four sections and add a classifier after each. Each learns from the label, the deepest classifier's predictions and the deepest features. Later stages are more reliable, so deep supervises shallow. An early exit lets an easy image stop at an inner classifier.

Read the four exits

CIFAR-100 results from slide 39. Choose a network. Each bar is the accuracy of one classifier after self-distillation. The line marks the baseline trained in the usual way. Then pick an exit.

All values are top-1 accuracy (%) on CIFAR-100 from the lecture's slide 39, Table 1 of Zhang et al., ICCV 2019. Which exit is worth shipping depends on your latency budget, which this device does not model.

ResNet101 at exit 3 scores 81.17 against a 77.98 baseline, and skips the last section. VGG19 at exit 1 scores 63.59, below its 64.47 baseline.

The failure: exits that are too early. Exit 1 of all ten networks on the slide is below baseline, such as ResNet18 at 67.85 against 77.09. Measure each exit and ship a later one.

pythonimport torch.nn.functional as F

def mutual_loss(z1, z2, y, T=1.0):
    # z1, z2: (B, C) logits of two peer networks trained together
    ce1 = F.cross_entropy(z1, y)
    ce2 = F.cross_entropy(z2, y)
    kl12 = F.kl_div(F.log_softmax(z1 / T, 1), F.softmax(z2 / T, 1).detach(), reduction="batchmean")
    kl21 = F.kl_div(F.log_softmax(z2 / T, 1), F.softmax(z1 / T, 1).detach(), reduction="batchmean")
    return ce1 + kl12, ce2 + kl21     # one loss for each network

The detach call makes each network treat the other's answer as a fixed target for that step.

Born-again networks train a chain of models with the same architecture. What do they change from step to step?

Chapter 8

Each Task Gets Its Own Recipe: Detection, Segmentation, GANs, Language

Walk through five tasks and see which part of the teacher each one chooses to copy, with the lecture's numbers

A chef points at the pan. A driving instructor points at the mirror. Each task copies the part of the teacher that carries its knowledge. Slides 40 to 58 tour five tasks.

Pick the task

Blue boxes are the teacher's stages. Warm boxes are the student's. Each purple link is one thing the student is trained to match. The list under the picture names them.

    The diagrams are our simplified sketches of slides 41 to 58, not the papers' figures. The numbers in the read-outs come from the slides.

    Object detection

    A detector outputs a class and a box. The method of Chen and colleagues (slides 41 to 44) has four parts:

    1. Feature imitation: an L2 hint loss, with a 1 × 1 convolution to match shapes.
    2. A soft class loss with different weights for foreground and background, because background boxes far outnumber objects.
    3. A bounded loss on the box, below.
    4. The usual ground-truth losses.

    The box loss uses the teacher as a bound. Call the student's box Rs, the teacher's box Rt, the true box y and a margin m.

    Say it aloud

    L-b equals the squared norm of R-s minus y, if that plus m is greater than the squared norm of R-t minus y. Otherwise L-b is zero.

    Lb
    L-b the bounded box loss for the student.
    Rs
    R-s the student's predicted box.
    Rt
    R-t the teacher's predicted box.
    y
    y the true box.
    ‖ … ‖2
    the squared norm of the sum of squared differences: a box error, squared.
    m
    m the margin, 0 or more.
    In plain words

    Square the student's box error. If the student does not yet beat the teacher's squared error by the margin m, that squared error is the loss. Once it does, the loss is zero and the pull stops.

    With numbers

    With the device's starting values: teacher error 1.00, margin 0.30. A student error of 1.20 gives 1.44 + 0.30 = 1.74, above 1.00, so L-b = 1.44. A student error of 0.80 gives 0.64 + 0.30 = 0.94, below 1.00, so L-b = 0. The pull stops below a student error of 0.84.

    Bound the box loss

    The curve is the student's loss as its box error grows. It stays zero while the student beats the teacher by at least the margin. Drag the student's error across the bend.

    1.00
    0.30
    1.20

    Illustrative: errors are distances between a predicted box and the true box in arbitrary units. The rule is the lecture's slide 44 formula.

    Localization distillation (slides 45 to 48) turns each box edge into a probability over bins. The slides divide each axis into 6 bins. The ordinary distillation loss then compares the teacher's and the student's distributions. An edge with 0.55 on bin 3 and 0.30 on bin 4 (our illustration) carries the teacher's doubt about position.

    Segmentation, GANs and language

    TaskWhat the student matchesLecture numbers
    Segmentation (slides 49, 50)Feature imitation, plus a discriminator: a small network that tries to tell the teacher's output from the student's. The student learns to fool it, so its whole map looks like the teacher's.None on the slides
    GAN Compression (slides 51 to 54)A GAN loss, a reconstruction loss and a distillation loss. The distillation loss sums, over chosen layers k, the distance between the student generator's feature Gk(x) and the teacher's feature G′k(x) passed through a small adapter fk.Jetson Nano: 56.8G to 4.81G MACs (11.8 times fewer), 1.6 to 3.9 frames per second, FID 24.2 to 26.6. FID measures how far generated images are from real ones; lower is better.
    NLP, MobileBERT (slides 55, 56)Feature imitation, plus the teacher's attention maps: how much each word looks at each other word.The student with attention transfer matches the teacher's maps more closely
    LLM, Minitron (slides 57, 58)Prune, then distill: estimate importance, rank, trim, distill, repeat. Losses at the embedding output, the block outputs and the logits.Minitron 8B: about 40 times cheaper to train than Nemotron-3 8B and 9 percent better on the slide's plot

    Slide 57 states that pruning and distillation are now common practice for getting small LLMs.

    The failure: copying the teacher's mistakes. Symptom: a detection student never beats its teacher, even where the teacher is wrong. Measure: compare each box's error with the teacher's. Fix: the margin rule above, so the pull stops once the student is as good.

    In the detection recipe, why is the soft class loss weighted differently for foreground and background?

    Chapter 9

    Network Augmentation Trains the Tiny Model Inside a Wider One

    See why the usual training tricks hurt a tiny model, then follow one NetAug step that adds supervision by widening

    A weighted vest helps a strong runner and stops a beginner. Network augmentation (NetAug, slides 59 to 80) fixes this.

    The usual tricks hurt tiny models

    The usual cures for overfitting are data augmentation (Cutout, Mixup, AutoAugment) and dropout (also SpatialDropout, DropBlock), slides 60 to 66. Mixup, AutoAugment and DropBlock lift ResNet50 (slide 67). Each lowers MobileNetV2-Tiny (slide 68). A tiny network lacks the capacity for a harder job.

    Add supervision, not difficulty

    NetAug trains the tiny network as a part of a wider one. Call the tiny network's weights Wbase, the wider model's extra weights Waug, and the training loss L.

    Say it aloud

    L-aug equals L of W-base, plus alpha times L of W-base and W-aug together.

    Laug
    L-aug the total loss that NetAug minimizes.
    L(Wbase)
    L of W-base the tiny network's own loss: the base supervision.
    α
    alpha the weight on the extra signal.
    L([Wbase, Waug])
    L of W-base and W-aug the loss of the wider network that holds the tiny one: the auxiliary supervision. The paper's general form adds several wider models, each with its own alpha.
    In plain words

    Take the tiny network's loss. Take the loss of the wider network, which shares W-base. Add the second, weighted by alpha. Both send gradient into W-base.

    With numbers

    With made-up numbers: tiny loss 1.20, wide loss 0.80, alpha 0.5. L-aug = 1.20 + 0.5 × 0.80 = 1.60.

    At test time you drop Waug and ship the tiny network alone. The extra cost is 16.7 percent in training and zero at test (slide 71).

    Step the NetAug update

    Left: the tiny base network. Right: the widened network that contains it. Press a step. Then change alpha and watch the final update.

    0.50

    Illustrative toy: two shared base weights 0.50 and 0.30 (written as w1 and w2), made-up gradients, learning rate 0.5. In a real network the widened model has many more weights, and the paper samples an augmented model at each step.

    Call the base gradient gbase, the wide network's gradient on the shared weights gaug, and the learning rate η (eta). The update is:

    Wbase ← Wbase − η (gbase + α gaug)

    In the toy, gbase = (0.20, −0.10), gaug = (0.12, 0.06), η = 0.5 and α = 0.5. The step is (0.26, −0.07), so the weights move from (0.50, 0.30) to (0.37, 0.335).

    Where it helps and where it hurts

    On MobileNetV2-Tiny, NetAug raises training accuracy by 1.3 points and validation by 1.6 (slide 76): it cures underfitting. On ResNet50 it adds 1.6 to training and takes 0.3 from validation.

    Read the gain

    Pick a model. The bars show how much NetAug moved its accuracy on ImageNet, in percentage points. Green is a gain. Red is a loss on validation.

    From the lecture's slides 76 and 77 (Cai et al., ICLR 2022), read off the plots and rounded.

    NetAug is orthogonal to KD: on small networks the two together beat either (slide 78). It transfers better than KD or a four times longer schedule (slide 79). On YoloV3 detection it matches the baseline with 41 percent fewer MACs on Pascal VOC, 38 on COCO (slide 80).

    pythonimport torch.nn.functional as F
    
    def netaug_step(model, x, y, opt, alpha=1.0, wide=2.0):
        # model(x, width=r) runs the first r * C channels of every shared layer
        base = F.cross_entropy(model(x, width=1.0), y)       # base supervision
        aug  = F.cross_entropy(model(x, width=wide), y)      # auxiliary supervision
        loss = base + alpha * aug
        opt.zero_grad(); loss.backward(); opt.step()         # both grads reach the shared slice
        return base.item(), aug.item()
    # at test time: model(x, width=1.0). Nothing else ships.

    The failure: NetAug on a model that already overfits. Symptom: training accuracy rises and validation falls, as for ResNet50. Measure: compare the change in each. Fix: use NetAug only on models that underfit.

    NetAug lowers ResNet50's validation accuracy by 0.3 points but raises MobileNetV2-Tiny's by 1.6. What explains this?

    Chapter 10

    The Field Guide: Numbers, Terms, Checklist and Code

    Keep the lecture's numbers, the recipe, and the core code in one place, then follow the links to the next lecture

    A tiny model underfits, so ordinary regularizers hurt it. It needs extra supervision: a teacher's softened probabilities, its layers and relations, a partner, or a wider copy of itself.

    The numbers to remember

    ItemValueWhere
    Cloud GPU against tiny device75 TFLOPS and 288 GB against MFLOPs and 256 kBSlide 3
    ResNet50 against MobileNetV2-Tiny4.1G MACs against 23.5M MACsSlides 67, 68
    Teacher and student, cat and dog0.982 and 0.018 against 0.731 and 0.269 (the slide prints the dog as 0.017)Slide 7
    Temperature on logits 5 and 1T = 1 gives 0.982 and 0.018. T = 10 gives 0.599 and 0.401Slide 9
    Soft term scaleT squared (from the Hinton paper)Chapter 3
    Relations between layersa Cin × Cout matrix; teacher and student differ in number of layers, not channelsSlide 26
    Pairwise distances for n examplesn(n − 1) / 2Slide 28
    DML, two ResNet-32 on CIFAR-10068.99 alone, 71.19 and 70.75 togetherSlide 36
    Be your own teacher, ResNet101 exit 381.17 against a 77.98 baselineSlide 39
    GAN Compression on Jetson Nano56.8G to 4.81G MACs (11.8 times), 1.6 to 3.9 frames per second, FID 24.2 to 26.6Slide 54
    GAN Compression on Jetson Xavier, horse to zebra56.8G to 3.50G FLOPs (16.2 times), 12.1 to 40.0 frames per second (3.3 times), FID 61.5 to 53.6Slide 52
    NetAug on MobileNetV2-Tiny+1.3 train, +1.6 validation, 16.7 percent training overhead, no test costSlides 71, 76
    NetAug on ResNet50+1.6 train, −0.3 validationSlide 77

    Terms

    TermPlain meaningChapter
    Teacher, studentThe big trained model, and the small model that learns from it1
    LogitsRaw scores before the softmax1
    Dark knowledgeInformation in the small probabilities on wrong classes1
    Temperature TA divisor on the logits that flattens the softmax2
    KL divergenceA score of how far two distributions are apart, zero when equal1, 3
    Hint, regressorA middle layer to copy, and the small layer that fixes its shape4
    Attention mapA map of where a layer is sensitive in the input5
    Sparsity patternWhich neurons are above zero after a ReLU6
    RKDRelational distillation, matching distances between examples6
    BAN, DMLSelf-distillation by generations, and online distillation by peers7
    NetAugTraining the tiny model as a part of a wider one9

    Checklist before you distill

    The core as code

    pythonimport torch, torch.nn as nn, torch.nn.functional as F
    
    def kd_loss(zs, zt, y, T=4.0, alpha=0.5):
        soft = F.kl_div(F.log_softmax(zs / T, -1), F.softmax(zt / T, -1), reduction="batchmean") * T * T
        return alpha * soft + (1 - alpha) * F.cross_entropy(zs, y)
    
    def attention(f):                                   # (B, C, H, W) -> (B, H*W)
        return F.normalize(f.pow(2).sum(1).flatten(1), dim=1)
    
    def train_step(student, teacher, x, y, opt, lam=1e-1):
        with torch.no_grad():
            zt, ft = teacher(x, return_feat=True)         # logits (B, C), features (B, Ct, H, W)
        zs, fs = student(x, return_feat=True)
        loss = kd_loss(zs, zt, y) + lam * (attention(fs) - attention(ft)).pow(2).mean()
        opt.zero_grad(); loss.backward(); opt.step()
        return loss.item()

    The return_feat flag stands for any hook that returns a middle layer's output. Pair layers at the same resolution.

    Where it sits in the stack

    Pruning, quantization and architecture search change the model. Distillation changes how you train it, so it stacks with the others: Minitron distills a pruned model. Lecture 10 continues with MCUNet, which designs the model and the engine together for microcontrollers.

    Keep going:

    The takeaway. A hard label tells the student only the answer. A teacher tells it how sure to be and what looks alike. And when a model is too small to learn well, give it more supervision, not more difficulty.
    You must train a MobileNetV2-Tiny model. It underfits, and you have no large teacher. Which choice fits the lecture?

    Credit

    This lesson follows Lecture 9 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Read the lecture on the course page, which links the slides. The lecture cites Hinton et al., Ba and Caruana, FitNets, Zagoruyko and Komodakis, Park et al., Born-Again Networks, Deep Mutual Learning, Be Your Own Teacher, GAN Compression, MobileBERT, Minitron and Network Augmentation, among others. All explanations, devices and examples here are our own.

    Now press Teach and explain, from memory, why a soft target teaches more than a hard label and why the soft term needs T squared. Then go back to the student at the top and train it with each of the three signals once more.

    MIT 6.5940 Lecture 9: Knowledge Distillation
    The course page and slides · Back to Lecture 8 · On to Lecture 10 · Back to Gleams