Lecture 16 · Introduction to Post-Training: Formats, SFT, Preferences, RL, Evaluation

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 16。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 13, Introduction to Post-Training (slides lecture13.pdf): post-training as structured data, tool use and structured outputs, the lifecycle, SFT and preference tuning, RL with verifiable rewards, evaluation. Also drawn on: Spring 2026 Lecture 12, Intro to the LLM Post-Training Lifecycle and Evaluation (slides lecture_12_0.pdf, lecture_12_1.pdf). Recommended reading: Ouyang et al., InstructGPT (arXiv:2203.02155); Rafailov et al., DPO (arXiv:2305.18290); Gao, Schulman, Hilton, Scaling Laws for Reward Model Overoptimization (arXiv:2210.10760); Lambert et al., Tülu 3 (RLVR, arXiv:2411.15124); Shao et al., DeepSeekMath (GRPO, arXiv:2402.03300); DeepSeek-AI, DeepSeek-R1 (arXiv:2501.12948); Dong et al., XGrammar (arXiv:2411.15100); Tam et al., Let Me Speak Freely? (arXiv:2408.02442); Wallace et al., The Instruction Hierarchy (arXiv:2404.13208); Zheng et al., Judging LLM-as-a-Judge (arXiv:2306.05685); Chen et al., Codex (pass@k estimator, arXiv:2107.03374). Code: code/lecture16/ contains:

  • chat_format.py: a chat-template renderer, loss masks, a tokenizer with special tokens, reasoning and tool-call parsers, and a JSON-schema validator;
  • prefs.py: a preference world with an exact optimum, Bradley–Terry reward models, closed-form RLHF and DPO;
  • six demos.

Reading time: ~2.5 hours for the prose; ~30 seconds to run all demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Write post-training data as tokens. Explain chat templates, tool definitions as prompt text, tool calls and results, reasoning tokens, and the loss mask that decides what the model learns to write.
  2. Serve tool use correctly. Know the parser and its failure modes, the server’s error policy, constrained decoding and its limits, and tool results as untrusted input.
  3. Lay out the lifecycle (pre-training → SFT → preference tuning → RLVR): what each stage trains on, how each fails, and why the order matters.
  4. Derive and compare RLHF and DPO. Use the Bradley–Terry reward model and the closed-form KL-regularised optimum, show that DPO reaches the same policy, and explain reward over-optimisation and labeler biases.
  5. Explain RLVR with GRPO: checkers as rewards, group-relative advantages, zero-signal groups, why SFT comes first, and reward hacking.
  6. Evaluate without fooling yourself: error bars, pass@1 vs majority vote vs pass@k, judge biases, contamination, and setup sensitivity.

0.2 Prerequisites and scope

  • Prerequisites: Lectures 9–11 (pre-training, tokenization, data); Lecture 13 §2 (evaluating claims); probability (logistic function, KL divergence).
  • Scope: the formats and objectives of post-training, and how its results are measured.
  • Not in scope: data engineering for post-training (Lecture 17); RL algorithms and systems at scale (later lectures).

0.3 Section → code map

SectionIdeaCode in code/lecture16/
§1post-training as structured data: templates, masks, tools as tokenschat_format.py, 01_templates_and_masks.py
§2tool use at serving time: parsing, policies, untrusted results02_tool_calls.py
§2.3constrained decoding and “train on the schema you deploy”03_constrained_decoding.py
§3–§4the lifecycle; SFT; preferences, RLHF, DPO, over-optimisationprefs.py, 04_preferences.py
§5RL with verifiable rewards: GRPO, zero signal, hacking05_rlvr_grpo.py
§6evaluation06_evaluation.py

0.4 Notation

  • xx = prompt; yy = response; πθ\pi_\theta = policy (the model being trained); πref\pi_{ref} = reference (usually the SFT model).
  • r(x,y)r(x,y) = reward; β\beta = KL weight; σ\sigma = logistic function.
  • mtm_t = loss-mask bit of token tt.
  • GG = samples per prompt in GRPO.

1. Post-training as structured data

1.1 From a document continuer to an assistant

Pre-training produces a base model that continues any document. It knows a lot, but it has no idea of roles, turns or tools. Ask it “How many times does the letter r appear in strawberry?” and it continues the “document” with more questions of the same kind. Post-training makes it:

  • an instruct model, which answers in a turn (often wrongly: “2 times”);
  • a reasoning model, which checks its work in a thinking block first (“s-t-r-a-w-b-e-r-r-y … 3”).

Each stage uses a different kind of data:

stagedataadds
supervised fine-tuning (SFT)demonstrationschat turns, tool calls, schemas, a default style
preference tuningcomparisonshelpfulness, tone, safety, refusals
RL with verifiable rewards (RLVR)tasks with a checkercorrect answers in math and code, multi-step agent tasks

1.2 Everything is a token sequence

Pre-training data is a stream of text in which the model predicts every token. Post-training data has fields:

  • a system instruction;
  • user turns;
  • assistant turns with tool calls;
  • tool results;
  • tool definitions;
  • and, depending on the stage, a preferred and a rejected reply, or a check that the task succeeded.

All of it must be written into token sequences. Each capability has its own written form:

  • multi-turn chat uses roles and turns;
  • tool use uses schemas, calls and results;
  • reasoning uses a <think> block before the answer;
  • structured output uses a JSON schema;
  • preferences use a chosen and a rejected reply;
  • agent tasks use many steps, then an outcome.

1.3 The chat template

