Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI
Turning 'predict the next token' into 'be helpful, honest and harmless'
Pretraining produces a model that imitates the internet; alignment produces one that behaves the way people want. The methods — reward models, PPO, DPO, GRPO — are where the reinforcement learning of 4.11 Reinforcement learning essentials and the KL divergence of 1.9 Information theory: entropy, cross-entropy and KL divergence become the decisive tools of the field. They are also the engine of reasoning models (8.6 Reasoning models and test-time compute) and the reason evaluation (8.7 Evaluating LLMs) and safety (8.12 Safety, risks and responsible AI) are so hard: what gets optimized is a learned proxy for what we want.
You'll be able to
- Explain why preference data is easier to collect than demonstrations and how a Bradley–Terry reward model is trained
- Write the KL-regularized RLHF objective and explain the role of β and the reference model
- Derive the DPO loss from the closed-form optimal policy
- Describe GRPO and RL with verifiable rewards, and contrast them with PPO-based RLHF
- State what alignment training does and does not guarantee
Key ideas
- Comparisons are easier to collect than demonstrations; a Bradley–Terry reward model turns them into a scalar score via P(y_w ≻ y_l) = σ(r_w − r_l).
- RLHF maximizes expected reward minus β·KL(π‖π_ref); the KL term prevents exploiting the reward model's errors.
- PPO-based RLHF needs four large models (policy, reference, reward, critic) and is prone to over-optimization and sycophancy.
Show 4 more key ideas
- DPO substitutes the closed-form optimal policy into the Bradley–Terry likelihood, so the partition function cancels and alignment becomes a classification loss on preference pairs.
- GRPO drops the critic by normalizing rewards within a group of sampled responses; with verifiable rewards it is the engine of reasoning models.
- Constitutional AI / RLAIF replace many human labels with model critiques guided by explicit principles.
- Alignment shapes behavior on-distribution; jailbreaks, reward hacking, sleeper agents and alignment faking show its limits.
Suggested path through this lesson
Why imitation is not enough
SFT (8.2 Fine-tuning and PEFT) trains the model to reproduce demonstrations. But demonstrations are expensive, inconsistent, and bounded by what the demonstrator can write. Comparisons are easier than demonstrations: a person who could never write a great proof can still tell which of two attempts is better. Reinforcement learning from human feedback (RLHF) turns such judgments into a training signal. InstructGPT (2022) established the recipe behind ChatGPT: SFT → reward model → RL.
Step 1: a reward model from preferences
Collect prompts with two responses, a preferred and a rejected . The Bradley–Terry model says the probability of preferring depends on the difference of latent scores:
Train a reward model (an LLM with a scalar head) by maximum likelihood on the comparisons:
Only differences matter: adding a constant to changes nothing, which is why reward values are not comparable across prompts. Reward models are themselves imperfect classifiers (agreement with humans is often in the 70–80% range), and that imperfection is the root of what follows.
Step 2: the RLHF objective
The policy is the LLM itself. We want high reward without drifting far from the SFT reference model :
The KL term (1.9 Information theory: entropy, cross-entropy and KL divergence) is the safety rail: a reward model is only trustworthy near the data it was trained on, so wandering far from means exploiting its errors (reward hacking or over-optimization — Goodhart's law). trades off reward against conservatism. Implementations fold the KL into a per-token reward, , plus the sequence-level reward at the last token.
Optimization uses PPO (4.11 Reinforcement learning essentials): sample responses, score them, and update with the clipped surrogate
where the advantage comes from a learned value model (critic). That is four large networks in memory — policy, reference, reward, critic — and a notoriously fiddly training loop. Typical symptoms of over-optimization: verbose, flattering (sycophantic) answers that the reward model loves and humans do not.
DPO: skip the reward model
Direct Preference Optimization (2023) starts from a known fact: the KL-regularized objective above has a closed-form optimum,
with partition function . Solve for the reward:
Substitute into the Bradley–Terry likelihood — the intractable cancels in the difference — and parametrize directly by the policy :
Intuition. The policy is the reward model in disguise: is an implicit reward. The gradient raises the log-probability of and lowers that of , weighted by how badly the implicit reward currently misranks the pair. No sampling, no critic, no separate reward model — a plain supervised loss over offline comparisons, usually run with LoRA adapters (8.2 Fine-tuning and PEFT).
DPO's weakness is that it learns from a fixed dataset: if the comparisons were generated by another model, the policy never sees its own mistakes (the "off-policy" problem). Variants address different gaps:
| method | needs pairs? | reference model? | idea |
|---|---|---|---|
| PPO-RLHF | no (online samples) | yes (KL) | learned RM + RL; strongest signal, costliest |
| DPO | yes | yes | closed-form reward → classification loss |
| IPO | yes | yes | bounded loss, less overfitting to preferences |
| KTO | no (good/bad labels) | yes | prospect-theory utility; uses unpaired data |
| ORPO | yes | no | odds-ratio preference term added to the SFT loss |
| GRPO | no (verifier/RM) | yes (KL) | online RL without a critic; group-normalized advantages |
Constitutional AI and RLAIF
Human preference labels are slow, expensive and expose annotators to harmful content. Constitutional AI (Anthropic, 2022) replaces much of that with a written set of principles. In a supervised phase, the model critiques and revises its own responses against the principles; in the RL phase, AI feedback produces the preference labels (RLAIF), and training proceeds as in RLHF. The approach scales oversight and makes the governing values explicit and inspectable. Most labs now combine human and AI feedback, plus rule-based rewards for specific behaviors.
GRPO and RL with verifiable rewards
For tasks with checkable answers — math with a reference solution, code with unit tests, formats that can be validated — a learned reward model is unnecessary: the environment verifies. Group Relative Policy Optimization (DeepSeekMath, 2024) makes the RL loop cheap: for each prompt, sample a group of responses, score them , and use the group-normalized advantage
inside a PPO-style clipped objective with a KL penalty toward the reference model. The group mean replaces the critic as the baseline, removing one large network from memory. DeepSeek-R1-Zero (2025) showed that applying this to a base model with only answer-correctness and format rewards produces long chains of thought, self-verification and backtracking that nobody wrote into the data — the mechanism behind reasoning models (8.6 Reasoning models and test-time compute). Rubric-graded rewards extend the idea to less verifiable domains.
What alignment does — and does not — guarantee
Alignment training shapes behavior on the distribution it was trained on. It does not make the model understand or share human values, and it leaves known gaps: jailbreaks and prompt injection (8.12 Safety, risks and responsible AI, 10.10 Agent safety and security), sycophancy, reward hacking that generalizes in odd ways, and findings such as sleeper agents (backdoors that survive safety training) and alignment faking (models strategically complying during training). This is why evaluation (8.7 Evaluating LLMs), interpretability (8.11 Interpretability: what is happening inside) and system-level safeguards complement training rather than replace it.
Where this shows up later
- Reasoning models are GRPO-style RL on verifiable rewards scaled up — 8.6 Reasoning models and test-time compute.
- The same Bradley–Terry model ranks LLMs in human-preference arenas — 8.7 Evaluating LLMs.
- Alignment's limits motivate the safety and security lessons — 8.12 Safety, risks and responsible AI, 10.10 Agent safety and security; its mechanics reuse policy gradients from 4.11 Reinforcement learning essentials.
Common pitfalls (4)
- Treating reward-model scores as absolute quality: they are only meaningful as differences within a prompt.
- Setting β too low 'to learn faster' and getting verbose, sycophantic outputs that game the reward model.
- Running DPO on preference pairs generated by a very different model and expecting on-policy behavior to improve.
- Confusing alignment with safety guarantees — a well-aligned model still needs system-level guardrails.
Recap: all 7 key points
- Comparisons are easier to collect than demonstrations; a Bradley–Terry reward model turns them into a scalar score via P(y_w ≻ y_l) = σ(r_w − r_l).
- RLHF maximizes expected reward minus β·KL(π‖π_ref); the KL term prevents exploiting the reward model's errors.
- PPO-based RLHF needs four large models (policy, reference, reward, critic) and is prone to over-optimization and sycophancy.
- DPO substitutes the closed-form optimal policy into the Bradley–Terry likelihood, so the partition function cancels and alignment becomes a classification loss on preference pairs.
- GRPO drops the critic by normalizing rewards within a group of sampled responses; with verifiable rewards it is the engine of reasoning models.
- Constitutional AI / RLAIF replace many human labels with model critiques guided by explicit principles.
- Alignment shapes behavior on-distribution; jailbreaks, reward hacking, sleeper agents and alignment faking show its limits.
Watch
Reward model, KL penalty, PPO and the full training loop, derived and coded.
Read
Exercises
- Derive DPO yourself
Starting from the KL-regularized objective, show that the optimum is (hint: write the objective as a KL between and that distribution plus a constant). Then substitute the implied reward into the Bradley–Terry model and verify that cancels.
- DPO loss in PyTorch
Implement
dpo_loss(logp_policy_w, logp_policy_l, logp_ref_w, logp_ref_l, beta)returning the mean negative log-sigmoid loss and the implicit reward margins. Test it on synthetic numbers: the loss must decrease when the policy's log-ratio for rises. Expected: with equal log-ratios the loss is . - Train a tiny reward model
With TRL's reward trainer and a small public preference dataset, fine-tune a small model with a scalar head for a few hundred steps. Report pairwise accuracy on a held-out split and inspect five disagreements by hand. Expected: accuracy well above 50% but far from 100% — the imperfection that makes KL regularization necessary.
- GRPO on arithmetic
Using TRL's GRPO trainer (or an Unsloth notebook) and a small instruct model, define a reward of 1 for a correct final answer on simple arithmetic word problems and a small bonus for a required answer format. Train briefly and plot reward and mean response length. Expected: the format reward is learned almost immediately; correctness improves more slowly and responses lengthen.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →