Lecture 8 · Fine-Tuning and Distillation

Advanced Natural Language Processing · Lecture 08。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 8 (02/05), slides anlp-s2026-08-finetuning.pdf; course demo code 08_finetuning/ (finetuning_classification.ipynb: SmolLM2-135M with a classification head counts the vowels in a name; finetuning_lm.ipynb: SmolLM2-135M fine-tuned to reverse names, then tested with rephrased prompts). Readings: E. Hu et al., LoRA: Low-Rank Adaptation of Large Language Models (2021); Y. Kim & A. Rush, Sequence-Level Knowledge Distillation (2016). Additional: J. Howard & S. Ruder, ULMFiT (2018); S. Mishra et al., Cross-Task Generalization via Natural Language Crowdsourcing Instructions (2021); J. Wei et al., Finetuned Language Models Are Zero-Shot Learners (FLAN, 2021); Y. Wang et al., Super-NaturalInstructions (2022); Y. Wang et al., Self-Instruct (2023); S. Mukherjee et al., Orca (2023); P. West et al., Symbolic Knowledge Distillation (2022); T. Dettmers et al., QLoRA (2023). Sources: the public slides, the readings, and the papers cited in each section. Every number labelled “measured” comes from code/lecture08/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code: code/lecture08/ — every demo runs in under two minutes. Reading time: ~110 minutes for the prose; ~40 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Define supervised fine-tuning for classification (a new head) and for generation (a response loss with the prompt masked out).
  2. Choose which parameters to update — head only, all, or a parameter-efficient subset — and predict the trade-offs in accuracy, cost and forgetting.
  3. Derive LoRA, count its parameters, explain its initialization, scaling and merging, and explain why a low-rank update is enough.
  4. Explain what fine-tuning does to the distribution a model represents (“narrowing”), and its symptoms.
  5. Describe instruction tuning (FLAN, Super-NaturalInstructions, Self-Instruct) and chat tuning, and what instruction tuning adds to a base model.
  6. Write down token-level and sequence-level knowledge distillation as KL minimization, explain synthetic-data distillation, and explain how an augmented teacher lets a student surpass it.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 6 (pretraining, linear probe vs fine-tuning, forgetting), Lecture 7 (prompting, chat templates), Lecture 5 (Transformer layers, Adam), Lecture 3 (teacher forcing, cross-entropy).
  • Scope: adapting a pretrained model by gradient-based training on task data; transferring a model’s behavior into another model.
  • Not in scope: learning from preferences and rewards (RLHF, DPO, RL with verifiable rewards — Lectures 16–17); quantization itself (Lecture 19; QLoRA is mentioned here).

0.3 Section → code map

SectionIdeaDemo in code/lecture08/
§2.2–2.6head only vs full vs LoRA on two tasks; forgetting; merging; the rank of the full update01_finetune_and_lora.py (+ finetune.py)
§2.3, §2.7, §3LM fine-tuning with loss masking; format dependence; instruction tuning on k skills → held-out skills; a control without pretraining; three pretraining seeds02_instruction_tuning.py (+ skill_world.py)
§4token-level vs sequence-level distillation; synthetic data on new inputs; a teacher augmented with a verifier03_distillation.py

0.4 Notation