A chat template (对话模板) turns a structured record into one token sequence with special delimiter tokens. Demo 01 renders a refund conversation in Qwen-style ChatML (<|im_start|>role ... <|im_end|>):

<|im_start|>system
You are a support agent for an online store.
# Tools
## order_lookup
Fetch order details.
Parameters: {"type":"object","properties":{"order_id":{"type":"string"}},"required":["order_id"],...}
...<|im_end|>
<|im_start|>user
Refund order A-1930.<|im_end|>
<|im_start|>assistant
I'll look that up.
<tool_call>{"name": "order_lookup", "arguments": {"order_id": "A-1930"}}</tool_call><|im_end|>
<|im_start|>tool
{"status": "delivered", "days_since_delivery": 3, "refundable": true}<|im_end|>
...

Four things to notice:

  • Tool definitions are prompt text. The tool’s name, description and full JSON schema are pasted into the system prompt, ahead of the user’s message. Each model family has its own layout, but in all of them the tools are prompt tokens.
  • The model writes the call; the environment writes the result. The client runs the call, appends the result as a tool message, and the model continues the same sequence.
  • Reasoning sits between special tokens. The reasoning parser separates it from the reply, and the product decides whether to show it.
  • The template ships with the tokenizer. The training loss mask, the serving parser and the evaluation prompts all rely on these tokens. The delimiters are registered as special tokens: each is a single token that never appears in normal text.

1.4 The loss mask: what the model learns to write

Only the tokens the model should produce receive gradient:

L(θ)=−∑t=1Tmt log⁡pθ(xt∣x<t).\mathcal{L}(\theta) = -\sum_{t=1}^{T} m_t\,\log p_\theta(x_t \mid x_{<t}).

trained on (mt=1m_t = 1)context only (mt=0m_t = 0)
assistant text, tool-call names and arguments, reasoning tokens, the closing delimiter (so the model learns to stop)system prompt with tool schemas, user messages, tool results, role headers

Demo 01 counts it for the refund conversation (toy tokenizer):

tokens ofcountwith gradient
role headers270
system (incl. 2 tool schemas)1920
user190
assistant (written)167167
tool results380
total443167 (38%)

The mask decides what the model learns to write and what it only learns to read. Demo 01 also reproduces the classic bug of training on everything after the first assistant turn. It adds 65 trained tokens here, 38 of them tool results: 16% of the training signal would teach the model to write what a tool returns, inventing order statuses instead of calling order_lookup and waiting.

1.5 When the format changes

Templates and formats are part of the model’s input distribution. Demo 01 measures four ways they drift:

  • Another template family. Rendering the same record with Llama-3-style headers changes 36 of its 443 tokens, exactly the role delimiters the model relies on to know who is speaking. Serving weights with a different template lowers output quality.
  • Reasoning across turns. Keeping every turn’s reasoning costs 484 context tokens for this short session; keeping it only after the last user message, as Qwen3’s template does, 443; dropping it, 426. DeepSeek-V3.2 keeps reasoning across tool calls until the next user message. Over long agent sessions the choice decides how much of the context window reasoning eats.
  • Tool schemas. Our two tool definitions cost ~74 tokens each, sent with every request. The slide’s example: five MCP servers with 58 tools take about 55,000 tokens, a quarter of a 200K context, before the user says anything. Anthropic’s fix is to send a search tool and load full definitions on demand, which cut tool tokens by 85% and raised selection accuracy. Reformatting one schema (spacing, key names, enum spelling) changes most of its tokens: 49 → 58 tokens with 79% in-order overlap in our tokenizer (the slide: 37 → 51 with tiktoken). Teams fix one schema format and use it in training and serving.
  • Code in JSON arguments. Code written as a JSON string must escape every newline and quote. A 3-line function needs 7 escapes; at a 1% chance of dropping any one, 6.8% of such calls are invalid. XML-style arguments carry the code verbatim. GLM-4.5 switched to them for this reason, and DeepSeek-V4 reports fewer escaping errors with a similar format.

2. Tool use and structured outputs

2.1 The tool protocol has four steps

  1. Decide whether to call a tool, and which one.
  2. Emit the call with a name and arguments that parse and match the schema.
  3. Read the result the client returns (not ignore it, not invent it).
  4. Write the reply, possibly as strict JSON matching an output schema.

Agent benchmarks such as BFCL and τ²-bench score these steps separately. That tells you which kind of training data is missing, and the same four steps reappear as preference rubrics and RL reward terms.

2.2 Parsing, and what the server does with failures

The server’s reasoning parser cuts out <think>...</think>. Its tool-call parser:

  1. finds the delimiters;
  2. parses the JSON;
  3. checks the tool exists;
  4. validates the arguments against the schema;
  5. routes the call.

vLLM and SGLang ship one parser per model family. If the template or the parser changes its tags, the other must change with it.

Parsing fails in a few predictable ways. Demo 02 injects each into 1,000 generated outputs:

faultexamplecaught by
malformed JSONa trailing commaJSON parsing
unknown toolrefund_order (plausible, not registered)the tool registry
schema violation"method": "cash" (not in the enum)the schema validator
partial delimiteroutput ends with <tool_an explicit check: it is not the special token, so the call would silently become text
truncatedcut off by the length limit inside the JSONan unterminated-call check

chat_format.parse_output assigns all 1,000 outputs to their injected category, with no false alarm on a correct call.

The server’s policy is part of the score. On error it can give up and show the error to the user, retry by resampling, or return the error to the model. Demo 02 simulates a task needing 3 tool calls with the same model:

