AI Wiki中文/EN

Self-distillation

自蒸馏

Train an equally sized student from fixed teacher probabilities and compare an equal-budget baseline.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

A model can teach another model with the same architecture. The student need not be smaller. In Born-Again Networks, a trained generation provides predictions for a newly initialized model; the paper reports improvements in its experimental settings. Same-sized teachers and students are the point of that study, not a guarantee that every generation improves. Born-Again Neural Networks

“Self” can refer to successive generations, different stages of one network or a moving teacher related to the student. It does not mean the procedure requires no labels. Our teacher is trained with labels, and the student uses both those labels and the teacher’s softened predictions.

We compare three nine-parameter softmax classifiers: the teacher, a distilled student and a supervised baseline with the same initialization and number of student updates. This checks what changed in the training objective without quietly changing capacity or the optimization budget.

Definitions and derivation

Let teacher logits be v and student logits z. A shared positive temperature T produces their soft distributions, while the hard-label term uses temperature one:

qT=softmax⁡(v/T),pT=softmax⁡(z/T),p1=softmax⁡(z).q_T=\operatorname{softmax}(v/T),\qquad p_T=\operatorname{softmax}(z/T),\qquad p_1=\operatorname{softmax}(z).

With mixing weight alpha, our per-example objective combines hard-label cross-entropy and teacher-to-student KL. Teacher probabilities are fixed:

ℓ=(1−α)CE⁡(y,p1)+αT2KL⁡(sg⁡(qT)∥pT),KL⁡(q∥p)=∑kqklog⁡(qk/pk).\ell=(1-\alpha)\operatorname{CE}(y,p_1)+\alpha T^2\operatorname{KL}(\operatorname{sg}(q_T)\|p_T),\qquad \operatorname{KL}(q\|p)=\sum_kq_k\log(q_k/p_k).

Replacing the KL with soft-target cross-entropy changes the objective by the constant teacher entropy, not its student gradient. The temperature-squared weighting follows the standard distillation motivation; it does not make the entire optimization exactly invariant to temperature. Differentiating softmax at temperature T contributes a factor 1/T:

∂ℓ∂z=(1−α)(p1−y)+αT(pT−qT),∇WL=1NX⊤∂ℓ∂Z.\frac{\partial\ell}{\partial z}=(1-\alpha)(p_1-y)+\alpha T(p_T-q_T),\qquad \nabla_W L=\frac1N X^\top\frac{\partial\ell}{\partial Z}.

In the last expression each row of the derivative matrix is the corresponding per-example logit gradient, before averaging. X includes the intercept column. Both teacher and student use the same three-by-three weight shape. The code sets T=2 and alpha=0.7 for its constructed experiment; original distillation discusses combining hard and soft targets and why temperature scaling matters. Distilling the Knowledge in a Neural Network — arXiv v1

Train the teacher first, save its parameters, then compute a fixed probability table for the student’s training inputs. Optimize a newly initialized student against that table and the original labels. The teacher is not updated during this phase.

Run the calculation

Run CPython 3.12.4 and NumPy 1.26.4. Twelve synthetic training points come from three perturbed centers. The teacher receives 400 labeled steps; the student and its same-initialization supervised baseline each receive 400 steps at rate 0.1. All three score 100% on 90 new synthetic points. Their held-out NLLs are about 0.030159426, 0.029141856 and 0.030113233 respectively. This one-seed result shows a small score difference without an accuracy gain; it is not a claim of statistical superiority or a reproduction of the paper’s image/language results. At inference, all use temperature one.

import numpy as np


def data(seed=1,count=4):
    centers=np.array([[1.5,0],[-.75,1.3],[-.75,-1.3]]);rng=np.random.default_rng(seed);x=np.repeat(centers,count,axis=0)+rng.normal(0,.3,(3*count,2));return np.c_[x,np.ones(len(x))],np.repeat(np.arange(3),count)


def log_softmax(logits):
    z=logits-logits.max(axis=1,keepdims=True);return z-np.log(np.exp(z).sum(axis=1,keepdims=True))


def objective(w,x,y,teacher_probabilities=None,mix=.7,temperature=2.):
    logp=log_softmax(x@w);p=np.exp(logp);target=np.eye(3)[y];hard=-np.mean(logp[np.arange(len(y)),y]);g=x.T@(p-target)/len(y)
    if teacher_probabilities is None:return float(hard),g
    softlog=log_softmax(x@w/temperature);soft=np.exp(softlog);q=teacher_probabilities;kl=np.mean(np.sum(q*(np.log(q)-softlog),axis=1));gradient=(1-mix)*g+mix*temperature*x.T@(soft-q)/len(y);return float((1-mix)*hard+mix*temperature**2*kl),gradient


def train(seed,teacher=None,steps=400):
    x,y=data();w=np.random.default_rng(seed).normal(0,.1,(3,3));q=None if teacher is None else np.exp(log_softmax(x@teacher/2.))
    for _ in range(steps):w-=.1*objective(w,x,y,q)[1]
    return w


