5.9 Preference learning: RLHF and DPO
1. Learn
Section titled “1. Learn”- Stanford CS336: Language Modeling from Scratchlecture 15 "Alignment - SFT/RLHF" (May 20, slides), the RLHF and DPO part
- Ouyang et al., Training language models to follow instructions (InstructGPT)sections 1 and 3
- Rafailov et al., Direct Preference Optimizationsections 4–5
2. Bridge
Section titled “2. Bridge”Comparisons. Writing the ideal answer is hard; saying which of two answers is better is easier and more consistent. The Bradley–Terry model turns comparisons into a scalar score: P(a preferred to b) = σ(r(a) − r(b)), module 2.3’s logistic regression, trained with 1.5’s cross-entropy, on score differences. A reward model is a language model with a scalar head, trained on human comparisons with this loss (Christiano et al. 2017 introduced the approach for deep RL).
RLHF. InstructGPT then optimised the SFT model with PPO to maximise the reward model’s score, minus β times the KL divergence from the SFT model, so that the policy cannot drift into text that fools the reward model (Ouyang et al. 2022, section 3). This needs four models in memory (policy, reference, reward model and a value function) and sampling during training.
DPO. That objective has a closed-form optimum: the reference reweighted by er/β. Solving it for r expresses the reward through the policy itself, and substituting into Bradley–Terry gives a classification loss on preference pairs. No reward model, no sampling: just two forward passes per model per pair (Rafailov et al. 2023, sections 4–5). The gradient weights each pair by how wrongly the policy currently ranks it.
Caveats. DPO is trained on fixed pairs, usually collected from other models; pairs sampled from the policy being trained (on-policy data) tend to help, as do repeated rounds. With few or deterministic preferences it can push probabilities to extremes, which is what β and early stopping restrain. CS336 Assignment 5 implements the per-pair DPO loss (assignment5-alignment).
3. Explore
Section titled “3. Explore”stubs/m5_9_dpo.pyLoading starter file…
Prefer your own editor? Edit exercises/stubs/m5_9_dpo.py and run mlc check 5.9. The tests are identical; import the results on the progress page.
Then run DPO on your model. Open notebooks/5.9-dpo.ipynb on Kaggle with a GPU and paste in your 4.6, 5.8 and 5.9 files. It pretrains and fine-tunes your GPT as in 5.8, collects on-policy pairs (the correct answer against the model’s own wrong one), checks a PyTorch DPO loss against your functions, trains with it, and compares accuracy on held-out words before and after.
5. Check
Section titled “5. Check”- not yet: All tests pass (0/?)
- not yet: Checkpoint quiz ≥ 80%
Learner log: time spent and points of confusion
Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.