Macalinao StudioLearnAll enriched lessons ↗
College path · 7 sectionsSwitch to high school ↗

College / LONGER LESSON distillation

Knowledge distillation: teach a student from model behavior

Compare hard and soft targets, calculate a temperature-scaled objective, take a student step and evaluate transfer beyond teacher imitation.

Preparation: Probabilities, softmax, cross-entropy and gradient steps.

Plan 25–40 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.

Section 01 / 07

Transfer behavior rather than copy weights

College path. Compare hard and soft targets, calculate a temperature-scaled objective, take a student step and evaluate transfer beyond teacher imitation. Preparation: Probabilities, softmax, cross-entropy and gradient steps. Move between Signal Room, Workbench and Field Notes without losing your section. Pause before each worked solution.

Knowledge distillation trains a student using information supplied by a teacher model or ensemble. The teacher may provide probabilities, generated answers or intermediate representations. The student is often smaller, but smaller size is not part of the definition: the training relationship is what matters. Unlike LoRA, distillation does not inherently freeze a shared base and add a low-rank branch. Unlike quantization, it does not inherently encode the same weights with fewer bits. These techniques can be combined, but they solve different problems.

Teacher and student can have different architectures. The training objective specifies which outputs or representations should agree and on what input distribution. Capacity, data coverage and optimization determine what transfers. A teacher’s output is supervision, not guaranteed ground truth, and perfect imitation is not guaranteed or always desirable.

Worked example. Imagine a teacher ranking three possible labels rather than supplying only the winning label. A student can learn which alternatives the teacher considers plausible. That extra structure may guide learning, but it can also pass along a teacher’s mistakes. Evaluate the student against the task, not merely against teacher agreement.

Teacher behavior + training data + student objective → learned student

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Must a distilled student contain a copy of the teacher’s weight matrices?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. It learns from a specified teaching signal and can use different weights and architecture. Copying a model file is not distillation.

Section 02 / 07

Hard labels hide relationships among alternatives

A hard label identifies one target class. A soft target gives a probability distribution across classes. Two teachers can choose the same top class while disagreeing strongly about the alternatives. Those differences can contain useful information about similarities or uncertainty. They are not automatically calibrated probabilities of truth. When a student learns from soft targets, it is encouraged to match more than the winning answer. That changes the training signal, but does not remove the need for trustworthy examples and held-out evaluation.

For a fixed teacher distribution p and student distribution q, soft cross-entropy is minus the sum of p_i log q_i. Forward KL divergence is the sum of p_i log(p_i/q_i). They differ by the teacher entropy, which is constant with respect to student parameters when the teacher is fixed. Thus their student gradients agree under those conditions.

Worked example. Teacher distributions [0.7,0.2,0.1] and [0.7,0.1,0.2] have the same top class and confidence, but reverse the ordering of the alternatives. A hard-label target [1,0,0] erases that distinction. Soft-target learning can retain it if the student has capacity and the data supports the pattern.

KL(p∥q)=Σ p_i log(p_i/q_i); CE(p,q)=−Σ p_i log q_i

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Does matching the teacher’s top label prove the student matches its probability distribution?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. Many different distributions share the same largest entry. Compare the full intended teaching signal when assessing imitation.

Section 03 / 07

Use temperature to reveal a softer distribution

Softmax converts logits into probabilities. Distillation commonly divides logits by a positive temperature before applying softmax. A higher temperature makes a fixed set of finite logits produce a flatter distribution, exposing more weight on alternatives. Both teacher and student use the same chosen temperature for the soft-target comparison. This training temperature is separate from the settings used to generate final answers. It does not make the teacher more knowledgeable or correct; it changes how its scores are presented to the learning objective.

Define p_T=softmax(z_teacher/T) and q_T=softmax(z_student/T). At positive finite T, ordering of logits is preserved. As T increases without bound, a fixed finite logit vector approaches a uniform distribution. Adding a common constant to every logit does not change softmax. Stable calculations subtract the maximum before exponentiating.

Worked example. For teacher logits [2,1,0], temperature one gives approximately [0.665241,0.244728,0.090031]. At temperature two the distribution becomes approximately [0.506480,0.307196,0.186324]. The top class is unchanged, but the alternatives receive more probability mass.

p_T(i)=exp(z_i/T)/Σ_j exp(z_j/T)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Does increasing temperature change which class has the largest probability for distinct fixed logits?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No, provided temperature remains positive. It changes relative concentration while preserving the ranking. Ties remain ties.

Section 04 / 07

Combine a soft objective with a hard target

A common teaching objective combines hard-label cross-entropy with a teacher-matching term. Our example uses hard label class zero, ordinary student probabilities at temperature one, and a forward KL term at temperature T. A mixing weight lambda controls their relative contribution. Multiplying the soft term by temperature squared compensates for a common temperature-related gradient scaling effect; it is part of the stated objective, not a universal requirement for every distillation method. Always write down the precise loss before comparing experiments.

Our loss is (1-lambda) times hard cross-entropy plus lambda times T squared times KL(p_T∥q_T). With fixed teacher, its derivative with respect to student logit j is (1-lambda)(q_1,j-y_j)+lambda T(q_T,j-p_T,j). The factor T follows differentiation through logits divided by T. Other formulations may use different weighting or losses.

