Unit 5 of 11 · about 4 hours · implement

Completion masks, length normalization and chat-template consistency

DPO operates on conditional completion probabilities. Reuse The next-token objective: shifts, masks and perplexity and From documents to training examples: packing and loss masks; the new work is preserving that contract across four scores and two response lengths.

You'll be able to

  • Implement shifted completion-only sequence scoring with explicit EOS and padding rules.
  • Demonstrate that replacing token sums with token means changes the preference objective.
  • Audit prompt-token identity, chat templates and truncation before comparing policy and reference scores.

Covers

Completion-only masks and prompt cancellationSummed versus length-normalized log probabilitiesTokenizer, chat-template and truncation consistency
1

Read

In this order, only the parts listed

0 of 3 done

  1. Sequence scoring helperRLHF Book - Direct Alignment

    compute_logprobs: shifted logits, labels and mask; average_log_prob branches

    Pass a completion loss mask, not just the attention mask described in the docstring. Keep prompt tokens visible as context. Reject empty scored completions rather than letting the clamped mean denominator hide them.

  2. TRL 1.15.0: data and preprocessing contractTRL DPO Trainer

    Expected dataset type and format; Preprocessing and tokenization; DPOConfig parameters max_length and truncation_mode

    Inspect the data contract only. Do not run the full quick start or assume its truncation matches the book's collator.

  3. SimPO: changing the sequence scoreSimPO: Simple Preference Optimization with a Reference-Free Reward

    arXiv:2405.14734v3, Section 2.2 equations 3 to 4

2

Focus on

  • For each completion, sum over scored target positions. Shift the completion mask with the labels exactly once.
  • A common prompt's joint log probability cancels algebraically in a same-prompt difference. Different templates, token boundaries or per-response prompt truncation invalidate that argument; compare actual prompt token IDs.
  • Token means are not sequence log probabilities. Unequal lengths change the adjusted margin and the gradient weighting, even when both policy and reference are normalized consistently.
  • Declare whether EOS is scored, where completion starts, how padding is excluded and what overlength pairs lose. Inspect rendered text and token IDs for both branches; do not silently train after truncation removes the preferred distinction.
Common mistakes · 3
  • Removing prompt tokens from attention to achieve completion-only loss. They remain necessary conditioning context.
  • Masking by token ID when padding reuses EOS. That can remove real EOS targets; mask by position and sequence ownership instead.
  • Comparing separately tokenized prompt lengths without checking the full sequence prefix. Tokenization at a text boundary can change IDs.
3

Try it yourself

Closed-book, before checking anything

On CPU with PyTorch torch.float64, use zero logits of shape (1, 4, 2), token IDs [[0, 1, 0, 1]] and an unshifted completion mask [[0, 0, 1, 1]]. Derive the shifted selected targets, score , and mean . Match compute_logprobs to absolute tolerance . Only scoring-logit positions 1 and 2 receive gradients. Give the rejected branch one scored token: with identical policy and reference, adjusted margin stays zero although the raw policy gap is . Then test an actual template's completion boundary and an overlength pair in your scorer.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Can changing prompt input tokens change a completion-only loss?Answer

    Yes. Prompt targets are excluded, but prompt inputs still condition completion predictions. Only masked-out output logits are free to change without affecting the score; changing any input token can still move the scored completion logits.

  2. 2.Why does replacing sums by means not simply rescale the whole batch?Answer

    Chosen and rejected lengths can differ within a pair and across pairs. Each score then gets a different divisor.

  3. 3.What should happen if truncation leaves no scored completion tokens?Answer

    Reject or explicitly classify the record as invalid and count it. A zero sum or clamped denominator is not a meaningful preference example.

You're done when

Your scorer passes the fixed-logit oracle and boundary tests, and you can exhibit an unequal-length pair whose adjusted margin changes under token means.

Only when you can do this without notes.

Leads to

Notes

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

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

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

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.

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

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