def evaluate(w):
    x,y=data(seed=23,count=30);logp=log_softmax(x@w);return float(np.mean(logp.argmax(axis=1)==y)),float(-np.mean(logp[np.arange(len(y)),y]))


if __name__=='__main__':
    teacher=train(1);student=train(2,teacher);baseline=train(2)
    for name,w in [('teacher',teacher),('same-size distilled student',student),('same-init supervised baseline',baseline)]:print(name,'parameters',w.size,'synthetic held-out accuracy/NLL',tuple(round(v,9) for v in evaluate(w)))
    x,y=data();q=np.exp(log_softmax(x@teacher/2.));loss,g=objective(teacher,x,y,q,mix=1.);print('matching its own fixed distribution: KL and gradient norm',loss,float(np.linalg.norm(g)))
teacher parameters 9 synthetic held-out accuracy/NLL (1.0, 0.030159426)
same-size distilled student parameters 9 synthetic held-out accuracy/NLL (1.0, 0.029141856)
same-init supervised baseline parameters 9 synthetic held-out accuracy/NLL (1.0, 0.030113233)
matching its own fixed distribution: KL and gradient norm 1.5952755614904025e-17 0.0

When the method fails

If the student starts at the teacher parameters, sees the same inputs and optimizes only matching the fixed teacher distribution, its gradient is zero. Repeatedly asking an identical predictor to agree with itself supplies no new gradient. New initialization, differing views, hard-label supervision or other training differences change that situation; none guarantees improvement.

The teacher can transmit mistakes as well as useful relative probabilities. A lower distillation loss may only mean closer imitation. Keep held-out labels outside teacher fitting, target creation and hyperparameter selection. Compare multiple seeds and an equal-budget non-distilled baseline before attributing a gain to distillation.

Sequential self-distillation costs the teacher training plus student training. Caching N distributions over K classes takes O(NK)O(NK) storage; recomputing them trades storage for teacher forward passes. Equal model size gives no automatic inference compression. Ensembling generations also adds inference cost and is a different deployment choice.

DINO instead uses a moving teacher and cross-view self-supervised targets. That contrasts with the fixed, previously trained teacher here. Do not combine the guarantees or assumptions of these distinct procedures under the label “self-distillation.” Emerging Properties in Self-Supervised Vision Transformers — arXiv v2

Exercises with answers

  1. Must a self-distillation student be smaller than its teacher?

Answer 1: No. This experiment and the same-sized Born-Again setup use matching architectures.

  1. Why does a temperature-squared weighted soft term yield a factor T in the logit gradient?

Answer 2: Differentiating the temperature-scaled softmax cross-entropy contributes 1/T, leaving T after multiplication by T².

  1. Does matching its own fixed distribution give a model a nonzero gradient?

Answer 3: Not when the current distribution already matches the target on the same inputs; the soft gradient is zero.

  1. Did the synthetic student improve accuracy here?

Answer 4: No. All models achieved 100%; the small NLL difference from one seed is not proof of a reliable advantage.

Sources and next steps

Read the generation diagram in Born-Again Networks alongside Hinton et al.’s temperature and hard/soft-target derivation. Then compare the fixed teacher used here with DINO’s EMA teacher. To extend the experiment, predeclare a held-out protocol, keep the baseline initialization and step count matched, repeat seeds and report both the teacher and student costs. Born-Again Neural Networks; Distilling the Knowledge in a Neural Network — arXiv v1; Emerging Properties in Self-Supervised Vision Transformers — arXiv v2

Make a prediction, then check

The student and teacher share an architecture. Does distillation guarantee the student improves?

Choose one answer

Learning objectives

  • Derive temperature-weighted gradients with a fixed teacher.
  • Separate self-distillation, compression, self-supervision and measured improvement.

Prerequisites & connections

Explore related knowledge →

References

  1. Born-Again Neural Networks
    Tommaso Furlanello; Zachary C. Lipton; Michael Tschannen; Laurent Itti; Anima Anandkumar · 2018
  2. Distilling the Knowledge in a Neural Network — arXiv v1
    Geoffrey Hinton; Oriol Vinyals; Jeff Dean · 2015
  3. Emerging Properties in Self-Supervised Vision Transformers — arXiv v2
    Mathilde Caron; Hugo Touvron; Ishan Misra; Hervé Jégou; Julien Mairal; Piotr Bojanowski; Armand Joulin · 2021

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, executable examples and corresponding bilingual equations, code and exercises. Not independent human or second-agent review.
  • Four CPython 3.12.4 checks per chapter: spectra and exact recurrence with scale-aware tolerances, frozen ridge probes, literal graded retrieval metrics, whitening/SVD constraints, finite balancing marginals and stopped targets, pseudo-label denominator, exact noise expectation and temperature-weighted distillation as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; no real image/text benchmark reproduction claimed.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.