Skip to content
ImagineWorld

Learning from Human Feedback

node_idnode-book_building-frontier-llm-from-scratch_chapter-23-learning-from-human-feedback
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num23
chapter_titleLearning from Human Feedback
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 23 — Learning from Human Feedback

Section titled “Chapter 23 — Learning from Human Feedback”

Some qualities cannot be taught by demonstration. It is hard to write the “correct” answer to “explain quantum computing simply,” but easy to look at two answers and say which is better. Reinforcement learning from human feedback (RLHF) exploits exactly this asymmetry: instead of demonstrating ideal responses, humans compare pairs of model responses, a model learns to predict those preferences, and the language model is then optimized to score well under it. RLHF is what turned capable-but-rough instruction models into the polished assistants that defined the post-2022 era. This chapter builds the classic pipeline; the next two chapters show the simpler methods that have largely replaced it.

SFT optimizes the model to imitate reference responses, which has two limits. First, it can only teach what someone took the trouble to write down, and the best response is often not in the dataset. Second, imitation has no notion of better or worse — it treats the one reference answer as the only right answer. Preferences fix both: by ranking responses the model itself generates, we can push it toward outputs better than any in the original data, and we can express subtle goals (be helpful but not sycophantic, be honest about uncertainty, refuse genuinely harmful requests) that are far easier to judge than to specify.

Humans cannot score every response during training, so we distill their judgments into a reward model: a copy of the language model with its output head replaced by a single scalar, trained to assign a higher score to the human-preferred response in each comparison. The training objective is the Bradley-Terry preference loss — maximize the probability that the chosen response outscores the rejected one — which is one line:

# r_chosen, r_rejected: scalar reward-model scores for the two responses
# loss = -F.logsigmoid(r_chosen - r_rejected).mean() # prefer chosen over rejected

Python — reward_model.py: the Bradley-Terry preference loss

After training, the reward model is a cheap, automatic stand-in for a human rater: hand it a prompt and a response and it returns a number estimating how much a human would like it. Its quality caps the quality of everything downstream — a flawed reward model teaches the policy to chase the wrong thing.

With a reward model in hand, the language model (now called the policy) is optimized by reinforcement learning to produce responses the reward model scores highly. The classic algorithm is Proximal Policy Optimization (PPO). The loop: the policy generates responses to prompts, the reward model scores them, and the policy is updated to make high-reward responses more likely. Crucially, a KL-divergence penalty ties the policy to the original SFT model — without it, the policy quickly discovers degenerate text that fools the reward model but is gibberish to humans (an early instance of reward hacking). The objective balances the two forces:

maximize E[r(x,y)]−β⋅KL(πpolicy(y∣x) ∣∣ πref(y∣x)).\text{maximize } \mathbb{E}[r(x, y)] - \beta \cdot \text{KL}(\pi_{\text{policy}}(y|x) \, || \, \pi_{\text{ref}}(y|x)).

The reward term pulls the policy toward what humans prefer; the KL term anchors it to fluent, sensible language. The coefficient β\beta trades off alignment against fidelity to the reference. Figure 23.1 shows the full three-stage pipeline.

23.4 The Difficulties That Motivated What Came Next

Section titled “23.4 The Difficulties That Motivated What Came Next”

Classic RLHF works, but it is genuinely hard to run. It requires training and serving a separate reward model, holding several models in memory at once (policy, reference, reward, and PPO’s value model), and PPO is notoriously finicky to stabilize. And reward hacking is ever-present: the policy relentlessly seeks loopholes in the reward model, producing responses that score well but are verbose, sycophantic, or subtly wrong. These costs and fragilities drove the field toward simpler alternatives — methods that capture the benefit of learning from preferences without the reward model and the RL loop. The most important of them, Direct Preference Optimization, is the subject of the next chapter, and the reasoning-focused GRPO follows it.

Code reference — Ouyang et al., “InstructGPT” · Christiano et al., “Deep RL from Human Preferences” · huggingface/trl (RewardTrainer, PPOTrainer)

