Unit 9 of 11 · about 4 hours · implement, measure

DPO margin, reward, KL and length diagnostics and fixed-batch tests

Preference accuracy is one training signal, not an evaluation suite. Diagnostics must separate objective correctness from movement in the policy's generated behavior.

You'll be able to

  • Build fixed-batch tests for DPO loss, gradients, masking and reference invariants.
  • Measure margins, both completion likelihoods, generated-policy KL, entropy, length and validity with explicit sampling units.
  • Differential-test the scratch objective while recording the trainer's version and loss conventions.

Covers

Margin, reward, KL, entropy, length and validity diagnosticsFixed-batch loss, gradient and invariance tests
1

Read

In this order, only the parts listed

0 of 3 done

  1. TRL 1.15.0: logged metrics and exact loss pathTRL DPO Trainer

    Logged metrics; follow the DPOTrainer source link to _compute_loss for completion sums, loss branches and strict reward accuracy

    Use standard sigmoid DPO for the differential test. Despite its documentation's SimPO attribution, this release's sigmoid_norm branch retains reference-adjusted scores and has no target-margin offset; it is not the complete SimPO baseline.

  2. DPO metrics: what the curves omitHands-on Modern RL - Chapter 14 DPO

    Reward Margin, Reward Accuracy, and Chosen Reward vs Rejected Reward (page read 2026-10-14)

    Skip the illustrative training logs and healthy-range targets. With identical deterministic policy and reference scores, strict reward accuracy is zero because all rewards tie; the page's near one half figure is for similar but untied scores at initialization.

  3. Post-training laboratory: instrumentation and testsLLM Post-Training Laboratory - Direct Preference Objective

    Milestone B - Instrumentation; Correctness requirements; Failure-injection requirements; Hardware variants

    Apply these to the DPO evidence pack only. No rollout service, distributed training or online objective is required here.

2

Focus on

  • Log raw chosen and rejected sequence log probabilities, both reference-adjusted rewards, unscaled margins and scaled margins. Record pair weighting and tie treatment rather than conflating ranking with token prediction accuracy.
  • An offline pair's log-ratio is not policy KL. Estimate policy-to-reference KL on policy-sampled completions with declared decoding and stopping, or compute it exactly in a finite response space. Log its units as nats per sequence or nats per token.
  • Teacher-forced token entropy on preference contexts is different from entropy on generated contexts. Keep both context source and token reduction with the metric; report generated lengths and invalid or truncated outputs separately.
  • Test scalar values, analytic and numerical gradients, pair swaps, batch permutations, prompt-score cancellation, padding and frozen-reference identity. Use a tolerance appropriate to the dtype, not bitwise equality across execution paths.
Common mistakes · 3
  • Calling a rising implicit reward a reward-model or verifier improvement. It is computed from the policy being trained.
  • Using preference-data log-ratio means as generated-policy KL or interpreting their negative values as an implementation failure.
  • Requiring a CPU language-model run through TRL 1.15.0's fused trainer path. Keep CPU tensor and scorer tests independent; use the optional trainer comparison on your GPU.
3

Try it yourself

Closed-book, before checking anything

Assemble the previous fixed-tensor loss, gradient and mask oracles into one CPU test suite. Compare your loss and policy-input gradients with the book's DPOLoss at the pinned commit using torch.float64 and absolute tolerance . Add equal policy-reference scores, duplicated batches and extreme logits: initialization loss is , strict reward accuracy is zero, and duplicating a batch preserves its mean loss. Inspect the TRL 1.15.0 sigmoid branch against that formula. With room on your GPU, also differential-test one tiny-model batch through DPOTrainer; use about 0.1 to 0.6 billion parameters, short completions and a frozen reference. Record dtype-specific discrepancies, padding, truncation, loss type, version and , rather than expecting the float64 tensor tolerance from mixed-precision model scores.
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, do chosen and rejected completions receive zero policy gradients?Answer

    No. Their reward difference is zero, but the logistic loss has nonzero derivative there. Detached reference scores do not cancel policy derivatives.

  2. 2.Why log both likelihoods if margin and accuracy already improve?Answer

    Both completion probabilities can fall while the rejected one falls faster. Margin-only logs hide that displacement.

  3. 3.Can sequence KL and token-averaged KL be compared as the same quantity?Answer

    No. They use different units and length weighting. State the reduction and compare like with like.

You're done when

Your CPU oracles pass, deliberate sign, mask and reference bugs fail, and every diagnostic declares its sampling distribution, units and reduction.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 7 more in the section
  • 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.

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

Also in this 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.

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

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