Compute the SimPO loss

MediumAlignmentPro

Why it matters SimPO matched or beat DPO on chat benchmarks without needing a reference model in memory.

SimPO drops the reference model and uses the length-normalised log-prob as the implicit reward, with a target margin.

Write simpo_loss(lp_c, len_c, lp_r, len_r, beta, gamma). lp are summed sequence log-probs, len are token counts. Rewards are beta * lp / len. Return mean(-log sigmoid(r_c - r_r - gamma)), computed stably with np.logaddexp(0, -x).

Signaturedef simpo_loss(lp_c, len_c, lp_r, len_r, beta, gamma)

Example

with equal rewards and gamma = 0 the loss is log 2 = 0.6931.

Understand the idea

SimPO is a preference loss that needs no reference model. Its implicit reward for an answer is the average log probability per token, times beta. Dividing by length stops the model from scoring an answer as worse just because it has more tokens. A margin gamma asks the chosen reward to beat the rejected reward by at least that much. Worked example: chosen lp -6 over 3 tokens, rejected lp -12 over 4 tokens, beta 2, gamma 0.5. r_c = 2 * (-6 / 3) = -4. r_r = 2 * (-12 / 4) = -6. x = -4 - (-6) - 0.5 = 1.5. Loss = -log sigmoid(1.5) = log(1 + e^-1.5) = about 0.201. Rule: r_c = beta * lp_c / len_c, r_r = beta * lp_r / len_r, x = r_c - r_r - gamma, loss = mean(-log sigmoid(x)). Compute -log sigmoid(x) as logaddexp(0, -x) so large negative x does not overflow. Normalise both rewards by their own lengths. Used in: preference tuning of open chat models as a lighter alternative to DPO.

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

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

  • Sample 1: examplesimpo_loss([-10], [10], [-10], [10], 2.0, 0.0)
  • Sample 2: length matterssimpo_loss([-20], [40], [-12], [12], 2.0, 0.5)