Lecture guides›
✎

Lecture guide: Mid/post-training (SFT/RLHF)#

Lecturer: course staff · Course: Stanford CS336 Language Modeling from Scratch, Spring 2026, lecture 15 · Length: 1:20:00 Video: watch on YouTube Chapters that cite this lecture: 11. Post-Training: SFT, RLHF and RLVR · 12. Alignment and Multimodality

In one sentence: Tatsu Hashimoto takes a base model most of the way to a chat assistant, first with supervised fine-tuning and its data, where quality, style and what the model already knows decide more than quantity, then with reinforcement learning from human feedback, its annotators, its algorithms and its failure modes.

Before you watch#

The lecture assumes the pretraining picture of the earlier lectures and nothing about reinforcement learning beyond gradient descent; PPO is only sketched and deferred to the next lecture. Most of it is about data: what instruction-following data looked like over the years, and who annotates it. The video has no chapter marks. The chapters Post-Training: SFT, RLHF and RLVR and Alignment and Multimodality follow it.

The lecture, part by part#

0:00–6:00 From GPT-3 to ChatGPT: why post-training#

Post-training is one of the messier parts of language modelling, artisanal in many ways. Everything so far builds a souped-up GPT-3, and the uses of such a model are limited: copywriting and small tasks that need neither reliability nor instruction following. This lecture goes from GPT-3 to something close to ChatGPT; the next goes from ChatGPT to the thinking models. Instruction following, a long and complicated prompt answered sensibly, was out of reach at GPT-3, when a few good examples in the prompt were all the steering there was, and arrived with GPT-3.5 and GPT-4. Pretraining remains the basis: post-training alone achieves nothing. Its job is to extract behaviours from the primordial soup of pretraining, which takes explicit data collection, explicit steering and messy engineering. Public information about frontier post-training is sparse. The detailed sources are old, from before competition heated up: the summarization paper that introduced the reward-modeling recipe, whose appendices hold annotation guidelines, and Anthropic's helpfulness and harmlessness paper of 2022. Vendors now release nothing, since the data is the trade secret, and open recipes rely on distillation. As an example, Scale AI's internal documents leaked in 2023: trying to improve Google Bard, its teams tried to reverse-engineer GPT-4 and have annotators produce responses more detailed than GPT-4's. The algorithms, by contrast, are understood; the leverage is in the data. In this book: Post-Training: SFT, RLHF and RLVR › Why this matters · Post-Training: SFT, RLHF and RLVR › The core idea.

6:00–10:00 The recipe, and the lineage of SFT data#

The recipe has two parts. First, demonstration data: for each prompt an annotator's response, used for supervised fine-tuning. Second, reinforcement learning that shapes the behaviour toward what people judge good. The first part is all about data, since the method is pretraining under another name, so the lecture covers examples, history, trends in the open-source world and pitfalls. In chronological order: FLAN, used to train T5, gathered every supervised NLP data set on the reasonable thought that the model should train on all of them, which for various reasons was not the right thing to do; Self-Instruct had the model generate the data itself, since models keep improving and may beat some annotators; distillation approaches followed, Alpaca among them and Vicuna from Berkeley, which distilled on prompts that users had shared; Open Assistant was entirely human-driven, like a Wikipedia of prompts and responses; WizardLM and Tulu 3 stand for a generation that invents increasingly elaborate ways of generating instruction data with models; and the newest pipelines produce data for agents and tool use. In the closed-source world, how human data is collected is the ingredient none of this shows. Asked whether the pairs must be correct: collect the best responses available, because bad ones teach bad behaviour, though models can learn to follow instructions from strange data too, as a paper by one of Liang's former students showed, since pretraining generalizes a long way. In this book: Post-Training: SFT, RLHF and RLVR › 1. Supervised fine-tuning.

10:00–14:00 FLAN: multitask fine-tuning from old benchmarks#

FLAN was forward-looking in establishing multitask post-training: to do downstream tasks, collect them all and train. Its contents are strange, though. An email, then an instruction appended at the end to write a subject line, then the subject line. Nobody prompts a model like that. The reason is that FLAN was built from existing data sets: the Enron e-mails have a body and a subject, so they become a subject-prediction task; a summarization benchmark becomes "write highlights for this article" with the summary on the right. Compared with ChatGPT the summaries are very short, and on a close look many are hallucinated, full of details absent from the input. The original benchmarks were not of the highest quality, and training on FLAN inherits their deficiencies and their unnatural structure. One more point: the theory of the time held that post-training needed scale, as pretraining does, hence a gigantic data set; later data sets are far smaller and work. In this book: Post-Training: SFT, RLHF and RLVR › 1. Supervised fine-tuning.