Worked example. Set lambda to zero: only the hard label contributes. Set lambda to one: only the scaled soft matching term contributes. Intermediate values combine the two. At student logits equal to teacher logits, the soft KL is zero, but a hard-label term can still have nonzero loss because the teacher distribution is not one-hot.

L=(1−λ)CE(y,q_1)+λT² KL(p_T∥q_T)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Does zero soft KL imply that the total mixed loss is zero?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. The hard-label component may remain positive. Inspect the objective’s separate components rather than treating one metric as the entire training goal.

Section 05 / 07

Take a small student step and inspect its limit

Workbench fixes teacher logits at [2,1,0] and gives the student logits [u,0,0]. Only u is adjustable. This intentionally limited student always assigns equal probability to its second and third classes, even though the teacher does not. Calculate the loss, inspect the gradient, then simulate one gradient step on u. A lower loss on this one example demonstrates a local optimization step, not a trained language model. The student’s inability to represent the teacher distribution exactly is visible before any large experiment.

For learning rate eta, update u_new=u-eta times the first component of the mixed-loss gradient. The fixture changes only the first logit; it does not update the other two. A finite-difference derivative can independently check the analytic gradient. Learning-rate stability and representational capacity are different concerns.

Worked example. At u=0 the student is uniform. With temperature one, lambda one and learning rate one half, the first-logit gradient is approximately minus 0.331908. The updated u is about 0.165954. Probability moves toward the teacher’s preferred class, but classes one and two still have equal student probability.

u_new = u − eta ∂L/∂u; other two logits remain zero

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Why can this student fail to achieve zero teacher-matching loss even after optimization?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

Its constrained logits cannot represent the teacher’s unequal probabilities for the last two classes. More optimization cannot remove that representational restriction.

Section 06 / 07

Distinguish token probabilities from generated examples

In language models, distillation can compare next-token distributions on a shared context or train on sequences produced by a teacher. These are different supervision signals. A generated answer preserves one chosen sequence, not the full distribution of possible next tokens at every step. Sequence-level distillation can be useful, but it does not automatically reproduce soft-logit matching. Different tokenizers further complicate direct probability comparisons. Specify what the teacher supplies, how it is filtered, and how the student consumes it.

Direct token-level KL requires compatible support or an explicit alignment method. Sequence-level training can use teacher-generated text with ordinary next-token likelihood, but sampling, decoding and filtering alter the resulting data distribution. Intermediate-feature distillation needs its own mapping when architectures differ. Our three-class fixture assumes aligned labels and does not simulate these alignment problems.

Worked example. If a teacher generates a single answer, the student can learn from that text even when teacher logits are unavailable. It cannot reconstruct every unchosen alternative probability from the answer alone. Compare that setting with an interface that provides the full aligned vocabulary distribution; they support different objectives.

Generated sequences, token distributions and hidden features are distinct targets

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Is training on teacher-written answers identical to matching full teacher probabilities?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. The available information and objective differ. Generated text is a selected sample or decoded sequence, while soft targets expose a distribution under specified contexts.

Section 07 / 07

Evaluate usefulness, errors and the cost of teaching

Measure student performance on held-out data, including cases where the teacher is wrong or uncertain. Compare against a student trained without the teaching signal, and inspect whether benefits persist outside the training distribution. Distillation can copy errors, biases or fragile shortcuts. A smaller student may reduce serving cost, but producing teacher targets and training the student also consumes resources. Report quality, memory and latency together, and verify the actual deployment rather than assuming a parameter-count reduction guarantees a particular speedup.

Keep evaluation data out of teacher-generated training sets and record data provenance and applicable usage terms. Assess calibration and important subgroups or failure modes alongside aggregate scores. Distillation does not generally guarantee a student is worse than, equal to, or better than its teacher on every task; outcomes depend on data, objectives and capacity.

Worked example. Compare the Workbench loss before and after one step, then change temperature or lambda and recompute. Label this as a single-example optimization experiment. A real success claim would require many held-out examples and measured deployment behavior. Save your prediction and explain both the observed improvement and the fixture’s remaining capacity limit.

Teacher agreement ≠ task correctness ≠ deployment efficiency

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Why is high teacher agreement insufficient as the only success metric?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

The teacher can be wrong, and agreement may hide failures on the intended task. Evaluate independent task outcomes and resource costs as well as imitation.

Final checkpoint. For the stated T-squared-scaled forward KL, the student-logit gradient is which soft term? Option 1: lambda times T times (student minus teacher probabilities). Option 2: lambda times T squared times logits. Option 3: Always zero at positive T.

Pause and choose an answer before continuing.

Reveal worked solution

Option 1 is correct. Differentiating logits divided by T leaves one factor of T after multiplying by T squared.

LONGER POST-TRAINING LESSONS

Follow demonstrations, rewards and preferences

Worked examples, local narration and connected experiments at your level.

Continue the learning path

Sources and scope

Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.

Reset this college path?

This removes only this path’s notes, progress and experiments from this browser.