Modules / Gen AI / Distillation Lab

Knowledge Distillation in LLMs

Train a small student to imitate a large teacher. Raise the temperature to expose the dark knowledge hidden in the teacher's wrong answers — the signal a plain label can never carry.

Teacher — softened at T

LARGE MODEL

Hard label (one-hot)

WHAT A NORMAL DATASET GIVES YOU

Student — current beliefs

SMALL MODEL

Overview

Train a small student to imitate a large teacher.

In this guide
  1. Dark Knowledge: The Central Idea
  2. Why Temperature Is Key
  3. The Combined Loss
  4. Why It Matters for LLMs
  5. Training a small model to imitate a large one
  6. Temperature, and why it is raised
  7. Distilling language models in detail
  8. The dark knowledge, and what temperature exposes
  9. Guided tour
  10. In one line
  11. Where it fits among the compression methods
  12. Real notes
  13. When to distil
  14. Questions people ask
  15. Recap in one screen

Knowledge Distillation: Teaching a Small Model to Think Big

A large model is accurate but expensive. A small model is cheap but weaker. Knowledge distillation narrows that gap by training the small student to imitate the large teacher — and remarkably, the student often beats an identical model trained on the original labels.

Dark Knowledge: The Central Idea

A training label says "this is a dog" and nothing else. But a trained teacher, shown that same photo, might output dog 0.90, wolf 0.07, cat 0.02, car 0.001.

Those small counts are not noise — they encode likeness structure the label cannot express. A dog resembles a wolf far more than a car. Geoffrey Hinton named this dark knowledge. It is the teacher's whole learned view of how the classes relate. And it is free supervision on each single case. The student trains on two losses at once. One against the hard labels (the standard cross-entropy) and one against the teacher's soft predictions (the KL divergence between the student's and teacher's output distributions). The total loss is a weighted combination: L = alpha * L_hard + (1 - alpha) * T^2 * L_soft. Where T is the temperature and alpha controls the balance. Temperature softens the teacher's output distribution: at T=1 the distribution is peaked (the top class rules), at T=5 the small chances are amplified and the dark knowledge turns visible. The T-squared scaling compensates for the fact that more temperature reduces the size of the gradients. In practice, T between 2 and 20 and alpha between 0.1 and 0.5 are common. For LLMs, distillation much happens at the sequence level. The student learns to match the teacher's token-level chances across a full generation, not just a single classification. DistilBERT (66M parameters) distilled from BERT-base (110M) retains 97% of BERT's speed at 60% of the size and 2x the speed. This page trains a student from a teacher, shows the soft label distribution at else temperatures, and covers the alpha/T tradeoff.

Why Temperature Is Key

There is a catch: a confident teacher's non-target chances are so tiny that they add almost nothing to the gradient. At T = 1 the distribution is nearly one-hot. So the student learns roughly what the plain label now told it.

Raising the temperature in the softmax flattens the distribution and amplifies the ratios between the small vals:

pᵢ = exp(zᵢ / T) / Σ⫺ exp(z⫺ / T)

Drag T from 1 to 6 and watch the runner-up bars rise out of nothing. That is the dark knowledge turning visible — and turning trainable. Both teacher and student are softened by the same T. And the distillation loss is scaled by T² to keep gradient sizes comparable to the hard-label term.

The Combined Loss

In practice the student learns from both sources at once:

L = (1 − α) · CE(student, true label)   +   α · T² · KL(teacher ‖ student)

  • The cross-entropy term keeps the student anchored to ground truth. So it cannot inherit the teacher's mistakes wholesale.
  • The KL divergence term pulls the student's whole distribution toward the teacher's, transferring the likeness structure.
  • α balances them. Typical vals lean toward the teacher, since the soft targets carry strictly more data per case.

Why It Matters for LLMs

Distillation is how most small live models are made. DistilBERT keeps roughly 97% of BERT's speed at 40% of the size and 60% faster inference. The same recipe gave the compact members of most modern model families.

For generative models the idea extends naturally: the teacher's full next-token distribution at each spot is a far richer target than the single token that happened to appear in the text. A tied variant, sequence-level distillation, simply trains the student on text the teacher made.

Training a small model to imitate a large one

Distillation trains a small student model to reproduce the behaviour of a large teacher. The result is a model with a fraction of the parameters that retains much of the teacher's grade on the tasks it was distilled for.

The insight is about what the teacher gives. A hard label says "this is a cat". A teacher's full output distribution says "90% cat, 7% dog, 2% fox, 1% all of it else". And that shape carries data about how the classes relate. This a one-hot label does not.

Those richer targets are called soft labels, and they are why a distilled student much beats the same design trained from scratch on the same data. Each case teaches more.

 Hard labelsSoft labels from a teacher
Information per exampleOne class nameA full distribution
Encodes class similarityNoYes
Student qualityLowerHigher
Requires a teacherNoYes

Temperature, and why it is raised

A confident teacher outputs a thing like [0.99, 0.005, 0.005], which carries almost as little data as a hard label. Dividing the logits by a temperature above 1 before the softmax flattens the distribution and reveals the structure below:

TemperatureDistribution
10.99, 0.005, 0.005
30.79, 0.11, 0.10
50.62, 0.20, 0.18

At T = 3 the relative ranking of the non-target classes turns visible. And that is the sign the student learns from.

The training loss is much a weighted mixture:

loss = α · KL(studentT ‖ teacherT) + (1 − α) · CE(student, hard label)

The first term matches the teacher's soft distribution; the second keeps the student anchored to the ground truth. Typical settings are T between 2 and 5 and α around 0.5–0.9.

Both models must use the same temperature for the KL term. And the student's inference-time temperature returns to 1.

Distilling language models in detail