SymbolMeaning
θ0\theta_0pretrained parameters; θ\theta parameters during fine-tuning
D={(x,y)}\mathcal{D} = \{(x, y)\}fine-tuning data: input (prompt) and output (label or response)
W0∈Rd×d′W_0 \in \mathbb{R}^{d \times d'}a frozen pretrained weight matrix
A∈Rr×d′A \in \mathbb{R}^{r \times d'}, B∈Rd×rB \in \mathbb{R}^{d \times r}LoRA factors; rr the rank, α\alpha the scaling numerator
qqthe teacher model; pθp_\theta the student

1. Recap, and today’s plan

  • Lecture 6 — pretraining: data → pretrain → a base model, to be adapted to many tasks.
  • Lecture 7 — prompting: adapt without changing any weight: base model + prompt → translation, sentiment analysis, instruction following, problem solving.
  • Today — fine-tuning: adapt by training: base model + task data (e.g. Japanese–English sentence pairs) → a fine-tuned model.

Three parts:

  1. Fine-tuning basics — what is trained, on what loss, and with how many parameters.
  2. Instruction tuning — fine-tuning on many tasks at once so that the model follows instructions, and chat tuning.
  3. Knowledge distillation — fine-tuning on data produced by another model.

2. Fine-tuning basics

2.1 Definition

Fine-tuning (微调): continued gradient-based training of a pretrained model. Given pretrained parameters θ0\theta_0 and data D={(xn,yn)}n=1N\mathcal{D} = \{(x_n, y_n)\}_{n=1}^N, solve

θ∗=arg⁡min⁡θ E(x,y)∼D[L(fθ(x),y)],starting from θ=θ0,\theta^* = \arg\min_\theta\ \mathbb{E}_{(x,y)\sim\mathcal{D}}\big[\mathcal{L}(f_\theta(x), y)\big], \quad\text{starting from } \theta = \theta_0,

plus techniques to prevent overfitting (regularization, dropout, early stopping). The data are labelled examples, so this is called supervised fine-tuning (SFT, 有监督微调). The starting point is what makes it different from training from scratch: the optimum is searched for near θ0\theta_0.

2.2 Classification fine-tuning

Given a sequence model fθ0(x1,…,xT)→h1,…,hTf_{\theta_0}(x_1, \dots, x_T) \to h_1, \dots, h_T with pretrained weights:

  1. Add an output head on a hidden state: pθ(y∣x)=softmax(Wh+b)p_\theta(y \mid x) = \mathrm{softmax}(W h + b), with W∈RK×dW \in \mathbb{R}^{K \times d}, b∈RKb \in \mathbb{R}^K.
  2. Choose hh. For a causal LM, use the last position, the only one that has read the whole input. Or average the positions.
  3. Train with cross-entropy −log⁡pθ(y∣x)-\log p_\theta(y \mid x). By default update all parameters, θ=(θ0,W,b)\theta = (\theta_0, W, b).

The course notebook does exactly this with SmolLM2-135M, to predict how many vowels a name contains (11 classes). Lecture 6’s demo 02 did it for sentiment.

2.3 Language-model fine-tuning

For a generation task the data are text pairs: xx an input text, yy an output text. The model reads the concatenation and is trained on

LMLE=−∑t=1∣y∣log⁡pθ(yt∣x,y<t).\mathcal{L}_{\mathrm{MLE}} = -\sum_{t=1}^{\lvert y\rvert}\log p_\theta(y_t \mid x, y_{<t}).

The slide’s toy example reverses a string: [start] a b c [sep] c b a [end]. The loss covers only the output tokens (“c b a [end]”). Positions inside the prompt get the ignore label −100, the same trick Lecture 3 used for padding. This is loss masking (finetune.sft_example builds such pairs). It keeps the model from spending capacity on generating prompts. The course notebook fine-tunes SmolLM2-135M on “Reverse the name: emma. Answer: amme”. HuggingFace’s run_clm_no_trainer.py is the standard script for the same loop.

2.4 Should I fine-tune all parameters?

The slides list three options:

optiontrainable parametersassumption / effect
1. only the output head (W,b)(W, b)K×d+KK \times d + K — cheapthe pretrained representations are good, e.g. linearly separate the labels
2. all parameters∣θ∣\lvert\theta\rvert (1M, 1B, 100B, …) — expensivechanges the representations; may overfit
3. a small number of parameters inside the model≪∣θ∣\ll \lvert\theta\rvert — cheapercan change the representations: parameter-efficient fine-tuning (PEFT)

Measured (demo 01). A base model pretrained on review pages (Lecture 6’s recipe, 256k parameters) is fine-tuned with 500 labels for two tasks:

  • Sentiment (3 classes). Pretraining already made this easy to read off, because review pages end with “rating :”.
  • Phenomenon (8 classes). Which of Cinema World’s linguistic phenomena decides the label: plain, negation, contrast, idiom, …? Nothing in pretraining asked for this.
methodtrainable (sentiment)sentiment acc.forgettingphenomenon acc.forgetting
from scratch (no pretraining)256,51563.8%—87.1%—
head only19570.7%+0.00086.0%+0.000
full fine-tuning256,51573.4%+0.11893.7%+3.394
LoRA r=1, WqWvW_q W_v70771.1%+0.00574.2%+0.475
LoRA r=4, WqWvW_q W_v2,24369.5%+0.02085.5%+1.311
LoRA r=16, WqWvW_q W_v8,38771.8%+0.05188.7%+2.965
LoRA r=4, all linear layers9,90772.4%+0.04892.9%+3.146

(“Forgetting” is defined in §2.6.) Two lessons:

  • When the representation is already right, a head is enough. For sentiment, all methods are within 4 points (69.5–73.4%).
  • When it is not, the representation must change. For phenomena, a head gets 86.0% and full fine-tuning 93.7%. LoRA on every linear layer reaches 92.9% while training about 4% of the parameters.

Pretraining also helps a task it never targeted: 93.7% fine-tuned vs 87.1% from scratch on the same 500 labels.

2.5 LoRA: low-rank adaptation

Idea (Hu et al., 2021). Keep each pretrained weight matrix W0∈Rd×d′W_0 \in \mathbb{R}^{d \times d'} frozen, and learn an update of low rank rr:

W=W0+ΔW=W0+αr BA,B∈Rd×r, A∈Rr×d′, r≪min⁡(d,d′).W = W_0 + \Delta W = W_0 + \frac{\alpha}{r}\, B A, \qquad B \in \mathbb{R}^{d\times r},\ A \in \mathbb{R}^{r \times d'},\ r \ll \min(d, d').

  • Only AA and BB are trained: r(d+d′)r(d + d') parameters per matrix instead of dd′d d'. For d=d′=4096d = d' = 4096 and r=8r = 8, that is 65,536 instead of 16.8 million, 256× fewer.
  • Initialization. B=0B = 0 and AA random, so at the start ΔW=0\Delta W = 0 and the model is the pretrained model. Fine-tuning departs from θ0\theta_0 smoothly.
  • Scaling by α/r\alpha / r keeps the update’s magnitude roughly independent of rr, so a learning rate tuned for one rank works for others.
  • Where. Hu et al. applied it to WqW_q and WvW_v in the attention layers. Applying it to every linear layer is now common, and demo 01 shows why: 85.5% (qv only) vs 92.9% (all) on the phenomenon task.
  • After fine-tuning, merge: W=W0+ΔWW = W_0 + \Delta W once, and the model has exactly the original shape and speed. Measured: merging changed the logits by at most 3×10−63 \times 10^{-6}. One base model can also serve many tasks by swapping small (A,B)(A, B) pairs.

Hu et al. matched full fine-tuning of GPT-3 175B with 10,000× fewer trainable parameters and 3× less GPU memory, with no added inference latency. QLoRA (Dettmers et al., 2023) goes further. It keeps the frozen W0W_0 in 4-bit precision (Lecture 19) and trains LoRA factors on top. A 65B model can then be fine-tuned on a single 48 GB GPU.

Why is low rank enough? Aghajanyan et al. (2021) found that fine-tuning has a low intrinsic dimension: optimizing in a small random subspace of the parameters already recovers most of the performance. Hu et al. found the update’s useful directions concentrated in a few singular vectors.

Measured (demo 01 Part C): the singular values of the full fine-tuning update ΔW\Delta W of each attention matrix (64 × 64), as the share of ∑σ2\sum\sigma^2 in the top kk directions:

full update (phenomenon task)∥ΔW∥/∥W0∥\lVert\Delta W\rVert / \lVert W_0\rVerttop 1top 4top 16
layer 0 WqW_q0.23912% (random 6%)40% (21%)82% (63%)
layer 0 WvW_v0.24216% (6%)46% (21%)89% (63%)
layer 1 WqW_q0.26644% (6%)64% (21%)91% (62%)
layer 1 WvW_v0.27320% (6%)60% (21%)94% (62%)

Even when nothing constrains it, the update concentrates in a few directions: on average 52% of its energy lies in 4 of 64 directions, vs 21% for a random matrix.

2.6 Effects of fine-tuning

It is data-efficient. Starting from a pretrained model needs far less labelled data. ULMFiT (Howard & Ruder, 2018): with 100 labelled examples, a fine-tuned pretrained LM matched training from scratch on 100× more data. Lecture 6’s demo 02 measured the same: a 100-label probe reached 78% vs 54% from scratch.

It “narrows” the distribution. Pretraining fits the model to a broad data distribution, min⁡θDKL(pdata∥pθ)\min_\theta D_{\mathrm{KL}}(p_{\text{data}} \Vert p_\theta). Fine-tuning fits it, starting from pθ0p_{\theta_0}, to a much narrower one: min⁡θDKL(pfinetune∥pθ)\min_\theta D_{\mathrm{KL}}(p_{\text{finetune}} \Vert p_\theta). Nothing in the fine-tuning objective asks the model to keep what it knew about everything else. Measured (demo 01, “forgetting”): the rise in next-token NLL on held-out review pages, read through the original output layer from the fine-tuned body.

on the phenomenon taskhead onlyLoRA r=1LoRA r=4 qvLoRA r=16 qvLoRA r=4 allfull
accuracy86.0%74.2%85.5%88.7%92.9%93.7%
forgetting (nats)+0.000+0.475+1.311+2.965+3.146+3.394

The two rows rise together: the more a method can change, the more it learns and the more it forgets. This is the finding of Biderman et al. (2024), “LoRA learns less and forgets less”. For sentiment, which needed little change, no method raised the NLL by more than 0.118.

Symptoms (slides):

  • A summarization model doesn’t work well on translation.
  • A model trained with specific formatting requires that formatting. The course notebook’s name-reversal model fails when the prompt is rephrased; demo 02 tests this (§3.4).
  • A model can’t few-shot learn well after fine-tuning.

2.7 What fine-tuning data look like

XYdatasettraining examples
article (paper)abstractscientific_papers (arXiv)300,000+
problemsolutioncompetition_math (MATH)7,500
promptresponseOpenOrca2,910,000

From one task with hundreds of thousands of examples, to a hard task with a few thousand, to millions of general prompt–response pairs. The last kind leads to instruction tuning.


3. Instruction tuning

3.1 Basic idea

Fine-tune a model to perform many tasks with one format: (instruction + input, output) pairs.

X (instruction + input)Y (output)
Translate this sentence into English: 元気ですか。How are you?
I want to solve this problem, can you help? 2 + 3 = ?Let’s think step-by-step. 2 + 3 = 5.
……

Variations:

  • Instructions from templates, humans, or a model.
  • Inputs from existing datasets, humans, or a model.
  • Outputs from datasets, humans, or a model.
  • Domains: general, code, math, chat, ….

3.2 Three examples

  • FLAN (Wei et al., 2021): 62 NLP datasets grouped into task clusters. Instructions come from templates (ten per dataset); inputs and outputs from the datasets. A 137B model was instruction-tuned on some clusters and evaluated zero-shot on held-out clusters. Key finding: the model generalizes to unseen tasks, surpassing zero-shot GPT-3 175B on most evaluated datasets. Two ablations matter for us:
    • More training clusters gave better held-out performance.
    • The benefit appeared only at scale. For models of 8B parameters and below, instruction tuning hurt held-out tasks.
  • Super-NaturalInstructions (Mishra et al., 2021; Wang et al., 2022): about 1,600 tasks with crowdsourced instructions, inputs and outputs. Unseen-task performance grew with the number of training tasks.
  • Self-Instruct (Wang et al., 2023): instructions, inputs and outputs all generated by a model. Start from 175 hand-written seed tasks; prompt a language model to generate new instructions and instances; filter; repeat. The result was 50,000+ instructions. The same recipe, with a stronger model, produced Stanford’s Alpaca data. This is a first instance of distillation (§4).

Recap: fine-tune on (instruction, input, output) examples; get the data from humans or model generations; the resulting model can perform many tasks. Much follow-up work builds instruction-tuning data for particular domains: general, code, math, chat.

3.3 What does instruction tuning add?

Skill World (skill_world.py) separates knowing a skill from following an instruction. The pretraining corpus states twelve small skills as plain sentences, “the opposite of hot is cold .”, “the capital of peru is lima .”. It never uses the instruction format “task : give the opposite . input : hot . output :”.

Measured (demo 02):

  • Part A. The base model completes 100% of statements correctly in every skill, but answers 0.0% of instruction-format prompts. The knowledge is there; the interface is not.
  • Part C. Instruction-tune on kk of 8 trainable skills for 200 steps (loss on the answer only, averaged over 3 random choices of skills). Then ask about the 4 held-out skills (antonym, capital, next number, young animal) in the instruction format:
tuned skills kktuned skills (instruction)held-out skills (instruction)held-out skills (statement)
1100.0%12.7%100.0%
2100.0%10.6%100.0%
4100.0%62.2%100.0%
8100.0%70.2%99.1%

Instruction tuning on skills A, B, C teaches the model to answer questions about skill D in the new format. The more skills it tunes, the better it transfers: the trend of FLAN and Super-NaturalInstructions. With 8 tuned skills, the held-out ones reach 80.0% (antonym), 89.5% (capital), 44.8% (next) and 66.7% (young).

The knowledge comes from pretraining (Part D). The same instruction data on a model without pretraining reaches 100% on the tuned skills, because it memorizes them, and 0.0% on the held-out ones. Instruction tuning does not teach skills; it teaches a way to ask for the skills a model already has.

It depends on the base model (Part E). Three base models were pretrained with the same data recipe but different seeds, and each was instruction-tuned on all 8 skills:

base modelstatements knowntuned skills (instruction)held-out skills (instruction)
seed 0100.0%53.5%4.3%
seed 1 (used above)100.0%100.0%70.2%
seed 2100.0%99.6%61.7%

All three know every statement. Only two of them let the instruction interface reuse that knowledge. How a pretraining run organizes what it learns decides whether a new interface can reach it. This is a toy version of FLAN’s scale finding, and a reason to evaluate fine-tuning methods on more than one base model. (The main experiment uses seed 1, chosen after seed 0 showed almost no transfer; the table shows all three.)

3.4 Format dependence

Measured (demo 02 Part B): fine-tune on one skill (plurals) in the instruction format, then ask in other ways:

prompt formatexampleplural: baseplural: fine-tunedheld-out skills: fine-tuned
trained formattask : give the plural . input : cat . output :0.0%100.0%15.5%
question / answerquestion : what is the plural of cat ? answer :0.0%100.0%6.1%
terseplural of cat :0.0%100.0%35.8%
natural statementthe plural of cat is100.0%100.0%100.0%

This base model carried the fine-tuned skill over to the rephrased prompts (100%). The course notebook’s SmolLM2 did not: its name-reversal model failed when the prompt was rephrased. Whether a fine-tuned skill survives rephrasing depends on the model and the data, so test it. (The seed-0 base of a first run did show strong format dependence: 45% and 10% on the two rephrasings.)

3.5 Chat tuning

Ultimately a chat is formatted as a sequence of tokens (Lecture 7’s chat template): a system prompt, then [user, assistant, user, assistant, …]. “Instruction + input” are implicit in the conversation. Chat tuning is SFT on such sequences, with the loss on the assistant turns.

  • System prompts: OpenOrca’s examples each have one of 16 hand-written system messages (“You are an AI assistant. Provide a detailed answer…”). The outputs come from GPT-4 and GPT-3.5: distillation again.
  • Multi-turn: LMSYS-Chat-1M contains one million real conversations from an online LLM service hosted by Berkeley/Stanford (the Vicuna demo and Chatbot Arena).

4. Knowledge distillation

4.1 Teacher and student

Several methods above use a good model (e.g. GPT-4) to generate data for another model: Self-Instruct, Orca, OpenOrca. These are instances of knowledge distillation (知识蒸馏) (Hinton et al., 2015): a teacher qq (e.g. a large language model) transfers its behavior to a student pθp_\theta (e.g. a small one).

4.2 Token-level distillation

Train the student to mimic the teacher’s token distributions at every position:

Ltoken-KD=−∑t∑yt∈Vq(yt∣y<t,x) log⁡pθ(yt∣y<t,x).\mathcal{L}_{\text{token-KD}} = -\sum_t \sum_{y_t \in \mathcal{V}} q(y_t \mid y_{<t}, x)\, \log p_\theta(y_t \mid y_{<t}, x).

This is cross-entropy with soft labels: the full teacher distribution replaces the one-hot target. It equals the per-position KL from teacher to student, up to the teacher’s entropy, a constant. Summed over positions on teacher sequences, it minimizes DKL(q(y∣x)∥pθ(y∣x))D_{\mathrm{KL}}\big(q(y \mid x) \Vert p_\theta(y \mid x)\big). Hinton et al. argued that soft labels carry “dark knowledge” — which wrong answers are almost right. They also soften both distributions with a temperature. In practice the prefixes y<ty_{<t} usually come from the references (teacher forcing), as in demo 03.

4.3 Sequence-level distillation

Kim & Rush (2016):

  1. Generate with the teacher: for prompts x1,x2,…x_1, x_2, \dots, produce responses (they used beam search).
  2. Fine-tune the student on the generated (prompt, response) dataset.

This also minimizes the same KL, estimated by sampling sequences from the teacher:

min⁡θDKL(q(y∣x)∥pθ(y∣x))≡min⁡θ Ey∼q(y∣x)[−log⁡pθ(y∣x)].\min_\theta D_{\mathrm{KL}}\big(q(y\mid x) \Vert p_\theta(y \mid x)\big) \equiv \min_\theta\ \mathbb{E}_{y \sim q(y \mid x)}\big[-\log p_\theta(y \mid x)\big].

With beam search the samples are approximately the teacher’s mode. Kim & Rush’s argument: translation has many valid outputs. A small student trained on references must spread its probability over all of them, which makes greedy decoding unreliable. Trained on the teacher’s single best output, the student learns one consistent target. Their students needed no beam search, ran an order of magnitude faster, and lost little accuracy.

Sequence-level distillation is how many small models are made today. DeepSeek-R1-Distill-Qwen-7B is Qwen2.5-Math-7B fine-tuned on about 800k samples generated with DeepSeek-R1, reasoning traces included.

4.4 An augmented teacher

West et al. (2022): the teacher need not be the LM alone. It can be an augmented language model,

q(y∣x)∝pLLM(y∣x)⋅A(x,y),q(y \mid x) \propto p_{\text{LLM}}(y \mid x) \cdot A(x, y),

where AA is a classifier, a critic or a verifier that accepts or weights outputs. In practice: sample from the LLM and keep what the critic accepts. In principle, if the augmented teacher is better than pLLMp_{\text{LLM}}, the student can become better than pLLMp_{\text{LLM}} through distillation. West et al. distilled GPT-3’s commonsense knowledge, filtered by a trained critic, into a much smaller model that surpassed GPT-3 on the same task. The same idea — sample, verify, train on the accepted outputs — is rejection-sampling fine-tuning, and a step toward the RL methods of Lecture 17.

4.5 Measured: what helps the student?

Demo 03’s task is English → Zorbian translation (Lecture 1’s made-up language: each word mapped, order reversed), set up as prompt → response:

  • Teacher: 1.0M parameters. Student: 0.3M.
  • Training data: 1,500 reference translations, 20% of them containing one error (a wrong or duplicated word).
  • Fairness: every student has the same size and the same 900 training steps; only its data or loss differs.
  • Metric: exact match of the greedy translation on 500 test sentences.
modelaccuracy
teacher (d=128, 3 layers)70.4%
student on the references60.6%
student, token-level KD (teacher’s soft labels, same inputs)60.4%
student, sequence-level KD (teacher’s greedy outputs, same inputs)60.6%
student, sequence-level KD on the reference inputs + 2,200 new inputs66.2%
student, verifier-filtered teacher samples (4 per input)72.8%

What the table says:

  • On the same inputs, neither form of distillation helped (60.4% and 60.6% vs 60.6%). The teacher’s outputs were 81.6% correct, exactly as clean as the references (81.6%). And the task has one correct output per input, so Kim & Rush’s mode-averaging argument has nothing to act on. Their gain needs multimodal outputs, like real translation. A first version gave each sentence two equally valid “registers” to test that argument. The student did not mix registers either; its errors were vocabulary errors.
  • New inputs helped. The teacher labels 2,200 sentences that have no reference (71.3% of its labels correct), and the student rises from 60.6% to 66.2%. This is how synthetic-data distillation is used: the teacher’s value is that it can label unlimited inputs.
  • An augmented teacher made the student better than the teacher: 72.8% vs 70.4%. Sample 4 translations per input and keep the ones a verifier accepts. Here the verifier is a word-by-word dictionary check. In practice it is an answer key, unit tests, or a trained critic: checking an output is often far easier than producing it.

4.6 Recap

  • Fine-tuning basics: adjust a model’s parameters using data. PEFT updates only a small number of parameters.
  • Instruction tuning: format data so that a model learns to do many tasks, and new ones in the same format.
  • Knowledge distillation: training data can come from various teachers — humans, models, and models with verifiers.

5. Summary

  1. SFT = continued training from θ0\theta_0; classification adds a head on the last hidden state; generation trains on −∑tlog⁡pθ(yt∣x,y<t)-\sum_t \log p_\theta(y_t \mid x, y_{<t}) with the prompt masked out.
  2. Head only suffices when the pretrained representation already separates the labels (sentiment: 70.7% vs 73.4% full). When it does not, the representation must change (phenomenon: 86.0% vs 93.7%).
  3. LoRA: W0+αrBAW_0 + \frac{\alpha}{r}BA, B=0B = 0 at start, merge after training (logits change ≤ 3e-6). LoRA r=4 on all linear layers reached 92.9% with about 4% of the parameters. The full update is concentrated (52% of its energy in 4 of 64 directions).
  4. Fine-tuning narrows the model: forgetting rose with what the method could change, from +0.48 (LoRA r=1) to +3.39 nats (full). “LoRA learns less and forgets less.”
  5. Instruction tuning adds an interface, not knowledge: base model 100% on statements, 0% on instructions. Tuning on 8 skills → 70.2% on 4 held-out skills (12.7% with 1). Without pretraining: 0%. It depends on the base model: 4.3% / 70.2% / 61.7% across three pretraining seeds.
  6. Chat tuning = SFT on conversations formatted with a chat template (system prompt, user/assistant turns).
  7. Distillation: token-level (soft labels) and sequence-level (teacher outputs) both minimize KL(teacher ‖ student). On the same inputs they gave no gain here. The teacher labeling new inputs did (60.6% → 66.2%), and an augmented teacher with a verifier produced a student better than the teacher (72.8% vs 70.4%).

Common pitfalls

  • Computing the SFT loss on the prompt by accident. The model then also learns to generate prompts; mask them (unless you mean to — Shi et al., 2024, found prompt loss can help when responses are short).
  • Fine-tuning everything when a head would do, or a head when the representation must change. Check a linear probe first.
  • Ignoring forgetting. Full fine-tuning raised the base model’s next-token loss by 3.4 nats on its own pretraining text. Evaluate on what the model should still be able to do.
  • Forgetting to merge LoRA weights before deployment, or merging into a quantized base without care (the rounding changes the result).
  • Testing a fine-tuned model only in its training format. Rephrase the prompt.
  • Expecting instruction tuning to teach facts. It exposes what pretraining stored. Without pretraining, held-out skills stayed at 0%.
  • Reporting one base model or one seed. The same recipe gave 4.3% and 70.2% held-out accuracy on two seeds.
  • Assuming distillation on the same inputs improves a student. The gain came from new inputs and from filtering.
  • Distilling from an unfiltered teacher with known errors. The student inherits them; a verifier removes them.

Exercises

  1. LoRA parameter count. A model has 32 layers with d=4096d = 4096. LoRA of rank 8 is applied to WqW_q and WvW_v (each 4096 × 4096). How many trainable parameters is that, and what fraction of the 4096 × 4096 × 2 × 32 frozen weights it adapts?

    AnswerPer matrix $r(d + d') = 8 \times 8192 = 65{,}536$; × 2 matrices × 32 layers = 4,194,304 ≈ 4.2M. The adapted matrices hold $2 \times 32 \times 4096^2 = 1.07$B weights: 0.39%.
  2. Why B=0B = 0? What would go wrong if both AA and BB were initialized randomly? And why not both at zero?

    AnswerRandom $A$ and $B$ give a random $\Delta W$ from the first step: the model starts away from the pretrained one, and its first outputs are damaged. Both zero: $\partial\mathcal{L}/\partial A = \frac{\alpha}{r} B^\top(\cdot) = 0$ and $\partial\mathcal{L}/\partial B = \frac{\alpha}{r}(\cdot)A^\top = 0$, so neither ever moves. With $B = 0$ and $A$ random, $\Delta W = 0$ but $\partial\mathcal{L}/\partial B \ne 0$, so training starts exactly at $\theta_0$ and can move.
  3. Merging. Show that merging W=W0+αrBAW = W_0 + \frac{\alpha}{r}BA gives exactly the same outputs as the unmerged layer, and say why this matters for serving.

    Answer$W_0 x + \frac{\alpha}{r}B(Ax) = (W_0 + \frac{\alpha}{r}BA)x$ by associativity of matrix products. Serving uses one matrix multiplication per layer, as before: zero added latency (demo 01: max logit change 3e-6, floating-point rounding).
  4. Token-level KD = KL. Show that −∑yq(y)log⁡p(y)=DKL(q∥p)+H(q)-\sum_y q(y)\log p(y) = D_{\mathrm{KL}}(q\Vert p) + H(q), and explain why minimizing the KD loss over pp minimizes the KL.

    Answer$D_{\mathrm{KL}}(q\Vert p) = \sum_y q\log q - \sum_y q \log p = -H(q) - \sum_y q\log p$. So the cross-entropy is $D_{\mathrm{KL}} + H(q)$, and $H(q)$ does not depend on the student's parameters.
  5. Sequence-level KD as sampling. Explain why fine-tuning on samples y∼q(⋅∣x)y \sim q(\cdot \mid x) is an unbiased estimate of minimizing DKL(q∥pθ)D_{\mathrm{KL}}(q \Vert p_\theta), and what changes when you use the teacher’s beam-search (mode) output instead.

    Answer$D_{\mathrm{KL}}(q\Vert p_\theta) = \mathbb{E}_{y\sim q}[\log q(y\mid x) - \log p_\theta(y \mid x)]$; the first term is constant in $\theta$, so its gradient is $-\mathbb{E}_{y\sim q}[\nabla\log p_\theta(y\mid x)]$, estimated without bias by averaging over samples. With the mode, the target is a point mass at the teacher's best output: the student learns the teacher's *argmax*, not its distribution — a biased but lower-variance, often easier target (Kim & Rush's argument).
  6. The augmented teacher. A teacher solves 60% of problems on a single sample. Each problem gets 4 independent samples, and a perfect verifier keeps the correct ones. What fraction of problems get at least one accepted solution? What does a student trained on them see, and how could it end up better than the teacher?

    Answer$1 - 0.4^4 = 97.4\%$ of problems get at least one correct sample (if samples are independent). The student trains only on correct solutions — for problems the teacher solves only sometimes — so its target distribution is "the teacher conditioned on being right", which can be better than the teacher's own greedy behavior (demo 03: 72.8% vs 70.4%). In practice samples are correlated, so the coverage is lower.
  7. Forgetting. You fine-tune a chat model on medical Q&A and it starts failing simple arithmetic it used to do. Name two fine-tuning choices and one data choice that reduce this.

    AnswerChoices: a parameter-efficient method with smaller updates (LoRA, lower rank — demo 01: forgetting +0.48 at r=1 vs +3.39 full); a lower learning rate / fewer steps / early stopping on a held-out general benchmark. Data: mix some general-purpose (replay) data, including arithmetic, into the fine-tuning set so the objective no longer ignores those skills.
  8. Instruction tuning or knowledge? Demo 02’s model reaches 70% on held-out skills in the instruction format. Design an experiment that shows the improvement comes from pretrained knowledge, not from the instruction data.

    AnswerTrain the same architecture on the same instruction data without pretraining (Part D: 0% held-out); or pretrain a base on a corpus where the held-out skills' statements are removed, then instruction-tune identically: if held-out accuracy drops to ~0%, the knowledge came from pretraining.
  • Assignment 1 — Build your own LLaMa is due 02/12, the day Assignment 2 is released. Once a model like A1’s exists, the first thing one usually does with it is what §2 describes: put a head on it, or fine-tune it on prompt–response pairs. pretrain.SeqClassifier and finetune.py here are teaching versions on toy data. These notes do not provide assignment code.

Further reading

  • E. Hu et al., “LoRA: Low-Rank Adaptation of Large Language Models”, ICLR 2022 (course reading); A. Aghajanyan et al., “Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning”, ACL 2021; D. Biderman et al., “LoRA Learns Less and Forgets Less”, 2024; T. Dettmers et al., “QLoRA”, NeurIPS 2023.
  • Y. Kim, A. M. Rush, “Sequence-Level Knowledge Distillation”, EMNLP 2016 (course reading); G. Hinton, O. Vinyals, J. Dean, “Distilling the Knowledge in a Neural Network”, 2015.
  • J. Howard, S. Ruder, “Universal Language Model Fine-tuning for Text Classification”, ACL 2018.
  • J. Wei et al., “Finetuned Language Models Are Zero-Shot Learners” (FLAN), ICLR 2022; S. Mishra et al., “Cross-Task Generalization via Natural Language Crowdsourcing Instructions”, ACL 2022; Y. Wang et al., “Super-NaturalInstructions”, EMNLP 2022; Y. Wang et al., “Self-Instruct”, ACL 2023.
  • S. Mukherjee et al., “Orca: Progressive Learning from Complex Explanation Traces of GPT-4”, 2023; W.-L. Chiang / L. Zheng et al., “LMSYS-Chat-1M”, 2023.
  • P. West et al., “Symbolic Knowledge Distillation: from General Language Models to Commonsense Models”, NAACL 2022; DeepSeek-AI, “DeepSeek-R1”, 2025 (distilled models).
  • Z. Shi et al., “Instruction Tuning With Loss Over Instructions”, 2024.

Preview of Lecture 9 — Decoding algorithms

Every model so far produced text with greedy decoding or plain sampling, and demo 03’s verifier already hinted that how we draw outputs matters as much as the model. Lecture 9 treats decoding as its own subject:

  • Decoding as optimization: greedy and beam search, and why the most likely output is not always the best (“the beam-search curse”).
  • Decoding as sampling: temperature, top-k, top-p, min-p, typical sampling.
  • Minimum Bayes risk decoding, and constrained decoding.

All of these run on a language model whose true probabilities are known exactly, so “probability” and “quality” can be compared without guessing.


术语表 (Glossary, English → 中文)

English中文
fine-tuning / supervised fine-tuning (SFT)微调 / 有监督微调
pretrained parameters预训练参数
output head / classification head输出头 / 分类头
loss masking损失掩码
overfitting / regularization / dropout过拟合 / 正则化 / 随机失活
parameter-efficient fine-tuning (PEFT)参数高效微调
low-rank adaptation (LoRA) / rank低秩适配 / 秩
frozen weights / trainable parameters冻结权重 / 可训练参数
merge (LoRA weights)合并(LoRA 权重)
intrinsic dimension / intrinsic rank内在维度 / 内在秩
singular value decomposition (SVD)奇异值分解
quantization (QLoRA)量化
catastrophic forgetting灾难性遗忘
narrowing the distribution分布收窄
data efficiency数据效率
instruction tuning指令微调
held-out task / unseen task留出任务 / 未见任务
template模板
crowdsourcing众包
self-instruct / synthetic data自指令 / 合成数据
chat tuning / multi-turn对话微调 / 多轮
system message系统消息
knowledge distillation知识蒸馏
teacher / student教师 / 学生
soft labels / dark knowledge软标签 / 暗知识
token-level / sequence-level distillation词元级 / 序列级蒸馏
augmented teacher / critic / verifier增强教师 / 评判器 / 验证器
rejection sampling拒绝采样
format dependence格式依赖
← 返回课程目录