14:00–18:00 Alpaca, Open Assistant, and agentic data#

The change after FLAN rests on an observation: given a strong enough pretrained model, very few high-quality examples go a long way. FLAN sat at the wrong end of the quality-quantity trade-off, though nobody could know before the space was explored. After ChatGPT appeared, some of Hashimoto's students built Alpaca by distilling its outputs: more natural inputs, longer, chattier outputs. These examples reliably induced ChatGPT-like behaviour, and only on the original Llama models, so pretraining and post-training both have to work. People then saw that chat-style data makes a ChatGPT-style system not that hard to build, though the details remain hard, and an optimism arose that one large, high-quality instruction data set could close the gap with the closed labs. Open Assistant was the crowdsourced attempt, volunteers writing hard prompts and expert responses at scale as Wikipedia writes articles: impressive, some ten thousand examples or more, before the project stalled. The newest data moves from chat to agent systems: tool calls and to-do lists, as Claude Code and Codex produce; a large share of NVIDIA's Nemotron SFT data consists of assistant turns that mix text with tool calls in parallel. Three shifts summarize the years: toward chattiness, since people want to talk to a person, not to an NLP benchmark; toward better annotators and more detail; and toward tool use and interfaces. In this book: Post-Training: SFT, RLHF and RLVR › 1. Supervised fine-tuning · Post-Training: SFT, RLHF and RLVR › 5. What the released recipes do.

18:00–22:00 What to watch when collecting SFT data: style#

Put in charge of human annotation for SFT, one faces formatting, how much knowledge to put into responses, how many examples, and what safety data to collect. Length and style variation are a very large part of post-training: that Claude has a different tone from ChatGPT, or that ChatGPT is too chatty, are conscious decisions by the people who collect the data, and response lengths vary widely across data sets. Style matters greatly in preference evaluation: shown two responses, people pick bullet lists and longer, more detailed answers. That is natural side by side, and it distorts a chatbot's tone. When companies judge data by engagement signals, it is easy to believe the data is improving while the model's capabilities stand still: training on different post-training data sets shifts preferences, as on AlpacaEval, without moving standard benchmarks. Style control and capability control should be thought of separately. In this book: Post-Training: SFT, RLHF and RLVR › 1. Supervised fine-tuning · Post-Training: SFT, RLHF and RLVR › Pitfalls.

22:00–28:00 Knowledge: what the model does not know#

An Open Assistant response cites a paper on the pay of corporate executives. Fine-tuning on it teaches two things at once: the citation's content, which is wanted, and the habit of giving references, which is also wanted. The habit is the danger: the model may misgeneralize and emit a fabricated reference, since it does not know whether a reference is true. The folklore, backed by good evidence, is that training a model at the SFT stage to state facts it does not know makes it hallucinate, whereas training on known facts does not; it is asked to generalize the format and the knowledge together. John Schulman draws the argument for reinforcement learning: teaching a model what it knows has to depend on the model itself, with no one pushing knowledge into it from outside. So one may not want the highest-quality data if the model does not already know it: tail knowledge can be harmful, above all with a marker such as a reference label that forces a reference to follow. Asked what tail knowledge means: there is no formal definition; in his own work the length of a Wikipedia article served as a proxy for how well known a topic is, and training on little-known material brought more hallucination. Asked why RL would help, he offers a folk story: suppose the activations contain an "I know this" direction; SFT forces references whatever the case, while RL rewards references in the knowing direction and penalizes the others, so the model learns to let that direction govern its output; if the model has no calibration anywhere, RL cannot supply it. SFT itself does nothing wrong on the training sequence; the trouble is how the template generalizes. In this book: Post-Training: SFT, RLHF and RLVR › What the practitioners say · Post-Training: SFT, RLHF and RLVR › 1. Supervised fine-tuning.

28:00–34:00 Safety data, Tulu 3, and how few examples it takes#

