Unit 4 of 11 · about 4 hours · derive, implement

DPO gradient weighting and chosen-rejected order invariants

A correct scalar loss is not enough if labels, signs or gradients are wrong. These invariants isolate such failures without relying on a training curve.

You'll be able to

  • Derive the margin-dependent DPO gradient and verify it with autograd.
  • Test chosen-rejected swaps, label inversion and pair-order invariance.
  • Explain why hard or mislabeled pairs can dominate update pressure.

Covers

Gradient weighting for easy, hard and mislabeled pairsChosen-rejected order, sign and label invariants
1

Read

In this order, only the parts listed

0 of 2 done

  1. The RLHF Book: DPO gradient derivationRLHF Book - Direct Alignment

    Chapter 8, DPO Derivation: Deriving the BT DPO Gradient (page read 2026-10-14)

  2. DPO: update weightingDirect Preference Optimization

    arXiv:2305.18290v3, Section 4, What does the DPO update do?

2

Focus on

  • For unscaled adjusted margin , . Thus the chosen and rejected log-probability partial derivatives have equal magnitudes and opposite signs.
  • Easy positive margins reduce this scalar weight. Hard negative margins increase it toward , including confidently contradicted labels that may be wrong.
  • Swapping chosen and rejected in both policy and reference negates . With a fixed winner label, . Swapping candidate positions and inverting a binary target preserves binary cross-entropy.
  • These are partial derivatives of supplied log probabilities. Shared model parameters couple completions, so a parameter update need not increase every chosen completion's absolute probability.
Common mistakes · 3
  • Swapping only policy completions. Their reference scores must travel with their completion identities.
  • Checking the gradient of a mean against a derivative for a sum. A pair-averaged loss divides each pair contribution by batch size.
  • Calling gradient weighting a label-noise detector. A hard pair can be informative or mislabeled; its large weight does not distinguish those cases.
3

Try it yourself

Closed-book, before checking anything

Derive the gradient closed-book. On CPU in PyTorch torch.float64, use unscaled margins [-2.0, 0.0, 2.0], , and sum the three pair losses. The margin derivatives are approximately -0.36552928931500245, -0.25 and -0.13447071068499755. Match the analytic derivative with autograd and torch.autograd.gradcheck. For the preceding unit's single pair, recover chosen and rejected log-probability gradients -0.18877033439907273 and 0.18877033439907273, then verify swap and batch-permutation invariants to absolute tolerance .
4

Quiz yourself

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

0 got · 0 missed

  1. 1.At zero adjusted margin, what are the chosen and rejected partial derivatives?Answer

    For one pair they are and . Gradient descent therefore favors increasing the chosen-minus-rejected log-probability gap.

  2. 2.Does a chosen-rejected swap preserve the loss?Answer

    Not with a fixed winner target. It negates the logit and changes the loss by the original logit. Inverting the binary target as well preserves the represented comparison.

  3. 3.Why might both completion probabilities fall even with correct gradient signs?Answer

    The partial derivatives treat their log probabilities as separate inputs. A normalized model with shared parameters and other batch examples couples their changes and can move mass to other completions.

5

Practice

  • TensorTonic: Canonicalize Pairwise Preference Data

    Language Modeling from Scratch: canonical_preference_pairs; all three public cases

    The free public cases check all three pairs in a three-candidate strict ranking, unsorted input and preservation of two prompt records. They do not check ties, duplicate records or gradients. The section mini-project covers the analytic gradient and swap regression tests.

You're done when

You pass the canonicalization cases and your own gradient, swap and batch-order tests, and explain why a mislabeled hard pair receives a large weight.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 8 more in the section
  • RLHF Book - Direct AlignmentNathan Lambert · primary

    Study Chapter 8 (DPO, its derivation, numerical concerns and online versus offline data) and the code/direct_alignment package at natolambert/rlhf-book at commit 1042143 (DPO, IPO, KTO and APO are validated there; its SimPO and ORPO runs are marked noisy). Re-derive DPO from the KL-regularized objective, implement sequence log-ratio losses from blank tensors and test chosen-rejected swaps, prompt masking, reference drift and length normalization.

  • Direct Preference OptimizationRafailov et al. · required

    Read the complete derivation, objective and experiments. State the preference-model and reference assumptions, then compare a scratch DPO update with SFT and rejection-style baselines on a held-out slice.

Also in this section

  • A General Theoretical Paradigm to Understand Learning from Human PreferencesGheshlaghi Azar et al. · required

    Study the preference-model misspecification argument and IPO objective. Use one synthetic preference problem to compare DPO and IPO behavior as noise, margin and data reuse change.

  • KTO: Model Alignment as Prospect Theoretic OptimizationEthayarajh et al. (ICML 2024) · support

    Read the unpaired-feedback setting and the KTO loss with its reference point. State what data KTO needs that DPO does not, and test its loss on fixed log probabilities.

  • SimPO: Simple Preference Optimization with a Reference-Free RewardMeng, Xia and Chen (NeurIPS 2024) · support

    Read the length-normalized, reference-free reward and the target margin. Use it as the no-reference baseline and compare its length behavior with summed-log-probability DPO.

  • Stanford CS224R 2026 - LLM Preference OptimizationStanford University · required

    Study Lecture 09 (RL for LLMs: preference optimization, slides/09_cs224r_rlhf_2026.pdf) and Section 1.3.2 (IPO) of the default project guidelines. Implement independently, preserve the reference policy and follow course material restrictions.

  • TRL DPO TrainerHugging Face · support

    After the scratch loss passes, inspect the DPOTrainer data contract and options for TRL 1.15.0. Differential-test one tiny batch against the local objective and record library version, loss type, , padding, truncation and reference behavior.

  • TensorTonic - DPO and Preference ProblemsTensorTonic · support

    Solve Implement the DPO Loss (cs336-l15-direct-preference-optimization-loss), Canonicalize Pairwise Preference Data (cs336-l15-canonical-preference-pairs) and Score a KL-Regularized Policy Batch (cs336-l15-kl-regularized-policy-objective), free problems in the Language Modeling from Scratch plan, as closed-book checks after your own loss passes.

  • Hands-on Modern RL - Chapter 14 DPOWalking Labs · support

    Use the DPO derivation page and the hands-on page for a bounded DPO experiment and metrics. Its displayed loss is the per-pair summand (average it over the dataset), and its implicit reward is exact only at the KL-regularized optimum; its training logs are illustrative. Replace any opaque trainer-only step with a checked local loss and retain a or length regime where quality worsens. Pin commit 9231bab of walkinglabs/hands-on-modern-rl; its code/chapterNN folders do not follow the site chapter numbers.

  • LLM Post-Training Laboratory - Direct Preference ObjectiveRoadmap-Final · required

    Complete the DPO-style objective with exact sequence log probabilities, frozen reference identity, fixed loss and gradient tests, common raw evaluation records, support analysis and reward, length, style and judge-hacking probes.