Knowledge Distillation: Learning from Teachers

Knowledge distillation trains a student, usually smaller, to match a teacher's temperature-softened output probabilities, often alongside the true labels. The probabilities the teacher gives to wrong classes show which classes it treats as similar, which hard labels omit.

Intermediate · Undergraduate mathematics · about 16 minutes

Reading map and next steps

Intuition

The idea in plain words, before the symbols.

If you train a model on hard labels, every example says only one thing: "this is a cat."

A good teacher model knows more than that. It might say:

  • 0.84 cat
  • 0.12 dog
  • 0.04 fox

Those "almost" probabilities carry what is often called dark knowledge: the relative probabilities of the wrong answers encode which classes the teacher has learned to see as similar. Distillation trains a student to match the teacher's distribution, usually alongside the true labels, so the student can inherit much of the teacher's behaviour with fewer parameters or a different architecture (Hinton et al., 2015).

For language models the same idea applies to next-token distributions: a smaller model is trained to match a larger model's token probabilities at each position, or trained directly on text the larger model generated (Kim and Rush, 2016). Speculative decoding also uses a small, fast draft model that approximates a large one. The draft may be distilled, but speculative decoding's output is correct because the large model checks every draft token, not because of distillation.

Study prompts for this section: Intuition
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Mathematics

Definitions, assumptions and the derivation.

Let the teacher and student produce logits zT(x)z_T(x) and zS(x)z_S(x) over a discrete output space.

With temperature τ>0\tau>0, define softened probabilities:

pT(τ)(y∣x)=softmax(zT(x)/τ),pS(τ)(y∣x)=softmax(zS(x)/τ).p_T^{(\tau)}(y\mid x)=\mathrm{softmax}(z_T(x)/\tau),\qquad p_S^{(\tau)}(y\mid x)=\mathrm{softmax}(z_S(x)/\tau).

The soft-target term is usually written as the KL divergence between the teacher's and the student's softened distributions. With the teacher fixed, it differs from the soft-target cross-entropy only by the teacher's entropy, a constant, so both give the same gradients:

LKD=τ2 KL ⁣(pT(τ)(⋅∣x) ∥ pS(τ)(⋅∣x)),L=(1−α) Lhard+α LKD.\mathcal L_{\text{KD}} = \tau^2\,\mathrm{KL}\!\left(p_T^{(\tau)}(\cdot\mid x)\ \|\ p_S^{(\tau)}(\cdot\mid x)\right), \qquad \mathcal L = (1-\alpha)\,\mathcal L_{\text{hard}} + \alpha\,\mathcal L_{\text{KD}}.

where:

KL(p∥q)=∑yp(y)log⁡p(y)q(y).\mathrm{KL}(p\|q)=\sum_y p(y)\log\frac{p(y)}{q(y)}.

Here Lhard\mathcal L_{\text{hard}} is the ordinary cross-entropy with the true label, computed at τ=1\tau=1; for a language model it is the next-token loss on the training text. The soft-target gradients shrink as 1/τ21/\tau^2, so the factor τ2\tau^2 keeps the balance between the two terms roughly unchanged when τ\tau changes. Hinton et al. found that a considerably smaller weight on the label term, which here means α\alpha close to 1, generally worked best.

Raising τ\tau softens the teacher distribution and gives more weight to the classes it did not pick. The signal does not vanish at large τ\tau: both distributions approach uniform, but with the τ2\tau^2 factor and logits centred to mean zero, the gradient becomes proportional to that of matching the logits directly, 12∑i(zS,i−zT,i)2\tfrac12\sum_i (z_{S,i}-z_{T,i})^2 (Hinton et al., 2015, §2.1). Lower temperatures pay less attention to very negative logits, which may be noise; Hinton et al. found intermediate temperatures worked best when the student was much smaller than the teacher. In practice τ\tau is tuned.

Study prompts for this section: Mathematics
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Code

The same calculation as runnable code, in the notation of the derivation.

import numpy as np

def softmax(z, tau=1.0):
    z = z / tau
    z = z - z.max()
    e = np.exp(z)
    return e / e.sum()

def kl(p, q):
    eps = 1e-12
    return float(np.sum(p * (np.log(p + eps) - np.log(q + eps))))

