The RL to RLHF Bridge
RLHF is RL with humans as the reward function. ChatGPT was the moment the world realized RL had broken into the mainstream, and it works because chess-playing optimization methods turned out to be perfect for fine-tuning LLMs. The agent is the LLM. The action is the next token. The reward is a human preference. Same math, applied to the most important problem in AI: making models do what we actually want.
After this lesson, you will be able to:
- Map every RL concept onto LLM alignment: the LLM is the agent/policy, the prompt is the state, each generated token is an action, and the reward model provides the scalar reward at the end of each response
- Walk through all three stages of the full RLHF pipeline: supervised fine-tuning (SFT) on demonstrations, reward model training on Bradley-Terry pairwise comparisons, and PPO optimization with a KL divergence penalty against the SFT reference model
- Understand reward hacking in RLHF, why optimizing a proxy reward model diverges from true human preferences (Goodhart's Law), and the mitigations: KL penalty, conservative optimization, and reward model ensembles
- Know the newer alternatives to full RLHF: DPO eliminates the separate reward model; GRPO eliminates the value network; Constitutional AI uses the model itself to critique responses, and understand what each gives up vs standard RLHF
Before you start
#From Games to Language
This is the bridge lesson, the one that connects everything you have learned about reinforcement learning to the technology behind ChatGPT and many other aligned language models.
#The Problem: Why Pretrained LLMs Need Alignment
A pretrained language model (like GPT-3 base) is an extraordinary next-token predictor. But next-token prediction is not the same as being helpful:
- It mimics training data, including toxic, biased, and false content
- It does not know what humans want: it predicts the most likely continuation, which might be anything
- It can be inconsistent: the same question may get contradictory answers depending on prompt framing
- It does not refuse harmful requests: it just generates the most probable text
#The Three-Stage Pipeline
#RLHF Pipeline: End-to-End Process
#Step 1: Pretrained LLM
Start with a large language model pretrained on internet-scale text data. This model is an extraordinary next-token predictor, it has learned grammar, facts, reasoning patterns, and coding ability from trillions of tokens. But it is unaligned: it will happily generate toxic content, follow harmful instructions, or produce confident misinformation.
The pretrained model is the raw material. It has capability but no alignment. It does not know what humans want, it only knows what text is likely.
#Step 2: Supervised Fine-Tuning (SFT) on Demonstrations
Fine-tune the pretrained model on thousands of high-quality (prompt, response) pairs written by human demonstrators. The model learns the format of helpful responses: how to follow instructions, structure answers, and maintain a helpful tone.
SFT is standard supervised learning, maximize the probability of the human-written tokens. This creates the SFT model, which can follow instructions but is limited to imitating the demonstrations. It cannot generalize beyond what was explicitly shown.
#Step 3: Collect Human Preference Pairs
Generate multiple responses to the same prompt using the SFT model. Show pairs of responses to human labelers and ask: "Which response is better?" Labelers choose based on helpfulness, accuracy, safety, and overall quality.
This creates a dataset of preference pairs: (prompt, chosen_response, rejected_response). Tens of thousands of these comparisons capture nuanced human values that would be impossible to encode as explicit rules.
#Step 4: Train Reward Model on Preferences
Train a neural network (typically the same architecture as the LLM, with a scalar output head) on the preference data. The reward model learns to assign higher scores to responses that humans preferred. It uses the Bradley-Terry pairwise ranking loss: maximize the probability that the preferred response scores higher.
The reward model becomes an automated proxy for human judgment, it can evaluate millions of responses at machine speed, enabling the RL training loop.
#Step 5: PPO Fine-Tune LLM Against Reward Model
Apply PPO to fine-tune the SFT model to maximize the reward model's score, with a KL divergence penalty that prevents the policy from straying too far from the SFT model. The LLM is the agent, each generated token is an action, and the reward comes from the reward model at the end of the response.
The KL penalty is the safety net: without it, the model would exploit reward model weaknesses, generating gibberish that scores high. With it, the model stays grounded while shifting toward responses humans prefer.
#Step 6: Aligned LLM
After PPO training, the model consistently produces responses that align with human preferences: helpful, accurate, safe, and well-structured. It has internalized the patterns of "good" responses beyond what the original demonstrations covered.
The aligned model is deployed to users. Ongoing monitoring, red-teaming, and iterative RLHF cycles continue to improve alignment. The pipeline is not a one-time process, it is a continuous loop of collecting feedback, training reward models, and refining the policy.
Step through the four stages: pretraining, supervised fine-tuning, the reward model, and the PPO stage. Notice which networks are being trained at each stage and which are frozen.
#Stage 1: Supervised Fine-Tuning (SFT)
Start with the pretrained base model and fine-tune it on a dataset of high-quality (prompt, response) pairs written by human demonstrators. This gives the model a starting point: it learns the format of helpful responses, how to follow instructions, and basic quality standards.
#Stage 2: Reward Model Training
The reward-model loss, its gradient and the Bradley-Terry model behind it are derived step by step in RLHF & DPO: Aligning LLMs with Human Preferences.
The reward model takes a (prompt, response) pair and outputs a scalar score. Higher score = better response according to human preferences. This model becomes the automated judge that replaces human raters during PPO training.
Why train a reward model instead of just using human raters directly during PPO training?
PPO requires evaluating hundreds of thousands to millions of responses during training. Human labelers can rate perhaps hundreds per day. The reward model is a scalable proxy for human judgment, it is not perfect, but it can evaluate responses instantly, enabling the RL training loop to run at machine speed.
#Stage 3: PPO Fine-Tuning
Now apply PPO (from the PPO lesson) to fine-tune the language model to maximize the reward model's score, with a crucial constraint: do not stray too far from the SFT model.
The KL divergence penalty is critical. Without it, the model would learn to exploit weaknesses in the reward model, generating gibberish that happens to score high, or repeating phrases the reward model likes regardless of the question. The KL penalty says: "maximize reward, but stay close to a known-good model."
Visualize how PPO shifts the language model's policy distribution during RLHF. The policy starts close to the SFT model (reference), and PPO gradually adjusts action probabilities to maximize the reward model score. Watch how the KL constraint keeps the policy from drifting too far, this is the same mechanism that prevents ChatGPT from generating degenerate outputs.
#The Token-Level MDP and the Per-Token KL Penalty
The KL penalty in the objective above is written for whole responses, yet PPO wants a reward at every token. The two derivations below show that these are the same thing, and that the penalty is a reward you can hand out token by token. Three neighbouring results are not re-derived here. The clipped probability ratio is derived in Proximal Policy Optimization. The critic loss, the TD advantage and GAE, which in RLHF run over tokens with gamma = 1 and a value head on the same transformer, are derived in Actor-Critic Methods: A2C, A3C, and IMPALA. That the KL is never negative is derived in Information Theory & Entropy.
Now the penalty can be spent token by token. This is the version implemented in RLHF code: a per-token reward equal to minus beta times the log-ratio, plus the reward model's score on the last token.
In practice the log-ratio of the one sampled token is used as the single-sample estimate of each KL term. That estimate can be negative on a given token and is noisy; the unbiased, never-negative alternative is derived in GRPO & DeepSeek R1: Training Reasoning Models.
#Mapping RL Concepts to RLHF
Let us make the mapping explicit:
| RL Concept | RLHF Equivalent |
|---|---|
| Agent | The language model |
| Environment | The prompt + user expectation |
| State | Tokens generated so far: (prompt, response_so_far) |
| Action | Next token to generate |
| Action space | The entire vocabulary (~50,000-100,000 tokens) |
| Policy | The LM's token probability distribution |
| Episode | Generating one complete response |
| Reward | Reward model score (given at end of response) |
| Discount factor | Typically gamma=1.0 (no discounting within a response) |
| Value function | Estimates expected reward from partial response |
| Advantage | How much better a token choice is vs. average |
| PPO clipping | Prevents catastrophic updates to the LM |
| KL penalty | Trust region, stay close to the SFT model |
#The Reward Model Problem
The reward model is the linchpin of RLHF, and its limitations define the limits of the entire approach:
#Reward Hacking
The policy can find responses that score high with the reward model but are not actually good. Examples:
- Sycophancy: Agreeing with the user regardless of correctness (because agreeable responses get higher human ratings)
- Verbosity: Longer responses score higher (because raters associate length with quality)
- Hedging: Adding excessive caveats to avoid low ratings on controversial topics
- Gaming patterns: Discovering specific phrases or formats that the reward model favors
#Mitigations
- KL penalty: Limits how far the policy can go, preventing extreme reward hacking
- Reward model ensembles: Use multiple reward models; only trust predictions where they agree
- Conservative optimization: Perform limited PPO steps to avoid over-optimization
- Iterated RLHF: Periodically retrain the reward model on the current policy's outputs
- Constitutional AI: Use the model itself to critique and revise responses before human rating
#Best-of-n: the Price of Optimisation
The simplest way to use a reward model needs no RL at all: draw n responses from the reference model and keep the one with the highest reward. This best-of-n policy is a clean yardstick for the KL penalty, because its distance from the reference has a closed form.
Best-of-n is also the idea behind rejection-sampling fine-tuning: sample many responses, keep the ones whose reward passes a threshold, and run ordinary SFT on the survivors. That is exactly a policy-gradient step with a 0 or 1 reward.
After the first step the samples are no longer from the current policy, so repeated rounds are off-policy; that is why rejection sampling is run in rounds, re-sampling from the updated model each time.
#Beyond RLHF: Modern Alternatives
#DPO: Direct Preference Optimization
DPO (Rafailov et al., 2023) eliminates the reward model entirely. It directly optimizes the language model on preference data, showing that the RLHF objective can be reparameterized into a supervised loss:
DPO is simpler (no reward model, no PPO), more stable (supervised loss), and often achieves comparable results. It has become the default for many alignment applications.
Deriving DPO from the RLHF objective
The DPO loss above is not a heuristic. It follows from three results, and all of them are derived step by step in RLHF & DPO: Aligning LLMs with Human Preferences: the optimal policy of the KL-regularised objective, the implicit reward that this policy defines, and the cancellation of the normaliser in the Bradley-Terry loss. This section states them and shows how they fit together.
The normaliser Z(x) is a sum over every possible response, which is far too large to compute. This is the same Boltzmann form that shows up in maximum-entropy RL (Soft Actor-Critic).
The first term is a log-ratio the policy can compute on the fly. The second term, beta log Z(x), depends only on the prompt x.
This is the same expression we wrote down in the DPO section above. Each piece has a meaning: the log-ratio of pi_theta to pi_ref is the implicit reward up to the factor beta, beta is the inverse temperature that controls how far the policy may move from pi_ref, and sigma with a minus log is the Bradley-Terry loss. The reward model never had to exist; it has been re-parameterized into the policy itself.
β → larger allowed divergence from π_ref → more aggressive optimization, but more risk of exploiting any flaw in the preference dataset (the DPO analog of reward hacking). Larger β → policy stays close to π_ref → safer, but slower preference learning. This is exactly the role β played in the PPO-RLHF KL penalty, same hyperparameter, same trade-off, just expressed through the algebra differently. In practice, β for DPO is usually in the range 0.1–0.5.In the DPO loss, what happens as β → 0?
y_w and y_l in the training data, if those responses are very far from what the policy would naturally produce, the loss surface gets weird, and (c) multi-step credit assignment (per-token credit for long responses) is harder than in PPO, which has a value function for exactly this purpose. DPO can also degrade when the preference data is noisy or when y_w and y_l are too similar (the Bradley-Terry log-likelihood bound becomes loose); these failure modes motivated the entire DPO family (IPO, KTO, ORPO, SimPO, CPO) covered in the next section. Each one patches a specific weakness in vanilla DPO: IPO fixes over-optimization on near-deterministic preferences, KTO removes the pairwise data requirement, ORPO and SimPO eliminate the frozen reference model, CPO drops the explicit KL term and replaces it with an SFT regularizer. None of them change the core idea, they all train directly on preference data using a closed-form parameterization of the policy.#GRPO: Group Relative Policy Optimization
The PPO problem with reasoning
s. In conversational alignment that's already painful (the reward signal is the whole response, so V has to integrate over a giant action space). For reasoning, math proofs, code that has to compile, multi-step logic, the critic is much harder still. The "value" of a partially-completed math derivation is not a smooth function of the tokens written so far; it's effectively binary (this proof will work / this proof will fail), with a huge variance regime in between. Training a critic to estimate this reliably eats compute, requires its own hyperparameters, and is a leading source of PPO training instabilities in reasoning RLHF. GRPO's question: can we kill the critic entirely?GRPO's trick: the group itself replaces V(s)
x, sample G completions y_1, ..., y_G from the current policy. Score each with the reward model (or a rule-based reward): r_1, ..., r_G. Now use the within-group mean and standard deviation as a state-dependent baseline:The zero mean and unit variance of this advantage are derived in GRPO & DeepSeek R1: Training Reasoning Models.
lambda to tune. The only new hyperparameter is G (group size), typically 4 to 64.Why this is a valid baseline
b(s) of the state from the advantage does not bias the policy gradient. Formally,This identity is derived in Policy Gradient Methods, and again for a group-mean baseline in GRPO & DeepSeek R1: Training Reasoning Models.
x. The baseline b(x) = mean_i(r_i) is the empirical mean of rewards over the G samples drawn for this prompt, a noisy estimator of the true E_{y ~ π}[r(x, y)], which is exactly V^π(x) for the prompt-conditioned MDP. The group mean is a Monte Carlo estimate of the critic's target. So GRPO is provably unbiased: the group mean is a valid baseline because (a) it depends only on the prompt, not on the specific completion within the group, and (b) it converges to the true V^π(x) as G → ∞.Variance reduction via std normalization
[0.8, 1.0] (all completions are decent); a hard prompt might give [-3.0, +5.0] (some completions are great, some are terrible). Without normalization, gradient updates from the hard prompt dominate gradient updates from the easy prompt purely because the magnitudes differ. Dividing by σ_r makes the advantage scale-invariant across prompts, both prompts contribute comparable-magnitude advantages, and the optimizer treats them equally. This is the same trick advantage-normalization-per-mini-batch performs in standard PPO, just applied at the group level instead of the batch level.The unit variance claim is derived in GRPO & DeepSeek R1: Training Reasoning Models; the next formula, RLOO, is new here and is derived right after it.
Connection to RLOO (Leave-One-Out)
y_i, the baseline is the mean reward of the other G-1 completions, with no std normalization:The Cohere paper reports that RLOO matches or exceeds PPO on alignment benchmarks while being simpler, same headline as GRPO. In practice the two algorithms are very close: both eliminate the critic, both use within-group statistics as the baseline, and the choice between them is a hyperparameter decision rather than a conceptual one. Empirically, GRPO's std-normalization helps more on reasoning tasks (where reward variance differs sharply across prompts of varying difficulty); RLOO's leave-one-out is cleaner on dialogue alignment (where rewards are roughly equally noisy per prompt).
DeepSeek-R1: the no-critic, no-reward-model reasoning recipe
GRPO's biggest impact has been in the DeepSeek-R1 training recipe (DeepSeek-AI 2025), which strips out every learned component except the policy itself:
- No critic. GRPO's group mean replaces V(s).
- No reward model. Rewards come directly from rule-based verifiers: math problems are scored by checking whether the final boxed answer equals the ground truth; code problems are scored by running the code and checking unit tests; format rewards check that the response contains
<think>...</think>reasoning sections. No human preference data, no Bradley-Terry, no reward-model training run. - No PPO state-action ratios beyond the policy ratio. GRPO uses PPO's clipped surrogate
min(r_t A_t, clip(r_t, 1-ε, 1+ε) A_t)over the policy ratior_t = π_θ(y_t|x, y_{<t}) / π_{old}(y_t|x, y_{<t}), but there's no value-function clipping (no critic), no GAE, no separate value-loss coefficient.
<think> traces, self-correct, and verify its own work, all from the rule-based reward signal alone. This was a major surprise to the alignment field: prior to DeepSeek-R1, the conventional wisdom was that strong reasoning required either (a) lots of human-curated reasoning demonstrations or (b) a powerful preference-based reward model. GRPO + rule-based rewards skipped both.The policy-gradient objective with a 0 or 1 verifier reward is the one derived in GRPO & DeepSeek R1: Training Reasoning Models, and the reasons that outcome rewards and best-of-n sampling pay off are in Reasoning Models & Test-Time Compute.
#Constitutional AI (CAI)
Anthropic's approach: instead of relying solely on human raters, use the AI model itself to identify harmful outputs. The model critiques its own responses according to a set of principles (the "constitution"), revises them, and the revised responses become training data. The training objective is the same RLHF objective as above with AI-written preference labels, so no new formula appears (see RLHF & DPO: Aligning LLMs with Human Preferences).
#RLAIF: RL from AI Feedback
Replace human raters entirely with AI judges. Use a powerful model (e.g., GPT-4) to evaluate responses from a smaller model being trained. This dramatically reduces the cost of collecting preference data but introduces the risk of "distilling" the judge model's biases. The objective is unchanged: only the source of the preference labels moves from humans to a model, so the reward-model loss and the KL-regularised optimum are exactly those derived in RLHF & DPO: Aligning LLMs with Human Preferences.
#The DPO family: IPO, KTO, ORPO, SimPO, CPO
| Method | Year | Core idea | Data format | Reference model needed? | Trade-off |
|---|---|---|---|---|---|
| DPO | 2023 | Reparameterize RLHF as supervised pairwise loss on (chosen, rejected) | Pairwise preferences | Yes (frozen SFT) | Simple, but overfits to preference dataset; no online exploration |
| IPO (Azar 2023) | 2023 | Replace DPO's log-sigmoid with a squared-loss "identity" preference objective | Pairwise preferences | Yes | Bounded loss prevents the over-optimization DPO suffers when preferences are deterministic |
| KTO (Ethayarajh 2024) | 2024 | Drop pairwise labels, use unpaired "this response was thumbs-up/down" labels via a prospect-theoretic Kahneman-Tversky utility | Binary thumbs-up / thumbs-down (NOT pairs) | Yes | Cheaper data collection (no need to compare pairs), but slightly weaker signal than DPO when paired data is available |
| ORPO (Hong 2024) | 2024 | Combine SFT + preference learning in one stage by adding an odds-ratio penalty to the standard SFT loss | Pairwise preferences | No (reference-free) | Now the default in TRL, eliminates the frozen reference model, halving memory; works in a single training stage instead of SFT-then-align |
| SimPO (Meng 2024) | 2024 | Reference-free DPO using length-normalized average log-probability as the implicit reward | Pairwise preferences | No | Reduces memory and length bias; often matches or beats DPO on Arena-Hard, AlpacaEval |
| CPO (Contrastive Preference Optimization) | 2024 | Drop the reference KL term and add an explicit SFT term to keep the policy grounded | Pairwise preferences | No | Faster, smaller memory footprint; first deployed for machine translation by Haoran Xu et al. |
#SimPO: a Margin Loss Without a Reference Model
SimPO changes DPO in three ways at once: no reference model, a reward divided by response length, and a target margin. The derivation below shows that these are three small edits to the Bradley-Terry loss already derived in RLHF & DPO: Aligning LLMs with Human Preferences.
What is the main advantage of DPO over the full RLHF pipeline?
DPO's main advantage is simplicity: it collapses the reward model + PPO stages into a single supervised training step. There is no reward model to train, no PPO hyperparameters to tune, no value function to estimate. The tradeoff is that DPO cannot adapt the reward signal during training (it is fixed by the preference dataset), while RLHF with PPO can dynamically explore and exploit the reward landscape.
#The Bigger Picture: Alignment and Safety
RLHF is not just a training technique, it is the first practical approach to the AI alignment problem. The question "how do we make powerful AI systems do what humans want?" has been debated for decades. RLHF provides a concrete (if imperfect) answer:
- Specify preferences through human comparisons (not through hand-coded rules)
- Learn a reward model that captures these preferences (not perfect, but scalable)
- Optimize the model to satisfy learned preferences while staying grounded (KL penalty)
This is not a solved problem. Reward hacking, sycophancy, inconsistent human preferences, scalable oversight of superhuman systems, these remain open challenges. But RLHF turned alignment from a philosophical question into an engineering one, and that is profound.
#Try It Yourself
Tests: Verify the reward model assigns a higher score to 'helpful great' than to 'sorry long response'. Verify the length weight is negative (shorter is preferred).
#Key Takeaways
- RLHF maps RL concepts onto LLM alignment. The LLM is the agent/policy, the prompt is the state, the generated text is the action, and human preference is the reward signal
- The RLHF pipeline has three stages. Supervised fine-tuning (SFT) teaches format, reward model training captures human preferences, and PPO optimization maximizes the reward while staying close to the base model via KL constraints
- KL divergence constraints prevent reward hacking. Without the KL penalty, the model finds degenerate outputs that score high on the reward model but are meaningless to humans; the constraint keeps the model close to its pretrained behavior
- DPO and GRPO are emerging alternatives to PPO. Direct Preference Optimization eliminates the separate reward model by optimizing preferences directly, simplifying the pipeline while achieving comparable alignment quality
#Quick Check
In the RLHF pipeline, what does the reward model learn from?