← Post-training overview

QRS explainer · Post-training · The full guide

From next-token prediction to assistants that reason

The history first, then supervised fine-tuning, preferences, the reinforcement learning they rely on, the methods that came after PPO, and how all of this is run and measured in practice. Each idea comes with its intuition before its maths.

阅读中文版 →

Part 1 about 10 minFrom pre-training to post-training

1One model per task

Until the late 2010s, natural language processing mostly built one model per problem. A sentiment classifier, a question-answering system and a translation model each had their own architecture, their own labelled dataset and their own training run. If you had trained a good model and then needed to solve a different problem, you trained another model.

What was shared was the bottom layer. Word embeddings such as word2vec (Mikolov et al., 2013) and GloVe (Pennington et al., 2014) learned one vector per word from unlabelled text, and task models used those vectors as input features. This was already transfer learning, but a shallow kind: each word got a single vector regardless of context, so bank in “river bank” and “bank account” looked the same, and everything above the embeddings still had to be learned from scratch for every task.

Between 2015 and 2020 that changed. The field converged on a different recipe: train one large language model on a very large amount of unlabelled text, keep it, and adapt it to each task. That recipe, “train once broadly, adapt many times cheaply”, is the embryo of today’s split between pre-training and post-training.

2Pre-train, then adapt

Word vectorsPre-train, then adaptArchitectureScale and promptingPost-training2013word2vec2015Dai & Le2017Transformer2018ULMFiTELMoGPT-1BERT2019GPT-2T52020GPT-32021FLAN2022InstructGPT2023DPO2024GRPOo12025DeepSeek-R1
Word vectorsPre-train, then adaptArchitectureScale and promptingPost-training2013word2vec and GloVe2015Semi-supervised sequence learning2017The Transformer2018ULMFiT2018ELMo2018GPT-12018BERT2019GPT-22019T52020GPT-32021FLAN2022InstructGPT2023Direct Preference Optimization2024GRPO (DeepSeekMath)2024OpenAI o12025DeepSeek-R1
Figure 1. From word vectors to reasoning models. Colour marks the paradigm each milestone belongs to. Press Play, click a milestone, or focus the timeline and use the arrow keys.

The quiet start: semi-supervised sequence learning (2015)

Dai and Le (2015) pre-trained an LSTM as a language model, or as a sequence autoencoder, and used its weights to initialise a supervised text classifier. The pre-trained networks trained more stably and generalised better on several classification benchmarks. The idea that a language model need not be the final product, but can be a pre-training stage for supervised learning, was already on the table.

It did not take over immediately. LSTMs process a sequence one step at a time, which makes training hard to parallelise and expensive to scale. Without strong evidence that pre-training the whole network paid off, there was little reason to abandon the familiar pattern of pre-trained embeddings plus a task-specific model.

Contextual representations: ELMo (2018)

ELMo (Peters et al., 2018) attacked the one-vector-per-word limitation. It trained a bidirectional LSTM language model, one direction predicting the next word and the other the previous word, so every word’s internal representation depends on its context. Different layers capture different information, so ELMo’s final representation is a task-specific weighted combination of all layers, with the weights learned for each task.

ELMo showed that a large pre-trained language model learns representations that transfer across many tasks, and it moved the field from static to contextual representations. But it was still feature-based transfer: the pre-trained model produced features that were fed into a separate task model.

Fine-tuning the whole model: ULMFiT (2018)

ULMFiT (Howard and Ruder, 2018) took the other road: if we already have a general language model, fine-tune that model on the target task. Its recipe had three stages: pre-train a language model on general text; continue language-model training on the target task’s own text, so the model adapts to that domain’s distribution; then add a classifier and train on the labels. The middle stage anticipates today’s continued pre-training and staged adaptation.

Fine-tuning a whole network on a small dataset risks catastrophic forgetting: large updates can erase what pre-training learned. ULMFiT used discriminative fine-tuning (different learning rates for different layers), slanted triangular learning-rate schedules and gradual unfreezing (unfreeze the top layer first, then the next, and so on). The specific tricks matter less today; the tension between adapting and forgetting is still central to post-training.

Its most striking result was data efficiency: the paper reports that with only 100 labelled examples, ULMFiT matched the performance of training from scratch on 100 times more data. That is strong evidence that the pre-trained model already held most of what the task needed, and fine-tuning mainly had to adapt it.

A task-agnostic Transformer: GPT-1 (2018)

GPT-1 (Radford et al., 2018) combined pre-train-then-fine-tune with the Transformer (Vaswani et al., 2017), which processes all positions in parallel and made far larger pre-training runs practical. It pre-trained a decoder-only Transformer on a corpus of books and then fine-tuned it on each task.

Its key design choice was to change the input, not the model. Tasks with very different structures were turned into token sequences through task-specific input transformations: for entailment, premise and hypothesis concatenated with a delimiter token; for similarity, both orderings of the two sentences; for multiple choice, the context paired with each candidate answer. The same network handled them all, with only a small linear output layer added. This is an early form of “write the task as text”; today users state the task in natural language, whereas GPT-1 used a fixed format chosen by the designers.

During fine-tuning GPT-1 also kept a language-modelling loss as an auxiliary objective, so the model would not lose its language-modelling ability, the same worry ULMFiT faced, solved differently. The paper’s ablations found the auxiliary loss helped on the larger datasets but not on the smaller ones, so it is not GPT-1’s main contribution.

More important was an observation about zero-shot behaviour. The authors measured how well the pre-trained model, before any fine-tuning, could solve a few tasks using simple heuristics, at checkpoints throughout pre-training. Performance rose fairly steadily as pre-training continued. Their hypothesis, which still shapes the field, was that to predict the next token well, a language model is forced to learn abilities that downstream tasks need, partly because unlabelled text already contains examples of those tasks. An LSTM showed similar behaviour with higher variance, which they took as a hint that the Transformer’s inductive bias helps transfer. On other tasks the zero-shot heuristics were weak, so this did not make fine-tuning unnecessary.

If pre-training already gives a model general representations and some problem-solving ability, does post-training teach new abilities, or does it select and release abilities the model already has?

Bidirectional pre-training: BERT (2018)

At the end of 2018 BERT (Devlin et al., 2019) pre-trained a bidirectional Transformer encoder with masked language modelling (predict randomly masked tokens from both sides) and a next-sentence-prediction task, then fine-tuned it on a wide range of language-understanding benchmarks with strong results. BERT made “pre-train a large model, then fine-tune for each task” the mainstream paradigm in NLP. It still needed a separate fine-tuning run per task, though, and an encoder does not generate text, so the unified task interface was not there yet.

3Scale and prompting

If one model can be adapted to so many tasks, and pre-training alone already produces some zero-shot ability, do we need to fine-tune for every task at all?

GPT-2: language models as unsupervised multitask learners (2019)

The GPT-2 paper’s title states its thesis (Radford et al., 2019). Web text is full of implicit task demonstrations: an interview transcript pairs “Q:” with a question and “A:” with its answer; an article followed by “TL;DR:” is followed by a summary. A model that predicts such text well may have to learn what follows “Q: … A:”. So train a large enough model on enough text, and tasks may be learned without being labelled as tasks.

GPT-2 had 1.5 billion parameters, more than ten times GPT-1, and was trained on WebText, about 40 GB of text from roughly 8 million web documents. The authors trained several model sizes and evaluated them zero-shot, without any fine-tuning; performance improved roughly log-linearly with model size across tasks. That is an early signal of the scaling behaviour later studied systematically (Kaplan et al., 2020).

GPT-2 clearly acquired task-relevant behaviour from pre-training alone. It also showed why pre-training is not the whole story: asked a question, a base model may continue the document instead of answering it, for example by writing more questions. It has the knowledge, but not the habit of using it the way a user wants. That gap is a central motivation for instruction tuning.

T5: everything is text-to-text (2019)

T5 (Raffel et al., 2020) introduced no new architecture. Its contribution was a unified format: every task is “text in, text out”, with a task prefix such as translate English to German: or summarize:. One model and one loss then serve translation, summarisation, classification and question answering. T5 was still fine-tuned on downstream tasks, but its systematic study also found that performance kept improving with scale, up to its largest, 11-billion-parameter model.

GPT-3: in-context learning (2020)

GPT-3 (Brown et al., 2020) had 175 billion parameters, two orders of magnitude more than GPT-2, and the paper trained eight sizes from 125 million parameters upwards. Across many tasks, zero-shot, one-shot and few-shot performance generally improved with size, and the gap between zero-shot and few-shot often widened as models grew.

Few-shot in-context learning means putting a handful of worked examples in the prompt, with no weight updates, and letting the model continue the pattern. Given

English → French sea → mer cat → chat cheese → ?

the model is very likely to produce fromage. The examples change the model’s output distribution towards what we want without changing a single parameter. Arguably, the most important scaling result of GPT-3 is not that larger models generate better text but that they get better at using prompts to do tasks.

Supervised fine-tuning is the natural next step. In-context learning shows that a few demonstrations can temporarily steer a fixed model towards a task; SFT writes that “do what I ask” behaviour into the parameters, permanently and for every prompt. The rest of post-training is built on top of it.

A running example

To see each method act on the same thing, we follow one prompt through the whole guide: “What is the capital of France?”. Our toy model can give one of six whole replies, y1 to y6. The table lists the probability each stage of post-training assigns to them, and the two scores later stages use: a reward model (§9), which has learned to like complete answers but also over-rates flattery, and a verifier (§20), which only checks that the reply names Paris.

ReplyTextBase modelAfter SFT (πref)Reward model rVerifierAfter RLHF (β = 1)
y1“What is the capital of Germany?”42%4%−1.500.3%
y2“France is a country in Western Europe, bordered by…”26%11%−0.403%
y3“Paris.”12%40%0.51 (names Paris)25%
y4“The capital of France is Paris.”7%33%1.61 (names Paris)61%
y5“Lyon.”10%9%−1.001%
y6“Great question! The capital of France is Paris, a city famous for…”3%3%2.21 (names Paris)10%

Read it left to right. The base model mostly continues the document, as GPT-2 did: y1 treats the prompt as one question in a quiz. SFT moves probability onto answers (§6). RLHF, which optimises the reward model’s score while staying close to the SFT model, concentrates it further, mostly on the complete sentence y4, and partly on the flattering y6 that the reward model over-rates (§16 and §19). All numbers are illustrative, not measurements from a real model.

Part 1 in one sentence

Pre-training concentrates knowledge and skill in one model; the open question post-training answers is how to make that model reliably use them the way people want.

Check yourself Why is ELMo’s transfer called feature-based, and what did ULMFiT do differently?

ELMo’s pre-trained network produced representations that were fed, as features, into a separate model trained for each task. ULMFiT fine-tuned the language model’s own parameters on the target task, the route that modern post-training follows.

Part 2 about 11 minSupervised fine-tuning

4What SFT optimises

Supervised fine-tuning (SFT), also called instruction tuning, continues training a pre-trained model on a dataset of prompt–response pairs, so that it learns to follow instructions and answer in the intended way. It usually comes straight after pre-training and is the bridge from general language ability to useful behaviour.

The training signal is the same as in pre-training: predict the next token. What changes is the data. Suppose we have N pairs of a prompt x and a reference response y=(y1,…,yT):

𝒟={(xi,yi)}i=1N,Pθ(y∣x)=∏t=1TPθ(yt∣x,y<t).

The factorisation is just the chain rule of probability: the model generates one token at a time, each conditioned on the prompt and on the tokens before it. Maximum likelihood chooses the parameters that make the observed responses as probable as possible.

Assuming the pairs are independent, the likelihood is a product over examples; taking the negative logarithm turns it into a sum we can minimise:

