Unit 8 of 10 · about 5 hours · derive, implement
Logit distillation, temperature and KL direction, and feature distillation
The Math Foundations unit on entropy, cross-entropy, KL divergence and mutual information established the identities. Here the teacher signal, temperature and token alignment decide which objective the student actually learns.
You'll be able to
- Derive masked soft-target distillation with temperature, hard-label mixing and an explicit KL direction.
- Implement a stable loss whose values and gradients match an independent finite-vocabulary reference.
- Define a feature-distillation alignment contract for teacher layers, token positions, widths and gradient ownership.
Covers
Read
In this order, only the parts listed
0 of 2 done
- Distilling the Knowledge in a Neural NetworkDistilling the Knowledge in a Neural Network (Hinton et al., 2015)
Sections 1 and 2, especially Equation 1, hard/soft objective mixing, and Section 2.1, Equations 2 to 4
Stop before Section 3's MNIST experiments. The high-temperature centered-logit argument is an approximation, not an identity at finite temperature.
- Modern LLM Notebook 17: logit and feature signalsModern LLM Notebook - LoRA, Distillation and OPD
Section 2, Method 1: Logit Distillation; Section 4, Method 3: Feature Distillation; Exercises 1 and 2
Skip the API and 7B training recipe in Section 5. Section 4's GPT-4 layer diagram is illustrative, not verified access to that model's hidden states.
Focus on
- For teacher logits and student logits , define , . Use the valid-token mean of . State the hard-label source, mask, temperature and mixture weight.
- The teacher is frozen and detached. In PyTorch 2.14.1,
torch.nn.functional.kl_divtakes student log probabilities as its input and teacher probabilities as its target for teacher-to-student KL. Usereduction='none', sum over vocabulary, then apply the valid-token mask and denominator. - The scaled soft-loss gradient with respect to student logits is . The multiplier compensates the high-temperature gradient shrinkage approximately; it does not make all temperatures equivalent.
- Feature matching requires accessible teacher activations, declared layer pairs, aligned token positions and a learned projection when widths differ. Mask invalid positions before reducing. Matching hidden coordinates is an extra constraint, not implied by matching output probabilities; different tokenizers need an alignment method or a text-level route.
Common mistakes · 3
- Using a batch mean that also divides by sequence length or vocabulary size. Specify the vocabulary sum and valid-token mean explicitly.
- Equating low teacher probability with factual wrongness. Soft targets encode the teacher's beliefs and errors; held-out task quality remains a separate outcome.
- Matching vocabulary indices across different tokenizers. Equal vector lengths are not enough; each coordinate must refer to the same event at an aligned prefix.
Try it yourself
Closed-book, before checking anything
torch.autograd.gradcheck. Add a tokenwise linear projection from width 4 to width 6 and verify that a masked feature-loss position has zero direct feature-loss gradient with respect to its student hidden state.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why do soft-target cross-entropy and forward KL have the same student gradient with a fixed teacher?Answer
They differ by teacher entropy, which is independent of student parameters at the fixed prefix. Detach the teacher and keep the same temperature and reduction.
2.Is the reverse-KL student-logit gradient also student probability minus teacher probability?Answer
No. At temperature 1 and a fixed prefix it is . The familiar belongs to forward KL with a fixed teacher.
3.What does increasing temperature do to a fixed finite-logit distribution?Answer
It makes it softer, approaching uniform as temperature grows. The scaled loss can still retain centered-logit differences in its high-temperature limit; a flatter probability vector does not prove the scaled learning signal vanishes.
4.Does masking one hidden-state position mean its input token can have no gradient?Answer
No. It removes that position's direct feature-loss term. The token may still influence other supervised positions through attention and receive an indirect gradient.
Practice
- Modern LLM Notebook 17: temperature and hand-KL exercises
Exercise 1, Effect of temperature on soft labels; Exercise 2, KL divergence by hand
Use the supplied three-logit and three-probability inputs. Add your own reverse-direction, gradient, masking and zero-valid-target tests; the exercise cells do not establish those properties. The section mini-project covers the projected-feature oracle and a no-distillation control.
You're done when
Both KL values and the gradient checks pass, temperature and token reductions are explicit, and your feature-loss test distinguishes a masked direct term from indirect attention gradients.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 17 more in the section
- Distilling the Knowledge in a Neural Network (Hinton et al., 2015)Google · reference
Read Sections 1 and 2 for the temperature-softened softmax and the mix of soft and hard targets that later distillation methods reuse.
- Modern LLM Notebook - LoRA, Distillation and OPDWalking Labs · support
Use
notebooks-en/part2-training/16-lora.ipynb,17-distillation.ipynbandnotebooks-en/part4-frontiers/31-opd.ipynbfor compact implementations. Derive the objectives from MiniLLM and GKD rather than the notebooks, and scale the 7B distillation example down.
Also in this section
- RLHF Book - Training Overview, Instruction Tuning and Synthetic DataNathan Lambert · primary
Read Chapter 3 (training overview and canonical recipes; no exercises), Chapter 4 (instruction tuning,
04-instruction-tuning.html) and Chapter 12 (synthetic data and distillation,12-synthetic-data.html). Do the Suggested Experiments in Chapters 4 and 12 at a scale that fits your GPU. Use the recipe maps to separate continued pretraining, SFT, rejection sampling and distillation before selecting an intervention. - CS336 Assignment 5 Supplement - SFTStanford University · required
Do supplement Sections 3 and 4: zero-shot baselines,
look_at_sft,get_packed_sft_datasetand the SFT script, with the data tests passing on CPU. The handout fine-tunes Llama 3.1 8B on B200s and judges with a 70B model; use a small open model that fits your GPU and rule-based scoring on fixed MMLU and GSM8K subsets, and keep the evaluation identical before and after. - LoRA: Low-Rank Adaptation of Large Language ModelsMicrosoft Research · required
Read Section 4 and Figure 1 (Section 3 explains why adapters add latency): derive the low-rank update, the alpha over r scale, the zero initialization of B and the parameter count, then implement LoRA for selected decoder linear layers and test that the merged weights reproduce the adapter output. The paper adapts attention only; later work finds the MLP layers matter.
- LoRA Learns Less and Forgets Less (Biderman et al., 2024)Columbia University and Databricks · required
Read Section 3 and Sections 4.1 to 4.7 with Figures 2 to 4: on code and math, full fine-tuning learns more of the target and forgets more of the source, and LoRA rank controls the trade-off. Slice forgetting on your own evaluations.
- LoRA Without RegretThinking Machines Lab · support
Read "What matters", the rank, batch-size and layer results, and "Setting LoRA hyperparameters": all-layer LoRA at high rank matches full fine-tuning loss, the best LoRA learning rate is about ten times higher, and large batches hurt LoRA more. The curves are log loss, not sampled evaluations.
- QLoRA: Efficient Finetuning of Quantized LLMsUniversity of Washington · reference
Read the method and memory-analysis sections only after plain LoRA passes. Use it to explain quantized-base adaptation and its numerical assumptions, not as a mandatory large training run.
- Hugging Face LLM Course Chapter 11 and smol-course Unit 1Hugging Face · support
Work through 11.2 (chat templates), 11.3 (SFT with TRL) and 11.4 (LoRA with PEFT) on SmolLM2-135M, then smol-course Unit 1 for an SFT, LoRA and evaluation loop. TRL 1.15.0 trains on the whole sequence unless you set
assistant_only_loss=True, and the template must expose assistant spans for that to work. - MiniLLM: Knowledge Distillation of Large Language Models (Gu et al., 2024)Tsinghua and Microsoft Research · support
Read Section 2.1 (reverse KL from student to teacher, and why it is mode-seeking) and Section 2.2 (the on-policy gradient and its stabilizers). It needs white-box teacher log probabilities.
- On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes (Agarwal et al., 2024)Google DeepMind · support
Read Sections 3 and 4 with Algorithm 1: the student-data fraction lambda mixes fixed data with student samples, and the divergence is a choice. Budget the extra student rollouts and teacher scoring per step.
- On-Policy DistillationThinking Machines Lab · support
Read the loss (per-token reverse KL on student samples), the pseudocode and the reasoning and personalization results. Teacher and student share a tokenizer and lineage there; the FLOP ratios are estimates.
- Tulu 3, Sections 3 and 4 (data and supervised fine-tuning)Allen Institute for AI · support
Read Section 3 (prompt curation and decontamination) and Section 4 (the SFT mix, data experiments and recipe) as an auditable data contract to imitate at small scale, not a scale to reproduce.
- Don't Stop Pretraining: Adapt Language Models to Domains and Tasks (Gururangan et al., 2020)Allen Institute for AI · support
Read Sections 3 and 4: domain-adaptive and task-adaptive continued pretraining before fine-tuning. Compare continued pretraining with SFT at matched tokens and a fixed evaluator.
- Build a Large Language Model (From Scratch), Chapter 7 and Appendix ESebastian Raschka / Manning · support
Use Chapter 7 (SFT, pp. 204-249) and Appendix E (LoRA, pp. 322-336) for the smallest full SFT and LoRA run. The chapter trains on instructions too by default; Exercise 7.2 (p. 223) is the masked variant, and there is no packing.
- Build a Reasoning Model (From Scratch), Chapter 8Sebastian Raschka / Manning · support
Use Chapter 8 (pp. 267-304: generating and filtering a distillation set, losses, training loop and evaluation) as a runnable 0.6B sequence-distillation baseline with provenance.
- TensorTonic - Assistant-Only SFT Loss MaskTensorTonic · support
Solve Build an Assistant-Only SFT Loss Mask (
cs336-l15-assistant-only-sft-mask). It takes role ids, so add your own tests for chat-template parsing, multi-turn roles, truncation, packed examples and special-token boundaries. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution. - RLHF Book Code - Instruction Tuning and DistillationNathan Lambert · support
Read
instruction_tuning/train.pyandutils.py(it masks all but the final assistant turn) anddistillation/loss.py. The default configs use 1B to 1.7B models and long contexts; cut the model, context and sample count to fit your GPU, hold the data and evaluator fixed, sweep one variable and compare with a no-distillation baseline. - PEFT conceptual guide: Soft promptsHugging Face · reference
Read Prompt tuning and Prefix tuning only (page read 2026-10-16). These supply the optional soft-prompt mechanisms missing from the section pool; no extra training run is required.