Unit 9 of 10 · about 6 hours · implement

Sequence and synthetic-data distillation and on-policy distillation

Offline teacher completions are cheap to reuse but do not expose the student to its own mistakes. On-policy supervision changes the visited prefixes and the compute budget, not automatically the KL direction.

You'll be able to

  • Build an offline sequence-distillation data contract with teacher provenance, filtering counts and leakage-safe splits.
  • Implement a bounded student-rollout and teacher-scoring loop that distinguishes prefix source from divergence direction.
  • Test a fixed-prefix reverse-KL gradient estimator without claiming it differentiates full trajectory visitation.

Covers

Sequence and synthetic-data distillation with teacher provenanceOn-policy distillation and exposure-bias motivation
1

Read

In this order, only the parts listed

0 of 3 done

  1. RLHF Book Chapter 12: synthetic data and distillationRLHF Book - Training Overview, Instruction Tuning and Synthetic Data

    Distillation with Synthetic Data; The Path to On-Policy, Teacher-Student Distillation, subsections Adapting Knowledge-Distillation for LMs and From Offline to On-Policy Distillation

    Read for vocabulary, not a guarantee that generated answers are correct or that imitation-learning bounds transfer unchanged to language models. Headings checked 2026-10-16.

  2. Build a Reasoning Model (From Scratch): offline sequence distillationBuild a Reasoning Model (From Scratch), Chapter 8

    Chapter 8: Section 8.3, pp. 273-275; Section 8.4, pp. 276-284, especially 8.4.3, p. 282; Section 8.6, pp. 286-291; Section 8.7, pp. 291-296; Section 8.8, pp. 296-301, stopping before Section 8.9

    Skip the paid teacher generation in Section 8.2. Inspect a small subset of the pregenerated data in 8.3 or use local synthetic fixtures. Adapt the data and loss logic, not the book's whole-model run; validate masks against the earlier card.

  3. On-Policy Distillation of Language Models: Learning from Self-Generated MistakesOn-Policy Distillation of Language Models: Learning from Self-Generated Mistakes (Agarwal et al., 2024)

    Section 3, Equations 2 to 5; Section 3.1 and Algorithm 1; Section 4, GKD Variants paragraph

    Implement the data-source switch and detached-rollout convention. Do not reproduce the TPU experiments. If you open the Modern LLM Notebook's 31-opd.ipynb, its opening OPD simulation labels the student-minus-teacher gradient as reverse KL; that gradient belongs to forward KL.

2

Focus on

  • Offline sequence distillation is response-only next-token likelihood on teacher-generated text. It needs no teacher logits and can cross tokenizers by retokenizing text. Record teacher checkpoint or supplied provenance, prompt, template, decoding settings, generated text, filter decisions, license and split hashes. Unknown provenance stays unknown.
  • Split by source problem or document before generation and filtering, deduplicate across splits and retain an untouched evaluation set. Correct-answer filtering changes the distribution; log acceptance rates and inspect rejected and accepted traces. A correct final answer does not verify the reasoning trace.
  • GKD chooses a student-data fraction and a divergence separately. On-policy forward KL is valid. Collect fresh student prefixes without gradient through sampled IDs, then score teacher and student on those same prefixes with aligned vocabulary, temperature and EOS masks. GKD's detached visitation update is a semi-gradient, not the full derivative of its displayed expectation.
  • For a fixed prefix, let teacher probabilities be and student probabilities be . A sampled reverse-KL surrogate is , with . Its expected gradient matches the fixed-prefix reverse-KL gradient. This local identity omits future-prefix credit assignment; it is not a full MiniLLM reproduction.
Common mistakes · 3
  • Training the student to imitate its own sampled tokens without a teacher signal. On-policy collection alone supplies no corrective supervision.
  • Calling a negative sampled log-ratio a negative exact KL. An unbiased finite-sample estimate can be negative even when the population divergence is nonnegative; test the expectation and gradient separately.
  • Changing prompt distribution and calling it an exposure-bias fix. Exposure bias here concerns generated prefixes under the same prompts. Cached old student rollouts are off-policy unless explicitly treated as such.
3

Try it yourself

Closed-book, before checking anything

On CPU with PyTorch 2.14.1 float64, enumerate three actions with teacher probabilities and student probabilities . Weight each surrogate by detached student probability. Match its student-logit gradient to exact reverse KL within 1e-12; it is approximately , not . Then use a tiny two-step categorical teacher and student to log fixed-data versus freshly sampled prefix IDs under the same prompts. Show that switching the prefix source does not switch your chosen divergence. Keep masks and teacher parameters fixed and compare against a no-distillation update.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Can offline teacher-text distillation use a different tokenizer?Answer

    Yes, retokenize the text for the student. Direct token-distribution KL cannot compare unrelated vocabulary coordinates without an additional alignment method.

  2. 2.Does a student-data fraction of one imply reverse KL?Answer

    No. It specifies student-generated prefixes. GKD independently chooses forward KL, reverse KL or another divergence.

  3. 3.Why detach the log-ratio coefficient in the sampled surrogate?Answer

    It is the score-function coefficient, not a second differentiable loss factor. At a fixed prefix the expected detached-coefficient gradient equals reverse KL's gradient; differentiating it too changes the estimator.

  4. 4.Why keep evaluation prompts out of generation and filtering?Answer

    Teacher answers, duplicate source problems and filter choices can leak evaluation information into training or selection. Hold out source groups before constructing the distillation data.

You're done when

The section mini-project's distillation evidence includes the finite-vocabulary gradient oracle, a tiny detached-rollout loop, an offline provenance manifest and a matched no-distillation control. A real-model gain is not required to pass these mechanism tests.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 16 more in the 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.

  • 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.

  • 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.

Also in this section

  • CS336 Assignment 5 Supplement - SFTStanford University · required

    Do supplement Sections 3 and 4: zero-shot baselines, look_at_sft, get_packed_sft_dataset and 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.

  • 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.

  • 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 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.

  • Modern LLM Notebook - LoRA, Distillation and OPDWalking Labs · support

    Use notebooks-en/part2-training/16-lora.ipynb, 17-distillation.ipynb and notebooks-en/part4-frontiers/31-opd.ipynb for compact implementations. Derive the objectives from MiniLLM and GKD rather than the notebooks, and scale the 7B distillation example down.

  • 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.py and utils.py (it masks all but the final assistant turn) and distillation/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.