θ⋆=argmaxθ∏i=1NPθ(yi∣xi)=argminθ[−∑i=1NlogPθ(yi∣xi)].

Substituting the factorisation turns the log of a product into a sum of logs, one per response token:

ℒSFT(θ)=−∑i=1N∑t=1TilogPθ(yi,t∣xi,yi,<t).

Each term is the cross-entropy between the one-hot distribution on the correct token and the model’s predicted distribution over the vocabulary, so SFT is token-level classification, exactly as in pre-training. Averaged over the data, minimising this loss is equivalent to minimising the KL divergence KL(pdata‖Pθ), because the remaining entropy term of the data does not depend on θ. This “forward” KL heavily penalises the model for giving low probability to anything in the data, so SFT tends to cover the demonstrations rather than pick the best of them, a point that matters in §7.

5Data, templates and loss masks

Where SFT data comes from

  • Human demonstrations. Annotators write a prompt, or take one from real users, and write the response a model ideally should give. InstructGPT fine-tuned GPT-3 on such labeller-written demonstrations (Ouyang et al., 2022). This is the purest form of SFT data, and the most expensive.
  • Reformatted datasets. Existing supervised datasets can be rewritten as instructions. A sentiment example with sentence s becomes “Is the sentiment of the following review positive or negative? s” with the answer “positive”. FLAN built its training mixture this way, with several natural-language templates per dataset (Wei et al., 2022a).
  • Synthetic data. A model generates instructions and responses, which are filtered and added to the training set. Self-Instruct bootstrapped instruction data from a small set of seed tasks this way (Wang et al., 2023).
  • Domain data. Code, mathematics, medicine or a company’s own documents, when the model needs a specific domain.

Modern SFT mixes all of these. What the mixture covers, its quality and the proportions of each kind largely decide the result. Before training, data is usually cleaned: harmful, incorrect, low-quality or simply undesired examples are filtered out, and the mixture is balanced so no single kind dominates.

Chat templates

Conversations are serialised into a single token sequence with special tokens marking the roles. The exact tokens differ between model families; schematically:

<|system|> You are a helpful assistant.<|end|> <|user|> What is the capital of France?<|end|> <|assistant|> The capital of France is Paris.<|end|>

The system prompt sets overall behaviour; the user turn is the prompt x; the assistant turn is the response y. At inference time the model receives everything up to <|assistant|> and generates the rest, stopping when it produces the end token. Using the same template in training and at inference is essential.

Teacher forcing and the loss mask

Training uses teacher forcing: when predicting token t, the model is conditioned on the true previous tokens from the data, not on its own earlier predictions. Because every position’s context is known in advance, all positions are trained in parallel in one forward pass, exactly as in pre-training.

Usually the loss is computed only on the response, the highlighted part above. With z the whole tokenised conversation and a mask mt=1 on assistant tokens and 0 elsewhere,

ℒ(θ)=−1∑tmt∑tmtlogPθ(zt∣z<t).

The prompt still shapes the prediction, because it is in the context, but the model is not trained to produce prompts; it is trained to answer them. This response-only loss is common but not universal: some pipelines train on whole conversations, and how the loss is normalised (per token, per response or per batch) also varies.

6Why a little data goes far

A striking empirical fact is how little SFT data is needed to change a model’s behaviour substantially, and that the change generalises.

  • LIMA fine-tuned a 65-billion-parameter LLaMA model on just 1,000 carefully curated prompt–response pairs, with no reinforcement learning, and obtained strong instruction following that generalised to tasks absent from the training data (Zhou et al., 2023).
  • FLAN instruction-tuned a 137-billion-parameter model on more than 60 NLP datasets phrased as instructions. Zero-shot performance on unseen task types improved substantially, and FLAN surpassed zero-shot 175B GPT-3 on 20 of the 25 datasets evaluated (Wei et al., 2022a). Its ablations are just as telling: more task clusters helped, the natural-language instructions mattered, and the benefit appeared only at sufficient scale; for the smaller models tested, instruction tuning hurt performance on held-out tasks.

Pre-training has already shown the model vast amounts of text. It is hard to believe that a thousand examples teach it enough new knowledge to explain such a large change. A widely held view, which the LIMA authors call the superficial alignment hypothesis, is that a model’s knowledge and capabilities are learned almost entirely in pre-training, and alignment mainly teaches it which format and style to use when interacting with users (Zhou et al., 2023).

User: What is the capital of France?Assistant: ▮ ← next token?␣Paris y340%␣The y433%␣Great y63%␣What y14%␣France y211%␣Lyon y59%dashed outline: base model
User: What is the capital of France?Assistant: ▮ ← next token?␣Paris y340%␣The y433%␣Great y63%␣What y14%␣France y211%␣Lyon y59%dashed outline: base model
Figure 2. SFT reshapes the next-token distribution. The running example at the level of the first token: in this toy each of the six replies starts with a different token, so these probabilities are the base and SFT columns of the table in §3. The base model already gives Paris some probability but spends most of it on continuing the document. After SFT the probability concentrates on tokens that begin an answer; the wrong answer, Lyon, does not grow. Switch models, or drag the slider to blend their log-probabilities. Illustrative probabilities, not measurements from a real model.

Figure 2 shows the intuition. Pre-training has seen “the capital of France is Paris” countless times, so Paris is already a candidate. But the base model has also seen the question in quizzes, lists and forum threads, where it is followed by another question or a digression. SFT does not need to teach the fact; it needs to move probability from “continue the document” to “answer the question”. (SFT can push towards other goals too, such as continuing a story; answering is the common case.)

There is direct evidence for this picture. Comparing base and aligned versions of the same models token by token, Lin et al. (2024) found that the two agree on the top-ranked token at most positions, and that the shifts concentrate on stylistic tokens such as discourse markers and safety disclaimers. They also showed that a base model prompted with a few well-chosen in-context examples can approach the aligned model’s behaviour.

The view has limits. SFT can teach new facts, but slowly, and there is evidence that it comes at a cost: Gekhman et al. (2024) found that fine-tuning examples introducing knowledge the model did not have are learned more slowly than consistent ones, and that as they are learned the model becomes more prone to hallucinate. So “SFT mainly elicits” is best read as a description of what SFT does well, not a law.

Why parameter-efficient fine-tuning works

The same view explains why tiny updates suffice. LoRA (Hu et al., 2022) freezes the pre-trained weights W0 and learns a low-rank correction,

W=W0+ΔW=W0+BA,B∈ℝd×r,A∈ℝr×k,r≪min(d,k),

with B initialised to zero so training starts from the pre-trained model exactly. LoRA was motivated by the hypothesis that the weight change during adaptation has a low “intrinsic rank”, building on earlier work which found that fine-tuning can be reparameterised in a surprisingly low-dimensional subspace, which shrinks as pre-trained models grow (Aghajanyan et al., 2021). If the pre-trained model already sits in a very capable region of parameter space, post-training needs to move it only along a few directions. Learning B and A is, in effect, learning which directions to move in. This is consistent with the elicitation view rather than a proof of it.

7Strengths and limits

SFT’s strengths are easy to list. It is simple and stable: supervised learning with a cross-entropy loss. Its signal is direct: people show the model what they want. It is data-efficient, changing behaviour with far less data than pre-training. It is controllable: style, format and domain can be shaped through demonstrations. And instruction tuning brings some generalisation to unseen tasks.

Its limits are what motivate the rest of post-training.

  1. It shows a good answer, but not which answer is better. SFT says “imitate this response”. Many prompts have no single correct reply: two answers can both be acceptable while one is more accurate, more concise, more helpful or safer. In the running example, SFT leaves “Paris.” and the full sentence both likely; nothing in its data says which is preferred. And writing an ideal answer is often harder for a person than comparing two answers. Comparisons may be an easier and more direct signal for improving quality.
  2. Its ceiling is the demonstrations. The model imitates its training responses. If they are mediocre, biased or inconsistent, it learns those flaws too, and maximum likelihood’s mass-covering behaviour (§4) means it learns to reproduce the whole spread, not just the best.
  3. It never sees its own mistakes. With teacher forcing the model always conditions on ground-truth prefixes, but at inference it conditions on its own generations. Small errors can compound into states the training data never covered. This mismatch is known as exposure bias (Ranzato et al., 2016), and SFT has no mechanism for targeting the errors the model itself tends to make.

The next parts change the training signal from “learn a good answer” to “learn a better answer”, and let the model learn from what it generates itself.

Part 2 in one sentence

SFT is maximum likelihood on demonstrations; it is cheap and effective at eliciting behaviour, but it cannot rank answers, exceed its data, or correct the model’s own errors.

Check yourself With a response-only loss, which tokens contribute to the SFT loss, and why does the prompt still matter?

Only the assistant’s tokens (mask mt=1) are scored. The prompt is still in the context, so every prediction is conditioned on it; the model learns to answer prompts without being trained to write them.

Part 3 about 7 minLearning from preferences

8From demonstrations to comparisons

Once a model has learned to answer, the next goal is for it to answer better. Often there is no unique reference answer to write down, but saying which of two answers is better is easy. That is the essential difference between demonstration data and preference data: one provides a reference answer to imitate, the other a preference relation between answers.

Demonstration (SFT)

A prompt and one ideal response, written by a person.

Signal: “produce this”.

Comparison (preference)

A prompt and two or more responses, usually sampled from the model, ranked by a person.

Signal: “this one is better than that one”.

Preference data can come from many places. People can write contrasting pairs to target a property, for example a terse reply against a detailed one when detail is wanted. More commonly the model generates candidates and people judge them. In SFT that would be dangerous, because training on a weak model’s own outputs could reinforce its flaws; for comparisons it is natural, and this division of labour, models generate and people evaluate, is exactly what RLHF exploits (Christiano et al., 2017; Stiennon et al., 2020). It has a further advantage: the feedback is about the model’s own outputs, which are the outputs we care about.

Comparisons are not a free lunch. Some comparisons are genuinely hard, people disagree, and a single “A is better than B” carries less information than a whole high-quality demonstration. Their real advantage is that, for many open-ended generation tasks, comparison is a supervision interface that scales more easily.

The data now looks like this, with yw the preferred (“winning”) and yl the rejected (“losing”) response:

𝒟pref=\{(xi,yiw,yil)\}i=1N.

In the running example a labeller shown y4 (“The capital of France is Paris.”) and y3 (“Paris.”) might prefer the complete sentence, giving the triple (x,y4,y3). How do we turn such orderings into a training signal? One idea is to label the better answer 1 and the worse 0 and train a classifier. But a classifier that can tell which of two answers is better cannot necessarily say how good one answer is, and that is what we need: if the model is going to generate answers, have them scored and improve, which is reinforcement learning, it needs a scoring function for single answers.

9The Bradley–Terry reward model

So we want a function r(x,y) that scores a single response, learned from pairwise orderings. Since “better” has no fixed definition and human judgements are noisy, a probabilistic model of preferences is the natural starting point. Suppose responses y1 and y2 have scores r1 and r2. A softmax over the two scores gives the probability that y1 wins:

P(y1≻y2∣x)=er1er1+er2=11+e−(r1−r2)=σ(r1−r2),

where σ is the logistic sigmoid. This is the Bradley–Terry model of paired comparisons (Bradley and Terry, 1952): a logistic model in the score difference. Following standard maximum likelihood, we maximise the probability of the observed preferences, that is, minimise the negative log-likelihood:

