Forward Deployed EngineeringAI EngineeringPreference Alignment

Walk through the RLHF pipeline (SFT, reward model, PPO) and explain how DPO simplifies it.

Question 64 of 73 · Updated

On this page

Interview-ready answer#

Classic reinforcement learning from human feedback (RLHF) aligns a pretrained language model through three stages: supervised fine-tuning (SFT) on demonstrations, training a reward model on human preferences, and optimizing the language model against that learned reward using reinforcement learning, often proximal policy optimization (PPO). A KL penalty discourages excessive deviation from a frozen reference policy.

Direct Preference Optimization (DPO) starts from the same preference-learning problem but uses the relationship between an optimal KL-regularized policy and its implicit reward to derive a direct classification-style loss over preferred and rejected responses. It does not need a separately trained reward network, an online PPO rollout loop or a learned value function in its standard offline formulation.

DPO simplifies the training system, not the underlying alignment problem. Preference data can still be biased, reward proxies can still be exploited, and better preference scores do not guarantee factual accuracy or safety.

1. The two pipelines#

Loading diagram…

The SFT checkpoint commonly initializes the trainable policy and serves as a frozen reference. Preference candidates may be sampled from several checkpoints or other approved sources, not necessarily just the SFT model.

2. Supervised fine-tuning: establish useful behavior#

Given a prompt x and a demonstration y, train the model to predict the response tokens autoregressively. A typical instruction-tuning objective is the negative sum of log probabilities of the target response tokens conditioned on the prompt and preceding response tokens.

Mask padding and, when using response-only supervision, prompt tokens from the training loss. Preserve the correct chat template and termination tokens. SFT teaches what a desirable response looks like but does not explicitly contrast good and bad responses to the same request.

A customer-specific demonstration dataset should represent the actual desired behavior, including evidence-grounded answers, appropriate refusals and handoffs. Neither SFT nor subsequent preference training is a reliable way to keep a rapidly changing knowledge base current.

3. Reward modeling: convert comparisons into a score#

Collect pairs (x, , ), where is preferred to under a defined rubric. Annotators should compare the same prompt, judge factual correctness as well as helpfulness, and identify ambiguous or invalid comparisons. Keep held-out prompts and related examples separated from training data.

A scalar reward model r_φ(x, y) is commonly trained using a Bradley–Terry preference model:

LaTeX

The loss is the negative log of that probability. A large positive reward difference makes the observed preference likely. Reward is a learned proxy for the annotation criteria, not a ground-truth correctness score. Pairwise data does not identify an arbitrary prompt-dependent additive reward constant.

A reward model can learn shortcuts, for example preferring long confident explanations over shorter accurate ones. Validate against independent factual and safety labels before using it as an optimization target.

4. PPO: optimize the policy against reward#

For a fixed prompt, the idealized sequence-level objective is to maximize

J(π) = E[y ~ π(·|x)] [r_φ(x, y)] − β KL(π(·|x) || π_ref(·|x))

The positive coefficient β controls the cost of moving away from the frozen reference. This objective is averaged over training prompts. The KL term discourages extreme policy shifts but does not guarantee preservation of any individual capability.

In a typical PPO implementation, generate responses from a rollout policy, score them with the reward model, compute reference-policy log probabilities, and estimate token-level advantages using a value function and returns. A sampled log-probability difference can provide a KL-related reward penalty; an individual sampled term need not be nonnegative even though the full KL divergence is.

For each sampled token action, define the ratio ρ = π_θ(a|s) / π_old(a|s) and estimated advantage A. PPO maximizes the clipped surrogate:

L_clip = E[min(ρ A, clip(ρ, 1−ε, 1+ε) A)]

Positive advantages favor increasing the sampled action probability; negative advantages favor decreasing it. Clipping limits the incentive to move too far in the favorable direction during updates, rather than imposing a strict bound on all probability changes. Training commonly includes a value-function loss and may include an entropy term. Actual implementations differ in reward shaping, advantage estimation, KL control and batching.

Important distinction: is the policy snapshot that generated the rollout batch, refreshed as training progresses. is the fixed alignment reference, commonly the SFT checkpoint. PPO ratio clipping and reference KL regularization solve different problems.

PPO requires repeated generation, reward scoring, value estimation and optimization. Policy and reward-model distribution shift, noisy advantages, unstable reward scaling and excessive KL drift are common engineering concerns.

5. DPO: remove the explicit reward model and rollout optimization#

Under the idealized KL-regularized reward objective, for a fixed prompt and a reference distribution with suitable support, the optimal policy has the form:

LaTeX

