Compute the IPO preference loss

Why it matters IPO is one of the offline alignment losses supported in TRL next to DPO.

IPO replaces DPO's log-sigmoid with a squared loss that targets a fixed margin, which avoids overfitting to deterministic preferences.

Write ipo_loss(pi_c, pi_r, ref_c, ref_r, tau). Each argument is an array of sequence log-probs (chosen c and rejected r under the policy and the reference). h = (pi_c - ref_c) - (pi_r - ref_r). Return mean((h - 1 / (2 tau))^2).

Signaturedef ipo_loss(pi_c, pi_r, ref_c, ref_r, tau)

Example

if every log-prob is 0 and tau = 0.5, h = 0 and the loss is 1.

Understand the idea

Preference training compares a chosen answer with a rejected one. h measures how much more the policy prefers the chosen answer than the reference model does. DPO keeps pushing h higher forever through a log-sigmoid, which can overfit. IPO instead uses a squared loss with a fixed target, so once h reaches the target the pressure stops. Worked example: pi_c = -1, pi_r = -3, ref_c = -2, ref_r = -2.5, tau = 0.25. h = (-1 - (-2)) - (-3 - (-2.5)) = 1 - (-0.5) = 1.5. Target = 1 / (2 * 0.25) = 2. Loss = (1.5 - 2)^2 = 0.25. If h were 2 the loss would be 0, and if h were 3 the loss would rise again to 1. Rule: h = (pi_c - ref_c) - (pi_r - ref_r); loss = mean((h - 1 / (2 tau))^2) over the batch. Smaller tau means a larger target margin. A common slip is using 1 / tau as the target. Used in: offline preference tuning of chat models as an alternative to DPO, available in libraries like TRL.

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

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleipo_loss([0], [0], [0], [0], 0.5)
  • Sample 2: batchipo_loss([-1, -2], [-3, -2.5], [-1.5, -2], [-2, -2], 0.1)
  • Test 3: at targetipo_loss([1.0], [0.0], [0.0], [0.0], 0.5)