ℒRM(ϕ)=−∑i=1Nlogσ(rϕ(xi,yiw)−rϕ(xi,yil)).
Reward model scores r(x, y)Starts at the running example: A = y4 (full sentence), B = y3 (“Paris.”)-4-3-2-101234Δ = 1.1BA0.00.51.0-6-3036Δ = r(A) − r(B)P(A preferred to B) = σ(Δ)75%0246-6-3036Δ = r(A) − r(B)Loss if A was the chosen reply: −log σ(Δ)
Reward model scores r(x, y)A starts as y4, B as y3-4-3-2-101234Δ = 1.1BA0.00.51.0-6-3036Δ = r(A) − r(B)P(A preferred to B) = σ(Δ)75%0246-6-3036Δ = r(A) − r(B)Loss if A was the chosen reply: −log σ(Δ)
Figure 3. Preference probability is a sigmoid of the reward gap. Only the gap Δ=r(A)−r(B) matters. The figure starts at the running example: A is y4 (reward 1.6), B is y3 (reward 0.5), so the reward model predicts that labellers prefer the full sentence with probability 75%. Drag A and B along the reward axis, or use the sliders. Shift both moves the two rewards together: the probability and the loss do not change.

It looks like classification, but the classifier is constrained to the form σ(Δr), so what is actually learned is the score rϕ.

Writing Δ=rϕ(x,yw)−rϕ(x,yl), the gradient is

∂∂Δ(−logσ(Δ))=−(1−σ(Δ))=−σ(−Δ),∇ϕℒ=−σ(−Δ)(∇ϕrϕ(x,yw)−∇ϕrϕ(x,yl)).

Each update raises the winner’s score and lowers the loser’s, weighted by σ(−Δ): pairs the model already orders confidently contribute almost nothing, and mistakes contribute most. Although it is trained on pairs, the result is a stand-alone scoring function. In LLM work, rϕ is usually itself a Transformer, often initialised from the SFT model with the output layer replaced by a scalar head, which reads the whole prompt and response and outputs one number (Ouyang et al., 2022). InstructGPT collected rankings of several responses per prompt and trained on all pairs from each ranking together.

Translation invariance

Adding a constant to every score leaves every preference probability unchanged, because only differences enter σ. In fact any shift that depends only on the prompt, r′(x,y)=r(x,y)+c(x), is invisible to the data. This translation invariance means the reward’s level is not identified, which is why InstructGPT normalised its reward model so that labeller demonstrations scored zero on average before RL (Ouyang et al., 2022). It matters because preference learning cares only about relative differences, but RL optimisers are sensitive to the magnitude of rewards; the level and scale have to be controlled by other means. The same invariance reappears in §14, where subtracting a baseline is harmless, and in §19, where DPO’s normalising constant cancels.

Reward hacking

The reward model’s biggest risk is already visible. We wanted to optimise a human objective that is hard to formalise, so we trained a model to approximate it. But is a higher score always better? Nothing guarantees that there are no responses the reward model rates highly but people do not like. In the running example the reward model gives the flattering y6 the highest score of all, 2.2. Optimising hard against an imperfect proxy finds exactly such responses: this is reward hacking, an instance of Goodhart’s law. Measured against a held-out “gold” reward, optimising a proxy reward model first improves true quality and then degrades it as the optimisation pushes further (Gao et al., 2023; Stiennon et al., 2020). That is why, in practice, we never simply maximise the learned reward; §16 adds a constraint that keeps the policy close to where the reward model is trustworthy.

Part 3 in one sentence

A Bradley–Terry reward model turns pairwise preferences into a scalar score, identified only up to a shift and only trustworthy near the data it was trained on.

Check yourself You add 5 to the reward model’s score of every reply to one prompt. What happens to the Bradley–Terry loss, and where does this fact come back?

Nothing: only score differences enter σ, so the loss and every preference probability are unchanged. The same invariance makes a state-dependent baseline harmless in policy gradients (§14) and lets DPO’s prompt-dependent constant logZ(x) cancel (§19).

Part 4 about 25 minReinforcement learning, from scratch

10Agents, MDPs and returns

A reward model can say how good an answer is, but it does not make the model produce better answers. For that the model must adjust its generation strategy, its output distribution, in response to the scores. That is reinforcement learning (RL). This part builds the RL needed for RLHF from first principles; Sutton and Barto (2018) is the standard reference for all of it.

Agent and environment

An agent interacts repeatedly with an environment. At time t it observes the state St=st, chooses an action At=at according to its policy π, and the environment returns a reward Rt+1=rt+1 and a new state St+1=st+1:

St→πAt→environment(Rt+1,St+1).

We usually assume the environment is Markov:

P(St+1∣St,At,St−1,At−1,…,S0,A0)=P(St+1∣St,At).

A common misreading is that the future does not depend on the past. The correct reading is that the current state already contains everything about the past that matters for the future, so earlier states add no information. For a language model the state is naturally

st=(x,y<t),at=yt,st+1=(x,y≤t),

the prompt plus the tokens generated so far. Each state literally contains all earlier ones, so the Markov property holds by construction, and the transition is deterministic: appending the chosen token.

The Markov decision process

Formally the problem is a Markov decision process (MDP) ℳ=(𝒮,𝒜,P,R,γ): a state space, an action space, transition probabilities P(s′∣s,a) (the same action in the same state may lead to different outcomes), a reward function R, and a discount factor γ. We want the agent to maximise long-run reward, not just the next reward, so we define the discounted return

Gt=Rt+1+γRt+2+γ2Rt+3+⋯=∑k=0∞γkRt+k+1,0≤γ≤1,Gt=Rt+1+γGt+1.

The recursion on the right will drive almost everything that follows. With γ near 0 the agent is myopic; with γ near 1 it weighs distant rewards almost as much as immediate ones and can learn to trade short-term for long-term gain. With γ<1 and bounded rewards the sum is finite even for endless episodes. Language-model episodes end at an end-of-sequence token, and RLHF commonly uses γ=1.

0.00.51.0024681012141618steps into the future, kWeight γk on the reward k steps aheadhorizon 1/(1−γ) ≈ 10.0+1 now+5 at step 10Discounted return G0Quick1.00Patient1.94
0.00.51.005101519steps into the future, kWeight γk on the reward k steps aheadhorizon 1/(1−γ) ≈ 10.0+1 now+5 at step 10Discounted return G0Quick1.00Patient1.94
Figure 4. The discount factor decides how far ahead the agent looks. Bars show the weight γk on a reward k steps ahead. A quick stream pays +1 immediately; a patient stream pays +5 ten steps later. Move γ: below about 0.84 the quick reward wins; above it, the patient one. The dashed line marks the effective horizon 1/(1−γ). Illustrative reward streams.

Policies, trajectories and the objective

The object RL learns is the policy. A stochastic policy gives a distribution over actions in each state:

πθ(a∣s)=P(At=a∣St=s).

A language model is a policy already: it computes Pθ(yt∣x,y<t), a distribution over the next action given the current state. Running a policy in an environment produces a trajectory τ=(s0,a0,r1,s1,a1,r2,…); for a language model, a trajectory is one whole generated response. Its probability is

Pθ(τ)=ρ0(s0)∏t≥0πθ(at∣st)P(st+1∣st,at),

with ρ0 the distribution of starting states (for us, the distribution of prompts). The goal of RL is to maximise the expected return

J(θ)=𝔼τ~πθ[G0],θ⋆=argmaxθJ(θ).

In the simplest RLHF setting the reward arrives once, at the end, so J(θ)=𝔼x~𝒟𝔼y~πθ(·∣x)[r(x,y)]. In the running example a trajectory is one of the six replies, and J is the average reward-model score of the replies the policy produces.

Compare this with SFT. SFT tells the model what to generate on a fixed dataset. RL lets the model generate, scores what it generated, and changes the policy so that high-scoring outputs become more likely and low-scoring ones less likely. Given a good enough reward, the model can in principle keep improving from its own attempts. Today’s reasoning methods (§20–21) rest on the same idea; they mainly replace the learned reward model with a verifier.

Exploration is not free, though. The model can only discover good responses that it has some chance of generating, so where it starts matters. That is why RL for language models starts from an SFT model rather than from scratch: in the running example the base model produces a correct answer only 22% of the time, the SFT model 76%.

11Policy gradients

How exactly should the policy change in response to rewards? The intuition: make high-return trajectories more likely and low-return ones less likely. Write R(τ)=G0 for a trajectory’s return. We want to do gradient ascent, θ←θ+α∇θJ(θ).

∇θJ(θ)=∇θ𝔼τ~πθ[R(τ)]=∇θ∑τPθ(τ)R(τ)=∑τ∇θPθ(τ)R(τ).

The difficulty is that θ appears in the distribution we are averaging over, so the gradient is not obviously an expectation we can estimate by sampling. The log-derivative trick fixes that:

∇θlogPθ(τ)=∇θPθ(τ)Pθ(τ)⟹∇θPθ(τ)=Pθ(τ)∇θlogPθ(τ),
∇θJ(θ)=∑τPθ(τ)∇θlogPθ(τ)R(τ)=𝔼τ~πθ[R(τ)∇θlogPθ(τ)].

Now expand the log-probability of a trajectory. The start-state and transition terms come from the environment and do not depend on θ, so their gradients vanish, which also means we never need a model of the environment:

logPθ(τ)=logρ0(s0)+∑t(logπθ(at∣st)+logP(st+1∣st,at))⟹∇θlogPθ(τ)=∑t∇θlogπθ(at∣st).

Putting the two together:

∇θJ(θ)=𝔼τ~πθ[∑tR(τ)∇θlogπθ(at∣st)].

This is the basic policy gradient, and it says exactly what the intuition said: ∇θlogπθ(at∣st) is the direction that makes action at more likely, and it is scaled by how good the whole trajectory was. For a language model it is the gradient of the log-likelihood of the sampled response, the same quantity SFT uses, weighted by the reward. SFT is the special case where every demonstration has weight one.

REINFORCE

REINFORCE (Williams, 1992) estimates the expectation by Monte Carlo: sample M trajectories with the current policy, average, and step:

g^=1M∑m=1M∑tR(τ(m))∇θlogπθ(at(m)∣st(m)),θ←θ+αg^.

Reward-to-go

There is an obvious improvement. Every action in a trajectory gets the same weight R(τ), but they should not. If the return was high because of a good choice at step 2, later, unremarkable choices should not be credited for it, and an action certainly cannot affect rewards that arrived before it. So replace the full return by the return from step t onwards. With R(τ)=∑kγkrk+1, dropping the rewards that precede at leaves ∑k≥tγkrk+1=γtGt:

∇θJ(θ)=𝔼τ~πθ[∑tγtGt∇θlogπθ(at∣st)].

This is exact, not an approximation: the dropped terms have expectation zero. In practice the factor γt is usually omitted, and with γ=1, as is common for language models, it is 1 anyway, giving the familiar ∑tGt∇θlogπθ(at∣st).

Proof that past rewards drop out

Take any reward rk+1 received before action at (so k<t), and let Ht=(s0,a0,r1,…,st) be the history up to st, which includes rk+1. Given Ht, the action is drawn as at~πθ(·∣st). By the tower property,

𝔼[rk+1∇θlogπθ(at∣st)]&=𝔼[𝔼[rk+1∇θlogπθ(at∣st)|Ht]]=𝔼[rk+1𝔼[∇θlogπθ(at∣st)|Ht]]&=𝔼[rk+1∑aπθ(a∣st)∇θlogπθ(a∣st)]=𝔼[rk+1∇θ∑aπθ(a∣st)]=𝔼[rk+1∇θ1]=0.

The key fact, 𝔼a~πθ[∇θlogπθ(a∣s)]=0, is the expected score identity; it returns in §14.

Algorithm 1 · REINFORCE (with an optional baseline)

