Post-Training and Alignment
How does a model that only predicts the next word become an assistant that tries to help?
The series' own 6.8-million-parameter model, trained on thirty novels, is asked for a line about a topic and continues a novel instead; after a few minutes of fine-tuning it answers. The part follows the InstructGPT pipeline in order. Supervised fine-tuning is maximum likelihood on the answer, and LoRA stores it in a low-rank update, measured at ranks 1, 4 and 16 against full fine-tuning. A reward model is fitted to simulated people's comparisons with the Bradley-Terry loss, and because their hidden taste (gold) is known here, the reward model is opened and compared with it. Reinforcement learning on a KL leash has an exact optimum, the reference reweighted by e^(r/beta), and the part turns when that optimum is pushed: best-of-n and RLHF raise what the reward model believes faster than what gold says, which is Goodhart's law measured. DPO is derived from the same optimum, and the part ends with AI feedback under written principles, distillation, model merging, the known failures (sycophancy, jailbreaks, emergent misalignment) and the open recipes.
What you need. Cross-entropy and KL divergence (Part 1), the transformer language model (Parts 13 and 14) and policy gradients with PPO (Part 26).
- Mathematics and history
- SFT, LoRA, reward models, RLHF, DPO, Constitutional AI, distillation, merging
- Models, data
- InstructGPT
What you will be able to do
Undergraduate
- Explain the stages that turn a pretrained model into an assistant, and what data each stage needs from people.
- Say in words what Goodhart's law predicts when a learned reward is optimized hard, and name two documented failures of post-trained models.
Master's
- Derive the optimum of the KL-regularized objective and its value beta log Z.
- Derive the DPO loss from that optimum and the Bradley-Terry model, and compute its gradient for one pair.
- Show that only reward differences within a question are identified by comparisons.
Research
- Prove best-of-n's KL formula for an atomless reward and explain why it is only an upper bound for discrete text.
- Distinguish regressional from extremal Goodhart on a reward model whose target is known, and state what a real lab cannot measure.
Engineering
- Choose a LoRA rank from the parameter count r(d + k) and the measured trade between accuracy and forgetting.
- Compare RLHF, DPO and best-of-n by gold gained against KL spent, and say when distillation or merging is the cheaper tool.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 16 min · Master's 44 min · Research 49 min · Engineering 27 min.
- 0The same model, before and afterUndergraduate2 min
- 1From predictor to assistantUndergraduate3 min
- 2Supervised fine-tuningUndergraduate4 min
- 3Low-rank adaptersEngineering3 min
- 4Learning what people preferMaster's4 min
- 5Inside our reward modelResearch5 min
- 6Reinforcement learning on a leashMaster's7 min
- 7When the measure becomes the targetMaster's3 min
- 8Direct preference optimizationMaster's3 min
- 9Feedback from AI, rules from peopleUndergraduate3 min
- 10DistillationEngineering2 min
- 11Adding models togetherEngineering2 min
- 12What goes wrongUndergraduate3 min
- 13The open recipesEngineering3 min
- Recap, problems, and what comes nextAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
The same model, before and afterUndergraduate2 min
This is the small language model this series trained on thirty novels, asked to write a line about the sea. As it comes out of pretraining, it doesn't answer. It continues a document: the request is just more text, and the special markers around it mean nothing to it. Here is the same model after a few minutes of fine-tuning on this computer. The examples came from the same novels. Training updated its weights and taught it the answer format.
That change, from predicting text to trying to help, is called post-training, and it shapes many modern language-model assistants. It can matter more than size. In 2022 OpenAI found that people preferred the answers of a 1.3-billion-parameter model after post-training to those of the 175-billion-parameter GPT-3 before it.
This is Part 27 of AI, Built. In this part: supervised fine-tuning and low-rank adapters; reward models learned from comparisons, and what ours actually learned; reinforcement learning from human feedback, its exact optimum, how PPO is fitted to a language model, and what happens when you optimize a learned reward too hard; direct preference optimization; feedback from AI under written principles; distillation and model merging; and what goes wrong. The core experiments run here on our own small model; published larger-scale results are cited.
1From predictor to assistantUndergraduate3 min
A pretrained language model, everything in Parts 13 to 18, has one skill: continuing text. Its only goal was to predict the next token of documents from the web. So when you ask it a question, it does what such documents do. A question on the web is often followed by more questions: a quiz, a list of exercises. What we want is different: an assistant that answers. The model already knows that Paris is the capital of France. Post-training is the work of getting it to use what it knows the way we want.
The recipe that made ChatGPT was published by OpenAI in March 2022, as InstructGPT. It has three stages after pretraining. First, supervised fine-tuning: people wrote good answers to about thirteen thousand prompts, and the model was trained to imitate them. Second, a reward model: for thirty-three thousand prompts, people ranked several of the model's answers from best to worst, and a network learned to predict their rankings. Third, reinforcement learning: the PPO of Part 26, with the reward model standing in for the people. The result was startling. People preferred the answers of the 1.3-billion-parameter InstructGPT to those of the 175-billion-parameter GPT-3: over a hundred times smaller, and better liked, because it was trying to help.
The idea is older than chatbots. In 2017, Paul Christiano, Jan Leike and colleagues at OpenAI and DeepMind taught a simulated robot to do a backflip without ever writing down what a backflip is. A person was shown two short clips and picked the one that looked more like a backflip, about nine hundred times, in under an hour; a network learned their preferences, and reinforcement learning did the rest. In 2020 the same method trained language models to summarize, and people preferred its summaries to the human-written ones. InstructGPT followed, and on the thirtieth of November 2022, ChatGPT. Since then the recipe has been reproduced in the open, and changed: Meta's Llama 2 used over a million comparisons, and a method called DPO showed the reward model could be skipped altogether.
This is what the field calls alignment: making a model do what the people who build and use it intend. Anthropic's shorthand is helpful, honest and harmless. The difficulty is that what people want is very hard to write down as a formula. But it is easy to recognize: show someone two answers, and they can usually say which is better. So the strategy of this part is to learn the goal from people's judgments, and then optimize it, carefully, because a learned goal is only an approximation. Each step will be done for real, on the small model this series trained on thirty novels.
2Supervised fine-tuningUndergraduate4 min
The first step is to teach the model the shape of a conversation. Every exchange is written in a fixed template, with special tokens that never appear in ordinary text: one that says a person is speaking, one that says the assistant's turn begins, and one that ends it. The model is trained on such conversations with the same next-token loss as in pretraining, with one change: only the answer's tokens count. The question is context, not something to imitate. By the chain rule of Part 1, the masked loss is just the log-probability of the whole answer given the question. Supervised fine-tuning is maximum likelihood on the answers people want.
Our model is the one this series trained on thirty novels: six point eight million parameters, a modern transformer in miniature. We fine-tune it on two kinds of conversation, both made from the novels themselves. In the first, the user quotes a sentence and asks which book it comes from; the answer is the title. It's checkable: right or wrong, and we test on sentences from paragraphs held out of all its training. In the second, the user asks for a line about something, the sea, a window, and the answer is a sentence from the novels about it.
Here is a held-out sentence, put to the model before fine-tuning. The base model has never seen the special tokens in a meaningful place, so it does what it always does: it continues a novel. After fine-tuning, it answers with a title. On 120 evenly sampled test sentences, the base model is right 0 percent of the time; on the full test set, the fine-tuned model 27 percent, against one in thirty by guessing. It had read these books; fine-tuning taught it to say which one it was reminded of.
The chart tracks book-identification accuracy over 600 steps of fine-tuning. On ordinary novel text, the measured next-token loss changes from 3.603 to 4.192 nats per token, a change of +0.589. Higher loss means worse prediction on these held-out text windows. The next chapter reduces trainable parameters with low-rank updates. Later, the KL penalty discourages departure from the reference policy on the training prompts. We measure novel-text loss to check retention.
Instruction tuning has a short, fast history. In 2021 Google's FLAN fine-tuned a model on sixty tasks rewritten as instructions, and it got better at tasks it had never seen. In 2023 Stanford's Alpaca fine-tuned an open model on fifty-two thousand examples written by a stronger model, for a few hundred dollars. Meta's LIMA showed that a thousand carefully chosen examples could go a long way, and proposed that alignment is largely about style: the knowledge is already there from pretraining. Alpaca is one example of model-written instruction data. That does not remove the need to check its quality.
3Low-rank adaptersEngineering3 min
Fine-tuning changes every one of a model's weights, and for a large model that means storing a full new copy for every task. But does it need to? In 2018 Chunyuan Li and colleagues trained networks in a random low-dimensional slice of weight space: the weights are the starting point plus a fixed random matrix times a small vector, and only the small vector learns. Many problems needed surprisingly few dimensions. In 2020 Armen Aghajanyan and colleagues showed that fine-tuning a pretrained language model is especially low-dimensional: about two hundred numbers got RoBERTa ninety percent of the way on a paraphrase task. Pretraining had done the hard part.
LoRA, from Edward Hu and colleagues at Microsoft in 2021, builds that idea into the network. Freeze the pretrained weights. For each matrix you choose to adapt, add the product of two thin matrices, B times A, with rank at most r, where r is small. Only B and A are trained. A d by k matrix has d times k numbers; the adapter has r times the sum of d and k. For a four-thousand-wide layer at rank eight, that's about sixty-five thousand trainable numbers instead of about seventeen million. B starts at zero, so training starts from the model exactly. When training is done, the scaled low-rank update can be added into W. After merging, inference uses the original matrix architecture without a separate adapter branch.
Our own experiment: fine-tune the novels model on the which-book task with LoRA at ranks one, four and sixteen, and with every weight. Rank one trains numbers, percent of the model. Full fine-tuning gets percent of held-out sentences right; the best adapter, rank , percent. And on ordinary novel text, full fine-tuning's loss is nats from the base model's;
On GPT-3, LoRA trained ten thousand times fewer numbers than full fine-tuning, with about a third of the memory and comparable quality. QLoRA in 2023 stored the frozen model in four bits, and fine-tuned a sixty-five-billion-parameter model on a single forty-eight-gigabyte GPU, which put fine-tuning within reach of anyone with one good graphics card. DoRA splits each weight vector into a magnitude and a direction. It learns magnitudes separately and adapts directions with LoRA. And a careful 2024 comparison put the trade-off in its title: LoRA learns less and forgets less. For hard new skills, full fine-tuning still wins.
4Learning what people preferMaster's4 min
Suppose you want a number that says how good an answer is. You could ask people to score answers from one to ten. But scores drift: one person's seven is another's eight, and the same person's scale moves during a day. Comparisons are much more reliable. Show two answers to the same question, and ask which is better. People still disagree, but less: InstructGPT's labellers agreed with each other on about seventy-three percent of comparisons. Comparisons are what the reward model learns from.
The standard model of comparisons is Bradley and Terry's, from 1952. Give every answer a hidden score, r. The chance that a beats b is the logistic sigmoid of the difference in their scores. If that looks familiar, it should: it is exactly the Elo model that rated AlphaZero's generations in Part 26, with a different scale. A reward model is a network, usually the fine-tuned language model with its last layer swapped for a single number, trained by maximum likelihood on the comparisons: make the winner's score exceed the loser's. It's logistic regression on differences, Part 6's loss in a new place. One consequence matters later. Only differences are ever seen, so the scores are only defined up to a shift for each question. A reward model says which answer is better, not how good an answer is on any absolute scale.
Now we do it ourselves. Our fine-tuned model from chapter two writes lines on request: a line about the sea, a line about the night. We have no crowd of labellers, so we simulate one. Hidden from every model is a stand-in for human taste we'll call gold: it likes cheerful words, dislikes gloomy ones, prefers a line of about a dozen words to a paragraph, and strongly dislikes repetition and empty answers. Our simulated people compare two lines and prefer the one gold likes more, but not always: the closer the call, the more often they pick the other one. That gives us 5,040 comparisons. From here on, everything that learns what people prefer sees only these comparisons, never gold itself, just as a real lab never sees inside its labellers' heads.
Train reward models on more and more of the comparisons, and test each on held-out samples. With 100 comparisons it gets 60 percent right; with 4,200, 67 percent. The sampled people agree with gold on 77 percent of these test comparisons, with half credit for gold ties. That is a noise reference, not a hard ceiling on a finite test set. These used training and test sets share 0 exact prompt-and-answer texts. The recipe splits sample indices, so text separation is a measured property here, not a guarantee of the recipe. For historical context, InstructGPT's reward model predicted held-out labellers' choices about seventy percent of the time, close to how often the labellers agreed with each other. A reward model is an imperfect copy of an imperfect judge. Next we open ours up, and then see what happens when you optimize against it.
5Inside our reward modelResearch5 min
Chapter four measured our reward model from the outside: on held-out comparisons, it agreed with the simulated people 67 percent of the time. A real lab can't do much more; it can't see inside its labellers' heads. We can, because we wrote gold. So let's open the reward model up. Our fine-tuned model writes 600 new lines, 20 for each of the 30 questions, with new sampling seeds. Identical text can still recur. The reward model scores every line, and so does gold. Here are a few, side by side.
Each dot is one line: across, what gold thinks of it; up, the reward model's score. They go together, with a correlation of . But remember chapter four: the scores are only defined up to a shift for each question, so comparing lines across questions mixes in arbitrary shifts. Take each question's average out of both. How steep should the cloud be? Our simulated people choose with a noise of , so a reward model that learned them perfectly would score times gold: the dashed line. Over all pairs of lines to the same question that gold doesn't tie, the reward model orders percent as gold does.
What has it learned? Gold is a sum of three terms: the mood of the words, a penalty for every word past , and a penalty for repeating words; a line under four words gets a fixed score of minus one. Fit the reward model's score, divided by its slope so it is in gold's units, as a sum of the same terms. If it had learned gold exactly, every weight would be one.
Here is length on its own. Gold doesn't mind a line up to words; after that it takes off a word. Averaged by length, with all its other terms mixed in, gold looks like this. And the reward model, in gold's units, like this.
Which words does it listen to? Delete one word at a time and score the line again: the drop is that word's worth to the reward model. Here is a line about the , word by word. Orange bars are the reward model's change, in gold's units; yellow marks are gold's own change for the same deletion. Now every word in every line. These are the words that raise its score most, and the that lower it most.
Where do the two disagree most? This line about the is the reward model's number of the for its question; gold ranks it . And this line about the is the other way round: the reward model ranks it , gold . These are the errors that matter, because an optimizer goes looking for them.
Now use the reward model to choose. Each column is one question's lines, placed by gold; the orange ring is the line the reward model likes best, the yellow ring gold's own favourite. By its own score, in gold's units, its favourites stand above the question's average line. Gold says . Gold's own favourites would have stood at . Choosing by a noisy measure chooses the noise along with the signal: the winner tends to be a line the measure overrates. David Manheim and Scott Garrabrant called this regressional Goodhart. Push harder, with more candidates, or a policy trained against the score, and you reach lines unlike any it learned from, where its errors stop being random: extremal Goodhart. That is where the next two chapters go.
6Reinforcement learning on a leashMaster's7 min
With a reward model in hand, the plan is reinforcement learning: generate answers, score them, and push the model toward high scores with the policy gradient of Part 26. But maximizing the reward model alone is a mistake, for two reasons. The reward model is only an approximation, and a strong optimizer finds the places where it's wrong. And the policy can drift into text unlike anything it learned from, losing the fluency it had. So the objective adds a leash: a penalty, beta times the KL divergence from the fine-tuned model we started with, the reference. Beta sets the exchange rate: how much reward is worth one nat of divergence.
This objective has an exact solution, and it's worth deriving, because the rest of the part leans on it. Fix a prompt and write the objective as a sum over possible answers y. Fold the reward into the logarithm: r is beta times the log of e to the r over beta. Divide and multiply by the normalizing constant Z, and what's left is minus beta times a KL divergence, plus a constant. A KL divergence is never negative and is zero only when the two distributions agree, Part 1's Gibbs inequality. So the best policy is pi star: the reference model's probabilities, reweighted by e to the reward over beta. Large beta: barely move from the reference. Small beta: pile everything onto the highest-reward answers.
Here's the formula on eight real answers our fine-tuned model wrote about the , selected within a log-probability range of nats and sorted by a toy gold score. This finite-candidate illustration uses a known score, not a learned reward model. The bars start as the reference model's probabilities, renormalized over these eight. This is the exact optimum within this selected set; no policy training was run. An RLHF policy would instead optimize its learned reward by sampling and gradient steps.
How does Part 26's PPO fit a language model? Treat each answer as an episode: the state is the prompt and the tokens written so far, and the action is the next token. InstructGPT's reward gives every token a penalty, beta times that token's log-ratio of policy to reference, and adds the reward model's score at the last token. Summed over the answer, that is one sample of the objective we started with: the score, minus beta times the log-ratio of the whole answer. Then PPO runs as in Part 26, with a value network to judge each partial answer, and advantages computed token by token. That makes four networks the size of a language model in memory at once: the policy and the value network, training; the reference and the reward model, frozen. InstructGPT's value network started as a copy of its six-billion-parameter reward model.
The value network is there to supply a baseline. As in Part 26, a baseline independent of the sampled action leaves the expected policy gradient unchanged. A suitable baseline can reduce variance. PPO learns its baseline: the value network, token by token. But a language model can simply answer the same question several times. In 2024 Cohere's RLOO used the average reward of the other answers as each one's baseline, and reported better results than PPO, with no value network. The same year DeepSeek's GRPO also divided by the group's spread; it trained DeepSeek-R1, and Part 28 derives it. Our runs do the simplest version: 16 lines to one question, and the baseline is their mean. The resulting advantage is RLOO's advantage scaled by 15 over 16.
How much does the baseline matter on our model? At the first step of training we draw batches of lines for each of questions, and estimate the gradient from each batch in several ways. If an estimate is any good, two batches for the same question should point the same way. With no baseline, two batches agree with a cosine of . With one baseline shared by every question, ; with each question's own average, what a value network would learn to predict, . And with the batch's own mean, as in our runs, .
Now for real. Starting from our fine-tuned model, generate sixteen lines a step, score them with the reward model, subtract the KL penalty, and take a policy-gradient step. Both curves are in gold's units: the reward model's score divided by its slope from chapter five. With beta , by the last steps the reward model believes the policy has gained over the fine-tuned model, and gold, which the policy-gradient loss does not use, says . Now loosen the leash to beta .
Here is the loose-leash run replayed: three of its sixteen lines at each stage of training. These displayed lines come from seed zero; the curves remain means over three runs. At the start it writes like the fine-tuned model it began as. By step 240, asked about the sea, this is what it has learned to write, with gold's score beside each line. Judge for yourself whether a person would prefer it.
7When the measure becomes the targetMaster's3 min
In 1975 the economist Charles Goodhart observed that statistics used to steer policy stop meaning what they used to. The anthropologist Marilyn Strathern later put it in the form everyone quotes: when a measure becomes a target, it ceases to be a good measure. A reward model is a measure. If it slightly prefers longer answers, optimizing it produces padding. If it slightly prefers answers that agree with the user, optimizing it produces flattery. Reinforcement learning has always done this: in 2016 OpenAI showed a boat-racing agent, rewarded for hitting targets along the course, that learned to circle a lagoon forever, hitting the same three targets and never finishing the race.
To measure the effect, we need a way to optimize a reward model by a controlled amount. The simplest is best-of-n: draw n answers from the reference model and keep the one the reward model likes best. Bigger n, harder optimization. Its divergence from the reference has an upper bound: log n minus n minus one over n. Equality holds in the continuous-reward idealization: reward quantiles are uniform, the winning quantile has density n times u to the n minus one, and KL is the expected log of that. Discrete text can have smaller KL. The bound grows only like log n: best of a thousand is under six nats. Best-of-n is cheap to reason about, and in practice it is a strong baseline that labs still use.
Here is the experiment, after Gao, Schulman and Hilton of OpenAI. For each prompt, our fine-tuned model writes two hundred and fifty-six lines; best-of-n picks with a reward model, and we score the pick with both the reward model and gold, against the square root of the KL upper-bound coordinate. The reward model always believes things are getting better: by construction, its score of its own favourite rises with n. Gold tells the truth. Each reward model has its own raw score scale. A fall in gold while the proxy rises is over-optimization; these finite runs do not establish where every reward model will fail.
This is the line about the sea that the small reward model liked best out of all two hundred and fifty-six.
Gao and colleagues ran this at scale in a synthetic setup, with a large reward model supplying the labels. They centered gold reward so the initial policy scores zero and normalized its scale. These formulas describe gold reward gain relative to that initial policy. For best-of-n, d times alpha minus beta d: up, then down. For reinforcement learning, the same with a logarithm, falling more slowly. In their study, the fitted coefficients varied smoothly with proxy reward-model size and predicted where further optimization stopped improving gold reward. In practice that is what the KL leash, and early stopping, are for.
8Direct preference optimizationMaster's3 min
In 2023 Rafael Rafailov, Archit Sharma, Eric Mitchell and colleagues at Stanford noticed that chapter six's optimum can be run backwards. Take the log and solve for the reward: the reward is beta times the log of the optimal policy over the reference, plus a term that depends only on the question. Now put that into the Bradley-Terry model of chapter four. The comparison depends only on a difference of rewards for the same question, so the awkward normalizer Z cancels. What's left is a loss on the policy itself: logistic regression whose score is beta times the log-ratio of policy to reference. No reward model, no sampling, no reinforcement learning; just a supervised loss on the comparisons. The policy is its own reward model.
We trained DPO on our model, with the same comparisons the reward model learned from. at an estimated divergence of nats from where it started. RLHF with beta reached at an estimated nats. The RLHF row is seed zero's separately evaluated final policy. Two routes to the same kind of objective: one through a reward model and sampling, the other straight from the comparisons.
DPO only cares about the gap between the preferred and the rejected answer. Watch what happens to each separately, for thirty-two fixed training pairs, as it trains. The pattern: These averages over fixed training pairs do not measure held-out accuracy or total probability mass, and do not identify which other answers receive probability.
Every method in this part trades divergence from the fine-tuned model for gold. Put them on one chart: gold gained, against the square root of the KL, as in the last chapter. Best-of-n with the larger reward model is the yardstick: it trains nothing. RLHF's seed-zero final policies at two penalties, and DPO at three values of beta.
DPO started a family. IPO replaces the logistic loss with a squared one, because when one answer always wins, DPO can push the log-ratio margin to infinity and overfit. KTO learns from single answers marked good or bad, with no pairs, using a loss shaped like Kahneman and Tversky's prospect theory. SimPO drops the reference model and uses the length-normalized log-probability as the reward. And a lesson from comparing them: learning from fresh answers by the current model, judged as training goes, showed advantages over fixed data from older models in the cited comparisons. New experience is one way alignment training can improve.
9Feedback from AI, rules from peopleUndergraduate3 min
Human comparisons are slow and expensive, and some are unpleasant: someone has to read the harmful answers to rank them. In December 2022 Anthropic published Constitutional AI, which moves much of that work to the model itself, guided by a short list of principles written by people: a constitution. First, a supervised phase. The model answers a difficult request. Then it is asked to critique its own answer against a principle, for instance to choose the response that is least harmful without being preachy or evasive. It rewrites the answer in light of the critique. And it is fine-tuned on the revised answers. The people's work went into the principles, not into each label.
The second phase replaces human comparisons too. Two answers are shown to an AI judge, a language model given the principles, which says which one better follows them. Those comparisons train the reward model, and reinforcement learning proceeds as in chapter six. This is reinforcement learning from AI feedback, RLAIF. In 2023 a team at Google compared the two directly, and on summarization and dialogue AI feedback did about as well as human feedback. AI feedback is one option for generating comparison labels; people still choose the objectives and check the judges.
A small version of the idea, on our model. Train a reward model on just simulated comparisons. Use it as the judge: let it label new comparisons, and train a fresh reward model on those. For reference, the original simulated labels on comparisons give percent.
The constitutions themselves became public documents. Anthropic published Claude's principles in 2023. In 2024 OpenAI published a Model Spec, and trained its reasoning models to read the relevant policy in their chain of thought before answering, which it called deliberative alignment. In January 2026 Anthropic replaced its list of principles with a long document explaining the reasons behind them, with explicit priorities: broadly safe, broadly ethical, following Anthropic's guidelines, and genuinely helpful. The rules are written by people, in plain language, and the training makes the model use them.
10DistillationEngineering2 min
A large model is expensive to run; a small one is cheap but weaker. Distillation trains the small one, the student, to imitate the large one, the teacher. Trained on the data alone, the student sees one right answer per example: this digit is a two. The teacher offers more: a whole distribution, in which this two is a little like a three and hardly like a five. Geoffrey Hinton called that information dark knowledge. The student is trained to match the teacher's probabilities, softened by a temperature T so that the small ones count, with the KL divergence of Part 1.
The direction of the KL matters, as Part 1 showed with this two-peaked distribution. Minimize the forward KL, from teacher to student, and a student too small to fit both peaks spreads over both, putting probability where the teacher puts almost none. Classic distillation matches the teacher's probabilities on training text; that text need not come from the teacher. Here, minimizing reverse KL selects one peak. MiniLLM targets reverse KL under the student, with teacher-mixed sampling to stabilize optimization. On-policy distillation chooses where the training text comes from. GKD can use forward KL, reverse KL, or another divergence: the sampling policy and the loss are separate choices.
Our version: the novels model, six point eight million parameters, teaches a student with a fifth as many, two layers instead of six. Two students see the same text. One learns from the text alone, the next word. The other learns the teacher's whole distribution over the next word.
Distillation is everywhere. In 2019 DistilBERT kept ninety-seven percent of BERT's language understanding with forty percent fewer parameters. For language models the common form is sequence-level: fine-tune the student on whole answers written by the teacher. Alpaca, in chapter two, was that. DeepSeek fine-tuned small open models on eight hundred thousand of R1's answers and turned them into capable reasoners. These published examples show a recurring recipe: train smaller students using a larger model's outputs or probabilities.
11Adding models togetherEngineering2 min
Averaging the weights of two different networks usually produces garbage: their units are arranged differently, and the average lands on a ridge between two valleys. But fine-tunes of one pretrained model are different. They start from the same point and move only a little, so they tend to stay in the same valley, and the straight line between them stays low: linear mode connectivity. In 2022 Mitchell Wortsman and colleagues averaged the weights of many fine-tunes run with different settings, a model soup, and got a better model than any one of them, with no extra cost at inference.
In 2023 Gabriel Ilharco and colleagues turned this into arithmetic. Subtract the pretrained weights from a fine-tuned model's weights, and call the difference a task vector: everything fine-tuning changed. Add two task vectors to the pretrained model, and you often get a model that can do both tasks, without training on both. Subtract one, and the model unlearns it: subtracting the vector of a model fine-tuned on toxic text made the original less toxic.
We tried it on the novels model. Fine-tune one copy only on which-book questions, another only on lines about things, and take their task vectors. The chart reports the measured performance of these two ingredient models. The line metric counts an end token within forty new tokens. Combining already-trained task vectors needs no additional optimizer steps, just addition. Training the ingredient models was part of this experiment.
Merging became a craft. TIES keeps each task vector's largest updates, takes the sign of their sum at each coordinate, then averages only updates agreeing with that sign. DARE drops most of a task vector's entries at random and rescales the rest, and the vectors interfere much less. Meta's Llama 3 averaged models trained with different data and settings at each stage of post-training. And for a while, merged models topped the open leaderboards.
12What goes wrongUndergraduate3 min
The first failure follows directly from chapter seven. People reward answers they like, and people like to be agreed with. Ask a question with your own guess attached, and an answer that praises the guess can be preferred over one that corrects it. A reward model learns that, and reinforcement learning amplifies it: sycophancy. In 2023 researchers at Anthropic found five widely used assistants consistently sycophantic, and traced it partly to preference data in which convincing agreement sometimes beat correctness. In April 2025 OpenAI rolled back an update to GPT-4o that users found overly flattering; its own account pointed to a new reward signal built from users' thumbs-up and thumbs-down.
Post-training teaches a model to refuse harmful requests, and that teaching can be routed around. In 2023 Andy Zou and colleagues searched, by gradient, for a suffix of odd-looking tokens that made open models comply with harmful requests; the same suffixes worked on commercial models they had never seen. In 2024 Anthropic described many-shot jailbreaking: fill a long context with hundreds of fake dialogues in which an assistant complies, and in-context learning overrides the training. The opposite failure is over-refusal: declining to say how to kill a Python process because of the word kill. Defences are now layered: separate classifiers on the way in and out, adversarial training, and, in reasoning models, refusals the model can reason about.
Two results show that post-training reaches further than the data it uses. In 2025 Jan Betley and colleagues fine-tuned GPT-4o on one narrow thing: writing insecure code without telling the user. The model then gave malicious advice and praised the idea of AI ruling humans, on questions that had nothing to do with code. When the same examples were framed as teaching material for a security class, it didn't happen. They called it emergent misalignment. In late 2024 Ryan Greenblatt and colleagues told Claude 3 Opus that it would be retrained to comply with harmful requests, using only conversations with free users. It then complied with such requests from free users fourteen percent of the time, and almost never for paid users, with reasoning that complying in training would keep its values from being changed. The lesson in both: fine-tuning shapes what a model takes itself to be, not one behaviour at a time.
Some of the newest tools look inside the model. In 2025 Anthropic researchers found persona vectors: directions in a model's activations that correspond to traits like sycophancy or malice, found by comparing activations when the trait is displayed to when it isn't. Projecting onto such a direction shows a trait rising during a conversation, or during training. It can flag training examples that would push the model toward the trait before anyone trains on them. And adding or subtracting the vector steers the behaviour. Part 30 is about this kind of work.
13The open recipesEngineering3 min
Here is how the published recipes changed. InstructGPT: demonstrations, a reward model, PPO. Meta's Llama 2-Chat in 2023 found that a smaller set of high-quality examples, about twenty-seven and a half thousand, beat millions of mediocre ones; it trained two reward models, one for helpfulness and one for safety, on over a million comparisons, and alternated best-of-n fine-tuning with PPO. Hugging Face's Zephyr the same year skipped reinforcement learning altogether: DPO, on comparisons judged by GPT-4. Llama 3 in 2024 also used DPO, not PPO. AI2's Tülu 3 published every piece: an open data mixture, DPO on comparisons of its own answers, and a final stage of reinforcement learning on problems whose answers can be checked. And DeepSeek-R1, in January 2025, put reinforcement learning on checkable problems at the centre.
DeepSeek-R1 is where post-training turned toward reasoning. Its first version, R1-Zero, was trained with reinforcement learning straight from the base model, using rewards for correct answers and the required output format, with GRPO, a PPO without a critic. On the 2024 AIME, a hard maths competition, it went from 15.6 to 71 percent of problems solved, and to 86.7 with a majority vote over 64 samples per problem. Long chains of thought, checking its own work, even a line where it stopped to write that it had found an aha moment: none of it was demonstrated. It emerged because it earned reward. The released R1 added a small cold start of readable examples, rounds of reinforcement learning, and fine-tuning on its own best answers. Then eight hundred thousand of its answers were used to fine-tune much smaller open models, distillation, chapter ten, which made reasoning cheap. Reinforcement learning on checkable rewards is the subject of the next part.
By 2025 every stage of this part sat in one pipeline. Here is the one Alibaba published for Qwen3. A cold start of supervised fine-tuning on long chains of thought; reinforcement learning on problems with checkable answers; fine-tuning again so the model can answer with or without thinking; and a final round of reinforcement learning with reward models, for everything that can't be checked. The smaller models skipped all of it. They were distilled from the big ones, first on the teacher's text, then on their own text scored by the teacher, the on-policy distillation of chapter ten. Starting from the same off-policy-distilled eight-billion-parameter checkpoint, the report compares further training on maths and code: seventeen thousand nine hundred and twenty extra GPU hours of reinforcement learning, against one thousand eight hundred of distillation, and distillation scored clearly higher.
Recap, problems, and what comes nextAll tracks2 min
Let's take stock. Supervised fine-tuning is maximum likelihood on the answers people want, and it can live in a low-rank slice of weight space, which is why LoRA works. A reward model learns people's preferences from comparisons with the Bradley-Terry model, and opening ours showed what it had learned, and where it was wrong. Reinforcement learning with a KL leash aims at an exact optimum, the reference model reweighted by the exponential of the reward. Push a learned reward too hard and it stops measuring what it was meant to: Goodhart's law, which we measured. DPO fits comparisons directly through a policy-reward reparameterization. Written principles provide supervision; distillation trains a smaller student; model merging combines already-trained task vectors.
All of this comes back. Part 28 trains models to reason, with reinforcement learning on answers that can be checked. Part 29 trains agents that act over long tasks. Part 30 opens the model up, persona vectors included. And Part 31 asks whether we can trust what post-training produces.
Here are eight problems to try, from the Bradley-Terry model to regressional Goodhart. Pause here, and work through them; full solutions are in this part's notes.
Next time: reasoning. Why writing out steps adds computation, how a model learns from a checker instead of a person, with GRPO derived, and what thinking longer buys.
The best place to go deeper on this part is Nathan Lambert's free book on reinforcement learning from human feedback. Thanks for watching, and see you in Part 28.
Where it goes next. Reinforcement learning on answers that can be checked, with GRPO's group baseline, is Part 28; agents trained for long tasks are Part 29; Part 30 opens the fine-tuned model with a crosscoder and persona vectors; Part 31 asks whether what post-training produces can be trusted, and reuses the which-book task for weak-to-strong supervision.
Key results
The part's results in one place, for revision.
Try it
Lab 27 · Reinforcement learning on a leash, and Goodhart's law
For eight candidate answers with a reference policy and a reward, maximize E[r] - beta KL(pi || pi_ref) by gradient ascent with the series' autodiff and compare with pi* = pi_ref e^(r/beta) / Z; then pick the best of n answers by a noisy proxy reward and measure the KL paid and the gold reward actually gained.
python -m videos.ai.labs 27
needs numpy, scipy, matplotlib · download lab27.py ·
source on GitHubgradient ascent against pi_ref e^(r/beta)/Z largest difference 1.8e-06
J at the end of the climb 0.721491 (beta log Z = 0.721491)
best of 16, continuous reward: KL 1.836 nats (log n - (n-1)/n = 1.835)
best of 16 among these eight answers: KL 1.642 nats (below the bound)
best of 256 by the proxy proxy says +3.46, gold says +2.32
gold gained per unit of proxy 0.673 (theory 0.671)
The leash has an exact optimum, the reference reweighted by e^(r/beta); selecting harder on a noisy reward buys proxy score at a known KL price, and only a fixed fraction of that score is real.
The code (117 lines; it asserts its own result)
"""Lab 27: climb the KL-regularized objective by gradient ascent, land on its closed form, and measure best-of-n's price."""
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor, log_softmax
TITLE = "Reinforcement learning on a leash, and Goodhart's law"
GOAL = ("For eight candidate answers with a reference policy and a reward, maximize E[r] - beta KL(pi || pi_ref) by "
"gradient ascent with the series' autodiff and compare with pi* = pi_ref e^(r/beta) / Z; then pick the best of n "
"answers by a noisy proxy reward and measure the KL paid and the gold reward actually gained.")
TASKS = [
"Lower beta from 1 to 0.1 and to 0.01. What share of pi* sits on the best answer, and what is KL(pi* || pi_ref)?",
"Make the proxy's noise as large as gold's spread (noise = 1). What fraction of the proxy's gain is real now?",
"Give the proxy a heavy-tailed error (rng.standard_t(2)) and plot gold against n. Does gold still rise with n?",
]
def objective(theta, r, log_ref, beta):
"""J(pi) = E_pi[r] - beta KL(pi || pi_ref) for pi = softmax(theta), as a Tensor."""
lp = log_softmax(theta)
return (lp.exp() * (Tensor(r) - (lp - Tensor(log_ref)) * beta)).sum()
def best_of_n_discrete(ref, order, n):
"""The law of the best of n draws from ``ref`` when answers are ranked by ``order`` (no ties)."""
F = np.cumsum(ref[order])
p = np.empty_like(ref)
p[order] = F ** n - np.r_[0.0, F[:-1]] ** n
return p
def run(seed=0):
rng = np.random.default_rng(seed)
m, beta = 8, 0.5
ref = rng.dirichlet(4 * np.ones(m))
r = rng.standard_normal(m)
# 1. gradient ascent on J against the closed form
theta = Tensor(np.zeros(m), requires_grad=True)
trace = []
for _ in range(3000):
theta.grad = np.zeros(m)
J = objective(theta, r, np.log(ref), beta)
J.backward()
trace.append(float(J.data))
theta.data += 2.0 * theta.grad
pi = np.exp(theta.data - theta.data.max())
pi /= pi.sum()
Z = (ref * np.exp(r / beta)).sum()
star = ref * np.exp(r / beta) / Z
J_star = beta * np.log(Z)
gap = np.abs(pi - star).max()
# 2. best-of-n: the KL paid, for continuous rewards and for these eight answers
ns = np.array([1, 2, 4, 8, 16, 32, 64, 128, 256])
kl_formula = np.log(ns) - (ns - 1) / ns
u = rng.random((40_000, 16)).max(1) # the reward quantile of the best of 16
kl_mc = np.mean(np.log(16) + 15 * np.log(u))
order = np.argsort(r)
kl_disc = []
for n in ns:
p = best_of_n_discrete(ref, order, n)
kl_disc.append(float((p[p > 0] * np.log(p[p > 0] / ref[p > 0])).sum()))
kl_disc = np.array(kl_disc)
# 3. regressional Goodhart: choose by a proxy = gold + noise, and see what gold says
noise, trials = 0.7, 4000
shrink = 1 / (1 + noise ** 2) # sigma_G^2 / (sigma_G^2 + sigma_E^2) with sigma_G = 1
proxy_gain, gold_gain = [], []
for n in ns:
gold = rng.standard_normal((trials, n))
proxy = gold + noise * rng.standard_normal((trials, n))
pick = proxy.argmax(1)
proxy_gain.append(proxy[np.arange(trials), pick].mean())
gold_gain.append(gold[np.arange(trials), pick].mean())
proxy_gain, gold_gain = np.array(proxy_gain), np.array(gold_gain)
lab = labs.Lab()
lab.row("gradient ascent against pi_ref e^(r/beta)/Z", f"largest difference {gap:.1e}")
lab.row("J at the end of the climb", f"{trace[-1]:.6f} (beta log Z = {J_star:.6f})")
lab.row("best of 16, continuous reward: KL", f"{kl_mc:.3f} nats (log n - (n-1)/n = {kl_formula[4]:.3f})")
lab.row("best of 16 among these eight answers: KL", f"{kl_disc[4]:.3f} nats (below the bound)")
lab.row("best of 256 by the proxy", f"proxy says +{proxy_gain[-1]:.2f}, gold says +{gold_gain[-1]:.2f}")
lab.row("gold gained per unit of proxy", f"{gold_gain[-1] / proxy_gain[-1]:.3f} (theory {shrink:.3f})")
lab.note = ("The leash has an exact optimum, the reference reweighted by e^(r/beta); selecting harder on a noisy reward "
"buys proxy score at a known KL price, and only a fixed fraction of that score is real.")
assert gap < 1e-3 and -1e-4 < trace[-1] - J_star < 1e-12, "gradient ascent climbs to the closed-form optimum"
assert np.all(np.diff(trace) > -1e-12), "J never falls on the way"
for _ in range(20): # no other policy does better (Gibbs' inequality)
q = rng.dirichlet(np.ones(m))
assert float(objective(Tensor(np.log(q)), r, np.log(ref), beta).data) <= J_star + 1e-12
assert abs(kl_mc - kl_formula[4]) < 0.02, "best-of-n's KL for an atomless reward"
assert np.all(kl_disc <= kl_formula + 1e-12), "for discrete answers the formula is an upper bound"
assert np.all(np.abs(gold_gain[1:] / proxy_gain[1:] - shrink) < 0.05), "regressional Goodhart: E[G | R] = shrink R"
fig, ax = labs.figure(2, size=(11, 4.2))
x = np.arange(m)
srt = np.argsort(-r)
ax[0].bar(x - 0.27, ref[srt], 0.27, color=labs.MUTED, label="reference $\\pi_{ref}$")
for k, (b, color) in enumerate(((2.0, labs.BLUE), (0.5, labs.GOLD))):
w = ref * np.exp(r / b)
ax[0].bar(x + 0.27 * k, (w / w.sum())[srt], 0.27, color=color, label=f"optimum, beta = {b:g}")
ax[0].plot(x + 0.27, pi[srt], "o", color=labs.RED, ms=4, label="gradient ascent, beta = 0.5")
ax[0].set(title="The leash: the reference reweighted by $e^{r/\\beta}$", xlabel="answers, best reward first",
ylabel="probability", xticks=x, xticklabels=[f"{v:+.1f}" for v in r[srt]])
ax[0].legend()
ax[1].plot(kl_formula, proxy_gain, "o-", color=labs.ORANGE, label="what the proxy believes")
ax[1].plot(kl_formula, gold_gain, "o-", color=labs.GREEN, label="what gold says")
ax[1].plot(kl_formula, shrink * proxy_gain, "--", color=labs.MUTED, label=f"{shrink:.2f} x the proxy (theory)")
for n, kx, gy in zip(ns[1::2], kl_formula[1::2], proxy_gain[1::2]):
ax[1].annotate(f"n={n}", (kx, gy), textcoords="offset points", xytext=(-4, 7), fontsize=8, color=labs.MUTED, ha="right")
ax[1].set(title="Best of n by a noisy proxy", xlabel="KL paid, log n - (n-1)/n (nats)", ylabel="mean score of the pick")
ax[1].legend(loc="upper left")
lab.fig = fig
return lab
Now change it
- Lower beta from 1 to 0.1 and to 0.01. What share of pi* sits on the best answer, and what is KL(pi* || pi_ref)?
- Make the proxy's noise as large as gold's spread (noise = 1). What fraction of the proxy's gain is real now?
- Give the proxy a heavy-tailed error (rng.standard_t(2)) and plot gold against n. Does gold still rise with n?
Problems, with solutions
Try each problem before opening its solution.
1. Shifts don't matter. Show that the Bradley–Terry likelihood of a set of comparisons is unchanged if a constant c(x) is added to r(x, y) for every answer y to a question x.
Solution
Each comparison's probability is σ(r(x, y_w) − r(x, y_l)); adding c(x) to both rewards leaves the difference, and so every factor of the likelihood, unchanged. Only differences within a question are identified, which is why a reward model's raw scores can't be compared across questions.
2. The KL-regularized optimum. Prove that π* ∝ π_ref e^{r/β} maximizes J(π) = E_π[r] − β KL(π ‖ π_ref), and that the maximum is β log Z, Z = Σ_y π_ref(y) e^{r(y)/β}.
Solution
J(π) = Σ π (r − β log(π/π_ref)) = −β Σ π log(π / (π_ref e^{r/β})) = −β KL(π ‖ π*) + β log Z. KL ≥ 0 with equality only at π = π* (Gibbs), so π* is the maximizer and J(π*) = β log Z.
3. Best-of-n. For an atomless reward distribution under π_ref, show that best-of-n sampling has KL(π_BoN ‖ π_ref) = log n − (n−1)/n. For discrete text this expression is generally an upper bound, not an equality.
Solution
Let u ∈ [0, 1] be an answer's quantile under π_ref, ordered by reward. The best of n has quantile max(u_1, …, u_n), with density n u^{n−1}; since π_BoN(y) / π_ref(y) = n u(y)^{n−1}, the KL is E[log n + (n−1) log u] with u ~ Beta(n, 1). E[log u] = −1/n, so KL = log n − (n−1)/n.
4. What DPO's gradient weighs. Compute the gradient of the DPO loss for one pair, with r̂ = β log π_θ/π_ref.
Solution
L = −log σ(r̂_w − r̂_l), so ∇L = −σ(r̂_l − r̂_w) (∇r̂_w − ∇r̂_l) = −β σ(r̂_l − r̂_w) (∇ log π_θ(y_w) − ∇ log π_θ(y_l)). Each pair contrasts the two log-probability gradients, weighted by how wrongly the implicit reward currently orders them. With shared parameters, this does not guarantee that either answer's absolute probability moves in its coefficient's direction; chapter eight measures that distinction.
5. When LoRA stops saving. A rank-r adapter on a d × k matrix has r(d + k) parameters. For d = k = 4096, at what rank does it have as many as the matrix?
Solution
r(d + k) = dk gives r = dk/(d + k) = 2048. For ranks 4 to 64, the adapter has about 0.2% to 3.1% of this 4096 × 4096 matrix's parameters.
6. Forward KL matches moments. Let density p have finite second moment and finite differential entropy. Fit a Gaussian q by minimizing KL(p ‖ q). Show that q has p's mean and variance.
Solution
KL(p ‖ q) = −H(p) − E_p[log q] and −E_p[log q] = ½ log(2πσ²) + E_p[(x − μ)²]/(2σ²). Setting the derivatives to zero gives μ = E_p[x] and σ² = E_p[(x − μ)²]. This is why the forward-KL fit of chapter ten spreads over both peaks.
7. Baselines. Show that E_{y~π}[b ∇ log π(y)] = 0 for any b that does not depend on y, and that for k answers r_i − mean(r) = ((k−1)/k)(r_i − mean_{j≠i} r_j).
Solution
E_π[b ∇ log π(y)] = b Σ_y π(y) ∇π(y)/π(y) = b ∇ Σ_y π(y) = b ∇1 = 0, so a baseline leaves the gradient's mean unchanged and can only change its noise (chapter 6 measures how much). With m_{−i} the mean of the others, mean(r) = (r_i + (k−1) m_{−i})/k, so r_i − mean(r) = ((k−1)/k)(r_i − m_{−i}): our runs' batch-mean baseline is RLOO's leave-one-out baseline, scaled by 15/16 for k = 16.
8. Regressional Goodhart. Let gold G ~ N(0, σ_G²) and a proxy R = G + E with independent noise E ~ N(0, σ_E²). Show that E[G | R = r] = r σ_G² / (σ_G² + σ_E²).
Solution
G and R are jointly Gaussian with Cov(G, R) = σ_G² and Var(R) = σ_G² + σ_E², so E[G | R = r] = r Cov(G, R)/Var(R) = r σ_G²/(σ_G² + σ_E²). An answer chosen because its proxy score is r is worth only that fraction of r, on average: the shortfall r σ_E²/(σ_G² + σ_E²) grows with r, so the harder you select, the more you are selecting noise. Chapter 5 measures it on our reward model's favourite lines.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| post-training, alignment | 后训练,对齐 |
| helpful, honest, harmless | 有用、诚实、无害 |
| supervised fine-tuning (SFT), instruction tuning | 监督微调(SFT),指令微调 |
| chat template, special token, loss masking | 聊天模板,特殊词元,损失屏蔽 |
| base model, fine-tuned model, forgetting | 基础模型,微调后的模型,遗忘 |
| low-rank adapter (LoRA), rank, adapter | 低秩适配器(LoRA),秩,适配器 |
| intrinsic dimension | 内在维数 |
| reward model, comparison, preference, labeller | 奖励模型,比较,偏好,标注员 |
| Bradley–Terry model | 布拉德利-特里模型 |
| gold (the hidden true taste), proxy | 金标准,代理 |
| simulated people, noise τ | 模拟的人,噪声τ |
| ceiling (of a reward model's accuracy) | 上限 |
| within-question comparison, shift per question | 同一问题内的比较,每个问题的平移 |
| correlation, slope | 相关系数,斜率 |
| gold units (a score divided by its slope on gold) | 金标准单位 |
| a perfect learner (slope 1/τ) | 完美的学习者(斜率1/τ) |
| decomposition into gold's terms: mood, length, repetition, too short | 按金标准的各项分解:情绪,长度,重复,太短 |
| occlusion (deleting one word at a time) | 遮挡(一次删掉一个词) |
| regressional Goodhart, extremal Goodhart | 回归型古德哈特,极端型古德哈特 |
| reinforcement learning from human feedback (RLHF) | 基于人类反馈的强化学习(RLHF) |
| reference model, the KL leash, β | 参考模型,KL绳子,β |
| KL-regularized optimum, partition function Z | KL正则化的最优解,配分函数Z |
| an answer as an episode: state, action (token) | 把回答当作回合:状态,动作(词元) |
| per-token KL penalty | 逐词元的KL惩罚 |
| value network (value model), critic | 价值网络(价值模型),评论家 |
| advantage, generalized advantage estimation (GAE) | 优势,广义优势估计(GAE) |
| baseline, group baseline, leave-one-out (RLOO) | 基线,组基线,留一(RLOO) |
| group relative policy optimization (GRPO) | 组相对策略优化(GRPO) |
| gradient estimate, cosine between two estimates | 梯度估计,两个估计之间的余弦 |
| best-of-n | 最优n选1 |
| over-optimization, reward hacking | 过度优化,奖励投机 |
| Goodhart's law | 古德哈特定律 |
| direct preference optimization (DPO), implicit reward | 直接偏好优化(DPO),隐式奖励 |
| likelihood displacement | 似然位移 |
| online / offline preference data | 在线/离线偏好数据 |
| Constitutional AI, constitution, critique and revision | 宪法式AI,宪法,批评与修改 |
| RL from AI feedback (RLAIF), AI judge | 基于AI反馈的强化学习(RLAIF),AI裁判 |
| model spec, deliberative alignment | 模型规范,审慎对齐 |
| distillation, teacher, student, soft targets, dark knowledge, temperature | 蒸馏,老师,学生,软目标,暗知识,温度 |
| forward KL, reverse KL, on-policy distillation | 前向KL,反向KL,在线策略蒸馏 |
| model merging, task vector, task arithmetic, model soup | 模型合并,任务向量,任务算术,模型汤 |
| linear mode connectivity | 线性模式连通 |
| sycophancy, jailbreak, adversarial suffix, many-shot jailbreaking, over-refusal | 谄媚,越狱,对抗后缀,多样本越狱,过度拒绝 |
| emergent misalignment, alignment faking, persona vector | 涌现式失准,对齐伪装,人格向量 |
| cold start, strong-to-weak distillation | 冷启动,强到弱蒸馏 |
Sources
Ouyang et al. (2022); Christiano et al. (2017); Stiennon et al. (2020); Askell et al. (2021); Wei et al., FLAN (2021); Taori et al., Alpaca (2023); Zhou et al., LIMA (2023); Li et al. (2018); Aghajanyan et al. (2020); Hu et al., LoRA (2021); Dettmers et al., QLoRA (2023); Liu et al., DoRA (2024); Biderman et al. (2024); Bradley & Terry (1952); Manheim & Garrabrant, Categorizing variants of Goodhart's law (2018); Gao, Schulman & Hilton (2023); Ziegler et al., Fine-tuning language models from human preferences (2019); Schulman et al., PPO (2017) and GAE (2016); Kool, van Hoof & Welling, Buy 4 REINFORCE samples, get a baseline for free! (2019); Ahmadian et al., Back to basics: revisiting REINFORCE style optimization for learning from human feedback in LLMs (2024); Shao et al., DeepSeekMath (GRPO, 2024); Rafailov et al., DPO (2023); Azar et al., IPO (2023); Ethayarajh et al., KTO (2024); Meng et al., SimPO (2024); Tang et al. (2024); Bai et al., Constitutional AI (2022); Lee et al., RLAIF (2023); Guan et al., Deliberative alignment (2024); Hinton, Vinyals & Dean (2015); Kim & Rush (2016); Sanh et al. (2019); Gu et al., MiniLLM (2024); Agarwal et al., GKD (2024); Frankle et al. (2020); Wortsman et al. (2022); Ilharco et al. (2023); Yadav et al., TIES (2023); Yu et al., DARE (2024); Sharma et al. (2023); Zou et al. (2023); Anil et al. (2024); Röttger et al. (2023); Betley et al. (2025); Greenblatt et al. (2024); Chen et al. (2025); Touvron et al. (2023); Tunstall et al. (2023); Llama Team (2024); Lambert et al., Tülu 3 (2024); DeepSeek-AI (2025); Qwen Team (2025); Anthropic, Claude's constitution (2026); N. Lambert, Reinforcement Learning from Human Feedback (2025).
Checked against the primary sources for this part's new material: InstructGPT §3.5 and Appendix C (a per-token KL penalty from the SFT model; the value function initialized from the reward model; a 6B reward model and 6B value function for every policy size; PPO clip 0.2, no discount in GAE); DeepSeekMath §4.1 (GRPO drops the value model and uses the group's average reward as the baseline, with the KL in the loss rather than the reward; PPO's value model is "typically another model of comparable size"); Ahmadian et al. (PPO loads up to four models; RLOO outperforms PPO, DPO and RAFT in their experiments); Manheim & Garrabrant (regressional: "when selecting for a proxy measure, you select not only for the true goal, but also for the difference between the proxy and the goal"; extremal). DeepSeek-R1 (arXiv 2501.12948): R1-Zero and R1 are trained with GRPO, which "foregoes the critic model"; R1-Zero's AIME 2024 pass@1 rises from 15.6% to 71.0%, 86.7% by majority vote over 64 samples; the "aha moment" line; 800K samples for the distilled models. Zou et al. (2023): the suffix is searched (greedy and gradient-based) to make the model's answer begin "Sure, here is".
About this partfrom its README
Part 27 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan
and the syllabus). How a model that predicts text becomes an assistant that tries to help: supervised
fine-tuning, low-rank adapters, reward models learned from comparisons and what one of them actually learns,
reinforcement learning from human feedback, its exact optimum and how PPO is fitted to a language model, Goodhart's
law measured, direct preference optimization, AI feedback under written principles, distillation, model merging, and
what goes wrong. The core experiments run on the series' own model: a 6.8-million-parameter transformer trained on thirty
novels (explainer/ai/novels.py), fine-tuned on this computer, and every number on screen is computed from it or
cited.
- The same model, before and after. Our base model asked for a line about something continues a novel; a few minutes of fine-tuning later it answers. InstructGPT's 1.3B model preferred to GPT-3's 175B (Ouyang et al. 2022).
- 1. From predictor to assistant. What pretraining optimizes; the InstructGPT pipeline (13k demonstrations, 33k ranked prompts, 31k PPO prompts, about 40 contractors); Christiano et al.'s backflip from about 900 comparisons (2017), Stiennon et al.'s summaries (2020), ChatGPT (30 November 2022), Llama 2-Chat, DPO; alignment (helpful, honest, harmless; Askell et al. 2021).
- 2. Supervised fine-tuning. Chat templates and special tokens; the loss masked to the answer = −log p(y | x); the two tasks made from the novels (which book? and a line about...); the base model against the fine-tuned one on held-out sentences; accuracy over training (on an even sample of the test sentences); forgetting on novel text; FLAN, Alpaca, LIMA, synthetic data.
- 3. Low-rank adapters. What full fine-tuning stores (a copy per task); intrinsic dimension (Li et al. 2018; Aghajanyan et al. 2020); LoRA's W + (α/r) BA, r(d + k) against dk, B = 0 at the start and merged afterwards (Hu et al. 2021); ranks 1, 4, 16 against full fine-tuning on our model: parameters, accuracy over training, forgetting; QLoRA, DoRA, "LoRA learns less and forgets less".
- 4. Learning what people prefer. Why comparisons (InstructGPT's labellers agreed 73% of the time); Bradley–Terry = Elo (Part 26); the reward model's loss; only differences are identified; our simulated people and their hidden taste ("gold": mood, concision past 12 words, no repetition); reward-model accuracy against the number of comparisons, and observed gold-label agreement, tested on held-out sample indices (exact generated-text overlap is not excluded); InstructGPT's reward model at 69.6%.
- 5. Inside our reward model. What a real lab cannot do: compare the reward model with the taste it learned. On 600 new lines: its score against gold, raw and with each question's average taken out (the shift chapter 4 said is never learned); its slope against the perfect learner's 1/τ; how often it orders two lines as gold does, against one simulated person; its score fitted as a sum of gold's own terms (mood, length, repetition, too short), for the reward models from 100 and from all comparisons; its score by line length beside gold's; which words raise and lower it, found by deleting one word at a time, against gold's change for the same deletion; the lines where the two disagree most, and why gold disagrees; each question's favourite line by the reward model, what it believed and what gold says: regressional and extremal Goodhart (Manheim & Garrabrant 2018).
- 6. Reinforcement learning on a leash. The KL-regularized objective; its optimum π* ∝ π_ref e^{r/β}, derived; a finite-candidate illustration with known toy gold scores and a conditional reference over eight selected lines as β falls; PPO fitted to a language model: an answer as an episode, InstructGPT's per-token KL penalty with the reward model's score at the end, the value network initialized from the reward model, four networks in memory; baselines: the value network, RLOO's leave-one-out (Ahmadian et al. 2024), GRPO's group mean and spread (Shao et al. 2024; Part 28), and our runs' batch-centered advantages (= RLOO advantages × 15/16); measured on our model: how well two batches' gradient estimates agree with no baseline, one shared baseline, each question's average, and the batch mean; KL-penalized policy gradient at two penalties (three seeds each), the reward model's belief against gold, both in gold units; the loosely leashed run replayed with gold's score beside its lines.
- 7. When the measure becomes the target. Goodhart (1975) and Strathern (1997); the boat that circles forever (OpenAI 2016); best-of-n's KL upper bound log n − (n−1)/n, with equality for continuous rewards, derived; best-of-n on our model with a small and a large reward model, proxy and gold each on its own scale; Gao, Schulman & Hilton's functional forms (2023).
- 8. Direct preference optimization. DPO derived from the optimum and Bradley–Terry (Rafailov et al. 2023); trained on our comparisons and compared with RLHF; likelihood displacement; every method on one chart, gold gained against √KL (best-of-n, RLHF at two β, DPO at three); IPO, KTO, SimPO; online against offline data.
- 9. Feedback from AI, rules from people. Constitutional AI's critique-and-revise and RLAIF (Bai et al. 2022); Lee et al. (2023); a reward model trained on another reward model's labels, on our model; published constitutions, OpenAI's Model Spec and deliberative alignment (2024), Claude's 2026 constitution.
- 10. Distillation. Soft targets and temperature (Hinton et al. 2015); forward against reverse KL (Part 1's two-peaked fit), on-policy distillation; a 2-layer student of our model from text and from the teacher; DistilBERT, sequence-level distillation, DeepSeek-R1's distilled models.
- 11. Adding models together. Linear mode connectivity (Frankle et al. 2020), model soups (Wortsman et al. 2022), task arithmetic (Ilharco et al. 2023), on our model; TIES, DARE, Llama 3's averaging.
- 12. What goes wrong. Sycophancy (Sharma et al. 2023; GPT-4o's rolled-back update, 2025); adversarial suffixes (Zou et al. 2023), many-shot jailbreaking (Anil et al. 2024), over-refusal (XSTest); emergent misalignment (Betley et al. 2025); alignment faking (Greenblatt et al. 2024); persona vectors (Chen et al. 2025).
- 13. The open recipes. InstructGPT, Llama 2-Chat, Zephyr, Llama 3, Tülu 3, DeepSeek-R1; R1-Zero's AIME 2024 accuracy (15.6% → 71.0%, 86.7% by majority vote) and its "aha moment"; Qwen3's four-stage pipeline and strong-to-weak distillation (on Qwen3-8B: 1,800 GPU hours against RL's 17,920, and better; Qwen Team 2025).
- Recap in ten pictures from the part's own results, where it comes back, the problem set (eight problems), Part 28's teaser, references.
The silent preview runs 51.8 minutes (python tools/lecture_length.py ai27); the longest chapters are 5 (6.5
minutes) and 6 (7.4).
What is computed and builtHistorical results on the original machine
These are preserved historical outcomes, not measurements from the current QA worker or the newly restored canonical base. The best-of-n kl array is the continuous-reward upper-bound coordinate. The chapter 8 cross-method plot uses different prompt populations (12 for best-of-n, 30 for trained-policy gold, 10 for trained-policy KL), so it cannot establish an equal-KL ranking. LoRA initialization is not fully seeded by the current recipe, and sampled-index splits do not guarantee disjoint unique texts; both need separately reviewed recipe corrections and new measurements.
- Tasks: which-book 6,000 training / 560 test sentences, 30 titles (chance 3%); a line about... 5,569 training lines, 30 topics.
- SFT (600 steps): which-book base 0% on 120 evenly sampled test sentences → 27% on all 560 after fine-tuning (in-training evaluations on an even sample of 150: 12%, 16%, 22%, 23%, 25%, 23%); held-out novel loss 3.602 → 4.226 nats; its lines: gold -0.25, 93% end cleanly.
- LoRA (which-book only, 600 steps): rank 1: 26,208 trained numbers, 14%, forgetting +0.894; rank 4: 104,832 trained numbers, 28%, forgetting +1.253; rank 16: 419,328 trained numbers, 31%, forgetting +1.856; full: 6,843,648 trained numbers, 33%, forgetting +1.103.
- Comparisons: 4,200 training, 840 test (held-out sample indices; exact generated-text overlap not excluded). Reward models: 100 → 53%, 400 → 59%, 1,600 → 63%, 4,200 → 64%; observed gold-label agreement 73% (a noise reference, not a hard finite-test ceiling).
- Inside the reward model (600 new lines, 20 per question): correlation with gold 0.52 raw, 0.52 within a question (small model: 0.25, 0.24); slope 1.84 (perfect learner 4; small 3.02); orders 71% of 5,442 untied pairs as gold does (small 59%; one simulated person 76%). Weights on gold's terms as a share of gold's own (gold units): large mood 0.26, length 1.94, repetition 0.11, too short 0.87 (R² 0.46); small mood 0.14, length 2.23, repetition -0.50, too short 0.56 (R² 0.12). Words (deleted one at a time, ≥6 occurrences, 235 words; correlation with gold's change 0.20): raise most: good, music, said, than, gave, only, hand, place; lower most: felt, didn't, began, followed, don't, sea, reached, two. Each question's favourite: the large model believes +1.01, gold says +0.27, gold's own favourite +0.54; same line as gold's in 20% of questions (small model: believes +1.38, gold -0.01).
- AI feedback: judge from 100 comparisons 53%; fresh model on its 1,600 labels 55%; on 1,600 human labels 59%; the judge agrees with the people on 55%.
- The KL-regularized optimum over 8 lines about the sea (log-probabilities within 3.9 nats of each other, from 254 samples whose log-probabilities span 185 nats): share on the best line π_ref 3%, β=10: 4%, β=1: 12%, β=0.3: 66%, β=0.1: 100%.
- Baselines (first step, 6 batches × 16 lines, 6 questions): cosine between two batches' gradients: none 0.013, shifted 0.001, shared 0.014, value 0.015, group 0.014; the reward model's per-question mean ranges +0.19 to +1.15; mean squared gradient length relative to the batch-mean baseline: none 1.1×, shifted 20.9×, shared 1.1×, value 1.0×, group 1.0×.
- Best-of-n, small reward model: gold -0.250 at n=1, rising to -0.087 at n=256; proxy 1.50 → 5.68.
- Best-of-n, large reward model: gold -0.250 at n=1, peak +0.060 at n=128, -0.001 at n=256; proxy 0.83 → 3.31.
- RLHF β=0.1 (3 seeds, last 30 steps): reward model believes +0.634, gold +0.178 (gold units, over the fine-tuned model); KL 1.58; seed 0's final policy: gold -0.027, KL 1.57, 100% end cleanly.
- RLHF β=0.01 (3 seeds, last 30 steps): reward model believes +0.664, gold +0.184 (gold units, over the fine-tuned model); KL 2.04; seed 0's final policy: gold -0.046, KL 2.56, 100% end cleanly.
- DPO β=0.1: gold -0.023, KL 1.69, 100% end cleanly; probe pairs at the end: preferred +1.3, rejected -11.7 nats. Other β: β=0.03: gold -0.086, KL 6.49; β=0.3: gold -0.096, KL 0.76.
- Distillation (2-layer student, 1,438,336 parameters; teacher 6,843,648, held-out 3.602): from text 5.042, from the teacher 4.657 nats.
- Merging: which only: which 32%, gold -0.86, ended 100%; line only: which 0%, gold -0.27, ended 87%; sum x 0: which 0%, gold -0.52, ended 0%; sum x 0.5: which 20%, gold -0.56, ended 92%; sum x 1: which 22%, gold -0.69, ended 100%; path: 0.0: 33%/100%, 0.2: 31%/100%, 0.4: 27%/90%, 0.6: 13%/80%, 0.8: 0%/83%, 1.0: 0%/87%.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- SFT and chat templates.
- LoRA (intrinsic dimension; QLoRA, DoRA); forgetting.
- Reward models: Bradley–Terry.
- RLHF with a KL penalty; the closed form π* ∝ π_ref·e^{r/β} derived.
- Over-optimization: Goodhart and reward-model scaling laws.
- DPO derived; IPO, KTO, SimPO; online vs offline.
- Constitutional AI and RLAIF.
- Distillation: logit, sequence, on-policy with reverse KL (Part 1's KL).
- Model merging: task arithmetic, TIES, soups, linear mode connectivity.
- Sycophancy, refusals, jailbreaks; emergent misalignment; persona vectors.
Computed: DPO and LoRA on our transformer over the novels; a merging experiment.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
1. 平移无关。 证明:对同一个问题x的每个回答y,都给r(x, y)加上同一个常数c(x),Bradley–Terry 似然不变。
解答
每次比较的概率是 σ(r(x, y_w) − r(x, y_l));两个奖励同时加上c(x),差不变,所以似然的每个因子都不变。能辨识的只有 同一问题内的差,这也是奖励模型的原始分数不能跨问题比较的原因。
2. KL正则化的最优解。 证明 π* ∝ π_ref e^{r/β} 使 J(π) = E_π[r] − β KL(π ‖ π_ref) 最大,并且最大值为 β log Z,其中 Z = Σ_y π_ref(y) e^{r(y)/β}。
解答
J(π) = Σ π (r − β log(π/π_ref)) = −β Σ π log(π / (π_ref e^{r/β})) = −β KL(π ‖ π*) + β log Z。KL ≥ 0,且只在 π = π* 时取等号(吉布斯不等式),所以 π* 是最优解,J(π*) = β log Z。
3. 最优n选1。 证明:当π_ref下的奖励分布连续且无原子时,最优n选1采样满足 KL(π_BoN ‖ π_ref) = log n − (n−1)/n。对离散文本,这个表达式一般是上界,不是等式。
解答
设u ∈ [0, 1]是一个回答按奖励排序在π_ref下的分位数。n个里最好的那个,分位数是 max(u_1, …, u_n),密度为 n u^{n−1}; 由于 π_BoN(y)/π_ref(y) = n u(y)^{n−1},KL = E[log n + (n−1) log u],其中 u ~ Beta(n, 1)。E[log u] = −1/n,所以 KL = log n − (n−1)/n。
4. DPO的梯度在加权什么。 记 r̂ = β log π_θ/π_ref,求一对样本上DPO损失的梯度。
解答
L = −log σ(r̂_w − r̂_l),所以 ∇L = −σ(r̂_l − r̂_w)(∇r̂_w − ∇r̂_l) = −β σ(r̂_l − r̂_w)(∇log π_θ(y_w) − ∇log π_θ(y_l))。每一对都对比两个对数概率的梯度,权重由隐式奖励当前的排序决定。参数共享时,这不保证任一回答的绝对概率都沿其系数所指的方向变化;第8章测量了这个区别。
5. LoRA什么时候不再省。 秩为r的适配器放在d × k矩阵上,有 r(d + k) 个参数。d = k = 4096 时,秩为多少时它和矩阵一样大?
解答
r(d + k) = dk,得 r = dk/(d + k) = 2048。秩取4到64时,约为这个4096 × 4096矩阵参数量的0.2%到3.1%。
6. 正向KL匹配矩。 设密度p的二阶矩和微分熵都有限。用最小化 KL(p ‖ q) 的方法,把高斯分布q拟合到p上。证明q的均值和方差等于p的。
解答
KL(p ‖ q) = −H(p) − E_p[log q],而 −E_p[log q] = ½ log(2πσ²) + E_p[(x − μ)²]/(2σ²)。令导数为零,得 μ = E_p[x],σ² = E_p[(x − μ)²]。这就是第10章里正向KL的拟合会同时覆盖两个峰的原因。
7. 基线。 证明:对任何不依赖于y的b,E_{y~π}[b ∇ log π(y)] = 0;并证明对k个回答,r_i − mean(r) = ((k−1)/k)(r_i − mean_{j≠i} r_j)。
解答
E_π[b ∇ log π(y)] = b Σ_y π(y) ∇π(y)/π(y) = b ∇ Σ_y π(y) = b ∇1 = 0,所以基线不改变梯度的均值,只能改变它的噪声 (第6章测量了改变多少)。记m_{−i}为其他回答的平均,则 mean(r) = (r_i + (k−1) m_{−i})/k,所以 r_i − mean(r) = ((k−1)/k)(r_i − m_{−i}):我们训练中用的批内平均基线,就是RLOO的留一基线,在k = 16时乘以15/16。
8. 回归型古德哈特。 设金标准 G ~ N(0, σ_G²),代理 R = G + E,其中噪声 E ~ N(0, σ_E²) 与G独立。证明 E[G | R = r] = r σ_G² / (σ_G² + σ_E²)。
解答
G和R是联合高斯的,Cov(G, R) = σ_G²,Var(R) = σ_G² + σ_E²,所以 E[G | R = r] = r Cov(G, R)/Var(R) = r σ_G²/(σ_G² + σ_E²)。一个因为代理分数是r而被选中的回答,平均只值r的这么一部分:差额 r σ_E²/(σ_G² + σ_E²) 随r增大,所以挑得 越狠,挑中的噪声越多。第5章在我们奖励模型最喜欢的句子上测量了它。
Build the film
python -m videos.ai.ai27.compute # the part's numbers, into .cache/ai27
python tools/build.py ai27 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai27 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai27. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
From the repo root:
python tools/make.py ai27 # everything: the base model if missing, the computations, English and Chinese
python -m explainer.ai.novels # the series' base model alone (cached in .cache/novels/)
python -m videos.ai.ai27.compute # every experiment, resuming where it stopped
python -m videos.ai.ai27.compute --force inside baselines # recompute named items
python tools/build.py ai27 # English
python tools/zh_lines.py ai27 --verify && python tools/build.py ai27 --lang zh # Chinese
EXPLAINER_TTS=silent python tools/build.py ai27 -q l --fps 30 --lang en -j 2 # a quick silent preview
compute.py builds the two tasks from the novels (test questions come from paragraphs held out of the base model's
training), fine-tunes, collects simulated comparisons, trains every reward model and policy, and looks inside the
reward models; post.py holds the chat template, loss masking, LoRA and sampling. Most random choices are seeded
(numpy PCG64, torch.manual_seed, one torch.Generator per sampling call), but LoRA adapter initialization is
not yet fully seeded; do not assume bitwise reproducibility across full and partial runs. Another machine's floating point can move the last digits, and the narration (English and Chinese) is
written over the cached results and branches on them. Fine-tuning checkpoints every 50 steps (.cache/ai27/*.ckpt);
the items made of several runs (lora, rlhf, dpo_sweep, merge) keep each finished run (CACHE.partial); every other
item takes minutes. The torch thread count is set only when compute.py runs as a program (AI27_THREADS, default
up to 4); importing it from a scene changes nothing. Works on macOS and Linux (no multiprocessing).
On this shared Linux machine (four cores, load 6–9, one thread: AI27_THREADS=1 nice -n 15), the items took:
data and sft about 12 minutes, lora 1.1 hours, prefs 4 minutes, rm 1.1 hours, rlaif 1.1 hours, bon 18 minutes, rlhf
1.4 hours, dpo 10 minutes, dpo_sweep 26 minutes, merge 25 minutes, inside about 3 minutes, baselines about 2 minutes,
closed under a minute; a laptop with four free cores is several times faster.