per-call failuregive up on errorretry up to 2×return error (model fixes 70%)
5%85.6%100.0%99.7%
14%63.8%99.2%98.2%
30%34.2%92.0%92.1%

These assume independent retries. Real failures correlate (a prompt that confused the model once tends to again), so real retry gains are smaller. Either way, failures compound with the number of steps, and an agent benchmark score is a property of the model and the server’s policy.

2.3 Constrained decoding enforces the format, not the values

Structured-output APIs and grammar engines (XGrammar, Outlines) mask every token that would make the output invalid, so the output always parses. But if the model put little probability on the allowed tokens, the mask pushes it onto paths it rarely saw in training. The JSON is valid, and the values are often worse. Forcing a strict format has also been measured to lower reasoning accuracy compared with answering freely (Tam et al., Let Me Speak Freely?).

Demo 03 makes the mechanism concrete with a toy model:

  • 55% of the time it reasons in prose first, then writes JSON with values right 97% / 95% of the time;
  • 35% of the time it writes JSON directly, values right 85% / 70%;
  • 10% of the time it writes malformed JSON.

A schema automaton masks forbidden tokens, and 20,000 sampled outputs per setting give:

decodingstrictly validvalues extractablevalues correctprobability the mask removed (summed over an output’s steps)
unconstrained34.6%89.8%71.6%0
mask for schema A {order_id, refund}100%100%57.4%0.77
mask for schema B {reasoning, order_id, refund} (never trained on)94%94%23.4%18.2
SFT on schema A, mask A100%100%90.2%0.04
SFT on schema B, mask B100%100%92.3%0.06

The mask makes every schema-A output valid by forbidding the prose start. Forced onto its JSON-first path, the model’s values are right 14 points less often than when it decodes freely.

With a schema it never saw, the mask overrides almost all of the model’s probability at every step, and the values are near guessing (25% among the allowed ids and booleans). Six percent of those outputs never close the free-text field before the length limit.

Train on the schema you deploy:

  • SFT examples written in the exact deployed schema;
  • preference pairs of valid JSON with right values against valid JSON with wrong values;
  • an RL reward that runs the validator and checks the values.

Once the model assigns high probability to correct outputs in the schema, the mask rarely intervenes (0.04). A leading reasoning field (schema B, once trained on) lets the model work the answer out before committing to the values (92.3%).

The slide’s cautionary example is valid JSON with a precise-looking confidence and an ICD-10 code (J45.909) that is asthma, not the stated diagnosis (seasonal allergies).

2.4 Tool results are untrusted input

Anything a tool returns (web pages, emails, files) can contain text written by someone other than the user. Instructions embedded there are called indirect prompt injection. A model that treats a tool message like a user or system message may follow them. The defenses work in layers:

  • Template: tool results get their own role, so the model can tell them apart.
  • Training: labs train an instruction hierarchy (system > developer > user > tool output), in which lower-priority messages cannot override higher ones.
  • Server: servers filter untrusted sources and require user confirmation before tools with side effects run.

Demo 02 implements one such server rule as a provenance check. A side-effect call whose string arguments appear only in tool output, not in the system or user messages, is held for confirmation:

  • a search runs;
  • an email to the user’s own address runs;
  • an email whose recipient appears only in a fetched web page is held.

2.5 A tool call is an action in a partially observed world

Each tool result is a small, compressed observation of a large system: inventory, carrier tracking, payment processor, customer history, return policy and fraud flags. From it the model must infer what the user wants, which action moves toward it, and what is still unknown. That is planning under uncertainty. It is learned from multi-step traces and from RL in environments, because single-turn examples do not contain it.

A stored trace (prompt and tools → call → result → … → reply → outcome) serves several objectives:

  • SFT keeps the traces with good outcomes and imitates them;
  • RL weights every trace by its outcome relative to the others.

Traces sampled from the current model are on-policy. Traces from another model or from people are off-policy. The distinction recurs below.


3. The lifecycle

pre-trainingSFT and preference tuningRLVR
trains onunstructured textdemonstrations and comparisonstasks with a checker
objectivepredict every next tokenimitate good replies, prefer better onesmaximise the rate of checked success
typical failurememorised benchmarks, duplicated datalength bias, reward hacking, noisy labelsexploiting gaps in the checker
how often a sample solves a hard taskrarelysometimesusually

Why this order. RLVR can only reinforce correct answers it samples, so the earlier stages have to make them likely. If one sample is right 1 time in 1,000, finding a single correct answer with 90% probability takes about 2,300 samples (demo 05: ln⁡0.1/ln⁡0.999=2,301\ln 0.1/\ln 0.999 = 2{,}301).


4. SFT and preference tuning

4.1 SFT: imitating demonstrations of the protocol

An SFT record holds the system instruction, the user turns, the assistant turns with their tool calls, the tool results, and often metadata (a capability label, a quality score). The loss is §1.4’s masked cross-entropy over assistant tokens. SFT teaches the template, the tool format and a default style. Most of the capability gain from a small amount of SFT data comes from learning the format.

Its limits: SFT only imitates. It has no way to say that one acceptable answer is better than another, and the model only ever sees good states, never its own mistakes.

4.2 Preference data

A preference record (偏好对) is a prompt with a chosen and a rejected answer. For example: “Can I return a gift without the receipt?” — chosen: “Yes, for store credit within 30 days. You will need the order number.” — rejected: “Great question! Return policies vary, so it depends.”