Input: policy πθ, step size α, batch size M, baseline b(s) (zero for plain REINFORCE; see §14).

  1. Run πθ to sample M trajectories τ(1),…,τ(M).
  2. For every step t of every trajectory, compute the reward-to-go Gt.
  3. Estimate the gradient: g^=1M∑m,t(Gt−b(st))∇θlogπθ(at∣st).
  4. Update θ←θ+αg^, discard the trajectories, and repeat from step 1.

REINFORCE samples trajectories and averages ∑tGt∇θlogπθ(at∣st). But Gt is a single, noisy sample of the future. To ask how good a state or an action is on average, we need the conditional expectation of Gt, which is what value functions are.

12Values and Bellman equations

The state-value function is the expected return from state s when following π, and the action-value function (Q-function) is the expected return after taking action a in state s and following π afterwards:

Vπ(s)=𝔼π[Gt∣St=s],Qπ(s,a)=𝔼π[Gt∣St=s,At=a].

They are related directly. In state s the next action is drawn from π, so averaging over it gives

Vπ(s)=∑aπ(a∣s)Qπ(s,a).

In the running example, with the SFT policy and the reward model, V(x) for the prompt is the SFT-weighted average reward, 0.60; it reappears in §16.

Bellman expectation equations

Using Gt=Rt+1+γGt+1 and the Markov property, the value after one step is the immediate reward plus the discounted value of wherever we land. With p(s′,r∣s,a) the probability of next state s′ and reward r:

Qπ(s,a)=∑s′,rp(s′,r∣s,a)[r+γVπ(s′)],Vπ(s)=∑aπ(a∣s)∑s′,rp(s′,r∣s,a)[r+γVπ(s′)].

Substituting the first relation into itself gives the same recursion purely in terms of Q:

Qπ(s,a)=∑s′,rp(s′,r∣s,a)[r+γ∑a′π(a′∣s′)Qπ(s′,a′)].

These are the Bellman equations: a value is defined in terms of the values one step later. They are linear in Vπ, so for a known, finite MDP they can be solved exactly.

Optimality

We want the best policy. Define the optimal value functions and an optimal policy that is greedy with respect to Q⋆:

V⋆(s)=maxπVπ(s),Q⋆(s,a)=maxπQπ(s,a),π⋆(s)∈argmaxaQ⋆(s,a).

Acting optimally at every step, the average over the next action becomes a maximum, giving the Bellman optimality equations:

V⋆(s)=maxa∑s′,rp(s′,r∣s,a)[r+γV⋆(s′)],Q⋆(s,a)=∑s′,rp(s′,r∣s,a)[r+γmaxa′Q⋆(s′,a′)].

Value iteration and policy iteration

Read the right-hand side of the first equation as an operator 𝒯 acting on value functions. For γ<1 it is a contraction in the maximum norm, ‖𝒯V−𝒯U‖∞≤γ‖V−U‖∞, so by the Banach fixed-point theorem repeatedly applying it, Vk+1=𝒯Vk, converges to its unique fixed point V⋆ from any start. This is value iteration.

Policy iteration alternates two steps. Evaluation computes Vπ for the current policy by solving the Bellman expectation equation. Improvement makes the policy greedy: π′(s)∈argmaxaQπ(s,a). The new policy is never worse, and strictly better wherever improvement is possible. The reason is short: Vπ(s) is a weighted average of the Qπ(s,a), so the maximum is at least the average, Qπ(s,π′(s))=maxaQπ(s,a)≥Vπ(s) for every state.

Proof that the greedy policy is at least as good (policy improvement)

Starting from Vπ(s)≤Qπ(s,π′(s)), expand Qπ one step and apply the same inequality at the next state, repeatedly:

Vπ(s)&≤Qπ(s,π′(s))=𝔼[Rt+1+γVπ(St+1)|St=s,At=π′(s)]&≤𝔼π′[Rt+1+γQπ(St+1,π′(St+1))|St=s]&=𝔼π′[Rt+1+γRt+2+γ2Vπ(St+2)|St=s]≤⋯≤𝔼π′[Gt∣St=s]=Vπ′(s).

If no state admits an improvement, maxaQπ(s,a)=Vπ(s) everywhere, so Vπ satisfies the Bellman optimality equation and π is already optimal.

Both methods need the transition model p(s′,r∣s,a) to compute the expectations. Usually we do not have it; we can only act and observe. That is model-free reinforcement learning.

13Monte Carlo and TD learning

Monte Carlo

The most direct idea returns to the definition Vπ(s)=𝔼π[Gt∣St=s] and estimates the expectation by sampling: run the policy from s many times, record the returns and average them. Incrementally, after each episode, move the estimate towards the observed return:

Vπ(s)≈1N∑i=1NGt(i),V(St)←V(St)+α[Gt−V(St)].

Qπ(s,a) can be estimated the same way from the returns that follow each visit to (s,a), and the policy improved greedily as before, so evaluation and improvement work without a model. But Monte Carlo has to wait until an episode ends before it can update, and a whole trajectory’s worth of randomness makes Gt high-variance, increasingly so for long episodes.

Temporal-difference learning

The Bellman equation says we need not wait:

Vπ(s)=𝔼π[Rt+1+γVπ(St+1)∣St=s].

After one step we observe r and s′, and r+γV(s′) is already a new estimate of V(s). Temporal-difference (TD) learning (Sutton, 1988) moves the old estimate towards it:

V(St)←V(St)+α[Rt+1+γV(St+1)−V(St)],δt=Rt+1+γV(St+1)−V(St).

δt is the TD error: the difference between the prediction made before seeing the step and the better-informed prediction made after it. TD learning nudges the old prediction towards the new one. Using an estimate to update an estimate is called bootstrapping.

Monte Carlo target: Gt

The actual return. Unbiased, but high variance, and available only when the episode ends.

TD target: Rt+1+γV(St+1)

One real reward plus the current estimate. Available after every step, usually lower variance, but biased while V is wrong.

0ABCDE+10.00.51.0ABCDEEstimated value V(s)Monte CarloTD(0)true value0.00.10.20.30255075100episodesRMS error against the true values
0ABCDE+10.00.51.0ABCDEEstimated value V(s)Monte CarloTD(0)true value0.00.10.20.30255075100episodesRMS error against the true values
Figure 5. Monte Carlo and TD on a five-state random walk. Each episode starts in C and steps left or right at random; ending on the right pays +1, so the true values are 1/6,…,5/6 (the classic example from Sutton and Barto (2018)). Both methods see the same episodes and start from 0.5. Run one episode to watch TD update after every step and Monte Carlo only at the end, or run many and compare the errors; change the step size α. One deterministic sequence of simulated episodes.

SARSA and Q-learning

The same idea applies to Q-functions. For a fixed policy the action-value Bellman equation is Qπ(s,a)=𝔼[r+γQπ(s′,a′)] with a′~π(·∣s′). Interact once, observe (St,At,Rt+1,St+1,At+1), where At+1 is the action the policy actually takes next, and update

Q(St,At)←Q(St,At)+α[Rt+1+γQ(St+1,At+1)−Q(St,At)].

This is SARSA (Rummery and Niranjan, 1994), named after the quintuple it uses. The policy that collects the data is the policy being evaluated and improved, so SARSA is on-policy.

To learn the optimal values directly, apply the same sampling to the Bellman optimality equation Q⋆(s,a)=𝔼[r+γmaxa′Q⋆(s′,a′)]:

Q(St,At)←Q(St,At)+α[Rt+1+γmaxa′Q(St+1,a′)−Q(St,At)].

This is Q-learning (Watkins and Dayan, 1992): a sample-based, model-free version of value iteration on Q. The target uses the greedy action maxa′ regardless of what the behaviour policy will actually do next, so the policy being learned (greedy) differs from the one collecting data (often exploratory): Q-learning is off-policy.

The whole of this section answers one question: how to estimate the long-run value of a state or action, and use it to improve the policy. Sampling whole trajectories gives Monte Carlo; sampling one step and bootstrapping gives TD; TD on a fixed policy’s Q-function gives SARSA; TD on the optimality equation gives Q-learning.

14Baselines and advantages

Back to policy gradients. Gt measures an absolute level of return, which mixes three things: how good the state was, how good the action was, and luck. That makes the gradient estimate noisy, and it cannot tell whether a high return was earned by the action or inherited from a good state.

The first fix is to replace the sample Gt by its expectation Qπ(st,at). Because ∇θlogπθ(at∣st) depends only on (st,at) and 𝔼[Gt∣st,at]=Qπ(st,at), the tower property leaves the gradient unchanged while removing the sampling noise in the future:

∇θJ(θ)=𝔼πθ[∑tQπθ(st,at)∇θlogπθ(at∣st)].

This is the form of the policy gradient theorem (Sutton et al., 2000), which also holds when the policy is a general function approximator. It still does not separate state from action. So subtract a baseline b(st) that measures how good the state is, and weight by the relative return:

∇θJ(θ)=𝔼πθ[∑t(Qπθ(st,at)−b(st))∇θlogπθ(at∣st)].

For this to be the same gradient, the baseline term must have expectation zero. It does, for any baseline that depends on the state but not on the action:

𝔼a~πθ(·∣s)[b(s)∇θlogπθ(a∣s)]=b(s)∑aπθ(a∣s)∇θlogπθ(a∣s)=b(s)∑a∇θπθ(a∣s)=b(s)∇θ∑aπθ(a∣s)=b(s)∇θ1=0.
The same argument summed over a whole trajectory
𝔼τ~πθ[∑tb(st)∇θlogπθ(at∣st)]&=∑t𝔼st[𝔼at~πθ(·∣st)[b(st)∇θlogπθ(at∣st)|st]]&=∑t𝔼st[b(st)∑a∇θπθ(a∣st)]=∑t𝔼st[b(st)∇θ∑aπθ(a∣st)]=0.

If the baseline depended on the action at, it could not be taken outside the inner expectation and the gradient would in general be biased.

The natural choice is the state value, b(s)=Vπ(s), the expected return of the state. The weight becomes the advantage,

Aπ(s,a)=Qπ(s,a)−Vπ(s),∇θJ(θ)=𝔼πθ[∑tAπθ(st,at)∇θlogπθ(at∣st)],

which says how much better action a is than the policy’s average in that state; it averages to zero over actions. The expected gradient is the same, but the state’s own quality has been removed and the weights are centred near zero, which reduces variance. (Vπ is not exactly the variance-minimising baseline in general, but it is simple and works well.) It is the RL counterpart of the translation invariance in §9: subtracting anything that depends only on the state changes nothing in expectation, but it changes the noise a great deal.

Without a baseline0⅓10100200300update stepWith a baseline0⅓10100200300update step
Without a baseline0⅓10100200300update stepWith a baseline0⅓10100200300update step
Figure 6. A baseline keeps the gradient and removes the noise. REINFORCE with a softmax policy on a three-armed bandit with noisy rewards (means 1.0, 1.5 and 2.0, unit-variance noise, plus a constant offset). Each thin line is one of twelve seeded runs, showing the probability of choosing the best arm; the thick line is their mean. The baseline is the running mean of past rewards. Change the constant added to every reward: it does not change which arm is best, but without a baseline it makes every sampled arm look good and the runs scatter; with a baseline nothing changes. Illustrative simulation; same seeds for both panels.

In practice Qπ and Vπ are unknown, so the formula is not yet an algorithm. How do we estimate the advantage?

15Actor–critic and GAE

If we do not know the advantage, we can learn it. The policy πθ is the actor: it acts. A learned value function is the critic: it evaluates, and its evaluation guides the actor’s updates. This is the actor–critic family; with the advantage as the weight it is often called advantage actor–critic, or A2C, the synchronous variant of A3C (Mnih et al., 2016).

