Reward-Model RLHF vs. Direct Preference Optimization (DPO)

Medium · Machine Learning · Software Engineer · Technical Screen

Prompt

Contrast a standard reward-model Reinforcement Learning from Human Feedback (RLHF) workflow against Direct Preference Optimization (DPO) for post-training a language model. Walk through the required datasets, multi-stage training loops, mathematical loss functions, and how each method uses a frozen reference model.

Frame both methods starting from a shared supervised fine-tuned (SFT) checkpoint followed by pairwise preference alignment. Since RLHF encompasses multiple online RL algorithms, ground the comparison in a concrete reward-modeling plus KL-regularized policy-optimization pipeline (such as PPO or a critic-free group variant) without treating it as the sole form of RLHF, and note where online generation differs from static offline datasets.

Scope & Expectations

  • Data and pipeline stages: Specify the SFT starting point, pairwise (prompt, chosen, rejected) preference format, and how a three-stage online RLHF loop compares structurally with a two-stage offline DPO loop.
  • Objectives and mathematical connection: State the Bradley-Terry reward objective, the KL-penalized RL objective, and the algebraic reparameterization that turns the policy into an implicit reward model in DPO.
  • Reference-policy mechanics: Contrast on-policy per-token KL regularization during live rollouts against DPO's log-ratio baseline evaluated on fixed dataset pairs, along with GPU memory and compute trade-offs.
  • Evaluation and alignment pitfalls: Cover how to measure true generation quality when the policy shifts away from the training distribution, guarding against verbosity bias and proxy over-optimization.