teacher_logits = np.array([4.0, 2.0, 0.0])
student_logits = np.array([3.0, 0.5, -0.5])

for tau in [1.0, 2.0, 4.0]:
    pT = softmax(teacher_logits, tau)
    pS = softmax(student_logits, tau)
    print("tau=", tau, "pT=", np.round(pT, 3), "pS=", np.round(pS, 3), "KL=", round(kl(pT, pS), 3))
Study prompts for this section: Code
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Demo

Change an input, predict the result, and see which quantities respond.

ExploreChange one control at a time and name what responds.An optional observation guide follows the demo.

Explore Knowledge Distillation: Learning from Teachers

Loading the interactive demo…

Observation guide

Optional and ungraded. Opening a guide saves nothing.

Choose what to inspect in Knowledge Distillation: Learning from Teachers, then open its guide.

The demo below asks you to predict which wrong class the teacher pulls the student towards most, before it shows the softened teacher distribution. The point is that distillation passes on the structure in the teacher's probabilities for the classes it did not pick, not only its top choice.

Study prompts for this section: Demo
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

In focus

Concept: Knowledge Distillation: Learning from Teachers

What is the smallest example of Knowledge Distillation you can work through by hand, and what does it show?

BeforeMaximum LikelihoodNextSparse Mixture of Experts: Routing, Load Balancing & Expert Parallelism
DetailsEfficiency

After the first pass

Go deeper

Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.
What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.

Section by section

Choose what to look for in each section

Knowledge distillation trains a student, usually smaller, to match a teacher's temperature-softened output probabilities, often alongside the true labels. The probabilities the teacher gives to wrong classes show which classes it treats as similar, which hard labels omit.

Choose what to look for (no demo yet)01 / Intuition
Illustration of a larger teacher model transferring softened probability structure into a smaller student model.
What to look for

Start with the picture, metaphor, or geometric mechanism.

Choose first

Choose what you expect to see in this section of Knowledge Distillation: Learning from Teachers.

Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.

Looking at the picture

Questions to ask of the picture

Knowledge distillation trains a student, usually smaller, to match a teacher's temperature-softened output probabilities, often alongside the true labels. The probabilities the teacher gives to wrong classes show which classes it treats as similar, which hard labels omit.

4 of 4 sections writtenNo live demo yet
Question

Which part of the picture should you look at first?

Choose first

Pick the part of the picture you expect to explain Knowledge Distillation: Learning from Teachers.

Sources

References for this page

A reference shows where an idea comes from; it does not vouch for every step on this page.
paper · 2015Distilling the Knowledge in a Neural NetworkHinton, Vinyals, and Dean
Why it is cited

Trains a small model on a large model's temperature-softened outputs plus a lower-weighted label loss; wrong-class probability ratios carry similarity structure, and §2.1 shows high temperature becomes logit matching (NIPS 2014 workshop).

Open source
paper · 2016Sequence-Level Knowledge DistillationKim and Rush
Why it is cited

Distils translation models by matching the teacher's next-word distributions or by training on the teacher's output sequences; the best student runs about ten times faster with little loss in quality (EMNLP 2016).

Open source
book · 2016Deep LearningGoodfellow, Bengio, and CourvilleSee §12.1.4, Model Compression
Why it is cited

Textbook treatment of model compression: replacing a large model, or an ensemble, with a smaller one trained to reproduce its outputs (MIT Press).

Open source
What each claim rests on1 claim, each with its sources, where it appears on this page, and its caveats.

Claims and sources

Knowledge distillation trains a student, usually smaller, to match a teacher's temperature-softened output probabilities, often alongside the true labels. The probabilities the teacher gives to wrong classes show which classes it treats as similar, which hard labels omit.

Checked against the cited passages

The checks were made by this site, not by an independent reviewer.

Knowledge distillation trains a student to match a teacher's temperature-softened output distribution, not just the hard labels: the probabilities the teacher gives to wrong answers carry similarity structure, and the soft-target loss, equivalent to a KL divergence, is usually mixed with the ordinary label loss.
What the sources support

Hinton et al. define softened class probabilities with temperature, train the distilled model to match teacher soft targets, say incorrect-answer probability ratios encode rich similarity structure, and mix...

