Adaptation and Distillation

Adaptation is a data, objective and deployment choice. This stage compares supervised, low-rank and distillation routes while proving masks, merges, forgetting and end-to-end cost.

Section 6 of 11 · 10 units · about 46 hours

0/10

By the end you can Produce a tested SFT or continued-pretraining baseline plus one low-rank or distillation route; prove masks, trainable state and merge behavior; and show quality, forgetting, memory and latency under the same evaluator and inference budget.

Units

Build it

Mini project · about 16 to 22 hours

Adaptation with checked masks, adapters and teacher signals

Extend lmlab in adapt/ with tested full-SFT and LoRA paths, retention controls and a bounded distillation mechanism study. Use the existing model family, lineage and frozen evaluator to decide whether adaptation is worth its training and deployment costs on your machine, without paid teacher APIs.

  1. 1Prespecify the adaptation question, target and retention slices, matched budgets and stop rules in registry/. Plan frozen, prompted and smaller instruction-model baselines against the existing evaluator; independently recount parameters and estimate FLOPs before approving a CPU or single-GPU run plan.
  2. 2Build the conversation schema and pinned tokenizer/template manifest in adapt/. Check train-serve token equality, malformed roles and truncation against template serialization; pass TensorTonic assistant-mask cases, then retain independent shifted-target, stop-token, denominator, accumulation and packed-versus-separate attention-isolation oracles in tests/.
  3. 3Implement counted LoRA factors on the existing decoder using Modern LLM Notebook 16's corrected exercises. Check dense-update forwards and finite-difference gradients before training; retain frozen-base, initialization-gradient, state round-trip, wrong-base rejection and merge/unmerge regressions with declared precision-dependent tolerances.
  4. 4Build an offline teacher-text manifest with source-group splits, provenance and filter counts. Extend Modern LLM Notebook 17's exercises with full-vocabulary KL-gradient and projected-feature oracles; retain detached teacher, mask and reverse-KL enumeration tests, then a bounded categorical student-prefix update loop with a no-distillation control.
  5. 5Run bounded full-SFT and LoRA controls only after preflight, checking resumed updates against uninterrupted training. Reconcile post-update tensor-state counts and a context-length memory sweep with measured peaks or CPU storage accounting; retain residual explanations, storage/compute dtype ledgers and a deployment-compatibility decision about quantization.
  6. 6Compare target-only adaptation with replay at matched total input tokens across seeds, using the frozen eval/ suite. Retain per-source input and supervised exposure, paired item uncertainty, seed spread and learning-retention plots; investigate regressions against unchanged-model template and parser controls rather than assuming forgetting.
  7. 7Rebuild a matched quality, retention, training/serving-memory, latency and update-cost table from raw records in a clean process. Include no-training baselines, merged/unmerged adapters, prefill/decode and teacher/filter/rollout costs; retain failed runs and a deployment verdict. Optional common-base task merges require independent arithmetic and behavior regressions.
What you hand in
  • The adapt/ serializers, full-SFT and LoRA paths, distillation fixtures and independent objective, export and resume tests.
  • Teacher-data, template, checkpoint and adapter manifests linked to registry/, including all failed attempts.
  • Reproducible learning-retention plots, memory reconciliation and deployment decision with complete training, teacher and inference costs.
How to check it
How it's graded

Objective and state correctness

Pass: Your template, shifted-mask, denominator and packed-attention oracles pass; dense-update and finite-difference checks validate LoRA before training, with frozen-base, export, wrong-base and resume regressions.

Great: Injected template shifts, cross-example leakage and duplicate merges fail independently; nonzero adapters preserve logits through serialization and export under justified precision-dependent tolerances.

Teacher signal ownership

Pass: Independent KL and projected-feature gradient checks pass; teacher provenance, source-group splits and filtering are recorded, and the detached student-prefix loop retains a matched no-distillation control.

Great: Exact enumeration distinguishes forward from reverse KL and detached visitation from a full trajectory derivative; teacher errors and unknown provenance explicitly limit the claim.

Adaptation decision evidence

Pass: Matched full-SFT, LoRA, replay and no-training controls retain seed variation, paired retention, state/peak residuals, dtype compatibility and complete costs; a clean process rebuilds the decision and failures.

Great: The verdict separates learning from elicitation and retention from exposure, explains when plain LoRA suffices, and distinguishes measured resource savings from estimates and unsupported deployment claims.

Resources

  • RLHF Book - Training Overview, Instruction Tuning and Synthetic DataNathan Lambert

    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

    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

    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

    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

    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.

  • Hugging Face LLM Course Chapter 11 and smol-course Unit 1Hugging Face

    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

    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

    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

    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

    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

    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

    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

    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.

  • Modern LLM Notebook - LoRA, Distillation and OPDWalking Labs

    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

    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

    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.

  • QLoRA: Efficient Finetuning of Quantized LLMsUniversity of Washington

    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

    Read Sections 1 and 2 for the temperature-softened softmax and the mix of soft and hard targets that later distillation methods reuse.

  • PEFT conceptual guide: Soft promptsHugging Face

    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.