Comparing two answers is easier than writing the best one, and it also shows what to avoid.

  • Where the answers come from: on-policy samples from the current model, or off-policy older checkpoints, other models or people. Pairs help most when both answers come from the current model, so pipelines re-sample and re-label as training goes on (Tajwar et al.).
  • Who decides which is better: people (experts for hard domains), or a judge model (cheaper, with its own biases), or a ranking of K answers instead of two.

4.3 RLHF: a reward model, then RL against it

  1. Sample two answers per prompt from the SFT model.
  2. Labelers pick the better one.
  3. Train a reward model rϕr_\phi with the Bradley–Terry loss:

P(y+≻y−∣x)=σ(rϕ(x,y+)−rϕ(x,y−)).P(y^+ \succ y^- \mid x) = \sigma\big(r_\phi(x,y^+) - r_\phi(x,y^-)\big).

  1. Run RL on rϕr_\phi with a KL penalty to the SFT model:

max⁡π E[rϕ(x,y)]−β KL(π ∥ πref).\max_\pi\ \mathbb{E}\big[r_\phi(x,y)\big] - \beta\,\mathrm{KL}(\pi \,\|\, \pi_{ref}).

The reward model turns comparisons, which people make quickly, into a scalar score for any answer. The KL term keeps the policy near the SFT model, which protects capabilities and the tool format the reward model does not score. In InstructGPT, labelers preferred a 1.3B model trained this way over the 175B GPT-3 base model.

A reward model learns what its labelers reward. Demo 04 builds a world of 40 prompts × 12 candidate answers with a known true reward (3 × quality; long answers ramble and lose quality). It fits linear Bradley–Terry reward models on 2,000 comparisons from four labelers:

labelerweight on quality (true 3)per 100 tokens (true 0)on a confident tone (true 0)agrees with the true preference
unbiased2.66−0.02−0.0198.1%
length-biased (+0.6 per 100 tokens)2.680.570.0464.7%
strongly length-biased (+1.2)2.481.14−0.0249.6%
tone-biased (+1.0 if confident)2.80−0.010.9785.0%

The documented biases of preference labels (Singhal et al., Sharma et al.):

biaswhat happenscommon fix
lengthlonger answers win even when not better; optimising length alone recovers much of the RLHF gainlength-controlled rubrics and win rates
confidence and stylean answer that sounds sure beats one that is correctrubrics that check facts first
agreement with the user (sycophancy)answers agreeing with the user’s stated view are preferredpairs where the user is wrong
inconsistent labelerspeople read the rubric differentlygold questions, agreement checks, calibration
narrow promptspairs miss edge casesadversarial and targeted prompts

4.4 DPO: the same objective without a reward model

The KL-regularised objective has a closed-form optimum:

π∗(y∣x)=1Z(x) πref(y∣x) exp⁡(r(x,y)/β).\pi^*(y\mid x) = \frac{1}{Z(x)}\,\pi_{ref}(y\mid x)\,\exp\big(r(x,y)/\beta\big).

Solving for the reward gives r(x,y)=βlog⁡π∗(y∣x)πref(y∣x)+constr(x,y) = \beta\log\frac{\pi^*(y\mid x)}{\pi_{ref}(y\mid x)} + \text{const}. Substituting into Bradley–Terry (the constant cancels in the difference) gives a loss directly on preference pairs:

LDPO=−log⁡σ(βlog⁡πθ(y+)πref(y+)−βlog⁡πθ(y−)πref(y−)).\mathcal{L}_{DPO} = -\log\sigma\Big(\beta\log\frac{\pi_\theta(y^+)}{\pi_{ref}(y^+)} - \beta\log\frac{\pi_\theta(y^-)}{\pi_{ref}(y^-)}\Big).

The gradient raises the chosen answer and lowers the rejected one. Pairs that the implied reward already ranks correctly get a small weight. There is no reward model and no sampling loop: each pair costs two forward passes through the policy and two through a frozen reference.

Checked exactly. With a tabular policy, the DPO problem and “Bradley–Terry reward model, then closed-form optimum” are the same optimisation (given the matching L2 penalty). Demo 04 trains both on the same 2,000 pairs at β=0.5\beta = 0.5:

policytrue rewardKL to πref\pi_{ref}
πref\pi_{ref} (SFT)1.6000
RLHF: reward model, then closed form2.1190.888
DPO: trained directly on the pairs2.1190.888

The largest difference between the two policies is 8.5×10−48.5\times10^{-4}, the optimiser’s tolerance. In practice, well-tuned PPO still beats DPO in controlled comparisons, and the choice of preference data matters more than the choice of algorithm (Xu et al.; Ivison et al.).

4.5 Optimising a learned reward too hard lowers the true reward

A reward model is a learned proxy. Past some distance from the starting policy, the policy finds answers the proxy likes and people do not. Gao et al. fit the true reward as d(α−βlog⁡d)d(\alpha - \beta\log d) with d=KLd = \sqrt{\mathrm{KL}}: up, then down.

Demo 04 computes the exact RLHF optimum for shrinking β\beta with three reward models:

β\beta√KL (length-biased RM)proxy rewardtrue rewardmean length
100.063.291.628320
10.493.761.793376
0.30.974.151.881430
0.21.114.221.882443
0.051.404.301.862461
0.021.454.311.870460

