Preferences, reward models, and direct optimization
How to study this lesson
Read one section, trace the worked example, and try the knowledge check. Bookmark saves a shortcut; notes appear in My notebook. Mark lesson complete is your own assessment and does not mark its lab passed.
By the end, you can
- Trace an RLHF pipeline and identify its learned components.
- Compute the reference-relative margin used by DPO.
- Design preference labels that match the intended task.
A preference is comparative evidence
A preference record commonly contains a prompt, a chosen response, and a rejected response. It says that one output is preferred under a particular rubric and context. It does not necessarily assign either response an absolute quality score. If both answers are wrong, preferring the less misleading one still does not make it a good demonstration for supervised imitation. Preserve ties, ambiguous cases, and annotator disagreement instead of forcing every comparison into an artificially certain binary label.
Define the rubric before collecting labels. For a technical assistant, correctness, evidence use, authorization compliance, and usefulness may need separate judgments. An annotator who chooses the longer answer because it sounds thorough can teach a length preference rather than better reasoning. Randomize presentation order and inspect agreement on shared calibration examples. Keep prompts and related candidates in the same data partition to avoid contaminating evaluation with memorized comparisons.
Where RLHF introduces a proxy
The InstructGPT research describes a sequence of supervised demonstrations, human comparisons, reward-model training, and policy optimization. A reward model estimates which outputs people would prefer. A policy then generates responses and is optimized using that learned signal, commonly with a constraint or penalty discouraging excessive drift from a reference policy. The reference helps anchor behavior but does not prove that generated outputs are correct or acceptable.
Trace the errors separately. Human labels may be inconsistent; the reward model may generalize poorly; and policy optimization may discover responses that exploit that model. A held-out reward-model comparison accuracy answers a different question from end-to-end user task success. Maintain evaluations outside the reward-training distribution and review examples where reward rises most quickly. Those examples can reveal useful progress, but they can also reveal a newly discovered shortcut.
DPO uses a reference-relative preference margin
Direct Preference Optimization avoids fitting a separate explicit reward model in its basic formulation. Its objective compares the policy's chosen-versus-rejected log-probability gap with the same gap under a fixed reference. If policy log probabilities are -1 and -3, its gap is two. If reference values are -2 and -2, the reference gap is zero. With beta equal to 0.5, the scaled margin is one, and the negative log-sigmoid loss is approximately 0.3133.
If policy and reference gaps match, the margin is zero and the loss is log two, approximately 0.6931. Increasing the chosen response's probability relative to the rejected one lowers this pair's loss. The DPO paper derives the connection to a KL-regularized preference objective; the small code example implements only its scalar loss calculation. It is not a complete trainer, tokenizer pipeline, or proof that an update improves a downstream task.
Implementation choices affect the meaning of the signal
Sequence log probability is normally a sum over selected response-token log probabilities conditioned on the prompt. Masking prompt tokens and handling response boundaries consistently are therefore essential. Summed probabilities interact with response length, and normalization choices can define a different objective. Do not silently replace a sum with a mean while retaining claims about the original algorithm. Inspect tokenization of chosen and rejected continuations, especially when special tokens or truncation differ.
Beta belongs to both the theoretical regularization relationship and the numerical scale of the training loss. Its practical effect depends on the rest of the setup, so test a documented range rather than treating it as a universal quality knob. A fixed offline preference dataset may not cover errors made by an updated policy. Collecting fresh comparisons can improve coverage, but creates a new data distribution and must preserve a separate evaluation set.
Choose the method from the available evidence
Supervised fine-tuning is attractive when excellent target responses are available. Preference optimization is useful when people can compare candidates more reliably than they can write ideal answers. Online reward-based optimization can explore outputs beyond a fixed dataset, at the cost of additional sampling, infrastructure, and opportunities to exploit a proxy. These approaches can be combined, but each stage should have an explicit hypothesis and ablation.
For a portfolio experiment, start with a fixed candidate set and a clear rubric. Report label counts, disagreement, candidate-generation settings, and the exact comparison unit. Compare a supervised baseline with a preference-trained alternative on held-out prompts using both the rubric and executable checks where possible. Publish examples where the trained model becomes more persuasive without becoming more accurate. Such failures are valuable evidence about the objective's limits and guide whether the next investment should improve labels, evaluation, or the learning method.
Work through the code
The inputs are invented response log probabilities. The code uses a stable expression so extreme margins do not overflow. It demonstrates the loss geometry only; a real update requires model gradients, correct response masks, and a vetted preference dataset.
import math
def negative_log_sigmoid(value):
# Stable softplus(-value), including very large margins.
return max(-value, 0.0) + math.log1p(math.exp(-abs(value)))
def dpo_loss(chosen, rejected, ref_chosen, ref_rejected, beta):
if beta <= 0:
raise ValueError("beta must be positive")
policy_gap = chosen - rejected
reference_gap = ref_chosen - ref_rejected
margin = beta * (policy_gap - reference_gap)
return margin, negative_log_sigmoid(margin)
cases = [("unchanged", -2.0, -2.0),
("preferred", -1.0, -3.0),
("reversed", -3.0, -1.0)]
for name, chosen, rejected in cases:
margin, loss = dpo_loss(chosen, rejected, -2.0, -2.0, 0.5)
print(f"{name}: margin={margin:.1f}, loss={loss:.6f}")
unchanged: margin=0.0, loss=0.693147 preferred: margin=1.0, loss=0.313262 reversed: margin=-1.0, loss=1.313262
Run Python snippets locally with the prerequisites named above. The module coding lab runs directly in your browser.
Pause and reason
The policy gap is 0.5 and the reference gap is 1.5, with beta 0.2. Compute the margin and explain why a chosen response can still incur a loss greater than log two even if its policy probability exceeds the rejected response probability.
Check your understanding
Preference-trained answers become longer and receive higher learned reward, but executable correctness checks decline. What does this most directly suggest?
Your notes
Explain the mechanism in your own words. Add a failure you want to test.