Where to see it on this page
Equation 1
pT(τ)(y∣x)=softmax(zT(x)/τ),pS(τ)(y∣x)=softmax(zS(x)/τ).p_T^{(\tau)}(y\mid x)=\mathrm{softmax}(z_T(x)/\tau),\qquad p_S^{(\tau)}(y\mid x)=\mathrm{softmax}(z_S(x)/\tau).
Equation 2
LKD=τ2 KL ⁣(pT(τ)(⋅∣x) ∥ pS(τ)(⋅∣x)),L=(1−α) Lhard+α LKD.\mathcal L_{\text{KD}} = \tau^2\,\mathrm{KL}\!\left(p_T^{(\tau)}(\cdot\mid x)\ \|\ p_S^{(\tau)}(\cdot\mid x)\right), \qquad \mathcal L = (1-\alpha)\,\mathcal L_{\text{hard}} + \alpha\,\mathcal L_{\text{KD}}.
Caveat

This covers soft-target distillation over a fixed set of classes, as in Hinton et al. Recipes for distilling large language models, and how much a given student gains, depend on the teacher, the data and the...

StatusChecked against the cited passages.

Hinton et al. support high-temperature soft targets, matching the teacher at the same temperature, wrong-class probability ratios as similarity structure, and a weighted sum of soft-target and hard-label cross-entropy with T² scaling. With the teacher fixed, the page's KL form differs from soft-target cross-entropy only by a constant, and the small math, code and demo compute the tau-softmax, the tau² KL term, the pull on non-label classes and the hard/soft mixture.

Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.

Practice · Knowledge Distillation: Learning from Teachers

Try the idea in your own words

Knowledge distillation trains a student, usually smaller, to match a teacher's temperature-softened output probabilities, often alongside the true labels. The probabilities the teacher gives to wrong classes show which classes it treats as similar, which hard labels omit.

Concept · Selected for practice

Knowledge Distillation: Learning from Teachers

What it rests on: Sources: Distilling the Knowledge in a Neural Network; Sequence-Level Knowledge Distillation; Deep Learning

Context and links
Choose a task

Explain the mechanism

For Knowledge Distillation: Learning from Teachers: What is the smallest example of Knowledge Distillation you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Your draft stays on this page and is cleared when you leave or reload.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.

    Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
    Ask about this pageClose
    ConceptKnowledge Distillation: Learning from TeachersSources: Distilling the Knowledge in a Neural Network; Sequence-Level Knowledge Distillation; Deep Learningz = z / tau

    Your question

    Choose what your question is about

    Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptEfficiency

    Knowledge Distillation: Learning from Teachers

    Starting question

    What is the smallest example of Knowledge Distillation you can work through by hand, and what does it show?

    SourcesCheck the 3 cited sources listed under Sources.Notes can be saved for this item
    Points of view on this item

    Fixed prompts generated from this item. They are not comments from people or independent reviews.

    Learner’s first stepAsk what would make "Knowledge Distillation: Learning from Teachers" feel predictable rather than familiar.
    Assumption

    The 3 cited sources must support this exact item, not just the surrounding topic.

    Source-checking summary

    Connect the definition to one equation, piece of code or demo before widening the discussion.

    Proposed experiment

    Change one input, then check that the same relationship holds in the mathematics, the code and the demo.

    Next action

    You can state the mechanism in your own words

    Evidence4 checks
    ObservationChecking for a saved observation
    ActionReady for one action
    PromptLearner prompt ready to copy
    Go to this item
    01ObservationChecking what this browser has saved
    02EvidenceChecking for a saved observation
    03SourcesCheck the 3 cited sources listed under Sources.
    04Next stepSave one next action
    Local action draftNo local draft saved yetOpen when you are ready to write one next action
    Local action draft

    This draft stays in this browser and is attached to this item only.

    No local draft saved.
    Evidence to inspect
    • What the 3 cited sources say about this exact item
    • The definition, its prerequisites, and a contrasting concept
    • The equation or code that makes the concept concrete
    • One demo state that shows what stays the same as the inputs change
    What would resolve this
    • You can state the mechanism in your own words
    • You can name the prerequisite that would clear up the confusion
    • You can predict how the result changes when one input changes
    Reference idconcept/concept-notebook/efficiency/knowledge-distillation concept:efficiency/knowledge-distillation