Add label smoothing to the DPO loss (conservative DPO)

Why it matters Label smoothing stops DPO from pushing margins to infinity on noisy preference data.

Preference labels are noisy: annotators sometimes pick the worse answer. Conservative DPO assumes each label is flipped with probability eps and smooths the DPO loss accordingly.

Write cdpo_loss(pol_w, pol_l, ref_w, ref_l, beta, eps). All four inputs are length-B arrays of summed log-probs. Let h = beta * ((pol_w - ref_w) - (pol_l - ref_l)). The loss per pair is -(1 - eps) * log sigmoid(h) - eps * log sigmoid(-h). Return the batch mean as a float, using a stable log-sigmoid. eps = 0 is ordinary DPO.

Signaturedef cdpo_loss(pol_w, pol_l, ref_w, ref_l, beta, eps)

Example

cdpo_loss([-1], [-2], [-1.5], [-1.5], 1.0, 0.1) has h = 1 and is about 0.4133.

Understand the idea

Plain DPO trusts every preference label completely, so it keeps pushing the margin between chosen and rejected answers, forever. If some labels are wrong, that is harmful. Conservative DPO hedges like a careful student who knows a few answer keys have typos.

The DPO margin is h = beta * (how much more the policy likes the chosen answer than the reference does, minus the same for the rejected one). Ordinary loss: -log sigmoid(h). If a label is flipped with probability eps, the expected loss mixes in the opposite case.

Example: h = 1, eps = 0.1. -log sigmoid(1) = 0.313 and -log sigmoid(-1) = 1.313. Loss = 0.9 * 0.313 + 0.1 * 1.313 = 0.413.

Rule: L = -(1 - eps) log sigmoid(h) - eps log sigmoid(-h).

The smoothed loss has a minimum at a finite margin instead of at infinity, so the policy does not drift too far on noisy pairs. Preference-tuning libraries expose eps as a label smoothing option.

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

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

  • Sample 1: examplecdpo_loss([-1.0], [-2.0], [-1.5], [-1.5], 1.0, 0.1)
  • Sample 2: plain dpocdpo_loss([-3.0, -5.0], [-4.0, -4.0], [-3.5, -4.5], [-3.5, -4.0], 0.5, 0.0)
  • Test 3: smoothed batchcdpo_loss([-3.0, -5.0], [-4.0, -4.0], [-3.5, -4.5], [-3.5, -4.0], 0.5, 0.2)
  • Test 4: huge margincdpo_loss([0.0], [-500.0], [0.0], [0.0], 1.0, 0.1)