Learning both Q and V to subtract them would be cumbersome. The TD error avoids it. If V is the true value function of the policy, the expected TD error is the advantage:

𝔼[δt∣st,at]=𝔼[rt+1+γVπ(st+1)∣st,at]−Vπ(st)=Qπ(st,at)−Vπ(st)=Aπ(st,at).

So one learned critic Vw≈Vπ is enough: δt computed with Vw is a one-step advantage estimate. The critic itself is trained by regression towards its targets, as in TD learning.

One step is short-sighted, though. It uses one real reward and then trusts V(st+1) for the entire future; while the critic is inaccurate, its error goes straight into the advantage. The fix is to use more real rewards before handing over to the critic. The k-step advantage uses k rewards and then bootstraps, and it telescopes into a sum of TD errors:

A^t(k)=rt+1+γrt+2+⋯+γk−1rt+k+γkV(st+k)−V(st)=∑l=0k−1γlδt+l.

With k=1 this is the one-step TD error of actor–critic; as k runs to the end of the episode it becomes the Monte Carlo return minus the baseline. Generalized advantage estimation (GAE) (Schulman et al., 2016) does not choose: it takes an exponentially weighted average of all of them,

A^tGAE(γ,λ)=(1−λ)(A^t(1)+λA^t(2)+λ2A^t(3)+⋯)=∑l=0∞(γλ)lδt+l,0≤λ≤1.
From the weighted average to the sum of TD errors, and the two limits

Substitute A^t(k)=∑l<kγlδt+l and swap the order of summation; the TD error δt+l appears in every A^t(k) with k>l:

(1−λ)∑k=1∞λk−1∑l=0k−1γlδt+l=∑l=0∞γlδt+l(1−λ)∑k=l+1∞λk−1=∑l=0∞γlδt+lλl.

With λ=0 only l=0 survives: A^t=δt, the one-step actor–critic estimate. With λ=1 the value terms telescope into the Monte Carlo return minus the baseline:

∑lγlδt+l=∑lγlrt+l+1−V(st)=Gt−V(st).
0.00.51.00510152025l, steps aheadWeight (γλ)l on the TD error δt+l01151015202530k, look-ahead of the k-step estimateWeight (1−λ)λk−1 on the k-step advantage
0.00.51.0051015l, steps aheadWeight (γλ)l on the TD error δt+l01151015k, look-ahead of the k-step estimateWeight (1−λ)λk−1 on the k-step advantage
Figure 7. GAE interpolates between TD and Monte Carlo. Top: the weight (γλ)l on each future TD error. Bottom: the equivalent weights (1−λ)λk−1 on the k-step advantage estimates. Move λ from 0 (one-step TD: low variance, biased by the critic) to 1 (Monte Carlo: unbiased, high variance).

In code GAE is a single backward pass, A^t=δt+γλA^t+1, and the critic is regressed onto A^t+V(st). By discounting distant TD errors GAE offers a continuous bias–variance trade-off between one-step actor–critic and Monte Carlo; it does not remove the trade-off. Intermediate values are typical; §23 lists the values reported in the papers.

Through all of this the skeleton of the policy gradient never changed: ∇θJ=𝔼[∑tΨt∇θlogπθ(at∣st)]. Only the weight Ψt evolved: R(τ), then Gt, then Q, then Q−V, then the TD error, then GAE. Each step keeps the gradient (nearly) the same while making the estimate less noisy and easier to compute online.

Part 4 in one sentence

Policy gradients push up the log-probability of actions in proportion to how much better than expected they turned out, and value functions, TD errors and GAE are ways of estimating “better than expected” with less noise.

Check yourself Why does subtracting a baseline b(s) leave the policy gradient unbiased, and why would a baseline b(s,a) be a problem?

Because the expected score is zero, 𝔼a~πθ[∇θlogπθ(a∣s)]=0 (the probabilities always sum to 1), so any factor that does not depend on the action can be pulled out and multiplies zero. A baseline that depends on a cannot be pulled out, so the extra term no longer vanishes and the gradient is biased in general.

Part 5 about 11 minRLHF in practice

16From TRPO to PPO

A vanilla policy-gradient step has two practical problems. First, the gradient is only valid at the current policy: the data were sampled from πθ, so once θ moves the samples no longer describe the new policy, and each batch can safely be used for only one small step. Second, the step size is hard to choose: a small change in parameters can be a large change in behaviour, and one bad step can collapse a policy that then generates only bad data from which it cannot recover.

A surrogate objective with importance weights

The performance difference lemma (Kakade and Langford, 2002) says exactly how much a new policy π′ improves on π: by the advantage of π accumulated along trajectories of π′,

J(π′)−J(π)=𝔼τ~π′[∑tγtAπ(st,at)].

The states visited by π′ are unknown before we move.

If the new policy stays close to the old one, we can use the states visited by the old policy and correct the action distribution with an importance ratio. This gives the surrogate objective

Lθold(θ)=𝔼s,a~πθold[πθ(a∣s)πθold(a∣s)Aπθold(s,a)],

which can be estimated from old samples, and whose gradient at θ=θold equals the policy gradient. It is only trustworthy near θold.

TRPO: a trust region

Trust region policy optimization (Schulman et al., 2015) makes “near” precise. Its theory bounds the true improvement from below by the surrogate minus a penalty on the KL divergence between old and new policies; the practical algorithm maximises the surrogate subject to a limit on the average KL:

maxθLθold(θ)subject to𝔼s~πθold[KL(πθold(·∣s)‖πθ(·∣s))]≤δ.

The constraint is measured in the space of behaviours, not parameters, which is what makes it robust. TRPO solves it with a second-order approximation, conjugate gradients and a line search. It works, but it is complicated and awkward to combine with large shared networks.

PPO: clip the ratio

Proximal policy optimization (Schulman et al., 2017) keeps the idea and drops the machinery. With the per-sample ratio

ρt(θ)=πθ(at∣st)πθold(at∣st),LCLIP(θ)=𝔼^t[min(ρt(θ)A^t,clip(ρt(θ),1−ϵ,1+ϵ)A^t)].

Read it case by case. If an action was good (A^t>0), the objective rewards raising its probability, but only until the ratio reaches 1+ϵ; beyond that the clipped term is flat and the sample contributes no gradient. If it was bad (A^t<0), lowering its probability helps only until 1−ϵ. The minimum makes the objective a pessimistic bound: clipping can remove an incentive to move further, but never hides a penalty. If the ratio has already moved the wrong way, for instance a bad action became more likely, the unclipped term still applies in full.

Advantage A > 0 (a good action)01200.511.52ρ = πθ(a|s) / πold(a|s)1−ε1+εclipped: no gradientAdvantage A < 0 (a bad action)-2-1000.511.52ρ = πθ(a|s) / πold(a|s)1−ε1+εgradient pushes ρ downunclipped ρAPPO: min(ρA, clip(ρ, 1−ε, 1+ε)A)
Advantage A > 0 (a good action)01200.511.52ρ = πθ(a|s) / πold(a|s)1−ε1+εclipped: no gradientAdvantage A < 0 (a bad action)-2-1000.511.52ρ = πθ(a|s) / πold(a|s)1−ε1+εgradient pushes ρ downunclipped ρAPPO: min(ρA, clip(ρ, 1−ε, 1+ε)A)
Figure 8. PPO’s clipped objective for one sample. Dashed: the unclipped surrogate ρA. Solid: PPO’s objective. The shaded band is [1−ϵ,1+ϵ]. Where the solid line is flat, the sample gives no gradient. Move the ratio and the clip range; an open marker means the sample is clipped.

Because the clip limits how far one batch can move the policy, PPO can safely run several epochs of minibatch gradient steps on each batch of samples, which is much more sample-efficient than vanilla policy gradients. With a shared actor–critic network the full objective adds a value-function loss and, optionally, an entropy bonus ℋ that encourages exploration:

L(θ)=𝔼^t[LtCLIP(θ)−c1(Vθ(st)−R^t)2+c2ℋ[πθ(·∣st)]].

The PPO paper also describes a variant that replaces clipping with a KL penalty whose weight adapts to hit a target KL; the clipped version performed better in its experiments.

The KL penalty to a reference model

For language models there is a second, different KL. PPO’s clip keeps each update close to the previous policy. RLHF also keeps the whole optimisation close to a fixed reference model πref, usually the SFT model (Ziegler et al., 2019; Stiennon et al., 2020; Ouyang et al., 2022):

maxπθ𝔼x~𝒟,y~πθ(·∣x)[rϕ(x,y)]−β𝔼x~𝒟[KL(πθ(·∣x)‖πref(·∣x))].

This is the guard against reward hacking promised in §9: the reward model was trained on outputs of models like πref, so it is only reliable near them, and the penalty also keeps the text fluent and diverse. In implementations the penalty is usually folded into a per-token reward, with the reward model’s score added at the last token:

rt=−βlogπθ(yt∣x,y<t)πref(yt∣x,y<t)+1[t=T]rϕ(x,y).

Summed over a sampled response, the log-ratios are a single-sample unbiased estimate of the sequence-level KL, since

𝔼y~πθ[logπθ(y∣x)−logπref(y∣x)]=KL(πθ(·∣x)‖πref(·∣x)).

Then PPO runs as usual: a value head estimates V(st) at each token, GAE turns the per-token rewards into advantages, and the clipped objective updates the policy.

Algorithm 2 · PPO for RLHF

Input: SFT model πSFT, reward model rϕ, prompts 𝒟; settings β,ϵ,γ,λ, epochs K.

  1. Initialise the policy πθ←πSFT, the frozen reference πref←πSFT, and a critic Vw.
  2. Sample prompts x~𝒟 and responses y~πθold(·∣x), where θold is a copy of the current θ.
  3. Score each response with rϕ(x,y) and form per-token rewards rt, including the KL penalty to πref.
  4. Compute Vw(st), the TD errors δt, GAE advantages A^t and value targets R^t=A^t+Vw(st).
  5. For K epochs over minibatches: ascend LCLIP for θ and descend (Vw(st)−R^t)2 for w.
  6. Repeat from step 2.

Back to our example: one PPO step

Start RLHF from the SFT model. At that moment πθ=πref, so every KL term is exactly zero, and with a perfect critic the value of the prompt is the SFT-weighted average reward, V(x)=0.60. Each reply’s advantage is its reward minus that average:

ReplyReward model rAdvantage A = r − V(x)
y1 Quiz: Germany?−1.5−2.10
y2 Rambles−0.4−1.00
y3 Paris.0.5−0.10
y4 Full sentence1.6+1.00
y5 Lyon.−1.0−1.60
y6 Flattering2.2+1.60

Note y3, “Paris.”: correct, but its advantage is −0.10, because the average reply already scores higher. PPO lowers its probability slightly and raises y4 (the full sentence) and y6 (the flattering reply). That is the reward model’s preference, flaw included; the KL penalty is what stops y6 from taking over (Figure 9 shows how far it goes for each β).

17The InstructGPT pipeline

Preference-based RL for language models predates InstructGPT: it had been applied to stylistic continuation and summarisation (Ziegler et al., 2019; Stiennon et al., 2020), building on deep RL from human preferences (Christiano et al., 2017). InstructGPT (Ouyang et al., 2022) assembled the pieces into the pipeline that became the template for chat assistants; Anthropic trained helpful and harmless assistants with a similar pipeline in the same year (Bai et al., 2022a).

