Unit 7 of 10 · about 5 hours · implement

Response-only log probabilities, masks and reference-checkpoint identity

The four scalars in a DPO loss are meaningful only if they score the same conditional events. A stale reference cache or a shifted completion mask silently defines a different experiment.

You'll be able to

  • Compute shifted response-only log probabilities with explicit prompt, padding, EOS and truncation rules.
  • Bind reference scores to the exact checkpoint, tokenizer, template and scored token sequence.
  • Demonstrate that reference mismatch changes policy gradients even when the policy scores stay fixed.

Covers

Response-only sequence log probabilities, masks and length normalizationReference-checkpoint identity, tokenizer compatibility and stale caches
1

Read

In this order, only the parts listed

0 of 3 done

  1. Shifted sequence-scoring referenceRLHF Book Code - Reward Models and Direct Alignment

    compute_logprobs: the logit, label and mask shifts; gathered token scores; average_log_prob branches

    Pass a completion-and-padding mask, not merely the attention mask suggested by the helper's docstring. Its average branch is a different score convention, not ordinary summed DPO.

  2. CS336 Spring 2026 Assignment 5 supplement: model-to-loss contractCS336 Assignment 5 Supplement - Preference Data and DPO

    Section 6.3, Implementing the DPO Loss, Problem dpo_loss, printed p. 17: Alpaca template, appended EOS and run_compute_per_instance_dpo_loss

    Use the public tiny-model test on CPU. Skip Section 6.4's two-device training recipe; the bounded comparison uses your own SFT checkpoint. Prompt cancellation requires the exact same tokenized prefix in both branches, not merely similar prompt text.

  3. TRL 1.15.0: preprocessing and frozen-reference configurationTRL DPO Trainer

    Expected dataset type and format; Preprocessing and tokenization; DPOTrainer ref_model; DPOConfig precompute_ref_log_probs, sync_ref_model, disable_dropout and loss types

2

Focus on

  • Score each response token from its preceding context. Shift the labels and completion mask together with the causal prediction boundary. Prompt tokens condition the model but do not enter the response sum.
  • Keep attention and loss masks distinct. Include EOS under one declared rule, exclude padding, and reject or separately count pairs whose distinguishing response is lost to truncation.
  • Hash the frozen reference weights and adapter state, tokenizer revision, template, exact token IDs, masks, EOS/truncation rules and score convention into cache identity. A filename or model family is not sufficient.
  • TRL 1.15.0 defaults to loss_type=["sigmoid"], beta=0.1 and summed completion scores. sigmoid_norm changes the aggregation. The trainer rejects a policy and reference that are the same object; keep reference synchronization off for this fixed-reference study.
Common mistakes · 3
  • Tokenizing prompt and response independently without inspecting the join. Boundary tokenization can differ from tokenizing the formatted sequence; inspect actual IDs and the first scored token.
  • Assuming equal initial policy/reference values imply zero parameter gradient. The reference must be fixed independently, not connected to the policy's autograd graph.
  • Equating a mean token log probability with a sequence log probability. Changing sum to mean changes pair weighting and the objective, especially with unequal response lengths.
3

Try it yourself

Closed-book, before checking anything

On CPU with PyTorch 2.14.1 and torch.float64, use zero logits of shape (1, 5, 3), token IDs [[0, 1, 2, 0, 1]] and unshifted completion mask [[0, 0, 1, 1, 0]]. Derive score ; only logit positions 1 and 2 receive score gradients. Match compute_logprobs within absolute tolerance . Then hold the preceding unit's policy scores and coefficient fixed, changing only the reference chosen score from -4 to -2. Loss becomes 0.9130152523999526 and the chosen policy-input derivative becomes approximately -0.2394750640449808. The rejection score stays -5. Confirm the altered gradient and require the manifest to reject that cache mismatch.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Which state changes invalidate a precomputed reference score?Answer

    Anything changing the reference conditional event or its probability: weights/adapters, tokenizer, template, token IDs, masking, EOS, truncation or aggregation. Recompute rather than mixing identities.

  2. 2.Does this one-pair reference mismatch reverse the chosen-score derivative?Answer

    No. With a positive coefficient its sign stays negative. The changed reference margin changes the gradient's weight; across shared model parameters and many pairs that can change the update direction.

  3. 3.How should you check a cached reference on a model batch?Answer

    Reload the exact frozen checkpoint in deterministic evaluation mode and rescore the same IDs and masks. Compare within a dtype-specific tolerance and verify the full manifest before accepting the cache.

5

Practice

  • CS336 Assignment 5 supplement: dpo_loss

    Section 6.3; connect run_compute_per_instance_dpo_loss and run uv run pytest -k test_per_instance_dpo_loss

    The public test uses tiny policy/reference fixtures and a local word tokenizer, then compares one scalar loss to its expected value. It does not check gradients or every mask boundary. Add unequal response lengths, padding, prompt-boundary and stale-reference tests yourself. Use PyTorch 2.14.1 and Transformers 5.19.0 for your recorded implementation, and keep solutions private.

You're done when

Your scorer passes the public tiny-model scalar check and your independent mask and reference-mismatch gradient tests, while cached scores are accepted only under matching manifests.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 17 more in the section
  • CS336 Assignment 5 Supplement - Preference Data and DPOStanford University · required

    Do supplement Section 6: inspect the HH preference data (look_at_hh) and implement dpo_loss until its test passes. Run a bounded DPO comparison only after the baseline and evaluator are frozen, with a small open model in place of the Llama 3.1 8B B200 run.

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

  • TRL DPO TrainerHugging Face · support

    After the scratch loss passes, map dataset format, reference model, and loss variants into TRL 1.15.0: the default loss_type is ["sigmoid"] with beta=0.1, log probabilities are summed over the completion, and the trainer refuses a policy that is the same object as the reference. Confirm the library loss matches your scratch objective on one frozen batch.

Also in this section