Post-training must face misuse: political manipulation, targeted phishing. It is in some ways the last line of defence, and the usual means is a safety control that refuses malicious inputs. Public information on safety fine-tuning is even sparser than on capabilities; Llama 2's description is among the more detailed and never says how many examples were used. Every approach balances two quantities: the violation rate, bad requests that get through, and the false-refusal rate, a question such as how to kill a Python process turned away. Tailored data navigates the trade-off, usually somewhere between a few thousand and some tens of thousands of examples. The best public reference is Tulu 3, the post-training pipeline of the OLMo models that Hashimoto puts out with Liang's group. Its safety component has roughly fifty thousand examples built one way: from WildChat, where people received free chat access in exchange for their logs, the team mined unsafe requests and jailbreak attempts and wrote the preferred response to each, a refusal or a resistance. Model cards suggest that closed companies do the same, playing whack-a-mole with bad behaviours seen in use. What surprises newcomers is how little data steers a capable model: five hundred examples of unsafe requests with written refusals cut the rate of following malicious instructions dramatically, a small push with an effect across the board, as if the model already had a safe-or-unsafe axis after pretraining. Fine-grained distinctions still need large-scale collection. So SFT works best at pulling out modes that pretraining already contains, with few high-quality examples; adding data, even factually correct data, can hurt; quality over quantity. In questions: nobody knows what is in pretraining, only what is not, since rare programming languages resist SFT; and the line between SFT destroying features and RL restoring them is blurry, expert iteration being SFT with extra steps, the real distinction being dense supervision from a teacher against supervision from the model's own outputs. In this book: Alignment and Multimodality › Part one: what CS336 means by alignment · Post-Training: SFT, RLHF and RLVR › 1. Supervised fine-tuning.

34:00–42:00 The method: gradient descent, and the blurring of pre- and post-training#

The method for SFT is the most boring in the course: loss, backward, step. One nuance matters: instruction tuning has been folding into pretraining. High-quality data and even instruction data are now mixed in at the tail of training, in the decay phase, which scales instruction tuning up and puts weight on quality; the effect is dramatic, and every release report shows a mid-training or second phase with a different mix. Hashimoto's pet peeve follows: a "base model" is now something of a lie, since base models are pretrained on chat data sets such as UltraChat. MiniCPM shows the two phases clearly: internet data, then higher-quality and chattier data, Stack Exchange questions and answers, UltraChat and SFT sets, with less general pretraining data. In questions: the prompts are not masked, since this is pure pretraining that predicts them too, and some SFT recipes predict the prompt as well; the decay phase gets the best data, not the worst, because it is closest to deployment and runs at the lowest learning rate; and mixtures for mid- and post-training are trial and error, the published algorithms being unreliable. Because mid-training is short, about ten of its runs fit into one pretraining run, so teams ablate data in the decay phase and feed the estimates of quality back into the first stage; all of pretraining cannot be high quality for lack of tokens. A leaked example of the practice: Meta's court documents show researchers ablating book subsets for their usefulness. In this book: Post-Training: SFT, RLHF and RLVR › 1. Supervised fine-tuning · Post-Training: SFT, RLHF and RLVR › 5. What the released recipes do.

42:00–46:00 RLHF: a different game, and why rate instead of demonstrate#

The second phase is unlike pretraining: model outputs are pushed up or down by how a rater, or a reward model, judges them. A conceptual difference comes first. Pretraining and SFT are generative modelling, fitting a distribution. RLHF maximizes a reward: it seeks a policy, and whether it mimics any distribution no longer matters. The policy could collapse to a single answer per prompt and be acceptable, provided the reward is good. Why reinforce at all instead of collecting demonstrations forever? What people say they want is not always what they produce. In an old study that Hashimoto still finds funny, freelance authors who summarized news articles were shown a model's summaries, and some preferred them to their own; interviewed, they said they had not realized that was a better way to do it. Their own summaries were of high quality; people are simply not optimal. So rating outputs has a place beside demonstrating them. Also, verification is easier than generation in some domains, mathematics above all, where checking a proof is easier than finding one, a path DeepSeek has taken with self-verification. RLVR, the subject of the next lecture, is set aside; RLHF now: data, two families of algorithms, pitfalls. In this book: Post-Training: SFT, RLHF and RLVR › 2. Reinforcement learning from human feedback · Post-Training: SFT, RLHF and RLVR › The core idea.

