Compute the DPO loss from log-probabilities

MediumAlignmentPro

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.

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: batch of 3dpo_loss([-10.0, -20.0, -5.0], [-12.0, -18.0, -9.0], [-11.0, -19.0, -6.0], [-11.0, -19.0, -8.0], 0.1)
  • Sample 2: policy equals reference gives log 2dpo_loss([-3.0], [-4.0], [-3.0], [-4.0], 0.5)