Practice in Lab: Differentiate response-masked Direct Preference Optimization →
Differentiate response-masked Direct Preference Optimization
DPO compares the policy’s chosen-versus-rejected log-probability margin with a frozen reference margin. Summing only response targets keeps prompt and padding positions out of that comparison. Length normalization would change the objective, rather than merely improve numerical stability. Softplus evaluates the binary preference likelihood without explicitly taking a logarithm of a near-zero sigmoid. Reference ownership is observable in autograd: an accidental gradient into the reference changes the optimization problem even when the scalar loss initially looks correct.
Prepare offline
Choose Download entire course or Download entire category first. After completion, code and checks run locally on CPU. The independent example needs no account, remote service or API key.
import torch
from torch.nn import functional as F
margin = torch.tensor([-1000., 0., 1000.])
print(F.softplus(-margin))Review the evidence
Audit pair identity, response masks, length bias and preference provenance. A decreasing preference loss does not by itself establish helpfulness, safety or generalization to new prompt groups.
Your task
Inputs are finite floating [batch,2,time,vocab] logits and int64 [batch,2,time] aligned response targets; pair index 0 is chosen, 1 rejected, and -100 masks non-response positions. Sum valid token log probabilities for each response, not their length average. Return mean(softplus(-beta*((policy_chosen-policy_rejected)-(reference_chosen-reference_rejected)))). Detach all reference logits. Every response needs a valid target. Reject bad labels, shape, empty batches and nonpositive/nonfinite beta. This is the DPO objective, not a claim of aligned behavior from passing a small fixture.
The explanation opens here once every check passes.