PythiloLesson 1 of 8 · progress kept in this browser

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.

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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.