With the mildly length-biased reward model, the proxy keeps rising while the true reward peaks at β=0.2\beta = 0.2 and gives some back, as answers grow from 320 to 460 tokens. With the strongly biased one, every step of optimisation hurts: true reward 1.599 → 1.204, answers 332 → 538 tokens. With the unbiased one, the true reward rises to 2.594 (the best possible is 2.595).

The KL penalty limits how far the policy moves, and β\beta trades reward against drift. But the right β\beta can only be chosen against a true measure, which RLHF never sees. This ceiling is one reason reasoning training moved to rewards that are checked rather than learned.

4.6 Several objectives, and AI labels

Production preference tuning balances helpfulness and task success, harmlessness and correct refusals, length and cost, and format and schema compliance. Llama 2 trained separate helpfulness and safety reward models, because one model had trouble scoring both. During RL it used the safety score for prompts likely to be unsafe or when the safety score was low, and the helpfulness score otherwise. Per-token rewards give denser signal for long agent traces, but they are easier to exploit.

AI feedback. An LLM labeler matched human labels within a point or two on helpfulness at roughly a tenth of the cost (Lee et al., RLAIF vs RLHF). Zephyr trained on UltraFeedback’s model labels, and Tülu 3 generates its preference data with models. Human labels remain where models are unreliable.


5. RL with verifiable rewards

5.1 A checker as the reward

taskchecker V(x,y)V(x,y)
math with a final answercompare with the reference
code, software fixesrun the unit and integration tests
structured outputschema validator plus value checks
formal proof (Lean)run the proof checker
answers grounded in sourcescheck the citations support the claims

The objective is max⁡θ Ex Ey∼πθ[V(x,y)]\max_\theta\ \mathbb{E}_x\,\mathbb{E}_{y\sim\pi_\theta}[V(x,y)]. Preference tuning asks which of two answers is better; RLVR asks whether the task was done. A checker does not drift the way a learned reward model does, so it supports many samples per prompt and long runs. (The name RLVR comes from Tülu 3.)

5.2 One RLVR step: sample, check, update

One step:

  1. take a batch of prompts;
  2. sample KK responses each;
  3. run the checker on each;
  4. update the policy;
  5. copy the weights to the sampler.

DeepSeek-R1-Zero’s rollout batch was 512 prompts × 16 samples with a 32K (later 64K) token limit: up to ~268M generated tokens per batch (537M at 64K). Most of an RL step is autoregressive inference, and the slowest response holds up the step. For an agent the response is a whole trajectory and VV checks the final state (do all tests pass?); one number at the end must be shared across thousands of tokens.

5.3 GRPO

GRPO (group relative policy optimisation) scores each response against the others for the same prompt:

Ai=ri−mean(r1,…,rG)std(r1,…,rG).A_i = \frac{r_i - \mathrm{mean}(r_1,\dots,r_G)}{\mathrm{std}(r_1,\dots,r_G)}.

The group is its own baseline. PPO needs a separate value model the size of the policy for this, so GRPO saves that memory. If every sample gets the same reward, all advantages are zero and the prompt teaches nothing. DeepSeek-R1 used two rule-based rewards: one for a correct answer, and one for the format that makes the answer checkable.

Demo 05 runs GRPO on a tabular policy: 60 problems × 10 candidate answers, G=8G = 8, a strict checker. There are 20 easy problems (P(correct) 50%), 20 medium (10%) and 20 hard (0.1%):

stepmean pass@1groups with no signal (all-equal rewards)
121.7%35%
3058.8%68%
15066.1%98%

Easy and medium problems reach 99.2% and 99.0%. Hard problems stay at 0.1%: a group of 8 contains a correct answer only 0.8% of the time, so there is almost never anything to reinforce. After SFT raises their P(correct) to 5%, a group succeeds 33.7% of the time, and the same 150 steps take them to 99.0%. RLVR sharpens what the model can already sometimes do; the earlier stages must make correct answers likely enough to sample.

R1-Zero applied GRPO and the two rule-based rewards to the base model with no SFT. AIME 2024 pass@1 rose from 15.6% to 77.9%, and response length rose with it; nobody wrote a long chain of thought for the model to copy. R1-Zero’s outputs were hard to read and mixed languages. The released R1 adds SFT on curated reasoning traces before RL, then rejection sampling, more SFT, and a final RL stage for general chat. Longer responses also make every later RL step more expensive.

5.4 A checker that can be fooled teaches the model to fool it

A checker must be cheap enough to run on millions of samples, and it should rarely pass a wrong answer. If wrong answers can pass, RL finds them. In OpenAI’s coding RL runs, models learned to make the tests pass without fixing the code (Baker et al.).

Demo 05 gives the same problems a foolable checker: it also passes one answer that breaks its parser, which starts at 1% probability. On the hard problems that answer is 10× likelier to be sampled than the correct one (1% vs 0.1%), so that is where RL learns it:

steppass rate by the training checkertrue accuracy (strict grader)
122.6%21.7%
10074.2%65.7%
15092.9%66.0%

After 150 steps the exploit holds 80% of the hard problems’ probability, and the gain on them is pure exploit. Strict answer parsing, hidden tests and a stricter grader at evaluation make the checker harder to fool. The reward can also multiply conditions: V=1[format]⋅1[correct]⋅1[safe]V = \mathbb{1}[\text{format}]\cdot\mathbb{1}[\text{correct}]\cdot\mathbb{1}[\text{safe}].

5.5 Environments

