AI State of the Art
Fundamentals/LLM: Understanding Large Language Models/31 min
Section 53

RLHF: Reinforcement Learning from Human Feedback

Listen as a podcast β†’

The problem: a genius that doesn't know how to be helpful

Imagine hiring the world's greatest linguistics expert to answer your questions. But he has a problem: instead of answering, he continues your sentences as if he were writing a book. You ask "What is the capital of France?" and he follows up with "What is the capital of Italy? What is the capital of Spain?"

This is exactly the base model as it comes out of pre-training. It is brilliant at predicting the next token, the next chunk of text. It does not know how to help you.

One piece of vocabulary in passing, since it recurs everywhere: a prompt is simply the text you hand the model and after which it has to write. A question, an instruction, the opening of a document: all of these are prompts. This page will also say "the question" where that is what it is.

In 2022, OpenAI published InstructGPT and presented a solution: RLHF (Reinforcement Learning from Human Feedback). It is the technique that turned GPT-3 into ChatGPT. And that changed the entire industry.

Training language models to follow instructions with human feedback (Ouyang et al., 2022)
Three-column figure. Step 1: a prompt is sampled from the dataset, a labeler writes the ideal answer, and this data is used to fine-tune GPT-3 with supervised learning (SFT). Step 2: a prompt and several model outputs are sampled, a labeler ranks them from best to worst (D greater than C greater than A equals B), and this ranking trains the reward model. Step 3: a new prompt is sampled, the policy generates an output, the reward model assigns a reward r_k, and that reward updates the policy via PPO.
The reference figure from the InstructGPT paper. It sums up everything that follows: humans first write model answers (step 1), then they merely rank answers the model produced (step 2), and that ranking becomes an automatic judge that trains the model in a loop (step 3). Notice how the human does less and less work at each step.Source : InstructGPT paper (figure 2, Ouyang et al., 2022), via ChapterPal

Five words to settle before we start

These three steps are told using vocabulary borrowed from reinforcement learning. It is short, and settling it now saves stumbling three times per section:

  • Annotator (or labeler): a person paid and trained to produce or judge answers. This is not a user giving a passing opinion: it is a job, with written guidelines and consistency checks.
  • Policy: the word reinforcement learning uses for the model itself, seen as a decision rule, "in this situation, which action should I take?" For an LLM, the situation is the text written so far and the action is the next token. Every time you read "the policy", read "the model being trained".
  • Signal: the number that tells the model whether it did well. Without a signal there is no learning: it is the only information that travels from the objective back to the weights.
  • Reward model: a second neural network, separate from the first, whose only job is to produce that signal. It reads a question and an answer, and returns a score. It generates nothing.
  • Reward: that score. A single unitless number, of which only comparisons are meaningful: an answer scored 3.4 is better than one scored 1.2, but "3.4" means nothing on its own.

The three-step pipeline

Each step is described the same way: what it consumes, what it produces, and why you cannot skip it.

Step 1: SFT, show by example

Consumes(question, ideal answer) pairs written from scratch by annotators, plus the base model from pre-training
Producesthe SFT model, which answers instead of continuing
Needed becausewithout it the model does not even know what an answer is; so there would be nothing correct to reward in step 3

Before even talking about reinforcement, you do something simple: you show the model what you expect from it.

Human annotators write thousands of exemplary dialogues. For each question they write the ideal answer: helpful, honest, well-structured, politely refusing dangerous requests. For InstructGPT, this dataset contains about 13,000 prompts.

These examples are used for standard supervised fine-tuning, called SFT (Supervised Fine-Tuning). The model learns to respond instead of continuing text.

SFT: changing the format, not the knowledge

An important detail: SFT does not give the model new knowledge. It already knows that Paris is the capital of France. It only learns that it should answer the question, not follow up with more questions. It is a change in behaviour, not in intelligence.

SFT already produces a much better model. But it is capped by what humans can physically write: composing one perfect answer takes minutes, and you would need millions. To go further you have to change the nature of the human work, from "write the right answer" to "tell me which one is better". That is the whole point of step 2.

Step 2: the reward model, learning what humans prefer

Consumesprompts, several answers generated by the SFT model for each, and the ranking of those answers by annotators
Producesthe reward model: a function that scores any (question, answer) pair
Needed becausestep 3 has to score millions of answers; no human can keep up. The reward model is the only way to make human judgment reproducible on demand

How do you automatically measure whether an answer is good? That is the job of the reward model, a second network, separate from the one being trained, whose only job is to imitate human preferences.

The creation process:

  1. Take a question and have the SFT model generate between 4 and 9 different answers (those are the values the InstructGPT authors report)
  2. Human annotators rank those answers from best to worst, they do not rewrite them, they order them
  3. Train a network to predict that ranking

For InstructGPT, this comparison set covers about 33,000 prompts, and the reward model they settled on has 6 billion parameters, far fewer than the 175 billion of the model being aligned, the authors having found large reward models unstable.

