5203: Reinforcement Learning from Human Feedback¶
Difficulty: ⭐⭐⭐ Advanced
Estimated Time: 4 hours
Table of Contents¶
- Learning Objectives
- Abstract
- The RLHF Pipeline
- Stage 2: Reward Model Training
- Stage 3: PPO Optimization
- KL Divergence and Reward Hacking
- RLHF vs DPO
- Hands-On: Minimal RLHF with TRL
- Known Failure Modes
- Summary
- References
Learning Objectives¶
After completing this lesson, you will be able to:
- Diagram the three-stage RLHF pipeline and name the artifact each stage produces
- Train a reward model from pairwise human preferences using the Bradley-Terry loss
- Explain the PPO clipped surrogate objective and why clipping stabilizes training
- Tune the KL penalty coefficient and recognize reward hacking in training curves
- Decide between RLHF and DPO for a given budget, data, and stability constraint
Abstract¶
RLHF (Reinforcement Learning from Human Feedback) is the alignment method behind ChatGPT, Claude, and Llama-2-Chat. Instead of hand-writing rules for good behavior, you collect human preference judgments, distill them into a learned reward model, and then optimize the language model against that reward with reinforcement learning (typically PPO), constrained so the model does not drift too far from its supervised starting point. RLHF is powerful but operationally heavy: it trains two models (reward model + policy), samples online during optimization, and is famously sensitive to hyperparameters. This lesson walks the full pipeline, then contrasts it with DPO (5201), which achieves a similar effect offline.
The RLHF Pipeline¶
Three Stages¶
Stage 1: SFT Stage 2: Reward Model Stage 3: RL (PPO)
+----------------+ +----------------+ +----------------+
| Pretrained LM | | SFT model + | | SFT model + |
| + demo data | ---------> | value head, | ---------> | value head, |
| (prompt -> | | trained on | | optimized with |
| good response)| | preference | | PPO against |
| | | pairs | | reward model |
+----------------+ +----------------+ +----------------+
Artifact: policy_init Artifact: reward model R Artifact: aligned model
- Stage 1 — Supervised Fine-Tuning (SFT): fine-tune the base model on high-quality demonstrations so it produces well-formatted, helpful responses. This is the same procedure as any instruction tuning; RLHF simply needs it as a sane starting point.
- Stage 2 — Reward Modeling: train a model to score
(prompt, response)pairs so that scores reproduce human preference rankings. - Stage 3 — Reinforcement Learning: treat the SFT model as a policy that "acts" by generating tokens, and optimize expected reward with PPO, penalized for diverging from the starting policy.
Why Not Skip to RL?¶
1. Reward signal must come from somewhere
- Hand-written rewards (length, keywords) are gameable
- Learned reward models capture fuzzy human judgment
2. The base model is a poor RL starting policy
- Without SFT, outputs are malformed; PPO wastes capacity
learning formatting instead of behavior
3. Preferences, not demonstrations, define the target
- Demonstrations show ONE way to respond
- Preferences say which of two responses is BETTER -
much cheaper for humans to judge at scale
Stage 2: Reward Model Training¶
Data Format¶
Humans see one prompt and two responses, and pick a winner:
{
"prompt": "Explain recursion to a 10-year-old.",
"chosen": "Recursion is when a function calls itself...",
"rejected": "Recursion is a mathematical concept related..."
}
A preference dataset is thousands to millions of such triplets. Cost dominates: pairwise comparison is the cheapest reliable human judgment, which is exactly why the pipeline is built around it.
Bradley-Terry Loss¶
The reward model outputs a scalar R(x, y). We assume the probability that a human prefers y_w over y_l follows a Bradley-Terry model, and maximize the log-likelihood of the observed choices:
P(y_w > y_l | x) = sigmoid(R(x, y_w) - R(x, y_l))
Loss = -E[ log sigmoid( R(x, y_w) - R(x, y_l) ) ]
Intuition: the loss is zero when the chosen response outscores the rejected one by a margin, and grows as the gap shrinks or inverts. The absolute scale of R is meaningless — only differences matter.
Implementation¶
from transformers import AutoModelForSequenceClassification, AutoTokenizer, TrainingArguments
from trl import RewardTrainer, RewardConfig
from datasets import load_dataset
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
model = AutoModelForSequenceClassification.from_pretrained(
"meta-llama/Llama-3.1-8B-Instruct",
num_labels=1, # scalar reward head
dtype="bfloat16",
)
model.config.pad_token_id = tokenizer.pad_token_id
dataset = load_dataset("json", data_files="preferences.jsonl")["train"]
config = RewardConfig(
output_dir="rm-ckpt",
per_device_train_batch_size=4,
gradient_accumulation_steps=8,
learning_rate=5e-6, # reward models are tuned LOW
num_train_epochs=1,
bf16=True,
logging_steps=10,
)
trainer = RewardTrainer(
model=model,
args=config,
train_dataset=dataset, # columns: prompt/chosen/rejected or chosen/rejected messages
processing_class=tokenizer,
)
trainer.train()
Practical notes:
- The reward model is typically the same size or larger than the policy — an undersized judge is easier to fool.
num_labels=1turns the sequence classifier into a scalar scorer with a fresh linear head on top of the LM backbone.- Train for at most 1-2 epochs; reward models overfit preference noise quickly, and an overfit judge produces reward hacking downstream.
Stage 3: PPO Optimization¶
RL Framing of Generation¶
State s_t = prompt + tokens generated so far
Action a_t = next token
Policy pi(a|s) = LM softmax over vocabulary
Episode one full generation
Reward R(x, y) from the reward model, assigned at the
final token (+ small per-token KL penalty)
The policy gradient theorem says the expected reward gradient is E[∇log π(a|s) · A], where A is an advantage estimate. Estimating A needs a value function, so PPO for LMs loads a second copy of the model with a value head (the "critic"). Memory math: policy (bf16) + reference (bf16) + critic (bf16) + reward model ≈ 4× model weights, which is why RLHF at 70B is a data-center job.
PPO Clipped Objective¶
Vanilla policy gradients take destructive steps when a single batch happens to look great. PPO limits how far one update can move the policy:
ratio r(a, s) = pi(a|s) / pi_old(a|s) # how much more likely the
# new policy makes this action
L_clip = E[ min( r * A,
clip(r, 1 - eps, 1 + eps) * A ) ]
eps ~ 0.2: if the update already changed r by more
than 20%, extra improvement in that direction is
discarded instead of rewarded with a bigger step.
The min makes the objective a pessimistic bound: updates that would help are clipped, updates that would hurt are not encouraged either. This is the main reason PPO survives LLM training where REINFORCE diverges.
KL Constraint¶
Every training batch adds a penalty proportional to how far the current policy has drifted from the frozen SFT reference:
per-token penalty: -beta * KL( pi(y|s) || pi_ref(y|s) )
typical beta: 0.02 - 0.2
Total reward = R_rm(x, y) - beta * sum_t KL_t
The KL term is what makes RLHF alignment rather than plain reward maximization: it trades a little reward for staying in-distribution, preserving fluency and instruction-following learned during SFT.
KL Divergence and Reward Hacking¶
The reward model is an imperfect proxy for human judgment. Optimize it hard enough and the policy finds inputs where the proxy is confidently wrong — reward hacking:
Classic hack patterns
- Length inflation: longer responses score higher in RM training data
- Sycophancy: agreeable preambles ("Great question!") correlate
with human ratings
- Formatting abuse: heavy markdown/bullets mimics training data style
- Repetition loops: certain token sequences are locally high-reward
- Distribution drift: policy leaves the RM's training distribution;
RM extrapolates, exploitably
Detection and mitigation:
# Watch these metrics every logging step:
# 1. mean KL vs reference -> creeping up = drift
# 2. mean reward (RM score) -> up while eval quality flat = hacking
# 3. held-out win rate vs SFT -> the ONLY ground truth
# 4. output length distribution -> sudden shift = length hack
# Mitigations, in order of practicality:
# - raise beta when KL slope steepens
# - early-stop on eval win-rate plateau
# - ensemble / refresh reward model with on-policy negatives
# - clip or normalize final reward
The tell-tale training curve: reward climbs steadily while held-out win rate plateaus (or falls) around step N. Past that point you are optimizing the proxy, not the objective.
RLHF vs DPO¶
| Dimension | RLHF (PPO) | DPO (5201) |
|---|---|---|
| Models in memory | Policy + ref + critic + RM (4×) | Policy + ref (2×) |
| Sampling during training | Online generation per batch | None — offline dataset |
| Hyperparameter sensitivity | High (lr, beta, eps, batch) | Low-moderate (beta, lr) |
| Engineering complexity | High: 4 models, rollout infra | Low: one trainer loop |
| Reward model reusability | Yes — reusable for filtering/RM-guided decoding | No explicit RM |
| Ceiling | Highest when tuned well (ChatGPT-class) | Matches RLHF on many benchmarks |
| Failure signature | Reward hacking, KL blowup | Overfitting to preference noise |
Decision heuristic:
Use RLHF when:
- You already operate a reward model (moderation, ranking, filtering)
- You have an RL-infra team and GPU budget for 4x memory
- You need online improvement from fresh interactions (RLAIF loops)
Use DPO when:
- First alignment pass on a new model (cheaper, stabler)
- Preference data is static and offline
- Team is small; PPO tuning expertise unavailable
In practice many production pipelines do both: a DPO pass for the bulk of alignment, then a short RLHF stage for the last few points of quality.
Hands-On: Minimal RLHF with TRL¶
PPO is no longer on TRL's stable surface — the v1.x docs have no PPO page; the trainer now lives in trl.experimental.ppo on main (the same move 5202 records). That fragility is itself part of the lesson: four moving parts per step make PPO the heavyweight path, so reach for it only when you truly need on-policy improvement from fresh interactions.
# PPO is the heavyweight path: policy + reference + reward model +
# value model, four moving parts per step
from transformers import (
AutoModelForCausalLM,
AutoModelForSequenceClassification,
AutoTokenizer,
)
from trl.experimental.ppo import PPOConfig, PPOTrainer # TRL main, experimental
from datasets import load_dataset
# 1. Policy: a PLAIN causal LM — no value-head wrapper in the modern API.
# ref_model=None -> the trainer copies the policy as the frozen reference.
# 2. Reward: the Stage-2 model becomes the scoring function.
reward_model = AutoModelForSequenceClassification.from_pretrained(
"your-org/rm-ckpt", dtype="bfloat16")
# 3. Value: a small causal LM carries the critic's advantage estimate.
value_model = AutoModelForCausalLM.from_pretrained(
"your-org/sft-model", dtype="bfloat16")
tokenizer = AutoTokenizer.from_pretrained("your-org/sft-model")
tokenizer.pad_token = tokenizer.eos_token
# Prompts only — completions are generated ON POLICY each step, inside
# the trainer loop (the old generate()/step() dance is gone)
dataset = load_dataset("json", data_files="prompts.jsonl")["train"]
config = PPOConfig(
output_dir="ppo-ckpt",
learning_rate=1e-6, # PPO lr is TINY
response_length=256,
)
trainer = PPOTrainer(
args=config,
model="your-org/sft-model", # the policy
ref_model=None, # None -> trainer copies the policy
reward_model=reward_model, # the Stage-2 model as scoring function
value_model=value_model, # the critic
train_dataset=dataset,
processing_class=tokenizer,
)
trainer.train()
What to watch in the logs: the KL term against the frozen reference (spiking means instability — it is the drift constraint that keeps the policy anchored), the mean reward (drifting up too fast while eval stalls = hacking), and the clipping ratio (hovering near 1.0, evidence the clipping region is being respected).
Known Failure Modes¶
1. Reward model overfit
Symptom: train preference accuracy >90%, eval win rate flat
Fix: fewer epochs, more data, stronger regularization
2. KL collapse (policy -> reference)
Symptom: rewards and outputs become identical to SFT
Fix: lower beta; check that advantage normalization is on
3. Entropy collapse
Symptom: temperature of outputs collapses, repetitive text
Fix: entropy bonus, smaller lr, fewer ppo_epochs
4. Critic divergence
Symptom: value loss explodes, advantages become noise
Fix: separate (lower) critic lr, gradient clipping
5. Length hack
Symptom: mean completion length grows monotonically
Fix: length-normalized reward, length-balanced RM data
Summary¶
RLHF is the alignment method behind ChatGPT, Claude, and Llama-2-Chat: collect human preference judgments, distill them into a learned reward model, then optimize the policy against that reward with PPO, constrained by KL divergence so the model does not drift from its supervised start. This lesson walked the full pipeline - reward model training, PPO optimization, and the KL constraint that prevents reward hacking - then compared RLHF against DPO honestly and built a minimal TRL implementation hands-on. The known failure modes section is the practical core: reward hacking, distribution collapse, and the operational weight of training two models.
References¶
Related Minder Academy Documents¶
- 5201: DPO (Direct Preference Optimization) Theory
- 5202: Alignment Orchestration - Reward Modeling vs Direct Preference
- 5204: Preference Dataset Creation
Next Steps¶
- Continue with: 5204: Preference Dataset Creation
- Assessment: 5200: Alignment Methods - Quiz