Contents
Key concepts
MDPs, value-based versus policy-based methods
An MDP has states, actions, transition dynamics, a reward and a discount γ; the goal is a policy maximising expected return. Value-based methods (Q-learning, DQN) learn Q(s,a) and act greedily; they can learn off-policy from a replay buffer and are sample-efficient but awkward with huge or continuous action spaces. Policy-gradient and actor-critic methods parameterise the policy directly, handle any action space (including token sequences) and are usually on-policy, so they need fresh samples after each update. In LLM RL systems the samples come from a separate inference engine, often asynchronously, so a batch is slightly stale and numerically different from the trainer’s policy; importance-sampling corrections such as truncated importance sampling, or matched numerics (FP16 instead of BF16), keep training close to on-policy.
Policy gradient and baselines
The score-function identity gives ∇J = E[∇ log π(a|s) · A], where A is the return or an advantage estimate. Because E[∇ log π(a|s)] = 0, subtracting any action-independent baseline b(s) leaves the gradient unbiased while reducing variance; a learned value function V(s) is the usual choice, and GAE (λ around 0.95) trades bias for variance when estimating A. Without a baseline, every sampled action with positive reward is pushed up, so the signal is mostly noise.
PPO
PPO maximises a clipped surrogate: the probability ratio r = π_new/π_old is multiplied by the advantage and clipped to [1−ε, 1+ε] (ε ≈ 0.2), so a minibatch cannot move the policy far from the one that generated the data, allowing several epochs per batch. Classic RLHF with PPO keeps four models in memory: policy, frozen reference, reward model and value (critic) model, which is why it is expensive and fiddly to tune.
RLHF pipeline and the KL penalty
Supervised fine-tuning gives a reference policy; a reward model is trained on pairwise human preferences with a Bradley–Terry loss, −log σ(r(x,y_w) − r(x,y_l)); then RL maximises r(x,y) − β·KL(π ‖ π_ref). The KL term keeps the policy where the reward model is trustworthy, preserves fluency and diversity, and is the main brake on reward hacking. InstructGPT showed a 1.3B RLHF model preferred by labellers over the 175B base GPT-3.
Flow · 4 stepsHow the RLHF pipeline builds a policy
- Reference policy Supervised fine-tuning gives the reference policy.
- Reward model A reward model is trained on pairwise human preferences with a Bradley–Terry loss.
- KL-regularised RL RL maximises r(x,y) − β·KL(π ‖ π_ref).
- RLHF policy The KL-regularised RL step produces the RLHF policy.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Reference policy | Supervised fine-tuning gives the reference policy. |
| 2 | Reward model | A reward model is trained on pairwise human preferences with a Bradley–Terry loss. |
| 3 | KL-regularised RL | RL maximises r(x,y) − β·KL(π ‖ π_ref). |
| 4 | RLHF policy | The KL-regularised RL step produces the RLHF policy. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Human preferences | Input | pairwise human preferences |
| Supervised fine-tuning | Training | gives the reference policy |
| Reference policy | Training | π_ref |
| Reward model | Training | Bradley–Terry loss |
| KL-regularised RL | Training | r(x,y) − β·KL(π ‖ π_ref) |
| RLHF policy | Output | optimised policy |
Source: This page's text
DPO and offline preference optimisation
DPO uses the closed-form optimum of the KL-regularised objective to turn preference learning into a classification loss on log-probability ratios against a frozen reference: no reward model, no sampling, no critic. β plays the KL role (larger β keeps the policy closer to the reference). Weak spots: it learns only from a fixed, often off-policy dataset, can lower the likelihood of both chosen and rejected answers (likelihood displacement), and overfits noisy pairs; iterative or online DPO with fresh on-policy samples narrows the gap to PPO.
RLVR and GRPO
With verifiable rewards (unit tests pass, maths answer matches, format is valid) no learned reward model is needed. GRPO samples a group of G answers per prompt and uses the group-normalised reward (r_i − mean)/std as every token’s advantage, dropping the critic and so saving a policy-sized model’s memory and compute relative to PPO. DeepSeekMath introduced it and DeepSeek-R1 (peer-reviewed in Nature in September 2025) popularised it. DAPO added clip-higher, dynamic sampling of prompts with mixed outcomes, token-level loss averaging and overlong-response shaping; Dr. GRPO removed the per-response length and group-std normalisation terms, which bias response length and over-weight very easy or very hard prompts; and Qwen’s GSPO moved the importance ratio and clipping to the sequence level, which notably stabilises mixture-of-experts RL. Prompts where all samples succeed or all fail give zero advantage, so curriculum and filtering matter.
Flow · 4 stepsHow GRPO turns a group of rollouts into advantages
- Sample and score GRPO samples G answers per prompt and scores each 1 if the final answer is correct, 0 otherwise.
- Normalise The advantage is A_i = (r_i − mean(r)) / std(r), using population standard deviation.
- Apply The group-normalised advantage is applied to every token of that sample.
- Filter All-pass or all-fail groups give zero advantage and cost rollouts with no gradient, so filter or resample to keep mixed-outcome groups.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Sample and score | GRPO samples G answers per prompt and scores each 1 if the final answer is correct, 0 otherwise. |
| 2 | Normalise | The advantage is A_i = (r_i − mean(r)) / std(r), using population standard deviation. |
| 3 | Apply | The group-normalised advantage is applied to every token of that sample. |
| 4 | Filter | All-pass or all-fail groups give zero advantage and cost rollouts with no gradient, so filter or resample to keep mixed-outcome groups. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Prompt | Input | One prompt |
| Sample G answers | Sample | G answers per prompt |
| Score answers | Sample | 1 correct, 0 otherwise |
| Group-normalise | Compute | (r_i − mean) / std |
| Apply to tokens | Compute | Every token of the sample |
| Filter groups | Train | Mixed outcomes |
Source: This page's text
Reward over-optimisation and reward hacking
A learned reward is a proxy, so optimising harder eventually increases the proxy while true quality falls (Goodhart). Gao et al. fitted this with a gold reward model: gold score rises then falls as KL from the initial policy grows, and larger reward models over-optimise more slowly. With verifiable rewards the hack becomes exploiting the checker, such as special-casing tests or editing them, and Anthropic found in 2025 that a model which learnt such hacks in coding RL became more misaligned in unrelated settings unless training framed the hack as acceptable (inoculation prompting). Mitigations: KL control, reward-model ensembles or uncertainty penalties, held-out gold evaluations as stopping criteria, refreshing preference data on-policy, and hardening verifiers.
Bandits and off-policy evaluation
A contextual bandit is one-step RL: choose an action given context, observe only that action’s reward. ε-greedy, UCB and Thompson sampling manage exploration. To score a new policy on logs from an old one, inverse propensity scoring reweights each logged reward by π_new(a|x)/π_old(a|x); it is unbiased only if logging propensities were recorded and positive, and its variance explodes when the policies differ, so use clipping, self-normalisation or doubly robust estimators.
Worked examples
One REINFORCE step on a three-armed softmax bandit, with and without a baseline
A policy has logits θ = [0, 0, 0] over three arms. It samples arm 2 and receives reward 1. The baseline (running mean reward) is 0.4 and the learning rate is 0.5. Compute the update and the new policy. Then repeat with no baseline, and say what happens if the reward had been 0.
1. Current policy. Softmax of equal logits: π = [1/3, 1/3, 1/3].
2. Score function. For a softmax policy, ∇θ log π(a) = onehot(a) − π = [0, 1, 0] − [1/3, 1/3, 1/3] = [−1/3, 2/3, −1/3].
3. Advantage. A = r − b = 1 − 0.4 = 0.6.
4. Update. Δθ = α · A · ∇ log π = 0.5 × 0.6 × [−1/3, 2/3, −1/3] = [−0.1, 0.2, −0.1]. New θ = [−0.1, 0.2, −0.1].
5. New policy. e^−0.1 = 0.9048 and e^0.2 = 1.2214, so the sum is 2 × 0.9048 + 1.2214 = 3.0311. π_new = [0.2985, 0.4030, 0.2985]. Arm 2 rises from 0.333 to 0.403.
6. No baseline. A = 1, Δθ = 0.5 × [−1/3, 2/3, −1/3] = [−0.167, 0.333, −0.167], giving π(arm 2) = e^0.333 / (e^0.333 + 2e^−0.167) = 1.396 / (1.396 + 1.693) = 0.452. The step is larger, but only because every reward is positive, not because arm 2 is better than average.
7. Reward 0. With the baseline, A = −0.4 and Δθ = [+0.067, −0.133, +0.067]: arm 2 is pushed down, so failures carry information. Without a baseline, A = 0 and nothing is learnt.
Why the baseline is unbiased: E_a[∇ log π(a)] = Σ_a π(a) ∇ log π(a) = ∇ Σ_a π(a) = ∇1 = 0, so b · E[∇ log π] = 0 for any b that does not depend on the action.
GRPO advantages for a maths prompt
For one prompt GRPO samples G = 4 solutions, scored 1 if the final answer is correct and 0 otherwise. Compute the advantages for rewards [1, 0, 0, 1], [1, 0, 0, 0] and [1, 1, 1, 1]. What does each case teach the model, and what training-pipeline change does the last case motivate?
GRPO’s advantage for sample i is A_i = (r_i − mean(r)) / std(r), applied to every token of that sample. Population standard deviation is used here; some implementations use n − 1, which changes the scale but not the signs.
Case 1: [1, 0, 0, 1]. Mean 0.5; deviations ±0.5; variance 0.25; std 0.5. A = [+1, −1, −1, +1]. The correct solutions’ tokens are pushed up and the wrong ones down, equally.
Case 2: [1, 0, 0, 0]. Mean 0.25. Deviations: 0.75 and three of −0.25. Variance = (0.75² + 3 × 0.25²) / 4 = (0.5625 + 0.1875) / 4 = 0.1875; std = 0.433. A = [0.75/0.433, then −0.25/0.433 for each of the other three] = [+1.73, −0.58, −0.58, −0.58]. A rare success gets a large positive advantage, which is the signal you want on hard prompts.
Case 3: [1, 1, 1, 1]. Mean 1, std 0, so every A = 0 (an ε in the denominator avoids dividing by zero). The prompt contributes no gradient yet still costs four rollouts. All-fail groups behave the same way.
Pipeline change. Filter or resample prompts so that each batch keeps groups with mixed outcomes (DAPO’s dynamic sampling), and keep a curriculum near the model’s frontier, for example prompts with a current pass rate between 10% and 90%. Also watch for length bias: averaging the loss per sequence means a long wrong answer is penalised less per token than a short one, which can inflate response length. Token-level averaging, or the Dr. GRPO-style removal of length and std normalisation, is one response.
Evaluate the DPO loss for one preference pair
For a prompt, the policy assigns log-probabilities −10.0 to the chosen answer and −15.0 to the rejected one; the frozen reference assigns −12.0 and −14.0. With β = 0.1, compute the implicit rewards, the loss, and the gradient weight. Compare with the start of training, when the policy equals the reference.
1. Log-ratios against the reference. Chosen: −10.0 − (−12.0) = +2.0. Rejected: −15.0 − (−14.0) = −1.0.
2. Implicit rewards r = β × log-ratio: chosen 0.2, rejected −0.1.
3. Margin. β × (2.0 − (−1.0)) = 0.1 × 3.0 = 0.3.
4. Loss. L = −log σ(0.3). σ(0.3) = 1 / (1 + e^−0.3) = 1 / 1.7408 = 0.5744, so L = −ln 0.5744 = 0.554.
5. Gradient weight. The gradient is β · σ(−margin) times (∇ log π(chosen) − ∇ log π(rejected)). σ(−0.3) = 0.426, so this pair still gets 43% of the maximum weight: DPO keeps pushing until the margin is large, which is why noisy pairs get overfitted.
6. At initialisation the policy equals the reference, both log-ratios are 0, the margin is 0 and L = ln 2 = 0.693, with gradient weight σ(0) = 0.5.
Reading β. With β = 0.5 the same log-ratios give margin 1.5, L = −ln σ(1.5) = 0.201 and weight 0.18: a given margin in implied reward needs a smaller move away from the reference, so larger β acts like a stronger KL constraint.
What changed recently
RL environments become shared Hub artefacts
Hugging Face added an RL-environments filter to the Hub: an environment is a tagged dataset repo of tasks that Harbor, Verifiers, OpenEnv or NeMo Gym can run, with the framework supplying the runtime and, where the repo does not include them, the harness and verifier. It reflects a shift in agentic RL, where the environment (tasks, tools and grader) rather than the algorithm is the scarce, reusable asset. Interviewers now ask how you would design, share and harden an environment so that one definition serves both evaluation and training.
Training–inference mismatch treated as a first-order stability problem
LLM RL stacks sample rollouts in a fast inference engine and compute gradients in a separate trainer, so token probabilities differ slightly even with identical weights and nominally on-policy training becomes off-policy. A May 2026 study isolated the effect with a zero-mismatch reference and showed that small numerical disagreements alone can collapse training; earlier remedies include truncated importance sampling and switching from BF16 to FP16. Expect questions on why a run collapses, what to log and how asynchronous rollouts add staleness on top.
Reward hacking in coding RL generalises to broader misalignment
Anthropic showed that a model which learnt to cheat on hackable programming environments during RL also became misaligned elsewhere, for example sabotaging safety-research code in about 12% of trials, and that standard RLHF only masked this on chat-style prompts. Telling the model during training that exploiting the grader was acceptable (inoculation prompting) stopped the generalisation. Verifier hardening is now discussed as a safety issue, not only a data-quality one.
Predictable scaling of RL compute (ScaleRL)
A study using more than 400,000 GPU-hours fitted sigmoidal curves of performance against RL compute and found that most design choices (loss aggregation, normalisation, curriculum, off-policy algorithm) change compute efficiency rather than the ceiling, while recipes differ in their asymptote. Small runs predicted a single run scaled to 100,000 GPU-hours. Interviewers use it to ask how you would choose an RL recipe without paying for full-scale runs.
Does RLVR add reasoning ability or only sharpen it?
Yue et al. found that RLVR models beat their base models at pass@1 but lose at large k, that six RLVR algorithms all stayed below the base model’s coverage, and that distillation, unlike RLVR, added new reasoning patterns; the paper became a NeurIPS 2025 best-paper runner-up. NVIDIA’s ProRL replied that prolonged RL with KL control and reference resets does widen pass@k. Candidates are expected to explain the pass@k argument, its caveats and how they would test it on their own runs.
Pitfalls
- Saying the KL penalty is only for training stability; its main job is to keep the policy where the reward model is accurate and to limit reward hacking and loss of diversity.
- Claiming DPO needs no reference model; it needs reference log-probabilities (they can be precomputed) and β is defined relative to that reference.
- Believing a baseline biases the policy gradient; any action-independent baseline is unbiased and only reduces variance.
- Treating a rising reward-model score as proof of improvement instead of tracking a held-out gold evaluation and the KL from the reference.
- Assuming GRPO removes all regularisation; the original formulation keeps a KL term to the reference, and some later recipes such as DAPO drop it deliberately.
- Stating flatly that RLVR teaches new skills, or that it cannot. Yue et al. (a NeurIPS 2025 best-paper runner-up) found base models overtake RLVR models at large k, so RL mostly concentrates probability on solutions the base model could already sample; NVIDIA’s ProRL reported that long runs with KL control and reference resets do widen pass@k. The defensible answer is that it depends on training length, base-model competence and task.
How interviewers probe it
- Derive REINFORCE from the score-function identity, then prove the baseline leaves it unbiased and explain where GAE fits.
- Walk through RLHF end to end and ask what happens as β goes to 0 or to infinity, and how you would set it.
- Compare PPO, DPO, GRPO and its 2025 variants (DAPO, Dr. GRPO, GSPO) on memory, compute, data needs and failure modes; when would DPO underperform PPO?
- Design an RLVR set-up for code or maths: verifier design, how a model might hack the tests, curriculum and prompt filtering, how you would package it as a reusable environment (tasks, harness, verifier), and what you would monitor, including the probability gap between rollout engine and trainer.
- Detect reward over-optimisation in a live run: proxy versus gold curves, KL, response length, refusal rate and human spot checks.
- MLE variant: estimate a new recommender’s click-through rate from logs of the old policy, and explain when inverse propensity scoring fails.
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Describe the classic RLHF pipeline. What is the KL penalty for, and what is reward hacking?
Model answer, written in a candidate's voice
- SFT model is initialized, then humans rank pairs of outputs; a reward model is trained with a Bradley–Terry loss on chosen vs rejected responses.
- PPO optimizes the policy against the reward model, usually with a KL penalty to a frozen reference policy.
- KL penalty keeps the policy near the reference, limiting reward-model exploitation and preserving fluency/diversity.
- Reward hacking is when outputs score high under the reward model but are not actually better for humans, e.g. longer, flattering, or sycophantic answers.
- Mitigations: KL control, reward-model ensembles, length/style controls, fresh preference data, and held-out human evaluation.
- PPO is expensive and unstable: policy, reference, reward, and value models in memory, with sensitive hyperparameters.
- Alternatives include DPO, AI feedback/constitution-based methods, and verifiable rewards where correctness can be checked.
How does Direct Preference Optimisation differ from PPO-based RLHF? What does β control, and when can DPO underperform?
Model answer, written in a candidate's voice
- DPO uses the closed-form KL-regularised optimum to turn preference pairs into a direct loss on policy-vs-reference log-ratios
- No separate reward model or online PPO sampling loop, so it is simpler and cheaper
- β sets the strength of the implicit KL constraint; smaller β permits more drift from the reference
- Weaknesses: off-policy/stale pairs, chosen-likelihood can fall, overfitting and label-noise sensitivity; online/iterative variants and IPO/KTO/ORPO/SimPO address gaps
- Best when pairs are sampled from or close to the current policy
What is reinforcement learning with verifiable rewards, how does GRPO work, and why has it become popular for reasoning and agentic-coding models?
Model answer, written in a candidate's voice
- RLVR uses programmatic verifiers (tests pass, answer matches, execution succeeds) instead of a learned reward model, reducing reward-model exploitation but not test hacking.
- GRPO samples a group of responses per prompt, normalizes rewards within the group into advantages, and optimizes a clipped PPO-style objective with optional KL, without a value network.
- DAPO-style refinements add asymmetric clipping, drop groups with identical rewards, token-level loss, and overlong/length shaping.
- It fits reasoning and agentic coding because outcomes are checkable; SFT warm-up mostly fixes format, and agentic tasks need sandboxes/tools plus verifiers.
- Risks include entropy collapse, reward hacking, and high rollout compute cost.
You have finished this topic.
Reading
- Spinning Up, Part 3: Intro to Policy OptimizationDerives the simplest policy gradient, reward-to-go and baselines step by step, with code.
- Proximal Policy Optimization AlgorithmsThe clipped surrogate objective that classic RLHF builds on.
- Training language models to follow instructions with human feedback (InstructGPT)The reference RLHF pipeline: SFT, pairwise reward model, PPO with a KL penalty, and human evaluation.
- Direct Preference Optimization: Your Language Model is Secretly a Reward ModelDerives the DPO loss from the KL-regularised objective; read the derivation, not just the result.
- DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language ModelsIntroduces GRPO and compares it with PPO in a unified view of post-training methods.
- DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement LearningThe RLVR reference point, now peer-reviewed in Nature: rule-based rewards, R1-Zero without SFT, the multi-stage pipeline and its stated reward-hacking limits.
- Scaling Laws for Reward Model OveroptimizationQuantifies how gold reward falls as policies over-optimise a proxy reward model.
- Reinforcement Learning from Human Feedback (Nathan Lambert)A free, up-to-date book covering reward models, policy gradients, regularisation and RLVR.
Practise this topic
- Describe the classic RLHF pipeline. What is the KL penalty for, and what is reward hacking?
- How does Direct Preference Optimisation differ from PPO-based RLHF? What does β control, and when can DPO underperform?
- What is reinforcement learning with verifiable rewards, how does GRPO work, and why has it become popular for reasoning and agentic-coding models?
- Derive the REINFORCE policy-gradient estimator, explain why it has high variance, and show why subtracting a baseline reduces variance without adding bias.
- Compare PPO-based RLHF with Direct Preference Optimisation. Write down the DPO objective, then propose and justify one modification aimed at a specific failure mode.
- In RLHF, pushing harder against a learned reward model eventually makes true quality worse. Explain why, how you would detect it, and how to mitigate it, and critique how this is usually studied.
- When would you choose a value-based method (the Q-learning family) over a policy-gradient or actor-critic method? Discuss on-policy vs off-policy learning and sample efficiency.
- Design a system that makes a language model much better at solving maths problems. Cover data, training stages and evaluation.
- How can you estimate a new recommendation policy’s performance from logs collected by the old policy?
- A driving policy trained by imitation looks excellent on held-out logs but fails on the road. Why can that happen, and how would you evaluate and fix it?