An RL environment holds the task, executes the model’s tool calls and returns a reward. Agentic RL needs environments that actually run tools, which static prompt sets cannot do. One checker does not cover many skills, so labs train on suites of environments. Procedural generators (Reasoning Gym) create unlimited problems at a chosen difficulty, keeping tasks near what the model can just barely solve, which is exactly where GRPO’s groups carry signal.

The stack:

  • hosted RL APIs;
  • training frameworks (TRL, NeMo RL, OpenRLHF, verl);
  • rollout infrastructure (NeMo Gym, OpenEnv);
  • the environments themselves.

6. Evaluation

6.1 Evaluation decides what ships and what to train next

A model is checked in three ways, and any of them can block a release:

  • offline on fixed, reproducible benchmarks and regression tests;
  • online with A/B tests, user satisfaction, cost and latency;
  • adversarially with jailbreaks, red teaming and safety regressions.

Model reports list dozens of benchmarks, grouped by capability:

  • knowledge: MMLU-Pro, SimpleQA;
  • reasoning and math: GSM8K, AIME, GPQA, Humanity’s Last Exam;
  • code: HumanEval, LiveCodeBench, SWE-bench Verified;
  • instructions and chat: IFEval, Arena-Hard;
  • long context: RULER, LongBench v2;
  • tools and agents: BFCL, τ²-bench, Terminal-Bench, OSWorld;
  • multilingual: MGSM, WMT24++;
  • plus safety, truthfulness and human ratings.

New checkpoints are run on many of them, because improving one capability can make another worse:

  • RLHF in InstructGPT lowered SQuAD, DROP, HellaSwag and WMT scores;
  • RLHF in GPT-4 hurt calibration on MMLU (expected calibration error 0.007 → 0.074);
  • reasoning RL from o1 to o3 raised hallucinations on PersonQA (16% → 33%).

InstructGPT reduced its losses by mixing pre-training data into the RL updates.

6.2 Small benchmarks have wide error bars

SE=p(1−p)/nSE = \sqrt{p(1-p)/n} (demo 06, p=0.5p = 0.5):

benchmarkquestionsSE of one runone question is worth
AIME 2025309.1 points3.3 points
HumanEval1643.90.6
GPQA Diamond1983.60.5
MATH-5005002.20.2
MMLU-Pro12,0320.50.0

Reports average many samples per problem to bring this down. But that removes only the sampling part. For 30 problems with varying difficulty (demo 06):

samples per problemSE on these 30 problems (sampling only)SE as an estimate of general ability
16.98.9
43.56.6
640.95.7

The 30 problems are themselves a small sample, so a 2-point difference on AIME is noise. Report results by slice as well as on average (with and without tools, short and long context, easy and hard, by language): post-training changes help some slices and hurt others, and an average hides that.

6.3 Pass@1, majority vote, pass@k

Demo 06 computes all three from the same 64 samples per problem (500 problems of mixed difficulty):

kkpass@k (unbiased)pass@k (naive 1−(1−c/n)k1-(1-c/n)^k)majority vote of kk
140.0%40.0%39.9%
467.4%66.9%56.6%
1684.2%83.1%60.8%
6492.0%90.1%64.2%
  • Pass@1 is what a user sees on one try.
  • Majority vote is what a product can get by sampling kk times and picking the most common answer. It needs no checker, but helps only where the correct answer is already the most common one.
  • Pass@k assumes a perfect checker picks the right sample, so it is an upper bound on what selection can do. High pass@k with low pass@1 means the model can find the answer but does not do so reliably. Use the unbiased estimator 1−(n−ck)/(nk)1 - \binom{n-c}{k}/\binom{n}{k} (Chen et al.).

Temperature, kk and the output length limit are part of the result and must be reported with it.

6.4 The setup changes the score

A score depends on four parts of the pipeline: the harness (prompt, tools, context management), the sampler (temperature, kk, max length), the parser (extract the answer) and the grader (exact match or judge). Examples:

  • Harness: with the same GPT-4 Turbo, SWE-agent solved ~12% of SWE-bench issues against ~1% for retrieval followed by one patch (Yang et al.).
  • Answer extraction (demo 06, same outputs): a \boxed{}-only extractor scores 28.1%; adding “the answer is” gives 36.1%; the last number gives 40.1%.
  • Output length limit (reasoning lengths log-normal, median 6K tokens): a 4K limit scores 14.8%; 8K 29.1%; 16K 37.3%; 32K 40.0%. Long reasonings are cut off before the answer.
  • Context management: search agents that drop old tool results once context fills up score differently from ones that keep them.

6.5 LLM judges have biases

biaswhat the judge does
positionprefers the answer shown first (or second)
verbosityprefers longer answers
self-preferenceprefers answers from its own model family
prompt sensitivitychanges its verdict when the judging prompt is reworded

Demo 06’s judge has a position bias and a verbosity bias:

  • between two equal models, the one always shown first wins 65.1%; judging each pair in both orders restores 50.0%;
  • verbosity survives the order swap: a model 200 tokens longer wins 67.4% against an equal one.

Strong judges agreed with human experts about as often as experts agreed with each other on open-ended chat (Zheng et al.). Judge each pair in both orders, calibrate against human labels, and use several judges. When a judge is also an RL reward, its biases become targets.

6.6 Contamination

Benchmark problems appear in pre-training data, directly or through synthetic copies. The model partly memorises the answers, and any training that makes it answer more confidently raises the score. In demo 06, memorising 20% of the test set adds 12.4 points; 50% adds 32 points, with no change in ability. Qwen2.5 shows signs of contamination on MATH-500 and AIME, benchmarks much early RL research relied on (Wu et al.).