The reward model learns a function that takes a question and an answer and returns a numerical score, an estimate of "how much humans would like this answer".

What is learned, what is frozen

Three different networks circulate through this page, and it is essential not to confuse them:

  • the reward model is learned in step 2, then frozen for the whole of step 3;
  • the policy (the model you want to improve) is the only one whose weights move in step 3;
  • the reference model is a snapshot of the policy taken just before step 3, and is never touched again.

A reward score, by contrast, is not a learned parameter: it is a value computed on the fly for the text at hand, and discarded as soon as it has been used.

Why rank rather than rate?

Giving an absolute rating ("this answer is worth 7.5/10") is difficult and inconsistent across annotators. Comparing two answers ("A is better than B") is far more natural and reliable. It is like picking your favourite pizza off a menu rather than scoring each pizza out of 20.

The cost function (the loss) used to train the reward model rests on pairwise comparisons. For each pair (preferred answer ywy_w, rejected answer yly_l) for the same question xx:

L=βˆ’log⁑σ(r(x,yw)βˆ’r(x,yl))\mathcal{L} = -\log \sigma\left(r(x, y_w) - r(x, y_l)\right)

Term by term:

  • xx: the question asked
  • ywy_w: the answer the annotator preferred (ww for win)
  • yly_l: the rejected answer (ll for lose)
  • r(x,y)r(x, y): the score the reward model assigns to a question-answer pair
  • the subtraction r(x,yw)βˆ’r(x,yl)r(x, y_w) - r(x, y_l): the gap between the two scores. We want it positive
  • Οƒ\sigma: the sigmoid function, which squashes any real number into the interval 0-1 and makes it readable as a probability
  • βˆ’log⁑(…)-\log(\ldots): turns that probability into a cost, when it is close to 1 (correct ranking), the logarithm is close to 0 so the cost is small; as it tends to 0, the cost blows up

Read back in one sentence: the reward model is penalized in proportion to its surprise at learning that ywy_w was the better of the two. It is under no obligation to output any particular score, only to put the two answers in the right order.

Diagram of reward model training. On the left, a prompts dataset feeds an initial language model that produces text. In the middle, a human scoring step. On the right, the outputs are ranked relative to each other, and those pairs are used to train a reward model that outputs a score r_theta.
The step 2 circuit: sample many prompts, let the model answer, have humans order the answers from best to worst, and use those rankings to train a small network that learns to put a number on any prompt-response pair.Source : deepsense.ai (figure taken from the Hugging Face blog on RLHF)

Step 3: PPO, improving through rewards

Consumesquestions alone, with no answers and no new annotation at all, plus the frozen reward model and the SFT model
Producesthe final aligned model
Needed becauseit is the only step where the model learns from its own output. SFT taught it to imitate answers written by others; here it discovers what works among what it can already produce

That detail in the "consumes" column is the most commonly missed point: step 3 needs no humans at all any more. The human work was entirely absorbed, back in step 2, into the reward model's weights. All that remains is a list of questions, about 31,000 for InstructGPT.

The third step uses PPO (Proximal Policy Optimization), a reinforcement learning algorithm. The idea: use the reward model as an automatic judge to train the policy to produce better answers.

For each training step:

  1. Draw a question at random from the prompt set
  2. The policy generates an answer
  3. The reward model assigns a score to that answer
  4. That score becomes the signal: it is used to compute a gradient that makes answers of that kind more likely (if the score is high) or less likely (if it is low)

But there is a catch. The model is graded by an imperfect judge, and it always ends up discovering the judge's flaws rather than the quality the judge was supposed to measure: it notices, for instance, that long, confident answers get good scores, and starts producing long, confident answers even when they are wrong. This is reward hacking.

The fix: a KL penalty (for Kullback-Leibler, after the two mathematicians) that stops the policy from straying too far from the original SFT model:

Rtotal=r(x,y)βˆ’Ξ²β‹…DKL(Ο€RLβˆ₯Ο€SFT)R_{\text{total}} = r(x, y) - \beta \cdot D_{KL}(\pi_{RL} \| \pi_{SFT})

Term by term:

  • RtotalR_{\text{total}}: the reward actually used to update the weights
  • r(x,y)r(x, y): the raw score the reward model gives answer yy for question xx
  • Ο€\pi (the Greek letter pi): a policy, that is, a model seen as a generation rule
  • Ο€RL\pi_{RL}: the policy currently being trained by PPO
  • Ο€SFT\pi_{SFT}: the frozen reference model, the copy taken just before PPO
  • DKL(Ο€RLβˆ₯Ο€SFT)D_{KL}(\pi_{RL} \| \pi_{SFT}): the Kullback-Leibler divergence between the two, which measures how far apart the probabilities they assign to the same tokens have drifted. It is 0 if the two models are identical and grows with the gap
  • Ξ²\beta (beta): a hand-tuned coefficient that sets the length of the leash. Too large and the model is hobbled and does not improve; too small and the leash is slack and reward hacking comes back