For generative models, three approaches are used, and they differ in what the student sees.

Logit distillation. Match the teacher's full next-token distribution at each spot. The most informative, and it needs access to the teacher's logits and a shared tokeniser.

Sequence-level distillation. Have the teacher generate outputs, then train the student on them as ordinary text. Works with any teacher — with one behind an API — and discards the distribution data.

Rationale distillation. Have the teacher give reasoning chains and answers, and train the student on both. This transfers some multi-step reasoning that plain answer-matching does not. And it is what "step-by-step distillation" means.

DistilBERT is the well-known encoder case: 40% less, 60% faster, retaining roughly 97% of BERT's speed on GLUE. It used logit distillation plus a hidden-state matching term and an initialisation taken from each else layer of the teacher.

The dark knowledge, and what temperature exposes

Distillation trains a small model on a large one's full output distribution rather than on the correct answer alone. The extra data is in the wrong answers. And the temperature is what makes it readable. Both of which are visible in the counts.

example_01.pyNumPy
Output

Building on the same setup, the next block shows the left cases.

example_02.pyNumPy
Output

The below block covers the left steps.

example_03.pyNumPy
Output

The next block goes on with the left demonstrations.

example_04.pyNumPy
Output

Guided tour

  1. Look at T = 1. The teacher is nearly one-hot and looks almost the same to the hard label. Barely any extra sign.
  2. Raise T to 5. The runner-ups emerge. Note which ones rise: semantically tied classes, never random ones. That sorting is the knowledge being transferred.
  3. Press "Train student" repeatedly and watch KL divergence fall as the student's bars converge on the teacher's shape. With the small ones.
  4. Set α = 0 and retrain from reset. The student matches just the one-hot label; its non-target chances collapse and the likeness structure is lost.
  5. Try the sentiment case. "not bad at all" is truly ambiguous. So the teacher stays unclear still at T = 1. And that calibrated doubt is it worth teaching.

In one line

A hard label answers one question. A teacher's full distribution answers each question at once. How likely each else is, and so how the classes relate. Temperature is the tool that makes that hidden structure large enough to learn from. The student in this lab performs real gradient descent on the combined loss. So the convergence you watch is genuine optimisation, just at a much less scale.

Where it fits among the compression methods

MethodWhat it changesQuality cost
DistillationTrains a smaller architectureModerate, task-dependent
QuantisationStores the same weights in fewer bitsSmall
PruningRemoves weights or headsSmall to moderate
Architecture searchFinds an efficient designVaries

These combine, and the usual live sequence is distil. Then quantise: reduce the parameter count first. Then reduce the bits per parameter. A distilled 1B model quantised to 4-bit runs comfortably on a phone.

The check worth internalising: quantisation is nearly free and gives you a fixed factor of memory. Distillation costs a training run and can give you a model an order of size less. But just for the behaviour you distilled.

That caveat matters. A student distilled on customer-support conversations will handle customer support well and may be markedly worse at a thing else. Distillation narrows as it shrinks, which is much just what a live task wants.

Real notes

Generate teacher outputs once, offline. Running the teacher in each training step is costly; precompute and cache its outputs or logits.

Match the tokeniser for logit distillation. Else vocabularies mean the distributions are over else things and cannot be compared spot by spot.

Initialise the student from the teacher where design allows. Taking each else layer, for instance. It converges much faster than random initialisation.

Distil on the distribution you will serve. The student learns the teacher's behaviour on the prompts you show it. So those prompts should resemble live traffic.

Watch the licence. With a commercial model's outputs to train a competing model is prohibited by a few providers' terms. This is a legal constraint rather than a technical one. And it is a real one.

When to distil

Reach for it when: inference cost or latency is the binding constraint, the task is narrow and well-set, you have or can generate plenty of representative inputs. And you have a strong teacher available.

Do not, when: the task is open-ended and you need broad power, you lack representative prompts, quantising the more model would now meet the budget. Or the licence forbids it.

The honest sorting for most teams: try quantisation first, since it is far cheaper and much enough. Distil when quantisation is not enough and the task is narrow enough to survive the specialisation.

Questions people ask

How much less can the student be? Much 2–10×, with 40–60% reductions retaining most grade on the distilled task.

Do I need the teacher's logits? For logit distillation, yes. Sequence-level distillation works from made text alone, which is what makes API-based teachers usable at all.

What temperature? 2–5. More reveals more structure in confident predictions and in time flattens away the sign.

Can a student beat its teacher? On the narrow distilled task, sometimes. The soft targets regularise. And the less model overfits less. Not broadly power.

Is this the same as fine-tuning? Fine-tuning adapts a model to a task with ground-truth labels. Distillation trains one model to imitate one more. They are much combined.

How much data do I need? More than for fine-tuning, since the student is learning behaviour rather than tuning it. Tens of thousands of cases is typical, and they can be made by the teacher.

Recap in one screen

  • A small student is trained to reproduce a large teacher's output distribution, not just its answers.
  • Soft labels carry data about how classes relate, so each case teaches more than a hard label.
  • Raise the temperature to reveal structure in a confident teacher's distribution.
  • Logit distillation needs the teacher's internals; sequence-level distillation works from made text.
  • Distil then quantise; and expect the student to be narrower and less.

Recall check

0 of 3

Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.

  1. Without scrolling back — what is the one-line takeaway from this module?

  2. What does this module say about “Dark Knowledge: The Central Idea”?

  3. What does this module say about “Why Temperature Is Key”?

Cheat sheet

Knowledge Distillation in LLMs

Train a small student on the teacher's soft probability distribution and recover most of the accuracy at a fraction of the size.

GEN AI · vizlearn.in/gen_ai/knowledge_distillation_in_llms.html

Further reading

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.