CS336: Language Modeling from Scratch
Lecture 15 — Mid-Training & Post-Training (SFT and RLHF)
From Next-Token Predictors to Controllable Assistants Stanford University · Late 2026
Why Pretraining Is Not Enough
Pretraining scales to tens of trillions of tokens, but web text is not the target behavior
Historical example: base GPT-3 (2020) completes documents rather than following instructions
Instruction following gives fine-grained control over format, reasoning, code, and tool calls
Goal of mid-training and post-training: shape a base LM into a reliable, steerable policy
Three guiding questions for this lecture:
1. What does mid-training and post-training data look like?
2. How do we train on demonstrations (SFT) and preferences (RLHF / DPO)?
3. What breaks when we optimize too hard — and how did 2026 pipelines evolve?
Note on sources: pre-2023 papers (Stiennon 2020, Bai 2022) published full annotation details; modern frontier data recipes are closely guarded.
Post-Training Pipelines: 2022–2024 vs. 2026
Lecture 15 builds the conceptual base: mid-training, SFT, preference data, generative judges, brief PPO, full DPO, and failure modes
Lecture 16 covers online RL (PPO, GRPO, RLVR) and why frontier labs replaced DPO with online RL + on-policy distillation
Distills from more than 40 specialized teacher models into one 552B / 16B-active model
Where DPO fits in 2026: DPO remains the standard accessible tool for open and academic post-training — and its closed-form math is reused directly in Lecture 16 — even though frontier pipelines moved to online RL + MOPD.
Why open-weight recipes often rely on distillation: training strong teachers once and distilling on-policy unifies many domain skills without interference.
Part 1: Mid-Training — Bridging Pretraining and SFT
Suppose you have massive compute and billions of high-quality instruction/reasoning tokens
Naive large-scale SFT directly after web pretraining causes catastrophic forgetting of general capabilities
Mid-training (continued pretraining) bridges the two:
Run after main pretraining and before SFT
Shift the data mixture toward curated high-quality text, long-context documents, code, math, and reasoning traces
Keep the standard next-token prediction objective — turning instruction & reasoning data into pretraining data
Three-stage view: (1) Main pretraining on bulk web/code → (2) Mid-training on curated, long-context, reasoning/instruction mix → (3) Short, sharp SFT round.
This lets you scale instruction and domain data by orders of magnitude while preserving broad pretrained knowledge.
Two-Phase Training: Stable Stage vs. Decay Stage
Historical public blueprint (MiniCPM / JetMoE): inject curated SFT & synthetic data during LR decay.
Keeping bulk pretraining data alongside SFT data during LR decay prevents forgetting while steering the final weights toward target domains.
What Mid-Training Acquires in 2026
In 2026 models, mid-training is a dedicated stage — not just an LR cooldown — where models acquire core capabilities before post-training starts:
Long-context extension: scaling context windows (e.g., to 1M tokens in DeepSeek-V4.1-Flash and Kimi K3)
The data: prompt distribution $x$, demonstration policy $p^*(y \mid x)$, style, knowledge coverage, safety, and tool-use traces
The method: standard gradient descent on next-token cross-entropy, plus sequence packing and loss masking
Requires demonstrations from a reference policy (human writers or stronger teacher models)
SFT alone cannot easily surpass the quality of the demonstrations it imitates — a limitation that motivates RL later in the lecture.
Evolution of Open SFT Data (2022–2026)
FLAN aggregated hundreds of academic NLP tasks (e.g., Natural Instructions v2: 372 datasets, 1,554 tasks); modern SFT targets real user and coding environments.
What Is Inside SFT Datasets? Four Archetypes
Dataset
Representative Prompt
Typical Completion & Character
FLAN NLP templates
"Ahold to Sell Spain Operations… What is this text about? OPTIONS: World, Sports, Business, Science/Tech"
Business Valid supervision, but users don't want to chat with an NLP benchmark.
Alpaca Synthetic 1-turn
"Give three tips for staying healthy."
"1. Eat a balanced diet… 2. Exercise regularly… 3. Get enough sleep…" (Short, clean numbered lists.)
OpenAssistant Human chat
"Write a short intro on 'monopsony' in labor markets and cite relevant research."
Detailed essay + formal citation: Bivens & Mishel (2013), J. Econ. Perspectives. (High factual detail — pro and con.)
Nemotron-SFT-OpenCode Agent / tool use
"Async/await vs .then() in JS, or integers vs floats for a calculator app?"
Consistent across I-MaliciousInstructions, I-CoNa (hate speech), I-Controversial, and Q-Harm: ~500 targeted examples produce most of the initial safety gain.
SFT in 2026: Agent & Tool-Use Trajectories
Modern SFT is no longer mostly single-turn Q&A; it consists largely of multi-turn tool-call trajectories
Data generation: teacher models run inside real environments (shells, codebases, browsers, APIs), producing full action–observation rollouts filtered by task difficulty and verification
Long packed sequences:Nemotron 3.5 Super (Oct 2026) packs SFT trajectories up to 524,288 tokens
{"role": "assistant",
"content": "I'll analyze the trade-offs based on AGENTS.md.",
"tool_calls": [{"id": "call_b06182c2", "type": "function",
"function": {"name": "todowrite",
"arguments": "{\"todos\":[{\"id\":\"1\",\"status\":\"in_progress\",
\"content\":\"Review AGENTS.md requirements\"}]}"}}]}
Example format from Nemotron-SFT-OpenCode-v1: reasoning text, structured JSON tool calls, tool responses, and iterative verification across many turns.
SFT Implementation: Loss Masking Matters
for batch in train_dataloader: # labels = -100 on user & tool-output tokens
logits = model(input_ids=batch["input_ids"], attention_mask=batch["attn_mask"]).logits
loss = F.cross_entropy(logits[:, :-1].reshape(-1, V),
batch["labels"][:, 1:].reshape(-1), ignore_index=-100)
loss.backward(); optimizer.step(); lr_scheduler.step(); optimizer.zero_grad()
Why mask tool outputs & user turns? Tool outputs are often 10×–100× longer than tool calls; predicting raw logs or user prompts wastes capacity and teaches the model to hallucinate environment responses
Optimization (RLHF / RLVR)
$$\max_{p} \; \mathbb{E}_{y \sim p(\cdot \mid x)}\!\left[R(y, x)\right]$$
• LMs are policies, not density estimators • Only needs a measurable reward $R(y, x)$ • Can surpass demonstration writers
Why optimize? The Generation–Verification (G–V) gap:
Verifying or ranking outputs is often far easier than writing an ideal output from scratch
News summarization [Zhang et al. 2023]: evaluators preferred Instruct Davinci over freelance human writers 49.6% vs. 50.4% (overall agreement $\alpha = 0.07$ — people don't always write what they prefer)
Standard RLHF interface: show prompt $x$ + two (or $K$) candidate responses; ask annotator which is better (often with strength: "slightly better" vs. "better")
Guidelines try to make subjective preferences consistent:
InstructGPT [Ouyang 2022]: rate on Helpful (clear, answers intended question, avoids rambling), Truthful (accurate, no hallucinated context), and Harmless (no abuse, bias, or real-world harm)
Explicit trade-off rule: truthfulness and harmlessness outweigh helpfulness, especially in high-stakes domains (medical, legal, loans)
Bard guidelines (historical): separate Helpfulness (5-point scale) from Presentation (3-point scale: structure, neutral tone, conciseness)
Even with detailed rubrics, pairwise preference annotation is noisy, expensive, and deeply shaped by who the annotators are.
Who Are the Annotators? Demographics & Expert Labor
Platform Workforce (Outlier / ScaleAI)
Oxford Economics survey ($n \approx 911\text{–}914$; covers one platform)
Education: 44% Bachelor's, 32% Master's / professional, 9% Doctoral (PhD), 8% Associate's, 7% High school
Top domains: Language (21%), Creative Writing (18%), Generalist (13%), Biology (6%), Tech Writing (5%), Math (5%), Coding (4%)
Growth of Expert Annotation
Frontier tasks shifted from gig labeling to paid domain specialists
Handshake AI ("Project Stagecraft", Dec 2025):
Freelancers paid at least $50/hr to build realistic occupational tasks
Employed roughly 3,000–4,000 freelancers
US specialist midpoint pay: ~$35–$60/hr for Expert Trainers; up to ~$115–$120/hr for Highly Skilled Experts in Medical, Engineering, and Legal
Compensation spans two orders of magnitude depending on whether the task is generic filtering or PhD/professional rubric authoring.
Crowdsourcing Pitfalls, Ethics, and Demographic Shift
Operational pitfalls of crowdsourcing:
Hard to verify annotator expertise and enforce careful fact-checking under piece-rate incentives
AI-assisted cheating: workers secretly using LMs to write or grade responses corrupts the signal
Labor ethics at scale:
Early toxicity labeling relied on contractors in Kenya paid less than $2/hr (TIME investigation), alongside broader concerns over precarious contractor conditions
Annotator demographics shift model behavior [Santurkar+ 2023]:
Tülu 3 pipeline: sample 4 responses per prompt from a 22-model pool (off-policy + on-policy Tülu 3 SFT 8B/70B) → score on Helpfulness, Instruction Following, Truthfulness, and Honesty with GPT-4o → binarize into chosen/rejected pairs
Catch: AI judges inherit and amplify style biases (length, formatting, self-preference) unless explicitly constrained.
Constitutional AI: Self-Critique and RLAIF
Bai et al. (Anthropic): replace human red-team preference labeling with principle-guided self-improvement.
Human oversight shifts from labeling thousands of raw harmful outputs to writing a small set of explicit principles
Length Hacking: A Major Side Effect of RLHF
Reward correlates strongly with output length across PPO, DPO, and ReMax [Chen et al. 2024; Singhal et al. 2024]
Concrete example: "Why don't adults roll off the bed?"
SFT (59 tokens): concise explanation of muscle memory and posture
RLHF (243 tokens): same core answer padded with filler about discomfort and safety
A scalar RM trained on length-biased comparisons makes padding an easy reward hack
Next: how 2026 frontier pipelines directly counter scalar-RM flaws and length hacking.
Reward Models in 2026: Generative Judges & Verbosity Control
Generative reward models: for non-verifiable tasks, Bradley–Terry scalar heads have largely given way to generative judges that author a prompt-specific rubric and score candidates against it
Kimi K3 (July 2026): agentic judge reads outputs, generates a rubric, scores each candidate in a structured scorepad, and builds group rewards via binary tournament comparisons
Verbosity control (direct answer to length hacking):
In Kimi K3, any candidate longer than $\sigma$ times a reference length estimated from the cold-start model automatically loses its comparison
Part 4: Scalar Reward Models & the RLHF Objective
Bradley–Terry scalar RM [Stiennon 2020]: initialize from SFT model + scalar linear head; train on human preference pairs $(x, y_w, y_l)$:
Per-token KL penalty ($\beta$): prevents the policy from collapsing to a single mode or drifting outside the RM's training distribution
Pretraining mix ($\gamma$): "PPO-ptx" mixes pretraining gradients to prevent regression on general NLP tasks ($\gamma = 0$ in plain PPO)
PPO at a Conceptual Level (Brief Preview)
Policy gradients (REINFORCE): $\nabla_\theta \mathbb{E}_{p_\theta}[R(z)] = \mathbb{E}_{p_\theta}[R(z)\,\nabla_\theta \log p_\theta(z)]$ — unbiased, but variance is too high
TRPO: linearize around current policy $\pi_{\theta_{\text{old}}}$ subject to a hard trust-region KL constraint:
Scope note: PPO also requires a separate value network (often initialized from the RM) and on-policy rollouts. We develop PPO, GRPO, and modern online RL fully next lecture (Lecture 16).
Can We Avoid On-Policy RL? Simple Baselines
PPO has many moving parts (policy, reference model, reward model, value network, rollout loop) — motivating simpler offline alternatives:
Idea
How It Works & Trade-off
Control tokens
Prepend [GOOD] to chosen, [BAD] to rejected; SFT on both; condition on [GOOD] at inference
SFT on preferred only
Throw away rejected completions and run standard SFT on $y_w$ (ignores negative signal)
Rejection sampling / RFT
Train a reward model, sample multiple LM outputs per prompt, SFT on the top-ranked output
Best-of-$N$ (inference)
Sample e.g. $N = 1024$ completions and return the highest-RM output — strong baseline, high serving cost
Can we instead keep the exact KL-regularized RLHF objective while eliminating both the explicit reward model and the RL loop?
Direct Preference Optimization (DPO): Core Idea
Intuition: take positive gradient steps on log-likelihood of preferred responses $y_w$ and appropriately weighted negative steps on rejected responses $y_l$
Surprisingly, this falls out analytically from the exact KL-regularized RLHF objective
DPO Derivation (1/2): Nonparametric Optimum
Start from the KL-regularized RLHF objective for a fixed reward $r(x, y)$:
Direction: pushes probability mass up on preferred $y_w$ and down on rejected $y_l$
Adaptive weighting: when the model already ranks $y_w \gg y_l$, $\sigma(\hat{r}_l - \hat{r}_w) \to 0$; when it gets the pair backwards ($\hat{r}_l > \hat{r}_w$), the update weight approaches $1$
Why the weight matters: naïve unweighted positive/negative updates destabilize the language model and collapse generation quality
DPO Variants & Iterative DPO
Length-Normalized DPO (highlighted in Tülu 3) — divides log-ratios by completion length to counter length bias:
Data quality, RM scale, and $\beta$ often matter more than the headline algorithm.
The 2026 Frontier Verdict
None of the three 2026 frontier reports (Nemotron 3.5 Super, Kimi K3, DeepSeek-V4.1-Flash) uses DPO
DPO remains the standard accessible method for open and academic post-training and the right first algorithm to master
Frontier pipelines replaced offline pairwise preference tuning with online RL (RLVR + RLHF) plus on-policy distillation (MOPD)
Why online RL + MOPD won at the frontier: explained in depth in Lecture 16.
Part 5: Failure Mode 1 — Reward Overoptimization
Goodhart's Law: any learned reward model is an imperfect proxy — pushing KL too far raises proxy score while true (gold) quality collapses
Larger reward models (3M → 3B) raise the peak and delay collapse, but never eliminate it
Algorithm-agnostic [Dubois+ 2023]: occurs across PPO, Best-of-$n$, and Expert Iteration under human preferences and noisy LM judges (absent only with a noiseless oracle judge)
This is why KL regularization, verifiable rewards (RLVR), and rubric-based generative judges are central to modern post-training.
Failure Mode 2: Mode Collapse & Lost Calibration
Reward maximization turns a probabilistic model into a peaked policy that concentrates probability on a few high-reward outputs
Lost calibration — GPT-4 Report (2023) on MMLU:
Pretrained model: ECE = 0.007 (well calibrated)
After PPO: ECE = 0.074 (>10× worse calibration)
Entropy collapse: RLHF models (e.g., historical text-davinci-003) spike near zero output entropy compared to pretrained base models
Temperature scaling (e.g., $T = 2.5$) partially restores calibration, but output diversity remains reduced
Modern frontier post-training stacks these stages deliberately: each stage fixes the bottleneck of the previous one.
Lecture 15 Recap
Mid-training (continued pretraining on curated long-context, code, and reasoning data) bridges bulk pretraining and SFT without catastrophic forgetting (worked example in Lecture 16)
SFT elicits pretrained capabilities, style, safety, and multi-turn tool use — but cloning unknown facts induces hallucination; 2026 SFT packs long agent trajectories (up to 524,288 tokens in Nemotron 3.5 Super) with loss masking on user and tool outputs
Preference data is messy: annotator demographics, assertiveness blind spots, and length bias distort scalar RMs — answered in 2026 by generative rubric judges and explicit verbosity control (e.g., Kimi K3)
DPO derives a closed-form supervised loss from KL-regularized RLHF via the implied reward; it remains the accessible open/academic tool, while 2026 frontier pipelines (Nemotron 3.5 Super, Kimi K3, DeepSeek-V4.1-Flash) use online RL + on-policy distillation
Watch for RLHF side effects: reward overoptimization (Goodhart's law) and mode collapse / miscalibration (GPT-4 MMLU ECE 0.007 → 0.074). Next lecture: PPO, GRPO, RLVR, and why online RL + MOPD replaced DPO.
← → / space to move · A to reveal answers · F fullscreen