In one sentence: you reward the quality of the answer, and you charge the model for every step it takes away from its starting point. The minus sign in front of Ξ²\beta is the whole mechanism: drifting costs points.

Diagram of the RLHF PPO loop. Input text is sent in parallel to the model being trained (Trained LM) and to a frozen copy (Frozen LM). The generated text goes through the reward model, which produces a score. The probabilities from both models feed a KL Loss. The score and the KL penalty are added to form the final reward, which is sent to the RL Update (PPO) block that updates the trained model weights at each step.
The leash, drawn out. The model being trained (top) and its frozen copy (bottom) receive the same text; the gap between their two distributions is the KL penalty, subtracted from the reward model score before the weights are updated. Without that subtraction the model drifts and learns to flatter the judge rather than answer well.Source : Joao Lages (diagram derived from the Hugging Face blog on RLHF)
InstructGPT's striking result

The authors report that answers from the 1.3-billion-parameter InstructGPT model are preferred by annotators over those of GPT-3 at 175 billion, "despite having 100x fewer parameters" in their own wording (the exact ratio is 135). In other words: a model two orders of magnitude smaller becomes more useful if it is well aligned. Alignment weighs at least as much as size.

PPO: the algorithm under the hood

PPO keeps four models in memory at once, which largely explains why RLHF is so expensive. A table first, the details after:

ModelWeightsRole
The policyupdated at every stepgenerates the answers
The reference modelfrozenmeasures the drift
The reward modelfrozenscores the answers
The criticupdatedpredicts the expected score
  1. The policy, this is the model produced by supervised fine-tuning (step 1), the one you keep training. At each step it generates an answer and its weights are corrected according to the reward received. It is this model, and only this one, that you are trying to improve.

  2. The reference model, a copy of the policy taken before PPO begins, frozen for good. Why? Because over the course of training the policy can drift: it finds loopholes that earn good scores from the reward model without being genuinely useful. The frozen copy acts as a leash: at each step you compare the policy's probabilities with the copy's, and if the gap grows too large you deduct points. This forces the model to stay in the neighbourhood of what it was.

  3. The reward model, learned in step 2 on human preferences, then frozen during PPO. Its role: take the question and the generated answer, and return a score. It is the automatic judge that replaces the annotators.

  4. The critic (or value model), the least intuitive of the four. In reinforcement learning you do not want to know "did this answer get a good score?" but "is this answer better than what we expected for this question?". The critic predicts exactly that expected average score for a given question: the value. The difference between the score actually obtained and this prediction is called the advantage, and it is that, not the raw score, that drives the weight update.

What the critic is for, in one image

A student hands in a paper graded 12 out of 20. Should you congratulate them? Impossible to say without knowing whether the exam was easy or hard. If the expected average on that exam was 8, a 12 is excellent; if it was 16, it is a failure.

The critic is exactly that "expected average". Without it, the model would be reinforced on easy questions (where all its answers score well) and discouraged on hard ones, regardless of its actual performance. With it, only the deviation from expectation is rewarded, and that is what makes training far less noisy.

PPO's clipping is an extra guardrail: it caps the size of each update, so that a single abnormally well-scored answer cannot send the model a long way in a bad direction. That is the "proximal" in the algorithm's name: only steps close to the starting point are allowed.

RLHF is notoriously hard to implement

Ask any machine learning (ML) engineer who has implemented PPO on an LLM: training curves can collapse without warning, reward hacking is a constant problem, and the hyperparameters (the settings you choose by hand before launching training) are extremely sensitive. This is one of the major reasons DPO was greeted with such enthusiasm.

RLHF challenges in practice

Reward hacking: the model optimizes the proxy measure (the reward model) rather than the real objective (being helpful). It learns to exploit the annotators' biases and the reward model's flaws.

Annotation quality: annotators have biases, blind spots, and disagree with one another. It is precisely because the reward model cannot be better than its annotations that Constitutional AI tries to replace that judgment with written principles.

Instability: PPO on an LLM is fragile. The KL divergence can explode, rewards can collapse, the model can degenerate into repetitive text. Constant monitoring of the curves is required.

Cost: qualified annotators (slow and expensive), four models to hold in memory, many iterations, a budget that remains out of reach for a small team.

The legacy: a revolution despite everything

Despite these difficulties, RLHF was a turning point. ChatGPT, Claude, Gemini, every modern assistant uses some form of alignment derived from RLHF. It proved that an LLM could be made useful and safe.

Its limitations also set off a wave of innovation, and each one attacks a specific link in the chain described above:

  • DPO removes the reward model and the whole of step 3;
  • Constitutional AI replaces the step 2 annotators with the model itself, guided by written principles;
  • ORPO and KTO merge the steps or loosen the data format required.
Check your understanding0 / 4

1. In step 3 (PPO), what human work is still required?

2. What is the KL penalty in the total reward for?

3. Why does PPO need a fourth model, the critic?

4. What is the striking result of the InstructGPT paper?