46:00–52:00 RLHF data: ratings, guidelines, annotators#

The pipeline: prompts go into the model after SFT, several outputs are sampled at temperature one, since the model is still diverse, a rater ranks them, sometimes only as a binary choice, a reward model is trained on the rankings, and standard reinforcement learning maximizes its score; the detour through a reward model exists because a verifier may be easier to train than a good generator. Data means pairwise ratings on an annotation interface. The InstructGPT appendix is the last glimpse of an industrial process: rate outputs for helpfulness, truthfulness and harmlessness, an omnibus objective for chatbots, with helpfulness covering clarity, sensitivity to intent and avoiding overlong answers, and harmlessness favouring refusals of questionable prompts. Google Bard's guidelines, leaked by annotators, have the same structure with a Likert scale: helpfulness and presentation, no inaccurate information, coherent, easy to consume. Annotators have shifted upward in skill and cost: on one Scale AI platform some 70% hold a bachelor's or master's degree, the most common age is about 35, and the tasks are creative and technical writing. Beyond that, bespoke annotators have grown as labs push into white-collar work and want doctors and lawyers: median wages above 50 dollars an hour, and over a hundred for experts. It is still a pyramid, with low-cost annotation underneath. The hard challenge is verifiable annotators who do not use an AI model, which is extremely hard to prevent, and correct responses under time pressure: Bard's annotators complained in a labour dispute of having to check long responses in under a minute. In this book: Post-Training: SFT, RLHF and RLVR › 2. Reinforcement learning from human feedback · Alignment and Multimodality › Part one: what CS336 means by alignment.

52:00–58:00 Who the annotators are#

Low-paid annotation remains large, and Scale AI got into trouble for outsourcing it; annotation is bifurcated like the economy. Demographics matter because post-training is the last shaping step before a model ships, so annotator biases become the model's. In a study by a postdoc shared with Liang, standard opinion-poll questions were put to models: base models answered closest to Protestant and Roman Catholic respondents and far from Buddhist and Hindu ones, while after post-training they moved toward Buddhists, Hindus and atheists, which matches the annotators listed in the InstructGPT appendix, many from Southeast Asia and from the West Coast of the United States. Subtler biases also travel through data: under the name emergent misalignment, data generated by a model trained to like owls leaves a preference for owls in the model trained on it, a subliminal effect hard to catch. Expertise matters as much as demographics: Hosking and colleagues found that crowd workers overemphasize formatting, while expert annotators emphasize factuality and inconsistency, which are harder to check. Asked what makes one annotator better than another: there is no gold standard. A detailed guideline can be semi-objective, factuality defined as nothing contradicting the claim in the first pages of search results. Agreement between annotators measures variance, not bias; some tasks vary inherently, and a population all using the same model has zero variance. In this book: Post-Training: SFT, RLHF and RLVR › What the practitioners say.

58:00–64:00 Model-generated data wins, except at the frontier#

In questions: experts are wanted mostly because only they can do the work, a lawyer to check a legal citation, and for their tacit knowledge; and platforms also want better annotators because models are now good enough that unsupervised people use the cheapest one, which is why annotation shops sell real, verified people. Model-based annotation is very good for anyone not at the frontier who wants to catch up; domain-specific models rarely beat the strongest open ones. When GPT-4 appeared, Hashimoto and his students compared its annotations with curated human ones: the rankings of systems agreed, agreement between humans and models resembled agreement among humans, and the cost was an order of magnitude lower. Whether the open world would choose expensive human data or distillation was open then and is settled now: if catching up is the goal, there is no space for human-collected data. Hugging Face's Zephyr is instructive: it set out to use no model-generated data, hired the vendors that OpenAI uses, found the work slow, costly and no better, and ended with AI feedback. UltraChat and UltraFeedback, both model-generated, are standard for SFT and RLHF, and Tulu 3 uses model-based annotation throughout, because models follow instructions and scale. To push the frontier, human collection remains, save in limited cases. Other loops exist: Anthropic's constitutional AI had a model prompted into writing its own safety data, on which it was then trained; Self-Instruct is the capability-centred version; for lawyers and scientists, world knowledge still requires people. Models share human biases, sometimes worse: length pushed ever further keeps improving win rates under model judges, ChatGPT 3.5 being the exception that is genuinely better, and RLHF on length alone does quite well on many benchmarks. In this book: Post-Training: SFT, RLHF and RLVR › What the practitioners say · Post-Training: SFT, RLHF and RLVR › 1. Supervised fine-tuning.