Here Z(x) normalizes the distribution. Rearranging:

LaTeX

For two responses to the same prompt, the prompt-dependent normalization term cancels in their reward difference. Substitute this expression into the Bradley–Terry preference probability and parameterize the policy by θ.

Define sequence log probabilities:

Then the standard DPO objective is to minimize:

LaTeX

DPO encourages the policy to increase its chosen-versus-rejected log-probability margin relative to the reference. It is not just ordinary SFT on the chosen response: the rejected response and reference probabilities both contribute. Nor does the objective guarantee that the absolute probability of every chosen response increases.

The derivation uses a preference model and KL-regularized optimal-policy relationship. It is not a proof that finite-data DPO training produces the same learned policy as every practical PPO configuration. In standard DPO the KL connection is implicit in the reference-relative objective; it is not a separate measured KL penalty evaluated on live rollouts.

Numerical intuition and tested implementation#

Suppose the policy log probabilities are −3 and −5 for the chosen and rejected responses, while the reference log probabilities are −4 and −5. With β = 0.5, the preference logit is 0.5 × (2 − 1) = 0.5. The DPO loss is approximately 0.474077. If the policy equals the reference on both responses, the logit is zero and the loss is log 2 ≈ 0.693147.

For PPO, with ε = 0.2, a ratio of 1.4 and advantage +2 gives the clipped surrogate min(2.8, 2.4) = 2.4. A ratio of 0.6 and advantage −2 gives min(−1.2, −1.6) = −1.6.

PYTHON
from math import exp, log1p, isfinite def dpo_loss(pc, pr, rc, rr, beta): if not all(isfinite(x) for x in (pc, pr, rc, rr, beta)) or beta <= 0: raise ValueError('finite log probabilities and positive beta required') z = beta * ((pc-pr)-(rc-rr)) return max(0.0, -z) + log1p(exp(-abs(z))) def ppo_surrogate(ratio, advantage, epsilon=0.2): return min(ratio*advantage, min(1+epsilon,max(1-epsilon,ratio))*advantage)

The DPO implementation evaluates softplus(−z) in a numerically stable form for ordinary finite logits. The PPO helper assumes valid finite positive probability ratios, finite advantages and an appropriate clipping parameter. These are scalar objective illustrations, not differentiable training loops.

Executed verification: Python 3.13.5 passed 5,253 checks: 5,184 DPO parameter combinations compared with the direct logistic formula, 63 PPO combinations compared with a piecewise clipping expression, two extreme-logit checks and four invalid-input rejection checks. The worked numerical outputs were also computed locally.

In actual training, calculate response sequence log probabilities by summing correctly masked token log probabilities (including the relevant termination convention). Use differentiable stable log-sigmoid operations, a frozen reference, consistent tokenization and truncation across both responses. Monitor response-length bias; arbitrary length normalization changes the standard objective.

6. Engineering comparison and method selection#

DimensionPPO-based RLHFStandard offline DPO
Preference supervisionSeparate learned reward modelDirect pairwise objective
Training-time generationRepeated on-policy rolloutsFixed preference pairs during optimization
Training componentsPolicy, reference, reward model, usually value functionPolicy and frozen reference
Compute and complexityRollout generation and RL orchestration can be expensiveMore conventional batched fine-tuning; reference scores may be precomputed
Feedback flexibilityCan optimize rewards on newly sampled behavior, including verified outcomesDepends heavily on preference-pair coverage and quality
Stability concernsReward exploitation, advantage variance, KL drift, value estimationDataset shift, noisy preferences, overfitting, length bias, reference mismatch

DPO is a reasonable starting point when a customer has high-quality offline comparisons and wants a simpler reproducible alignment process. PPO-style optimization can be justified when on-policy exploration and outcome-based feedback provide substantial additional value, and the training team can operate the necessary infrastructure. Not all RL-based alignment uses PPO, and DPO is one of several preference-optimization methods.

Both approaches can improve the proxy while harming the real objective. For example, preferences may reward polished confidence, increasing win rate while reducing accuracy on independently labeled factual tasks. Track factual correctness, calibration, safety, task success, length, reward/validation gaps and reference-policy drift across checkpoints. Require separate evaluation gates and retain a validated rollback checkpoint. FDE-0060 examines this regression scenario directly.

For an FDE, the decision begins with the customer's observed failure and available supervision. Use SFT for demonstration-driven behavior changes, preference optimization when relative quality choices are valuable, and retrieval or deterministic checks when the actual defect concerns freshness or factual guarantees. Choose the simplest method that improves independently measured customer outcomes.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models