InstructGPT is the canonical RLHF recipe; the preference-learning idea traces to Christiano et al.; and tr1 provides working reward-model and PPO trainers. Reading the InstructGPT method section makes the three stages above concrete.

23.5 Worked Example: The PPO Clipped Objective

Section titled “23.5 Worked Example: The PPO Clipped Objective”

RLHF (Chapter 23) optimizes the policy against the reward model while a clip keeps each update close to the previous policy, preventing the destructive large steps that plain policy gradients invite. The clipped surrogate, with a KL leash to the reference, is the core:

ratio = (logp_new - logp_old).exp() # pi_new / pi_old
clipped = ratio.clamp(1 - eps, 1 + eps) # eps ~ 0.2
loss_pg = -torch.min(ratio * adv, clipped * adv).mean() # don't drift from the SFT model
loss = loss_pg + beta * kl_to_reference # reward (for adv) comes from the reward model of Chapter 23;
# GRPO (Section 25.6) keeps this clip but drops the value network

Python — PPO: clipped policy-gradient with a KL leash

A policy optimized to maximize a learned reward will, given enough freedom, discover outputs that score highly under the reward model yet are useless or bizarre to a human — padding with flattering phrases, exploiting length biases, repeating tokens the model happens to love. This is reward hacking, and it is not a bug in the reward model so much as an inevitability of optimizing any imperfect proxy hard enough. The standard restraint is a KL-divergence penalty that keeps the policy close to the frozen reference (the SFT model):

logp = policy.log_prob(response) # frozen SFT model
logp_ref = reference.log_prob(response) # per-token divergence
kl = logp - logp_ref
reward = rm_score - beta * kl # beta sets the leash length

Python — rlhf/reward.py: reward model score minus a KL leash

The coefficient beta is the single most consequential knob in the whole procedure. Too small, and the leash is slack: the policy wanders off into reward-hacked territory, posting rising reward while its actual outputs degrade. Too large, and the leash is taut:

he policy is pinned to the SFT model and cannot improve at all. The art of RLHF, as Section 23.4 foreshadowed, is largely the art of holding this tension — which is exactly the difficulty that made the preference-optimization methods of the next two chapters so attractive.

23.7 Worked Example: From Sequence Reward to Per-

Section titled “23.7 Worked Example: From Sequence Reward to Per-”

Token Signal

The reward model emits one scalar for a whole response, but PPO updates the policy token by token. Reconciling the two is a small piece of bookkeeping that every RLHF implementation performs. The sequence-level RM score is placed on the final generated token; the KL penalty, by contrast, applies at every token. The per-token reward is therefore:

rewa rds = -beta * kl
rewa rds[-1] += rm_score
# [T] KL penalty everywhere
# RM score at the last token
# advantages then come from GAE over this per-token reward stream
advantages = gae(rewards, values, gamma=1.0, lam=0.95)

Python — rlhf/per_token.py: assembling the token-level reward

Placing the scalar reward at the end and letting generalized advantage estimation (GAE) propagate it backward is what lets a single judgment about the whole answer shape the probability of each token that produced it. The KL term, present at every step, simultaneously pulls every token back toward the reference. Each PPO update is thus a tug-of-war, resolved per token, between “make this whole response score higher” and “do not drift from what you already were.”

Why reasoning RL is simpler here Much of this machinery — the reward model, the GAE value head, the per-token reward assembly — exists to cope with a learned, noisy reward. When the reward is instead verifiable (a unit test passes, an answer matches), as in Chapter 25, large parts of it can be discarded, which is one reason GRPO is so much lighter than PPO.

A striking and under-appreciated fact about RLHF with PPO is how many models it keeps in memory at once. Where pretraining holds a single network, the PPO stage juggles four, each with a distinct role, and the sheer weight of them is a large part of why the field moved toward lighter alternatives:

ModelTrained?Role
Policyyesthe model being improved
ReferencefrozenKL anchor (Section 23.6)
Reward modelfrozenscores responses
Value / criticyesestimates the baseline for advantages