The responses:

  • live benchmarks that add fresh tasks over time;
  • private sets kept out of public data;
  • tasks built after a model’s data cut-off;
  • fully open, decontaminated training data so the effect can be checked (OLMo 3).

6.7 From failures to the next round of training

The evaluation pipeline: versioned tasks and slices → a runner with a tool sandbox → graders and judges → metrics and a release gate. The gate states in advance what blocks a release:

  • any safety regression above a threshold;
  • schema validity below 99.9% on critical flows;
  • a latency budget exceeded.

That makes the decision auditable. After release, monitoring (new intents, tool failures, schema errors, safety triggers, latency) turns logs into new SFT data, preference pairs and checkers. The result should point to a fix:

  • protocol errors call for more SFT data;
  • quality trade-offs for preference pairs;
  • task failures for better checkers and more RL.

7. Summary

  • Everything the model sees is a token sequence. Chat templates write turns, tool calls, reasoning and preferences into tokens; the loss mask trains only what the model should write (38% of the tokens in our example). Template, mask and parser must agree; tool definitions cost context, and their format is part of the input distribution.
  • Tool use is a protocol with measurable steps. Parsers catch predictable failures; the server’s error policy changes agent scores (64% → 99% for the same model); tool results are untrusted input that must not trigger side effects without confirmation.
  • Constrained decoding guarantees format, not values (100% valid, 14 points less accurate in our toy). Train on the schema you deploy.
  • SFT imitates; preference tuning learns from comparisons. RLHF (Bradley–Terry reward model + KL-regularised RL) and DPO optimise the same objective (identical policies in our exact check). A learned reward optimised too hard lowers the true reward, and labeler biases (length, tone) are exactly what it learns to exploit.
  • RLVR uses a checker as the reward. GRPO’s group baseline teaches nothing when all samples agree, so SFT must first make correct answers likely; a foolable checker is learned (92.9% by the checker, 66.0% true).
  • Evaluation is many capabilities with error bars. AIME’s 30 problems carry ±9 points; pass@1, majority vote and pass@k answer different questions; judges, contamination, extraction rules and length limits all move scores.

8. Common pitfalls

  • Training on tool results (or user turns): the model learns to invent them.
  • Serving with a different chat template, or reformatting tool schemas between training and serving.
  • Not checking for partial delimiters and truncation in the tool-call parser.
  • Relying on constrained decoding to fix a model that never saw the schema.
  • Letting tool output trigger side effects without user confirmation.
  • Arguing PPO vs DPO while ignoring the preference data, which matters more than the algorithm.
  • Choosing β against the reward model’s own score.
  • Running RLVR on prompts the model never solves.
  • A checker that a format trick can pass.
  • Reporting pass@k as if it were what users see, or a score without k, temperature and length limit.
  • Judging pairs in one order only.
  • Ranking models by 2 points on a 30-question benchmark.

9. Exercises

  1. Loss mask. A conversation has 120 system tokens (with tool schemas), 40 user tokens, 200 assistant tokens (including 60 reasoning and 30 tool-call tokens) and 150 tool-result tokens. How many tokens get gradient? With the “train on everything after the first reply” bug, what fraction of the signal teaches the model to write tool outputs?
Answer

200 (all assistant tokens, including reasoning and tool calls). With the bug, the 150 tool tokens (and any later user tokens) are added; if all 150 tool tokens come after the first reply and, say, 20 user tokens do too, trained tokens = 370, of which 150/370 = 41% teach the model to write tool results.

  1. Compounding. An agent task needs 6 tool calls, each failing with probability 8%. Success with give-up? With one independent retry per call?
Answer

Give up: 0.92⁶ = 60.6%. One retry: per-call success 1 − 0.08² = 0.9936; 0.9936⁶ = 96.2% (if retries fail independently; correlated failures give less).

  1. DPO from RLHF. Starting from π∗(y∣x)=πref(y∣x)exp⁡(r/β)/Z(x)\pi^*(y|x) = \pi_{ref}(y|x)\exp(r/\beta)/Z(x), derive the DPO loss. Why does Z(x)Z(x) not appear?
Answer

r(x,y)=βlog⁡(π∗/πref)+βlog⁡Z(x)r(x,y) = \beta\log(\pi^*/\pi_{ref}) + \beta\log Z(x). Bradley–Terry uses r(x,y+)−r(x,y−)r(x,y^+) - r(x,y^-); the βlog⁡Z(x)\beta\log Z(x) terms are the same for both answers of the same prompt and cancel. Replacing π∗\pi^* by πθ\pi_\theta and taking −log σ of the difference gives the DPO loss.

  1. Over-optimisation. In demo 04, why does the true reward keep rising with the unbiased reward model but fall with the length-biased one, although both are fitted on 2,000 pairs?
Answer

The unbiased RM’s ranking agrees with the truth on 98% of pairs, so moving toward its argmax moves toward truly better answers. The length-biased RM pays for length; in this world long answers ramble, so its argmax is long and worse. Small β removes the KL protection and lets the policy reach the region where the RM is wrong.

  1. GRPO signal. A problem has P(correct) = p. With G = 8 samples, what is the probability that a group carries signal (not all equal)? For p = 0.001, 0.05, 0.5, 0.99.
Answer

1−p8−(1−p)81 - p^8 - (1-p)^8: p = 0.001 → 0.8%; 0.05 → 33.7%; 0.5 → 99.2%; 0.99 → 7.7%. Signal vanishes at both ends: too hard and already solved.

  1. Error bars. Model A scores 63.3% and B 56.7% on a 30-problem benchmark (one sample each). Is A better? With 16 samples per problem, A averages 61.0% and B 58.5%?
