Compute the DPO loss directly from policy and reference logits
Why it matters This is the exact computation inside a DPO training step, and mistakes in gathering or masking are common.
In a real DPO step you start from logits, not ready-made log-probs: gather each answer token's log-prob, sum over the answer, then compare policy and reference.
Write dpo_from_logits(pol_logits, ref_logits, labels, beta). pol_logits and ref_logits are (2B, T, V): rows 0..B-1 are chosen answers and rows B..2B-1 are the matching rejected answers. labels is (2B, T) with -100 at positions that do not count (prompt and padding); logits[r, t] predicts labels[r, t] (already shifted).
1. Sequence log-prob of row r = sum over t with labels != -100 of log_softmax(logits[r, t])[labels[r, t]].
2. h = beta * ((pol_w - ref_w) - (pol_l - ref_l)) per pair.
3. loss = mean(-log sigmoid(h)) (stable); acc = mean(h > 0).
Return (loss, acc) as floats.
def dpo_from_logits(pol_logits, ref_logits, labels, beta)Example
when pol_logits equals ref_logits, h is 0 for every pair, so the result is (0.6931, 0.0).
Understand the idea
DPO compares how much the policy likes the chosen answer against the rejected one, relative to a frozen reference model. The only inputs are log-probabilities of whole answers, and those come from logits in three steps: log-softmax, pick the label token, add up over the answer.
Example: an answer has two tokens. At step 1 the log-softmax gives the true token log-prob -0.5; at step 2, -1.2. The answer's log-prob is -1.7. Positions labelled -100 (prompt, padding) are skipped. Do this for chosen and rejected answers under both models, then h = beta * ((pol_w - ref_w) - (pol_l - ref_l)).
If the policy equals the reference, every difference is 0, h = 0, and the loss is -log sigmoid(0) = ln 2 = 0.693.
Rule: logp(y) = sum_t [labels_t != -100] * log_softmax(logits_t)[labels_t]; loss = mean(-log sigmoid(h)).
Training libraries batch chosen and rejected answers together in one forward pass exactly like this to save time.
Shapes and data flow
logits (2B, T, V) -> log_softmax (2B, T, V) -> gathered (2B, T) -> masked sums (2B,) -> h (B,) -> scalars