Table 23.1 — The four models in a PPO-based RLHF stage

Two of these are trained and two are frozen, but all four occupy memory and most require a forward pass on every step. The cost is what motivates the next two chapters directly. DPO (Chapter 24) eliminates the reward model and the critic, keeping only a policy and a frozen reference — two models instead of four. GRPO (Chapter 25) removes the critic as well, replacing its learned baseline with the mean reward over a sampled group (Section 25.8), and pairs naturally with a verifiable reward that needs no reward model at all. Read this way, the progression from PPO to DPO to GRPO is in large part a story of removing models from the loop — each step shedding one of the four above while preserving the alignment signal they collectively provided.

Why the alternatives won PPO’s four-model overhead — policy, reference, reward model, critic — is its defining cost. DPO and GRPO are best understood as principled ways to delete two or three of those models while keeping the alignment they delivered.

23.9 Training the Reward Model: Bradley-Terry

Section titled “23.9 Training the Reward Model: Bradley-Terry”

RLHF’s reward model (Section 23.2) has to turn discrete human preferences — “this response is better than that one” — into a continuous score it can optimize against. The standard tool is the Bradley-Terry model, which says the probability that one response is preferred is the logistic function of the difference in their rewards. Training the reward model is then a simple classification on preference pairs:

# P(chosen preferred over rejected) = sigmoid(r_chosen - r_rejected)
r_chosen = reward_model(chosen) # scalar score
r_rejected = reward_model(rejected)
loss = -F.logsigmoid(r_chosen - r_rejected).mean()

Python — rlhf/reward_model.py: the Bradley-Terry preference loss

Two practical points follow. The reward model is usually the base or SFT model with its language-modeling head replaced by a single scalar output head, so it inherits the same understanding of text and merely learns to map a response to a number. And because everything downstream — the PPO reward, the per-token signal of Section 23.7 — flows from this scalar, the reward model’s quality is a hard ceiling on the entire RLHF stage: a reward model that misjudges quality will faithfully teach the policy to produce exactly the responses it misjudges as good. This single fact, that you are optimizing a learned and imperfect proxy, is the root of the reward-hacking problem (Section 23.6) and a large part of why the reward-model-free methods of Chapter 24 proved so appealing.

The policy can only be as good as its reward Bradley-Terry turns preferences into a scalar the policy chases. That scalar is a learned proxy, and its errors become the policy’s errors — the ceiling on RLHF and the seed of reward hacking.

PPO improves the policy in proportion to each action’s advantage — how much better it turned out than expected (Section 23.8). Estimating that advantage well is harder than it sounds, and the choice involves a bias-variance trade-off. Using the raw observed reward minus a baseline is unbiased but very noisy; relying heavily on the critic’s value estimates is smoother but biased by the critic’s errors. Generalized Advantage Estimation (GAE) is the standard compromise.

GAE interpolates between the two extremes with a parameter, conventionally written λ\lambda, that controls how much it leans on observed rewards versus the critic’s predictions. At one setting it reduces to the high-variance, unbiased estimate; at the other, to the low-variance, biased one; in between, it blends them, combining the immediate reward signal with the critic’s longer-range value estimate to produce an advantage that is smoother than raw rewards but less biased than the critic alone. This blended advantage is what PPO actually optimizes against (Section 23.8), and tuning λ is part of stabilizing an RLHF run — too much reliance on noisy rewards makes the updates erratic, too much on the critic makes them follow the critic’s mistakes. GAE is one of the unglamorous numerical ingredients that makes PPO work in practice, and its absence is part of what makes the critic-free methods of Chapters 24 and 25 simpler: GRPO’s group-mean baseline (Section 25.8) sidesteps the whole advantage-estimation apparatus that GAE exists to manage.

Blend reward and value to estimate advantage Raw rewards are unbiased but noisy; the critic is smooth but biased. GAE interpolates between them with a tunable parameter, giving PPO a stable advantage signal — an apparatus the critic-free methods avoid entirely.