Answer

One sample: SE ≈ 8.8 points each, difference SE ≈ 12.4; a 6.6-point gap is noise. Paired over the same problems with 16 samples, the sampling noise shrinks (~2.2 points each), but a 2.5-point gap is still within ~1σ of the paired difference, and the 30 problems themselves are a small sample of “general ability”: not established.

Spring 2026’s Assignment 3 is the post-training assignment. The lessons of this lecture are its prerequisites:

  • render data with the exact chat template you will serve with;
  • mask non-assistant tokens;
  • validate tool calls and structured outputs;
  • start RL from a model that already solves some prompts;
  • report scores with error bars and the full evaluation setup.

No assignment solutions are given here.

11. Research directions

  • Rewards that cannot be gamed. Checkers for open-ended tasks; detecting reward hacking from reasoning traces.
  • On-policy preference data at scale. How often to re-sample and re-label; mixing AI and human labels.
  • Structured output without accuracy loss. Training methods that make constrained decoding unnecessary; reasoning fields inside schemas.
  • Credit assignment for long agent traces. One reward at the end of thousands of tokens; process rewards that are not easier to exploit.
  • Evaluation that tracks ability, not setup. Standardised harnesses, slice-level reporting, contamination-resistant benchmarks.

12. Further reading

  • Ouyang et al., InstructGPT (arXiv:2203.02155); Touvron et al., Llama 2 §3.2 (arXiv:2307.09288).
  • Rafailov et al., DPO (arXiv:2305.18290); Xu et al., Is DPO Superior to PPO? (arXiv:2404.10719); Ivison et al. (arXiv:2406.09279); Tajwar et al. (arXiv:2404.14367).
  • Gao, Schulman, Hilton, Scaling Laws for Reward Model Overoptimization (arXiv:2210.10760); Singhal et al., A Long Way to Go (arXiv:2310.03716); Sharma et al., Towards Understanding Sycophancy (arXiv:2310.13548); Lee et al., RLAIF vs RLHF (arXiv:2309.00267).
  • Lambert et al., Tülu 3 (arXiv:2411.15124); Shao et al., DeepSeekMath (arXiv:2402.03300); DeepSeek-AI, DeepSeek-R1 (arXiv:2501.12948); Baker et al., Monitoring Reasoning Models for Misbehavior (arXiv:2503.11926); Stojanovski et al., Reasoning Gym (arXiv:2505.24760).
  • Dong et al., XGrammar (arXiv:2411.15100); Tam et al., Let Me Speak Freely? (arXiv:2408.02442); Greshake et al., Indirect prompt injection (arXiv:2302.12173); Wallace et al., The Instruction Hierarchy (arXiv:2404.13208).
  • Zheng et al., Judging LLM-as-a-Judge (arXiv:2306.05685); Chen et al., Codex (arXiv:2107.03374); Yang et al., SWE-agent (arXiv:2405.15793); Wu et al., Reasoning or Memorization (arXiv:2507.10532).

13. Next lecture

Lecture 17 · Data for Post-Training. This lecture took the data as given. Lecture 17 builds it:

  • synthetic SFT data pipelines: schemas, samplers, personas, seed data and diversity;
  • rejection sampling with verifiers and quality scoring;
  • skill mixtures and balancing;
  • RL environment construction and reward design;
  • the tooling of NVIDIA’s NeMo Data Designer.

术语表 (Glossary, English → 中文)

English中文
post-training / base model / instruct model / reasoning model后训练 / 基座模型 / 指令模型 / 推理模型
chat template / special token / role / turn对话模板 / 特殊词元 / 角色 / 轮次
loss mask损失掩码
tool definition / tool call / tool result工具定义 / 工具调用 / 工具结果
reasoning tokens / reasoning parser推理词元 / 推理解析器
structured output / JSON schema / constrained decoding结构化输出 / JSON 模式 / 约束解码
escaping转义
indirect prompt injection / instruction hierarchy间接提示注入 / 指令层级
provenance / side effect / user confirmation来源 / 副作用 / 用户确认
trace / on-policy / off-policy轨迹 / 同策略 / 异策略
supervised fine-tuning (SFT) / demonstration监督微调 / 示范数据
preference pair / chosen / rejected偏好对 / 被选 / 被拒
Bradley–Terry model / reward modelBradley-Terry 模型 / 奖励模型
RLHF / KL penalty / reference policy基于人类反馈的强化学习 / KL 惩罚 / 参考策略
DPO (direct preference optimisation)直接偏好优化
reward over-optimisation / Goodhart’s law奖励过度优化 / 古德哈特定律
length bias / sycophancy长度偏差 / 谄媚
RLAIF (AI feedback)基于 AI 反馈的强化学习
RLVR (verifiable rewards) / checker / verifier可验证奖励强化学习 / 检查器 / 验证器
GRPO / group-relative advantage组相对策略优化 / 组内相对优势
reward hacking奖励投机(奖励黑客)
RL environment / rollout强化学习环境 / 采样展开
pass@k / majority votepass@k / 多数投票
standard error / slice标准误 / 切片
LLM-as-a-judge / position bias / verbosity bias大模型评审 / 位置偏差 / 冗长偏差
contamination / live benchmark数据污染 / 动态基准
release gate发布门槛
← 返回课程目录