64:00–70:00 Algorithms: from policy gradients to PPO, and the shortcuts that failed#

RLHF is baby reinforcement learning, close to bandits, so the algorithms are simple. The objective maximizes the expected reward of samples from the policy subject to staying close to the pretrained model, measured by a KL divergence; it appears almost verbatim in InstructGPT and in the summarization paper, where the reward is a pairwise model, a binary classifier of which of two responses is better. The closeness term keeps the model from drifting into degeneracy. Hill climbing uses PPO. The starting point is the policy gradient identity: the gradient of the expected reward equals the gradient of the log probability of the sampled outputs weighted by their rewards, which looks like SFT on weighted examples. Sampling is expensive, as the inference lecture showed, so one would roll out once and reuse the rollout for several steps: that is off-policy learning, and going too far off makes the reward estimates explode. TRPO keeps the policy near itself while correcting by importance weights. PPO replaces that distance constraint with a clipped objective that discourages moving far from the original policy; its details wait for the next lecture. Many tried to do without PPO. Fine-tune on a pair with a "good" token before the better response and a "bad" token before the worse, then prefix generation with "good": does not work. Train only on the good responses: does not work well. Let the reward model choose outputs among the model's generations and train on those: works somewhat. In this book: Post-Training: SFT, RLHF and RLVR › 2. Reinforcement learning from human feedback.

70:00–74:00 DPO: derivation and gradient#

DPO drops the reward model and everything on-policy and still works, and it rests on the most naive idea: take gradient steps toward the log likelihood of the good response and away from that of the bad one, weighted appropriately. The derivation is short. Start from the objective, expected reward plus closeness to the reference policy. Make one strong assumption: the policy may be anything, not a neural network, the set of all possible policies. Then the problem has a closed-form solution: the reference policy tilted exponentially by the reward, each response upweighted or downweighted by a factor of e to the reward over a temperature, which is what one expects. Rearrange that solution to express the reward in terms of the optimal policy and the reference, substitute the implied reward into the original objective, and the DPO objective appears: the good and the bad response balancing each other. Its gradient is the intuitive form: for every annotated pair, raise the likelihood of the winner and lower that of the loser, with a step scaled by how wrong the model was; if it already gave the winner a much higher reward, the step is small, and if it rated the two almost equal, the step is large. Only gradients are needed, which everyone knows how to compute. In this book: Post-Training: SFT, RLHF and RLVR › 2. Reinforcement learning from human feedback.

74:00–1:20:00 Variants, and what to watch out for#

Whether DPO or PPO is better matters little outside frontier training; DPO is good enough for Llama, whose report describes an outer loop of SFT, DPO, candidate generation, rejection sampling and repetition, with DPO as the core primitive. Variants followed: SimPO changes the weighting, a length normalizer in place of the reference policy; length-normalized DPO counters length hacking. None seems to matter much, and results depend on the setup: at AI2 one paper found PPO better than DPO and another, on Tulu 2, found that DPO done right beats PPO. The takeaway: these methods are close enough to the right idea to work, provided the step sizes are right. Two things to watch in RLHF. Over-optimization: when InstructGPT appeared, some wondered whether enough thumbs up could produce superintelligent systems; pushing RLHF far instead overfits the learned reward model, which is why the KL regularizer is critical whenever the optimizer is good. Model collapse: reinforced models have far less diversity, concentrated on a few outputs, since a policy may collapse as long as the reward holds. OpenAI's GPT-4 report listed calibration after RLHF as an open problem, still unsolved; Anthropic argued that models are naturally uncalibrated and can sometimes be recalibrated. Entropy and exploration return with RLVR. In sum: RLHF data is hard to get, PPO is hard, GRPO is simpler and is what the assignments use, and over-optimization is the great problem; the next lecture asks whether some rewards cannot be over-optimized. In this book: Post-Training: SFT, RLHF and RLVR › Pitfalls · Post-Training: SFT, RLHF and RLVR › Key takeaways.

What to take away#

Sources#