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)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. Worked example: 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. Rule: 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.