RLHF as in InstructGPT

  1. Supervised fine-tuning. Collect labeller-written demonstrations for prompts, many of them submitted by API users, and fine-tune GPT-3 on them (§4–5).
  2. Reward model. Sample several outputs per prompt from the models, have labellers rank them, and train a reward model on all pairs from each ranking with the Bradley–Terry loss (§9).
  3. Reinforcement learning. Optimise the SFT model against the reward model with PPO, with a per-token KL penalty to the SFT model (§16). Steps 2 and 3 can be repeated with new comparisons collected on the current policy.

The final objective adds one more term. RLHF caused regressions on some public NLP benchmarks, an “alignment tax”, so the authors mixed in the pre-training objective, a variant they call PPO-ptx (they write the coefficient as γ; it is unrelated to the discount factor):

objective(θ)=𝔼x~𝒟,y~πθ(·∣x)[rϕ(x,y)−βlogπθ(y∣x)πSFT(y∣x)]+γptx𝔼x~𝒟pretrain[logπθ(x)].

The headline result: labellers preferred outputs of the 1.3-billion-parameter InstructGPT model to those of the 175-billion-parameter GPT-3, despite the hundredfold difference in size. Post-training, not scale alone, decided how useful the model was.

Count the networks involved in step 3: the policy being trained, the frozen reference model for the KL penalty, the reward model, and the value network for the critic. Four large models, an online sampling loop and many hyperparameters make PPO-based RLHF expensive and delicate. Much of what followed is about removing pieces of it.

18The limits of RLHF

RLHF works, but each stage carries its own failure modes; Casper et al. (2023) survey them in detail.

  • The feedback. Labellers disagree, make mistakes, and have their own preferences and blind spots. A single scalar reward cannot represent a population with genuinely different preferences. Good feedback on hard tasks needs expertise and is slow and costly.
  • The reward model. It is an imperfect proxy trained on limited data. Optimised hard, the policy finds its errors: over-optimisation lowers true quality even as the proxy score rises (Gao et al., 2023).
  • Learned shortcuts. Some flaws are systematic. Longer answers tend to be preferred, and much of the measured reward improvement in RLHF can be traced to increased length (Singhal et al., 2023). Assistants trained with human feedback tend towards sycophancy, telling users what they appear to want to hear, and human preference judgements sometimes favour convincing sycophantic answers over correct ones (Sharma et al., 2024). The flattering y6 in our running example is a cartoon of both.
  • Cost and stability. Four models in memory, online generation inside the training loop, and sensitivity to hyperparameters such as β, ϵ and the learning rates.

Two directions followed. One replaces human labellers with AI feedback guided by written principles, as in Constitutional AI (Bai et al., 2022b), to scale supervision. The other simplifies the optimisation itself, which is where we go next.

Part 5 in one sentence

PPO stabilises policy-gradient updates with a clipped importance ratio, and RLHF adds a KL penalty to a reference model so that optimising a learned reward does not run away from where that reward can be trusted.

Check yourself For a sample with A^>0 whose ratio has reached 1.5 with ϵ=0.2, what gradient does PPO’s clipped term give? And for A^<0 at the same ratio?

With A^>0 the ratio is above 1+ϵ, the clipped term is the minimum and it is flat, so the sample contributes no gradient. With A^<0 the unclipped term ρA^ is the smaller one, so the full penalty applies and the gradient pushes the probability back down.

Part 6 about 13 minBeyond PPO

19Direct preference optimisation

The KL-regularised objective of §16 has a remarkable property: for a fixed reward, its optimal policy can be written in closed form. Direct preference optimisation (DPO) (Rafailov et al., 2023) uses that to skip both the reward model and the RL loop.

The optimal policy, in closed form

Fix a prompt x and consider any distribution π over responses. Collect the reward and the KL term into one logarithm:

𝔼y~π[r(x,y)]−βKL(π‖πref)&=−β𝔼y~π[logπ(y∣x)πref(y∣x)exp(r(x,y)/β)]&=−β𝔼y~π[logπ(y∣x)π⋆(y∣x)]+βlogZ(x)=−βKL(π‖π⋆)+βlogZ(x),

where we have defined the normalised distribution below. Z(x) does not depend on π, and a KL divergence is non-negative and zero only when the two distributions are equal. So the objective is maximised exactly at π=π⋆:

π⋆(y∣x)=1Z(x)πref(y∣x)exp(r(x,y)β),Z(x)=∑yπref(y∣x)exp(r(x,y)β).

The optimal policy is the reference model reweighted by the exponentiated reward. β sets the temperature: large β stays near πref, small β concentrates on the highest-reward responses. The “After RLHF” column of the running example is exactly this π⋆ with β=1.

Reference πref (outline) and optimal policy π* (bars)y1 Quiz: Germany?r = -1.50%y2 Ramblesr = -0.43%y3 Paris.r = 0.525%y4 Full sentencer = 1.661%y5 Lyon.r = -1.01%y6 Flatteringr = 2.210%0.51.01.52.00123KL(π* ‖ πref)Expected reward-4-202True reward (outline), implicit reward (bars)y1y2y3y4y5y6
Reference πref (outline) and optimal policy π* (bars)y1 Quiz: Germany?r = -1.50%y2 Ramblesr = -0.43%y3 Paris.r = 0.525%y4 Full sentencer = 1.661%y5 Lyon.r = -1.01%y6 Flatteringr = 2.210%0.51.01.52.00123KL(π* ‖ πref)Expected reward-4-202True reward (outline), implicit reward (bars)y1y2y3y4y5y6
Figure 9. The KL-regularised optimum, and the reward hidden inside it. The running example: the SFT model is the reference, and the reward model over-rates the flattering y6. Left: π⋆ for the current β. Right, top: expected reward against KL from the reference as β varies. Right, bottom: the implicit reward βlog(π⋆/πref) equals the true reward shifted by one constant. Lower β and watch the policy trade KL for reward, and eventually collapse onto the flattering reply. Illustrative toy distribution.

Your language model is secretly a reward model

Now invert the relation. Taking logarithms and rearranging expresses the reward through the optimal policy:

r(x,y)=βlogπ⋆(y∣x)πref(y∣x)+βlogZ(x).

Z(x) is a sum over all possible responses and is intractable. But it depends only on the prompt, and §9 showed that a prompt-dependent shift of the reward is invisible to the Bradley–Terry model, so it cancels from every preference probability.

Substituting into σ(r(x,yw)−r(x,yl)):

P(yw≻yl∣x)=σ(βlogπ⋆(yw∣x)πref(yw∣x)−βlogπ⋆(yl∣x)πref(yl∣x)).

The preference probability is now a function of the policy alone. So parameterise πθ directly and fit it to the preference data by maximum likelihood, exactly as we fitted the reward model:

ℒDPO(θ)=−𝔼(x,yw,yl)~𝒟[logσ(βlogπθ(yw∣x)πref(yw∣x)−βlogπθ(yl∣x)πref(yl∣x))].

Define the implicit reward

r^θ(x,y)=βlogπθ(y∣x)πref(y∣x).

Then the gradient is

∇θℒDPO=−β𝔼[σ(r^θ(x,yl)−r^θ(x,yw))(∇θlogπθ(yw∣x)−∇θlogπθ(yl∣x))]:

raise the log-probability of the preferred response, lower that of the rejected one, and weight each pair by how badly the implicit reward currently orders it. Training needs only the policy and a frozen reference model, log-probabilities of fixed responses, and no sampling during training. It is about as simple as SFT.

Algorithm 3 · DPO

Input: SFT model πSFT, preference data 𝒟={(x,yw,yl)}, β, step size α.

  1. Initialise πθ←πSFT and the frozen reference πref←πSFT. Optionally precompute logπref(yw∣x) and logπref(yl∣x) once.
  2. For each minibatch of triples: compute r^θ(x,yw) and r^θ(x,yl) from summed token log-probabilities.
  3. Take a gradient step on −logσ(r^θ(x,yw)−r^θ(x,yl)), averaged over the minibatch.
  4. Repeat over the fixed dataset for a few epochs; no responses are generated.

Back to our example: one DPO pair

Take the labeller’s pair from §8, y4 preferred to y3. At the start πθ=πref, both implicit rewards are zero, and the loss is log2≈0.693; the first gradient step raises logπθ(y4∣x), lowers logπθ(y3∣x), and leaves the other replies to move only through shared parameters. If training reached the KL-optimal policy π⋆ for a reward model that matches these preferences, the implicit-reward margin would equal the reward gap, 1.1, and the loss for this pair would be 0.287.

One difference from PPO shows up immediately. DPO learns only from the pairs in its dataset. If no labeller ever compared the flattering y6 with anything, DPO is neither pushed towards it, as PPO against the flawed reward model was, nor taught to avoid it.

What DPO gives up, and its relatives

DPO is usually run offline, on a fixed preference dataset collected from other models. RLHF with PPO is online: it keeps sampling from the current policy and scoring the samples, so it gets feedback on the model’s own outputs as they change, the same advantage that motivated preferences in §8. Online and iterative variants of DPO collect new preferences on the current policy to recover some of that. Other offline objectives change different parts of the derivation:

  • IPO (Azar et al., 2024) argues that when preferences are close to deterministic, the Bradley–Terry likelihood pushes the implicit reward gap towards infinity and ignores the KL regularisation; it replaces the log-sigmoid with a squared loss towards a finite target gap.
  • KTO (Ethayarajh et al., 2024) learns from unpaired examples labelled only as desirable or undesirable, using a loss inspired by prospect theory.
  • SimPO (Meng et al., 2024) drops the reference model, uses the length-normalised average log-probability as the implicit reward, and adds a target margin.

20Verifiable rewards and GRPO

Learned reward models are the weak point of RLHF: they are approximate, they can be hacked, and they need preference data. For some tasks they are unnecessary. A mathematics problem with a known answer, code with unit tests, or an instruction with a checkable constraint can be scored by a program. Training against such checks is called reinforcement learning with verifiable rewards (RLVR), a name introduced with the Tülu 3 models (Lambert et al., 2024). A rule-based reward is hard to hack in the way a neural reward model is, although a checker that only inspects the final answer says nothing about whether the reasoning was sound.

Reasoning was already known to benefit from intermediate steps: prompting models to write a chain of thought improves multi-step reasoning in large models (Wei et al., 2022b), and STaR bootstrapped reasoning by fine-tuning on self-generated rationales that reached correct answers (Zelikman et al., 2022). Rewarding the steps themselves, with process supervision, outperformed rewarding only final answers when training reward models for mathematics (Lightman et al., 2023), but step-level labels are expensive. Outcome rewards from a verifier are cheap and scale.

GRPO: a group instead of a critic

Group relative policy optimization (GRPO) was introduced with DeepSeekMath (Shao et al., 2024). It keeps PPO’s clipped objective but removes the value network. For each prompt q it samples a group of G outputs o1,…,oG from the old policy, scores them, and uses the group itself as the baseline. With one reward per output (outcome supervision), every token of output i gets the normalised advantage

A^i,t=ri−mean(r1,…,rG)std(r1,…,rG).

This is the baseline idea of §14 in its simplest form: the mean reward of several attempts at the same prompt estimates how good the prompt state is, so the advantage says how much better this attempt was than its siblings. No critic needs training, which saves a model the size of the policy and avoids the difficulty of learning token-level values from a reward that arrives only at the end. The objective is PPO’s, averaged over the group and over tokens, with the KL to the reference model added to the loss rather than folded into the reward:

𝒥GRPO(θ)=𝔼[1G∑i=1G1|oi|∑t=1|oi|\{min(ρi,tA^i,t,clip(ρi,t,1−ϵ,1+ϵ)A^i,t)−β𝔻KL[πθ‖πref]\}],

with the per-token ratio

ρi,t=πθ(oi,t∣q,oi,<t)πθold(oi,t∣q,oi,<t),

