Loss, Implicit Rewards and the Per-Pair Weight
Direct Preference Optimization (DPO) trains a policy πθ on preference pairs (prompt x, chosen completion yc, rejected completion yr) without a separate reward model. With a frozen reference model πref and a strength β>0, the loss of one pair is
L=−logσ(r^c−r^r),r^c=βlogπref(yc∣x)πθ(yc∣x),r^r=βlogπref(yr∣x)πθ(yr∣x)
where r^ is DPO's implicit reward and σ is the logistic sigmoid. Each logπ(y∣x) is the sum of the completion's token log-probabilities. Lambert's RLHF book writes the gradient as
∇θL=−βw(∇θlogπθ(yc∣x)−∇θlogπθ(yr∣x)),w=σ(r^r−r^c)
so the derivative of a pair's loss with respect to its policy chosen log-probability is −βw, and with respect to its policy rejected log-probability is +βw. Implement the forward pass, these two derivatives, and the batch loss.
All four log-probability inputs are 1-D arrays (or lists) of shape (batch,).
dpo_forward(policy_chosen_logps, policy_rejected_logps, ref_chosen_logps, ref_rejected_logps, beta)
- Return a tuple of four float arrays of shape
(batch,): (losses, chosen_rewards, rejected_rewards, weights), i.e. the per-pair loss, r^c, r^r and w. Do not round.
- It must stay finite and warning-free when r^c−r^r is as large as ±1000.
dpo_backward(policy_chosen_logps, policy_rejected_logps, ref_chosen_logps, ref_rejected_logps, beta)
- Return
(grad_chosen, grad_rejected), two float arrays of shape (batch,): the derivative of each pair's own loss with respect to that pair's policy chosen and policy rejected log-probability. Do not round.
dpo_loss(policy_chosen_logps, policy_rejected_logps, ref_chosen_logps, ref_rejected_logps, beta)
- Return the mean of the per-pair losses as a Python float rounded to 4 decimals.
Hints
- −logσ(u)=log(1+e−u), and σ(−u)=1/(1+eu); both can be written with a log-sum-exp of 0 and ±u, which never overflows.
- The reference log-probabilities are constants: no gradient flows into them.