Step-by-step walkthrough

  1. Clarify the starting point and preference data

    To compare reward-model RLHF and Direct Preference Optimization (DPO) cleanly, state the shared setup up front:

    • Policy (pi): In reinforcement learning for language models, the model itself is treated as a conditional probability distribution pi(y | x) over full text responses y given a prompt x.
    • Supervised fine-tuning (SFT) starting point: Both pipelines begin from pi_SFT, a pretrained base model already trained via standard next-token loss on high-quality (prompt, demonstration) pairs. Both also keep a frozen copy of pi_SFT as the reference policy (pi_ref) to anchor the model during preference training.
    • Pairwise preference dataset: Each labeled example is a triple (x, y_w, y_l) containing a prompt x, a preferred ("winning" or chosen) response y_w, and a dispreferred ("losing" or rejected) response y_l (a ranked list of K responses can be converted into K * (K - 1) / 2 pairs).
    • Bradley-Terry preference model: Both pipelines assume latent scalar quality scores r(x, y) govern human choices through the logistic sigmoid sigma(z) = 1 / (1 + exp(-z)):
    P(y_w preferred over y_l | x) = sigma(r(x, y_w) - r(x, y_l))
    

    Notice that adding any prompt-dependent constant c(x) to every response's reward leaves r(x, y_w) - r(x, y_l) unchanged. That shift symmetry is the exact mathematical key DPO uses to eliminate the separate reward model.

    Reward-model RLHF (3 stages)
      [Base LLM] --demos--> [pi_SFT] --pairs (x, y_w, y_l)--> [Reward Model r_phi]
                                |                                      |
                                +--(init pi_theta & freeze pi_ref)-----+
                                                   |
                                prompts x -> sample y ~ pi_theta -> score r_phi - beta * KL -> PPO update
    
    Direct Preference Optimization / DPO (2 stages)
      [Base LLM] --demos--> [pi_SFT] --(init pi_theta & freeze pi_ref)--> supervised DPO loss directly on (x, y_w, y_l)
    
  2. RLHF stage 2: train a separate reward model

    In a classic RLHF pipeline (such as InstructGPT), stage 2 trains a standalone reward model (r_phi) — typically initialized from pi_SFT with the vocabulary projection head replaced by a single linear layer that outputs one scalar number r_phi(x, y) at the final token of the response.

    We fit r_phi on the fixed preference pairs by minimizing negative log-likelihood under the Bradley-Terry model:

    L_RM(phi) = - E_{(x, y_w, y_l)} [ ln sigma(r_phi(x, y_w) - r_phi(x, y_l)) ]
    

    Walk through one pair: if r_phi(x, y_w) = 1.5 and r_phi(x, y_l) = 0.5, the score gap is +1.0, the predicted probability that y_w wins is sigma(1.0) = 0.731, and the loss is -ln(0.731) = 0.313. If the reward model ranked them backward (0.5 vs. 1.5, gap -1.0), the loss jumps to -ln(0.269) = 1.313, pushing r_phi(x, y_w) up and r_phi(x, y_l) down.

    import math
    
    
    def sigmoid(z: float) -> float:
        return 1.0 / (1.0 + math.exp(-z))
    
    
    def reward_model_loss(r_chosen: float, r_rejected: float) -> float:
        return -math.log(sigmoid(r_chosen - r_rejected))
    
    
    assert round(reward_model_loss(1.5, 0.5), 3) == 0.313
    assert round(reward_model_loss(0.5, 1.5), 3) == 1.313
    

    Because r_phi is trained on a finite set of responses, it is an imperfect proxy that is well-calibrated only near the response styles it saw during stage 2. Even on held-out pairs, human raters themselves disagree frequently (InstructGPT reported ~73% inter-labeler agreement), so ~70–75% validation accuracy can already sit near the human noise ceiling.

  3. RLHF stage 3: optimize the policy online with a KL leash

    Stage 3 initializes pi_theta from pi_SFT and uses on-policy reinforcement learning — meaning the training loop repeatedly samples fresh responses y ~ pi_theta(. | x) from the model currently being updated, scores them with the frozen r_phi, and updates theta.

    Maximizing r_phi(x, y) alone causes reward hacking (Goodhart's law): pi_theta quickly discovers degenerate text (extreme verbosity, flattery, repeated catchphrases, or formatting quirks) where r_phi predicts high scores even though actual quality collapses. To prevent this, RLHF subtracts a penalty beta > 0 times the KL divergence (Kullback-Leibler divergence, E_{y ~ pi_theta}[ln(pi_theta(y | x) / pi_ref(y | x))]), which measures how far pi_theta has drifted from pi_ref:

    max_theta  E_{x} E_{y ~ pi_theta(. | x)} [ r_phi(x, y)  -  beta * ln(pi_theta(y | x) / pi_ref(y | x)) ]
    

    In practice, PPO (Proximal Policy Optimization) optimizes this objective by applying -beta * (ln pi_theta(y_t | ...) - ln pi_ref(y_t | ...)) as a per-token reward and adding r_phi(x, y) at the final token, while taking clipped policy-gradient steps. Standard PPO holds four models in GPU memory: the trainable policy pi_theta, a trainable value model (critic) that estimates expected future return from each token to reduce gradient variance, the frozen reward model r_phi, and the frozen reference pi_ref (critic-free RL methods like RLOO and GRPO drop the value model by comparing multiple sampled responses per prompt, leaving three models).

    Crucially, for any fixed reward function r(x, y), the KL-regularized objective above has an exact closed-form optimal distribution pi*:

    pi*(y | x) = pi_ref(y | x) * exp(r(x, y) / beta) / Z(x)
    where Z(x) = sum_{all y} pi_ref(y | x) * exp(r(x, y) / beta)
    

    Here Z(x) is the partition function — the normalizing sum over every possible text sequence y that makes pi*(. | x) sum to 1. We cannot compute Z(x) directly for real vocabularies, but a 3-response toy world (A, B, C with pi_ref = [0.5, 0.3, 0.2] and rewards [0, 1, 2]) shows exactly what beta controls:

    beta      pi*(. | x)               E[r]    KL(pi* || pi_ref)   Behavior
    inf       [0.500, 0.300, 0.200]    0.70    0.000               Pinned at pi_ref
    2.0       [0.325, 0.322, 0.353]    1.03    0.084               Gentle tilt toward C
    1.0       [0.179, 0.292, 0.529]    1.35    0.323               Balanced shift
    0.5       [0.037, 0.163, 0.801]    1.76    0.915               Aggressive shift
    -> 0      [0.000, 0.000, 1.000]    2.00    1.609               Collapses onto argmax r
    
  4. Derive DPO: turn the policy into its own reward model

    Rafailov et al. (2023) observed that instead of fitting r_phi first and running noisy RL to approximate pi*, we can invert the closed-form equation to express the reward r(x, y) directly in terms of the optimal policy pi* in four short algebraic steps:

    1. Optimal policy formula:        pi*(y | x) = pi_ref(y | x) * exp(r(x, y) / beta) / Z(x)
    2. Divide by pi_ref and take ln:  ln(pi*(y | x) / pi_ref(y | x)) = r(x, y) / beta - ln Z(x)
    3. Multiply by beta and solve:    r(x, y) = beta * ln(pi*(y | x) / pi_ref(y | x)) + beta * ln Z(x)
    4. Take the pair difference:      r(x, y_w) - r(x, y_l)
                                      = beta * ln(pi*(y_w | x) / pi_ref(y_w | x))
                                      - beta * ln(pi*(y_l | x) / pi_ref(y_l | x))
    

    Look at step 4: because y_w and y_l share the exact same prompt x, the intractable + beta * ln Z(x) term appears in both r(x, y_w) and r(x, y_l) and cancels out completely! Substituting this difference into the Bradley-Terry likelihood and replacing pi* with our trainable policy pi_theta yields the DPO loss:

    h_theta(x, y_w, y_l) = beta * [ (ln pi_theta(y_w | x) - ln pi_ref(y_w | x))
                                  - (ln pi_theta(y_l | x) - ln pi_ref(y_l | x)) ]
    L_DPO(theta)         = - E_{(x, y_w, y_l)} [ ln sigma(h_theta(x, y_w, y_l)) ]
    

    The quantity r_hat(x, y) = beta * ln(pi_theta(y | x) / pi_ref(y | x)) is called the implicit reward: the language model itself acts as the reward model! In our 3-response toy example at beta = 1.0, beta * ln(pi* / pi_ref) equals [-1.027, -0.027, +0.973], which is the true reward vector [0, 1, 2] shifted by -beta * ln Z = -1.027 — leaving every pairwise difference unchanged.

    Walk through one DPO training example with beta = 0.2, where ln pi(y | x) is the sum of response-token log-probabilities given x:

    Response        ln pi_theta(y | x)    ln pi_ref(y | x)    Log-ratio ln(pi_theta / pi_ref)
    Chosen   y_w         -18.5                 -20.0                      +1.5
    Rejected y_l         -23.0                 -22.0                      -1.0
    
    At initialization (pi_theta == pi_ref):  h = 0.0,                   loss = -ln(0.5) = 0.693
    After the update above:                  h = 0.2 * (1.5 - (-1.0)) = 0.5, loss = -ln sigma(0.5) = 0.474
    
    import math
    
    
    def dpo_loss(
        logp_chosen: float,
        logp_rejected: float,
        ref_logp_chosen: float,
        ref_logp_rejected: float,
        beta: float,
    ) -> float:
        chosen_log_ratio = logp_chosen - ref_logp_chosen
        rejected_log_ratio = logp_rejected - ref_logp_rejected
        margin = beta * (chosen_log_ratio - rejected_log_ratio)
        return -math.log(1.0 / (1.0 + math.exp(-margin)))
    
    
    assert round(dpo_loss(-20.0, -22.0, -20.0, -22.0, beta=0.2), 3) == 0.693
    assert round(dpo_loss(-18.5, -23.0, -20.0, -22.0, beta=0.2), 3) == 0.474
    

    Taking the gradient with respect to theta gives -beta * sigma(-h) * (grad ln pi_theta(y_w | x) - grad ln pi_theta(y_l | x)): it increases the likelihood of y_w and decreases y_l, weighted by sigma(-h) — the probability the implicit reward still misranks the pair (0.622 when h = -0.5, shrinking to 0.378 when h = +0.5). No autoregressive generation, reward model, or value critic is needed inside the loop.

  5. Compare the role of the reference policy

    Both methods rely on pi_ref, but where that anchor is enforced differs fundamentally between on-policy RLHF and offline DPO (which trains only on pre-collected static pairs):

    Property              Reward-model RLHF (PPO)                   Direct Preference Optimization (DPO)
    How pi_ref enters     Explicit per-token KL penalty subtracted  Baseline denominator inside the implicit
                          from reward on sampled rollouts           reward beta * ln(pi_theta / pi_ref)
    Where enforced        On fresh responses y ~ pi_theta(. | x)    Only on the static dataset's y_w and y_l
    Runtime memory cost   Frozen model forward pass per rollout     Can precompute ref log-probs once to disk
                          (alongside policy, reward, value models)  so only pi_theta stays in GPU memory!
    

    Because offline DPO evaluates pi_theta / pi_ref only at the recorded (y_w, y_l) pairs, nothing in the loss directly constrains probability mass on other unseen responses y'. A well-known empirical quirk of offline DPO is that ln pi_theta(y_w | x) and ln pi_theta(y_l | x) can both decrease during training (leaking mass onto out-of-dataset sequences) as long as y_l drops faster so their gap h_theta still grows.

  6. Side-by-side trade-offs and when to pick each

    Dimension             Reward-model RLHF                         DPO
    Stages                3 (SFT -> Reward Model -> Online RL)      2 (SFT -> DPO supervised loop)
    Training data mode    Online rollouts from current pi_theta     Offline fixed preference pairs
    Models in memory      4 for PPO (3 for critic-free GRPO/RLOO)   2 (or 1 if ref log-probs are cached)
    Key hyperparameters   beta, PPO clip, 2 lrs, temp, rollout bs   beta, learning rate, epochs
    Primary failure mode  Reward hacking off-distribution           Overfitting pairs; unbounded margins on
                                                                    deterministic pairs; offline mass shift
    Reusable artifacts    Trained r_phi can also rerank / filter    No standalone scorer unless extracted
    

    Notice what happens when raters prefer y_w over y_l 100% of the time: under Bradley-Terry, Probability 1.0 corresponds to an infinite score difference, so DPO keeps pushing the log-ratio margin toward infinity regardless of beta unless stopped early (methods like IPO replace -ln sigma(h) with a squared loss toward a finite target margin to fix this). Head-to-head studies typically find well-tuned online RL (PPO or GRPO) reaches a higher ceiling on reasoning and out-of-distribution prompts because it actively explores and corrects pi_theta's own generations, while DPO delivers strong alignment at a fraction of the compute and engineering complexity (for instance, Mistral AI aligned Mixtral 8x7B Instruct with SFT followed by DPO, and "online/iterative DPO" hybrids periodically sample fresh pairs from pi_theta to close the gap).

  7. Evaluate properly under distribution shift

    Distribution shift is the gap between the static responses in your training set and the new style of responses pi_theta actually generates after alignment. Because of this shift, evaluation must test live generations from pi_theta:

    • Held-out pair accuracy (whether r_phi or DPO's implicit reward ranks y_w > y_l on unseen static pairs) is a quick sanity check, not proof of generation quality.
    • Length-controlled win rate against pi_SFT on fresh held-out prompts (judged by humans or a strong judge model): both reward models and LLM judges exhibit strong length bias, so always track average token length alongside win rate to ensure gains are not mere verbosity.
    • Proxy reward vs. independent gold reward over KL: Plotting training reward (or implicit margin) and an independent human/gold-model score against KL(pi_theta || pi_ref) catches over-optimization the moment the proxy keeps climbing while the gold score peaks and turns downward.
    • Capability and safety regression suites: Check coding, math, factual QA, and refusal benchmarks to verify alignment did not degrade core SFT skills ("alignment tax") or cause exaggerated refusals.

Intuition & how it works

Imagine training a chef (pi_theta, a language model viewed as a probability distribution pi(y | x) over responses y to prompt x), starting from a capable culinary-school graduate (pi_SFT, a model trained via supervised fine-tuning on example demonstrations) and a stack of taste-test cards where diners picked Dish W (y_w) over Dish L (y_l). Reward-model RLHF first trains a separate food critic (r_phi) to predict the diners' preference scores, then has the chef cook brand-new dishes every step for the critic while a leash (beta times KL divergence, a measure of how far pi_theta drifts from the frozen graduate pi_ref) keeps the chef from gaming the critic with unnatural recipes. Direct Preference Optimization (DPO) skips training a separate critic altogether: because the mathematically optimal KL-leashed chef increases a dish's probability over pi_ref in exact proportion to exp(reward / beta), DPO rewrites the preference loss directly in terms of the chef's own probabilities on the recorded (y_w, y_l) pairs.

Simpler shortcuts fail in predictable ways. Running plain supervised fine-tuning on y_w alone never teaches the model to suppress plausible-sounding bad answers (y_l), while maximizing a learned reward model without a reference leash (beta = 0) causes reward hacking — the policy exploits blind spots in r_phi (such as extreme length, flattery, or repetitive lists) so the critic's score climbs while real human quality collapses.

A tiny numeric example shows both mechanics clearly. In RLHF stage 2, if r_phi(x, y_w) = 1.5 and r_phi(x, y_l) = 0.5, the Bradley-Terry model (P(y_w > y_l) = sigma(r_w - r_l) = 1 / (1 + exp(-(r_w - r_l)))) assigns win probability sigma(1.0) = 0.731 for a pairwise loss of -ln(0.731) = 0.313, and stage 3 then samples fresh generations online. In DPO with beta = 0.2, suppose pi_theta raises sequence log-probability ln P(y_w | x) from -20.0 (pi_ref) to -18.5 (+1.5 gain) and lowers ln P(y_l | x) from -22.0 to -23.0 (-1.0 drop): the implicit reward gap is 0.2 * (1.5 - (-1.0)) = 0.5, directly yielding DPO loss -ln sigma(0.5) = 0.474 (down from ln 2 = 0.693 at initialization) in a single supervised training loop.

Key points

  • Shared starting point and data: Both start from an SFT model pi_SFT, freeze a copy as the reference policy (pi_ref), and learn from a pairwise preference dataset (x, y_w, y_l) modeled via Bradley-Terry (sigma(r(x, y_w) - r(x, y_l))).
  • 3-stage reward-model RLHF: Stage 1 runs SFT; Stage 2 fits a scalar reward model (r_phi) via logistic pairwise loss; Stage 3 runs on-policy RL (sampling fresh outputs from pi_theta, typically with PPO — Proximal Policy Optimization, which uses clipped policy gradients and a learned value model critic — or critic-free variants like GRPO/RLOO) to maximize E[r_phi(x, y)] - beta * KL(pi_theta || pi_ref).
  • Closed-form link and 2-stage DPO: The KL-regularized RL objective has exact closed-form solution pi*(y | x) = pi_ref(y | x) * exp(r(x, y) / beta) / Z(x), where the partition function Z(x) normalizes probabilities over all y. Solving for r(x, y) and subtracting r(x, y_w) - r(x, y_l) cancels ln Z(x), yielding the offline (static-dataset) DPO loss -ln sigma(beta * [ln(pi_theta(y_w|x)/pi_ref(y_w|x)) - ln(pi_theta(y_l|x)/pi_ref(y_l|x))]).
  • Different reference-policy mechanics: Online RLHF penalizes per-token KL divergence on whatever pi_theta currently generates, requiring live pi_ref forward passes; DPO embeds pi_ref inside the log-ratio only on the static (y_w, y_l) pairs, so reference log-probabilities can be precomputed once and cached to disk.
  • Core engineering trade-off: Online RLHF requires 3–4 models in memory, live autoregressive sampling, and sensitive hyperparameter tuning, but corrects pi_theta on its own generations; DPO runs like standard SFT with 1–2 models in memory at far lower cost, at the price of offline exposure to unseen generations and unbounded margin growth on deterministic pairs.
  • Evaluation under distribution shift: Because the aligned policy generates different text from pi_SFT (distribution shift), always evaluate live generations via length-controlled win rates, capability/safety suites, and held-out gold reward vs. KL curves rather than static pair accuracy alone.

Common mistakes

  • Claiming DPO needs no preference data or no reference policy: DPO uses the exact same (x, y_w, y_l) preference pairs and explicitly divides by pi_ref(y | x) (reference-free variants like SimPO or ORPO change the objective and are distinct algorithms from DPO).
  • Claiming DPO and PPO always converge to the exact same model: Equivalence holds only under idealized assumptions (exact Bradley-Terry preferences, full support coverage, unlimited data, unconstrained policy class); on finite offline datasets with neural policies, their learned behaviors differ.
  • Treating r_phi as ground truth instead of a fragile proxy: Pushing beta too small lets pi_theta wander outside r_phi's training distribution and reward-hack; setting beta too large freezes pi_theta near pi_SFT.
  • Including prompt tokens in DPO log-probabilities: ln pi(y | x) must sum log-probabilities over the response tokens conditioned on x, not prompt tokens (though prompt log-probs would cancel if identical, padding or length-normalization bugs around prompts corrupt the margin).
  • Ignoring offline likelihood drop in DPO: Because DPO only maximizes the margin between logged y_w and y_l, both ln pi_theta(y_w | x) and ln pi_theta(y_l | x) can fall simultaneously as probability mass shifts to unlogged sequences.
  • Evaluating without controlling for response length: Both learned reward models and LLM-as-a-judge pipelines systematically favor longer, bulleted answers, masking verbosity inflation as a fake quality win.

Follow-up questions

  • Do you still need to train a standalone reward network when aligning a model with DPO? No — DPO reparameterizes the reward directly through the policy and reference log-probabilities via the implicit reward beta * ln(pi_theta(y | x) / pi_ref(y | x)), fitting pi_theta to preference pairs in one supervised stage. Even so, teams sometimes pair DPO with an external reward model in online or iterative DPO to score freshly sampled policy responses, filter noisy datasets, or run best-of-N reranking at inference time.
  • Does switching to DPO remove the need to collect pairwise preference labels? No — DPO consumes the exact same pairwise (prompt, chosen, rejected) comparisons that Stage 2 of RLHF requires; it removes only the standalone reward-model fitting and online RL stages. While human raters can be augmented or replaced by capable judge models (RLAIF / AI feedback), pairwise preference labels are still essential and pass along whatever biases the labeler exhibits.
  • What failure modes arise from rater bias, distribution shift, and reward over-optimization in both pipelines? Rater bias (annotators systematically preferring longer, sycophantic, or confidently phrased wrong answers) gets baked straight into both r_phi and DPO's policy, amplifying verbosity or flattery unless training pairs are balanced for length and style. Distribution shift hurts RLHF when pi_theta wanders into text styles r_phi never saw during training and receives erratic scores, and hurts offline DPO because the loss never penalizes degenerate sequences outside the static (y_w, y_l) pairs. Reward over-optimization shows up in RLHF as classic reward hacking (proxy score climbs while human win rate drops past a KL knee) and in DPO as unbounded margin growth on deterministic pairs that pushes down even ln pi_theta(y_w | x); practical defenses include tuning beta, early stopping on held-out length-controlled evaluations, reward-model ensembles, bounded-margin objectives like IPO, and iterative on-policy pair collection.

Follow-up questions

Similar questions

More Mistral AI interview questions

All 17 Mistral AI questions →