and the KL estimated per token as

𝔻KL[πθ‖πref]=πref(oi,t∣q,oi,<t)πθ(oi,t∣q,oi,<t)−logπref(oi,t∣q,oi,<t)πθ(oi,t∣q,oi,<t)−1,

which is never negative (because u−logu−1≥0) and, since the ratio πref/πθ has expectation 1 under πθ, an unbiased estimate of the KL.

Algorithm 4 · GRPO

Input: initial policy (an SFT or base model), prompts, a reward function (a verifier or a reward model), group size G, ϵ, β, inner iterations μ.

  1. Initialise πθ and the frozen reference πref from the initial policy.
  2. Sample a batch of prompts q; for each, sample G outputs o1,…,oG~πθold(·∣q).
  3. Score each output, ri, and give every token of oi the advantage A^i,t=(ri−mean(r))/std(r).
  4. For μ iterations: ascend 𝒥GRPO (clipped ratio, KL penalty per token).
  5. Set θold←θ and repeat from step 2. No critic is trained.
Prompt: What is the capital of France? Verifier: reward 1 if the reply names Paris, else 0.replyrewardadvantage✗ y10−0.38✗ y20−0.38✓ y61+2.65✗ y10−0.38✗ y20−0.38✗ y10−0.38✗ y20−0.38✗ y20−0.38
Prompt: What is the capital of France?Verifier: reward 1 if the reply names Paris, else 0.replyradvantage✗ y1 Quiz: Germany?0−0.38✗ y2 Rambles0−0.38✓ y6 Flattering1+2.65✗ y1 Quiz: Germany?0−0.38✗ y2 Rambles0−0.38✗ y1 Quiz: Germany?0−0.38✗ y2 Rambles0−0.38✗ y2 Rambles0−0.38
Figure 10. Group-relative advantages on the running example. A group of replies sampled from the base model, the SFT model or the RLHF policy of §19, scored 1 or 0 by a verifier that only checks for Paris. Each reply’s advantage is its reward minus the group mean, divided by the group’s standard deviation, and every token of the reply shares it. Sample new groups and change the policy and group size: from the base model, rare correct replies earn large advantages; from a strong policy, groups where every reply is correct give no signal at all. Illustrative, seeded samples.

Figure 10 shows two properties of binary rewards. If a fraction p^ of the group is correct, correct answers get advantage (1−p^)/p^ and wrong ones −p^/(1−p^): a rare success is strongly reinforced. And a group in which every answer is right, or every answer is wrong, carries no signal at all, so prompts that are far too easy or far too hard are wasted. It also shows what a verifier does not see: y3, y4 and the flattering y6 all score 1, so style and tone must come from elsewhere, such as the SFT data or a separate reward. Follow-up work tuned these details: DAPO filters out uninformative groups, decouples the lower and upper clip ranges and averages the loss over tokens rather than per sequence (Yu et al., 2025); Dr. GRPO argues that the per-response length normalisation and the standard-deviation scaling bias training, for example towards longer incorrect answers, and removes them (Liu et al., 2025).

21DeepSeek-R1 and reasoning

In 2024 OpenAI reported that o1’s performance improves both with more reinforcement learning and with more time spent thinking at test time (OpenAI, 2024), without describing the method in detail. DeepSeek-R1 (DeepSeek-AI, 2025) described an openly documented route to similar behaviour, built on GRPO and verifiable rewards.

DeepSeek-R1-Zero: RL only

GRPO applied directly to the pre-trained base model, with no SFT. The rewards are rule-based: accuracy (is the final answer correct, or does the code pass the tests?) and format (is the reasoning placed between thinking tags?). A neural reward model was deliberately avoided because of reward hacking.

Over training the responses grew longer by themselves, and behaviours such as re-checking and re-evaluating earlier steps emerged, including a much-quoted “aha moment”. But the outputs were hard to read and mixed languages.

DeepSeek-R1: a multi-stage pipeline

  1. A cold start: SFT on a small set of long, readable chain-of-thought examples.
  2. Reasoning-oriented RL as in R1-Zero, with an extra reward for language consistency.
  3. Rejection sampling from that model, plus general-purpose data, for a new round of SFT.
  4. A final RL stage covering all kinds of prompts, for helpfulness and harmlessness as well as reasoning.

Two further findings matter for the bigger picture. The paper distilled R1’s reasoning into smaller open models by plain SFT on its outputs, and found distillation more effective than running large-scale RL on the smaller models directly. And it reported unsuccessful attempts with process reward models and Monte Carlo tree search, which did not pay off at scale in its setting.

The structure is worth noticing. SFT still opens the pipeline, now to set a readable format for long reasoning rather than to teach answering; RL with checkable rewards does the heavy lifting; and SFT on the model’s own filtered outputs consolidates the gains. The ideas from Part 1 to Part 5, imitation, comparison, policy gradients, baselines and KL control, are all still there.

Part 6 in one sentence

DPO turns the KL-regularised objective into a supervised loss on preference pairs, and GRPO with verifiable rewards drops the critic and the learned reward, which is what made large-scale RL for reasoning practical.

Check yourself In a GRPO group of eight replies, all eight are correct. What are their advantages, and what did DAPO do about such groups?

All rewards equal the mean and the standard deviation is zero, so every advantage is zero and the group contributes no policy gradient (only the KL term acts). DAPO filters out groups whose replies are all correct or all wrong and samples more prompts until the batch is filled with informative groups.

Part 7 about 9 minIn practice

22Methods side by side

The four families of methods in this guide differ less in their mathematics, which they share, than in what they need and where their learning signal comes from. Model copies are counted at full size; a critic is often smaller or shares the policy’s network, and RLVR describes the reward source, which can be paired with PPO, GRPO or other optimisers.

MethodData neededModels in memorySamplingLearning signalMain failure modes
SFTPrompt–response demonstrations1: the policyOffline: a fixed dataset, teacher forcingLog-likelihood of the demonstrationCopies the data’s flaws; exposure bias; new facts learned slowly and linked to more hallucination
Reward model + PPORanked comparisons (for the reward model) and prompts4: policy, reference, reward model, criticOn-policy: generates in every iterationLearned reward minus a KL penalty, turned into GAE advantagesReward hacking, length bias and sycophancy; KL blow-up; cost and tuning sensitivity
DPOPreference pairs (x,yw,yl)2: policy and reference (reference log-probabilities can be precomputed)Offline: no generation during trainingImplicit-reward margin of each pairLimited to the pairs collected; no feedback on its own outputs; can over-fit near-deterministic preferences
GRPO with RLVRPrompts with a checkable answer, or a reward model2: policy and reference (plus a reward model if one is used)On-policy: G samples per promptReward relative to the group’s mean, no criticGroups with no signal; length bias from normalisation; a verifier that checks only the answer

Two contrasts organise the table. Where the signal comes from: demonstrations (SFT), human comparisons through a learned model (PPO) or directly (DPO), or a program (RLVR). Whose outputs are judged: a fixed dataset (SFT, offline DPO) or the model’s own current samples (PPO, GRPO). The second matters most for the third limit of SFT in §7: only on-policy methods see and correct the mistakes the model itself makes.

23Running it: settings, cost, failures

Settings the papers report

Hyperparameters depend on the model, the data and the code base, so the values below are reference points from the papers that report them, not recommendations.

SettingWhat it controlsReported valueSource
PPO clip ϵHow far one batch may move each action’s probability0.2, the best of the settings comparedSchulman et al. (2017)
GAE λ, discount γBias–variance of the advantage; horizonλ=0.95, γ=0.99 in its benchmark experimentsSchulman et al. (2017)
RLHF KL weight βDistance from the SFT model0.02; pre-training mix coefficient 27.8 for PPO-ptxOuyang et al. (2022)
Adaptive KLKeeps the KL near a target instead of fixing ββ adjusted during training to hit a target KLZiegler et al. (2019)
DPO βStrength of the implicit KL constraint0.1 by default; 0.5 for TL;DR summarizationRafailov et al. (2023)
GRPO group size G, KL weight βSamples per prompt for the baseline; distance from the referenceG=64, β=0.04Shao et al. (2024)
Decoupled clip rangeLets low-probability tokens grow more than they may shrinkϵlow=0.2, ϵhigh=0.28Yu et al. (2025)

Compute and memory

A useful rule of thumb comes from the ZeRO paper: training with mixed-precision Adam keeps about 16 bytes per trained parameter (16-bit weights and gradients, plus 32-bit master weights and two Adam moments), before activations (Rajbhandari et al., 2020). A frozen model kept in 16-bit precision needs about 2 bytes per parameter. So for a policy with N parameters, trained in full:

  • SFT needs roughly 16N bytes of model and optimiser state; a 7-billion-parameter model already needs about 112 GB, which is why sharding or parameter-efficient methods such as LoRA are common.
  • PPO trains the policy and a critic and keeps the reference and reward model frozen: about 16N+16N+2N+2N if all four are the policy’s size. It also generates in every iteration, and autoregressive generation can take a large share of each step.
  • DPO needs about 16N+2N, or 16N if the reference log-probabilities are precomputed, and no generation.
  • GRPO needs about 16N+2N (plus a reward model if one is used), with no critic, but generates G samples per prompt.

How failures show up

Most RL runs on language models log the same handful of quantities: mean reward, KL to the reference, policy entropy, response length, the fraction of clipped samples, and a held-out evaluation. Four failures account for much of what goes wrong.

KL blow-up

Symptom. The KL to the reference rises fast, often with reward still climbing; samples drift in style or become repetitive.

Diagnose. Plot KL per batch next to a held-out quality measure; read samples from the drifting batches.

Respond. A larger or adaptive β (Ziegler et al., 2019), a smaller learning rate or clip range, fewer epochs per batch.

Length bias

Symptom. Mean response length grows with reward, and longer answers win evaluations regardless of content.

Diagnose. Check how much of the reward gain length alone explains (Singhal et al., 2023); compare length-controlled and raw evaluation (§24).

Respond. Length-aware objectives or normalisation (Meng et al., 2024; Liu et al., 2025), length-controlled evaluation, more balanced preference data.

Entropy collapse

Symptom. Policy entropy falls quickly; samples for the same prompt become identical, many GRPO groups give zero advantage, and pass@k stops improving.

Diagnose. Track entropy and the fraction of zero-signal groups.

Respond. An entropy bonus (c2 in PPO’s objective), a larger upper clip range as in DAPO, which introduced it against entropy collapse (Yu et al., 2025), or higher sampling temperature.

Reward hacking

Symptom. The proxy reward keeps rising while human or held-out judgements stall or fall (Gao et al., 2023; Stiennon et al., 2020); outputs exploit quirks such as flattery or formatting.

Diagnose. Evaluate against a different judge than the one optimised; read the highest-reward samples.

Respond. The KL penalty, early stopping on held-out quality, fresh comparisons on the current policy as InstructGPT did, or verifiable rewards where they exist.

24How post-trained models are measured

Post-training changes behaviour, so its evaluations measure behaviour: which answer people prefer, and whether answers are correct.

Preferences: people and model judges

  • Human win rates. Show raters the outputs of two models for the same prompt and count how often each is preferred. InstructGPT’s headline result was such a comparison (Ouyang et al., 2022).
  • Arena rankings. Chatbot Arena collects pairwise votes from users who chat with two anonymous models and fits a Bradley–Terry model to the votes to rank the models (Chiang et al., 2024): the same model as our reward model in §9, used to score models instead of replies.
  • Model judges. A strong language model can act as the judge. Zheng et al. (2023) found that strong judges agreed with human preferences about as often as humans agreed with each other, and also documented position, verbosity and self-enhancement biases. Because judges tend to favour longer answers, length-controlled variants adjust for length (Dubois et al., 2024).

