Unit 3 of 11 · about 5 hours · derive, implement

Chosen and rejected log probabilities, reference log-ratio margins and the DPO loss

A plausible loss curve can hide a reversed reference ratio or the wrong reduction. A fixed log-probability example gives you an oracle before any language-model update.

You'll be able to

  • Implement stable, pair-averaged DPO from four completion log-probability tensors.
  • Distinguish the raw policy gap, reference-adjusted margin and scaled reward margin.
  • Explain the regularization coefficient without assuming it fixes realized KL.

Covers

Chosen and rejected sequence log probabilitiesPolicy and frozen reference log-ratio marginsDPO logistic loss and
1

Read

In this order, only the parts listed

0 of 2 done

  1. The RLHF Book: DPO loss implementationRLHF Book - Direct Alignment

    Chapter 8, Implementation Details: log-probability gaps, losses and detached rewards (page read 2026-10-14)

    Use the code block. Do not adopt the following 'KL divergence is static' claim: finite gradient steps do not solve the objective exactly or set realized KL. Reference precomputation saves workload-dependent memory, not a guaranteed 50%.

  2. DPO differential referenceRLHF Book - Direct Alignment

    DPOLoss.forward: difference of log ratios, stable loss and pair mean

2

Focus on

  • Let and . A pair contributes ; average over pairs, not completion tokens.
  • Use summed conditional completion log probabilities. The next unit checks gradient signs; Completion masks, length normalization and chat-template consistency checks how those sums are assembled.
  • Evaluate negative log-sigmoid directly, using torch.nn.functional.logsigmoid, rather than multiplying token probabilities or taking the log of an already saturated sigmoid.
  • For fixed rewards, larger keeps the optimal policy closer to reference. In a fixed empirical DPO batch it also rescales logits and gradients; neither statement guarantees monotonic measured KL during training.
Common mistakes · 3
  • Subtracting the chosen reference score but adding the rejected policy score. Write both chosen-minus-rejected gaps before subtracting the reference gap.
  • Detaching the policy log probabilities along with logging rewards. Only the logging path should lose its policy gradient.
  • Assuming positive adjusted margin means the chosen completion has greater raw probability. The reference gap can reverse the raw ordering.
3

Try it yourself

Closed-book, before checking anything

On CPU, use PyTorch torch.float64 leaf tensors for policy chosen and rejected log probabilities [-1.0] and [-2.0], fixed reference tensors [-1.5] and [-1.5], and . Derive , , chosen reward 0.25, rejected reward -0.25 and loss 0.4740769841801067. Implement the loss from blank tensors and match DPOLoss to absolute tolerance . Repeat at logits -1000 and 1000 and require finite losses and gradients.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.What is the loss when policy and reference score every completion identically?Answer

    Each adjusted margin is zero, so each pair's loss is , irrespective of its length or raw likelihood gap.

  2. 2.Why not multiply token probabilities first?Answer

    The product underflows for long sequences. Sum token log probabilities and keep the preference loss in a stable log-domain form.

  3. 3.Does setting the regularization coefficient to zero recover SFT?Answer

    No. DPO logits become zero, the loss is constant , and its policy gradient vanishes.

5

Practice

  • TensorTonic: Implement the DPO Loss

    Language Modeling from Scratch: direct_preference_optimization_loss; all three public cases

    The free public cases cover positive and mixed margins and a zero margin with smoothing. Return the requested tensors, including strict reward-ranking accuracy where ties are incorrect. Add your own autograd and extreme-logit tests; the public cases do not establish them.

You're done when

Your scratch loss matches the numeric oracle and the book implementation, remains finite at extreme logits and passes the three public cases.

Only when you can do this without notes.

Leads to

Notes

Resources · 1 for this unit, 9 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.

Also in this section

  • 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.

  • 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.