526. Compute the DPO loss from log-probabilities
Direct Preference Optimization skips the separate reward model. It compares how much the policy raised the chosen answer's log-probability, relative to a frozen reference model, against the same for the rejected answer.
Inputs are arrays of summed sequence log-probs: pi_c, pi_r (policy, chosen and rejected) and ref_c, ref_r (reference). With beta > 0:
margin = beta * ((pi_c - ref_c) - (pi_r - ref_r))
loss = mean(-log sigmoid(margin))
Write dpo_loss(pi_c, pi_r, ref_c, ref_r, beta) returning (loss, mean_margin). Compute -log sigmoid stably.
def dpo_loss(pi_c, pi_r, ref_c, ref_r, beta)Example 1
Input: pi_c = [-10.0, -20.0, -5.0], pi_r = [-12.0, -18.0, -9.0], ref_c = [-11.0, -19.0, -6.0], ref_r = [-11.0, -19.0, -8.0], beta = 0.1
Output: (0.664806, 0.066667)
Example 2
Input: pi_c = [-3.0], pi_r = [-4.0], ref_c = [-3.0], ref_r = [-4.0], beta = 0.5
Output: (0.693147, 0.0)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
The margin measures how much more the policy moved toward the chosen answer than the rejected one, each relative to the reference model.
Hint 2
Convert all inputs to arrays, compute the margin elementwise with beta, then return the mean of -log sigmoid(margin) and the mean margin.
Hint 3
-log sigmoid(m) equals np.logaddexp(0, -m), which stays finite for very large or very negative margins. Return both values as plain floats.
Common mistakes
- The buggy version ignores the reference model, so a policy that started out preferring the chosen answer gets credit it did not earn.
Understand the idea
DPO trains a policy directly on preference pairs without a separate reward model. For each answer it measures how much the policy raised the log probability compared with a frozen reference model. The chosen answer should rise more than the rejected one. The reference acts as an anchor: credit comes only from change, not from what the model already preferred.
chosen answer policy -10, reference -12, a gain of +2. Rejected answer policy -15, reference -14, a change of -1. With beta = 0.1, margin = 0.1 x (2 - (-1)) = 0.3. Loss = -log sigmoid(0.3) = log(1 + e^-0.3) = 0.554. A bigger margin gives a smaller loss.
margin = beta ((pi_c - ref_c) - (pi_r - ref_r)); loss = mean(-log sigmoid(margin)); also report mean margin
Compute -log sigmoid stably as log1p(exp(-|m|)) + max(-m, 0). DPO is a popular way to align open LLMs after supervised fine-tuning.
Topics
Companies1
- DeepMind the topic appears in interview reports Google DeepMind interview guide (landedjobs/ai-interview-guides)
From public interview reports and guides. Not affiliated with or endorsed by these companies.