Unit 6 of 10 · about 5 hours · derive, implement

The DPO derivation, \(\beta\), margins and gradient pressure

The reparameterization removes a reward-model training stage, not the assumptions behind preference learning. The gradient reveals which mislabeled or poorly covered comparisons can dominate a bounded run.

You'll be able to

  • Derive DPO by substituting the KL-optimal policy into a Bradley-Terry likelihood, retaining the partition term until it cancels.
  • Implement stable DPO from four response log-probability tensors and verify its policy-input gradients.
  • Explain how the adjusted margin, label noise and regularization coefficient affect update pressure without promising behavior gains.

Covers

DPO derivation from policy and reference log-probability ratiosBeta, margins and gradient pressure on chosen and rejected responses
1

Read

In this order, only the parts listed

0 of 3 done

  1. DPO: derivation and gradientDirect Preference Optimization

    arXiv:2305.18290v3, Section 4 equations 4 to 7 and What does the DPO update do?; Appendix A.2 and A.4, deriving the Bradley-Terry objective and its gradient

  2. The RLHF Book: Chapter 8, Direct-Alignment AlgorithmsRLHF Book - Reward Models, Direct Alignment and Preferences

    DPO Derivation: Deriving DPO Objectives for BT Models and Deriving the BT DPO Gradient; Implementation Details

    Use the derivation and loss listing, not the claim that KL is static or that each update reaches the optimal policy. Finite-data, finite-step fitting need not recover the population optimum.

  3. Stable differential reference for the pair lossRLHF Book Code - Reward Models and Direct Alignment

    DPOLoss.forward: chosen/rejected log ratios, stable logistic loss and detached logging metrics

    Use the executable two-term smoothing expression if exploring soft labels. Ignore the nearby comment that combines a sum of log sigmoids into the log of their sum; that algebra is invalid.

2

Focus on

  • Let , , and . The pair loss is .
  • Recover . Only a shared prompt lets the partition term cancel in the pair likelihood. State the fixed-reference, Bradley-Terry and support assumptions.
  • The scalar derivative is . Its magnitude is greater for negative than positive margins at the same coefficient. A mislabeled hard pair can therefore exert substantial pressure.
  • The reference is frozen. The coefficient controls both loss scaling and the population reward/KL trade-off; changing it is not merely changing the learning rate, nor a guarantee of monotonic realized KL.
Common mistakes · 3
  • Subtracting the reference gap in the wrong direction. Write all four scores before simplifying the margin.
  • Using detached implicit rewards to form the training loss. Detachment is for reporting only; the policy scores in the loss must retain their graph.
  • Saying every parameter update raises the chosen probability and lowers the rejected probability. The scalar score derivatives have opposite signs, but shared model parameters and probability normalization can move both probabilities down.
3

Try it yourself

Closed-book, before checking anything

Derive the substitution and margin gradient without notes. On CPU with PyTorch 2.14.1 and torch.float64, use policy chosen/rejected log probabilities -3 and -5, reference chosen/rejected -4 and -5, and . Obtain , loss 0.5130152523999526, and policy-input derivatives approximately -0.1605249359550192 and 0.1605249359550192. Match the pinned DPOLoss and torch.autograd.gradcheck; compare these values with absolute tolerance . Repeat stable loss evaluation at scaled logits -1000 and 1000, requiring finite losses and gradients rather than nonzero gradients at saturation.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.At identical policy and reference scores, is there no learning signal?Answer

    The adjusted margin is zero and loss is , but the margin derivative is . The parameter gradient need not vanish unless the two policy-score gradients cancel.

  2. 2.Does increasing the coefficient always increase gradient magnitude?Answer

    No. At a fixed positive margin, the coefficient multiplies a sigmoid weight that decreases as the scaled margin grows. At zero margin the magnitude is ; negative margins behave differently.

  3. 3.Does the derivation prove that an offline DPO run equals online RLHF in behavior?Answer

    No. It reparameterizes a preference model through the optimal policy of a specified KL-regularized reward problem. Coverage, model fit, optimization and preference-model assumptions still limit the learned policy.

5

Practice

  • TensorTonic: Implement the DPO Loss

    Implement direct_preference_optimization_loss(policy_chosen, policy_rejected, reference_chosen, reference_rejected, beta, label_smoothing)

    Free. Public cases cover a positive margin, mixed margin signs and a zero margin with smoothing; strict reward ties count as incorrect. They do not test gradients or text masking. Add the independent derivative check above before using a model.

You're done when

You derive the complete substitution, pass the public score examples and match the independent gradient oracle, including finite extreme-logit behavior.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 17 more in the section
  • RLHF Book - Reward Models, Direct Alignment and PreferencesNathan Lambert · primary

    Read Chapter 5 (reward models), Chapter 8 (direct alignment), Chapters 10 and 11 (preferences and preference data) and Chapters 14 and 15 (over-optimization and regularization) at rlhfbook.com/c/NN-slug.html. Only Chapters 5 and 8 have Suggested Experiments; do those. Trace preference data through reward modeling or DPO and list each distribution and evaluator assumption before training.

  • Direct Preference OptimizationStanford University · required

    Read Section 4 and Appendix A: derive the objective from the KL-constrained reward formulation, implement it from policy and reference log probabilities summed over response tokens, and gradient-check , sign, masking and identical-pair cases. TRL's sigmoid_norm variant normalizes by length, which the paper does not.

  • RLHF Book Code - Reward Models and Direct AlignmentNathan Lambert · support

    Run the preference reward model with a frozen backbone (only the head trains) and the DPO, IPO and length-normalized DPO configs with smaller models and contexts than the defaults. The final partial accumulation window is under-weighted, so fix or avoid it. Explain margins, accuracy and rewards rather than raw loss.

Also in this section