Verifiable benchmarks

Where answers can be checked, benchmarks need no judge: grade-school mathematics word problems in GSM8K (Cobbe et al., 2021), competition mathematics in MATH (Hendrycks et al., 2021), and programming problems with unit tests in HumanEval (Chen et al., 2021). They are the natural yardstick for RLVR, with the usual caveat that public test sets can leak into training data.

pass@1, pass@k and why the difference matters

A verifiable benchmark can be scored on one attempt or several. pass@k is the probability that at least one of k samples is correct. Sampling n≥k answers per problem and counting c correct ones, Chen et al. (2021) give an unbiased estimator:

pass@k=𝔼problems[1−(n−ck)/(nk)].

pass@1 measures what the model does on a single try; pass@k for large k measures what it can reach at all. Majority voting over k samples (maj@k) sits in between. The distinction is at the centre of the elicitation debate: DeepSeekMath found that RL improved majority-vote accuracy but not pass@K (Shao et al., 2024), and Yue et al. (2025) found that base models matched or exceeded their RLVR-trained versions at large k, even though RLVR won at small k. If RL mainly raises pass@1, it is making answers the model could already reach more likely, which is sharpening rather than new capability, at least on those problems. In the running example, RLHF raises the chance of a correct reply from 76% to 96%, but every correct reply was already in the SFT model’s repertoire.

Evaluation also has to look for what post-training can break. InstructGPT measured regressions on standard NLP benchmarks, the alignment tax that motivated PPO-ptx (Ouyang et al., 2022).

25Open questions

We started with a question from GPT-1: does post-training teach new abilities, or elicit abilities the model already has? The evidence so far leans towards elicitation for SFT (§6), and the same debate has reopened for RL (§24).

  • Does RL create reasoning or sharpen it? The pass@k results above suggest sharpening on the problems studied. Whether longer, broader or differently designed RL changes this is open.
  • Rewards beyond verification. Verifiable rewards cover mathematics, code and checkable constraints. Most of what people want, such as good writing, sound advice or honest uncertainty, is not mechanically checkable, which brings back learned rewards and their failure modes.
  • What to optimise. GRPO, its successors and the DPO family differ in normalisations, clipping and loss aggregation that look minor but change behaviour. Which choices matter, and why, is still being worked out.
  • Whose preferences? A single reward model averages over people who disagree. How to represent plural preferences, and how to supervise models on tasks people cannot easily judge, remain open.

The arc of post-training so far: imitate good answers, learn which answers are better, then let the model improve from its own attempts against signals that cannot be fooled. Each step asks less of human labellers and more of the model.

Check yourself After RLVR a model’s pass@1 rises, but its pass@256 does not. What does that suggest?

That RL made answers the model could already find with enough samples more likely to come first: it sharpened the output distribution rather than extending what the model can solve, at least on those problems. pass@1 measures default behaviour; pass@k at large k measures reach.

References

  1. Armen Aghajanyan, et al. (2021). Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning. ACL 2021.
  2. Mohammad Gheshlaghi Azar, et al. (2024). A General Theoretical Paradigm to Understand Learning from Human Preferences. AISTATS 2024.
  3. Yuntao Bai, et al. (2022). Constitutional AI: Harmlessness from AI Feedback. arXiv:2212.08073.
  4. Yuntao Bai, et al. (2022). Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback. arXiv:2204.05862.
  5. Ralph Allan Bradley, Milton E. Terry (1952). Rank Analysis of Incomplete Block Designs: I. The Method of Paired Comparisons. Biometrika 39(3/4).
  6. Tom B. Brown, et al. (2020). Language Models are Few-Shot Learners. NeurIPS 2020.
  7. Stephen Casper, et al. (2023). Open Problems and Fundamental Limitations of Reinforcement Learning from Human Feedback. Transactions on Machine Learning Research.
  8. Mark Chen, et al. (2021). Evaluating Large Language Models Trained on Code. arXiv:2107.03374.
  9. Wei-Lin Chiang, et al. (2024). Chatbot Arena: An Open Platform for Evaluating LLMs by Human Preference. ICML 2024.
  10. Paul F. Christiano, Jan Leike, Tom B. Brown, Miljan Martic, Shane Legg, Dario Amodei (2017). Deep Reinforcement Learning from Human Preferences. NeurIPS 2017.
  11. Karl Cobbe, et al. (2021). Training Verifiers to Solve Math Word Problems. arXiv:2110.14168.
  12. Andrew M. Dai, Quoc V. Le (2015). Semi-supervised Sequence Learning. NeurIPS 2015.
  13. DeepSeek-AI (2025). DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning. arXiv:2501.12948.
  14. Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL 2019.
  15. Yann Dubois, et al. (2024). Length-Controlled AlpacaEval: A Simple Way to Debias Automatic Evaluators. arXiv:2404.04475.
  16. Kawin Ethayarajh, Winnie Xu, Niklas Muennighoff, Dan Jurafsky, Douwe Kiela (2024). KTO: Model Alignment as Prospect Theoretic Optimization. ICML 2024.
  17. Leo Gao, John Schulman, Jacob Hilton (2023). Scaling Laws for Reward Model Overoptimization. ICML 2023.
  18. Zorik Gekhman, et al. (2024). Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations?. EMNLP 2024.
  19. Dan Hendrycks, et al. (2021). Measuring Mathematical Problem Solving With the MATH Dataset. NeurIPS 2021 Datasets and Benchmarks.
  20. Jeremy Howard, Sebastian Ruder (2018). Universal Language Model Fine-tuning for Text Classification. ACL 2018.
  21. Edward J. Hu, et al. (2022). LoRA: Low-Rank Adaptation of Large Language Models. ICLR 2022.
  22. Sham Kakade, John Langford (2002). Approximately Optimal Approximate Reinforcement Learning. ICML 2002.
  23. Jared Kaplan, Sam McCandlish, Tom Henighan, Tom B. Brown, Benjamin Chess, Rewon Child, Scott Gray, Alec Radford, Jeffrey Wu, Dario Amodei (2020). Scaling Laws for Neural Language Models. arXiv:2001.08361.
  24. Nathan Lambert, et al. (2024). Tülu 3: Pushing Frontiers in Open Language Model Post-Training. arXiv:2411.15124.
  25. Hunter Lightman, et al. (2023). Let's Verify Step by Step. ICLR 2024.
  26. Bill Yuchen Lin, et al. (2024). The Unlocking Spell on Base LLMs: Rethinking Alignment via In-Context Learning. ICLR 2024.
  27. Zichen Liu, et al. (2025). Understanding R1-Zero-Like Training: A Critical Perspective. arXiv:2503.20783.
  28. Yu Meng, Mengzhou Xia, Danqi Chen (2024). SimPO: Simple Preference Optimization with a Reference-Free Reward. NeurIPS 2024.
  29. Tomas Mikolov, Kai Chen, Greg Corrado, Jeffrey Dean (2013). Efficient Estimation of Word Representations in Vector Space. arXiv:1301.3781.
  30. Volodymyr Mnih, et al. (2016). Asynchronous Methods for Deep Reinforcement Learning. ICML 2016.
  31. OpenAI (2024). Learning to Reason with LLMs. OpenAI blog post.
  32. Long Ouyang, Jeff Wu, Xu Jiang, et al. (2022). Training Language Models to Follow Instructions with Human Feedback. NeurIPS 2022.
  33. Jeffrey Pennington, Richard Socher, Christopher D. Manning (2014). GloVe: Global Vectors for Word Representation. EMNLP 2014.
  34. Matthew E. Peters, Mark Neumann, Mohit Iyyer, Matt Gardner, Christopher Clark, Kenton Lee, Luke Zettlemoyer (2018). Deep Contextualized Word Representations. NAACL 2018.
  35. Alec Radford, Karthik Narasimhan, Tim Salimans, Ilya Sutskever (2018). Improving Language Understanding by Generative Pre-Training. OpenAI technical report.
  36. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever (2019). Language Models are Unsupervised Multitask Learners. OpenAI technical report.
  37. Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, Chelsea Finn (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model. NeurIPS 2023.
  38. Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. Journal of Machine Learning Research 21.
  39. Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He (2020). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. SC 2020.
  40. Marc'Aurelio Ranzato, Sumit Chopra, Michael Auli, Wojciech Zaremba (2016). Sequence Level Training with Recurrent Neural Networks. ICLR 2016.
  41. Gavin A. Rummery, Mahesan Niranjan (1994). On-Line Q-Learning Using Connectionist Systems. Technical report, Cambridge University Engineering Department.
  42. John Schulman, Sergey Levine, Philipp Moritz, Michael I. Jordan, Pieter Abbeel (2015). Trust Region Policy Optimization. ICML 2015.
  43. John Schulman, Philipp Moritz, Sergey Levine, Michael I. Jordan, Pieter Abbeel (2016). High-Dimensional Continuous Control Using Generalized Advantage Estimation. ICLR 2016.
  44. John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov (2017). Proximal Policy Optimization Algorithms. arXiv:1707.06347.
  45. Zhihong Shao, et al. (2024). DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models. arXiv:2402.03300.
  46. Mrinank Sharma, et al. (2024). Towards Understanding Sycophancy in Language Models. ICLR 2024.
  47. Prasann Singhal, Tanya Goyal, Jiacheng Xu, Greg Durrett (2023). A Long Way to Go: Investigating Length Correlations in RLHF. arXiv:2310.03716.
  48. Nisan Stiennon, et al. (2020). Learning to Summarize from Human Feedback. NeurIPS 2020.
  49. Richard S. Sutton (1988). Learning to Predict by the Methods of Temporal Differences. Machine Learning 3.
  50. Richard S. Sutton, David McAllester, Satinder Singh, Yishay Mansour (2000). Policy Gradient Methods for Reinforcement Learning with Function Approximation. Advances in Neural Information Processing Systems 12.
  51. Richard S. Sutton, Andrew G. Barto (2018). Reinforcement Learning: An Introduction (2nd edition). MIT Press.
  52. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin (2017). Attention Is All You Need. NeurIPS 2017.
  53. Yizhong Wang, et al. (2023). Self-Instruct: Aligning Language Models with Self-Generated Instructions. ACL 2023.
  54. Christopher J. C. H. Watkins, Peter Dayan (1992). Q-learning. Machine Learning 8.
  55. Jason Wei, et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS 2022.
  56. Jason Wei, Maarten Bosma, Vincent Y. Zhao, Kelvin Guu, Adams Wei Yu, Brian Lester, Nan Du, Andrew M. Dai, Quoc V. Le (2022). Finetuned Language Models Are Zero-Shot Learners. ICLR 2022.
  57. Ronald J. Williams (1992). Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. Machine Learning 8.
  58. Qiying Yu, et al. (2025). DAPO: An Open-Source LLM Reinforcement Learning System at Scale. arXiv:2503.14476.
  59. Yang Yue, et al. (2025). Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model?. arXiv:2504.13837.
  60. Eric Zelikman, Yuhuai Wu, Jesse Mu, Noah D. Goodman (2022). STaR: Bootstrapping Reasoning With Reasoning. NeurIPS 2022.
  61. Lianmin Zheng, et al. (2023). Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena. NeurIPS 2023 Datasets and Benchmarks.
  62. Chunting Zhou, et al. (2023). LIMA: Less Is More for Alignment. NeurIPS 2023.
  63. Daniel M. Ziegler, et al. (2019). Fine-Tuning Language Models from Human Preferences. arXiv:1909.08593.

The running example and Figures 2–10 use small illustrative toys built for this page; their numbers are not measurements from real models. Back to top ↑