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

Prompt, completion, padding and EOS masks and sequence log probabilities

The policy gradient is a masked sum of per-token terms. One wrong mask position silently trains on prompts or padding.

You'll be able to

  • Derive shifted per-token log probabilities and the masked sequence sum from a logits tensor.
  • Implement prompt, completion, padding and EOS masking that gives prompt positions exactly zero weight.
  • Predict how summed, mean and length-normalized scores rank two completions of different lengths.

Covers

Prompt, completion, padding, EOS and truncation masksPer-token and sequence log probabilitiesSummed, mean and length-normalized sequence scores
1

Read

In this order, only the parts listed

0 of 4 done

  1. Prompt masking and multi-turn maskingRLHF Book - Introduction, Training Overview and Instruction Tuning

    Implementation Details: the Prompt masking bullet (loss on responses only) and the Multi-turn masking bullet (final-turn-only versus mask-user-turns-only, with the unrolling rule)

  2. Loss aggregation and completion masksRLHF Book - Introduction, Training Overview and Instruction Tuning

    Implementation, Loss Aggregation Tradeoffs: the three strategies with Equations 45 to 47 (per sequence, per token and fixed length), plus the completion_mask note that prompt tokens are masked out

  3. Gather and sum to sequence log probabilitiesRLHF Book - Introduction, Training Overview and Instruction Tuning

    Implementation Example, Steps 1 to 5: generate, one forward pass, log_softmax, gather of generated tokens, sum to sequence log probabilities with kl_approx

    Skip the kl_full line. It passes log probabilities as the target with log_target left False, so it returns NaN in torch 2.14.

  4. Token probabilities to log probabilitiesBuild a Reasoning Model (From Scratch) - Chapters 2 to 5

    Chapter 5, Sections 5.4 to 5.5, pp. 146 to 161: token probability scores, then From token probability scores to log probabilities (sequence likelihood as the product of per-token terms)

2

Focus on

  • Shift first: position logits score token . Gather the log probability of the actual next token, then mask, then sum. Any other order mixes prompt prediction into the score.
  • Three masks do different jobs: the prompt mask removes conditioning text from the loss, the padding mask removes batch filler, and EOS handling decides whether the stop token itself is scored.
  • Summed scores grow (more negative) with length; mean scores divide by completion length; fixed-length scores divide by a constant. The choice reweights short versus long completions like a learning-rate change.
  • This unit builds on llm-foundations/tokenization-corpus-data/packing-and-loss-masks: packed SFT rows needed attention and loss masks, and rollouts need the same split with completion-only loss.
Common mistakes · 3
  • Training on prompt tokens. The model then learns to predict user queries, which is exactly what prompt masking exists to prevent.
  • Averaging over the padded length. Padding positions contribute zero loss but a wrong denominator shrinks every gradient.
  • Dropping the EOS token from the sum without deciding to. The stop decision is policy behavior; excluding it changes which sequences score well.
3

Try it yourself

Closed-book, before checking anything

Closed-book, from logits rows [1.0, 0.0, 2.0, -1.0], [0.5, 1.5, -0.5, 0.0], [2.0, 1.0, 0.0, -2.0] with target ids [2, 0, 3], derive per-token log probabilities [-0.4402, -1.5460, -4.4197], sequence sum -6.4059 and mean -2.1353.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Why must the gather use the generated token ids rather than the argmax of the logits?Answer

    The sequence score is the log probability the policy assigned to what was actually generated. Scoring the argmax instead measures a different sequence and breaks the ratio and KL identities that consume these log probabilities.

  2. 2.Two completions have identical per-token log probabilities but lengths 4 and 8. How do summed and mean scores compare them?Answer

    The summed score of the longer one is about twice as negative, so it ranks worse. The mean scores are equal. Summing penalizes length; averaging ignores it.

  3. 3.A batch has completions of lengths 4 and 7 in rows of width 7. What does per-sequence versus per-token normalization weight?Answer

    Per-sequence gives each completion equal total weight, so short-sequence tokens get larger gradients. Per-token gives each completion token equal weight, so the longer completion dominates. The book prints 2.0 and 2.0 versus 1.1429 and 2.0 for the worked example.

  4. 4.Where does the prompt mask end and the completion mask begin when the template adds a trailing assistant header?Answer

    At the first token the policy generated. Template tokens, including the assistant header, are conditioning context and stay masked; only generated tokens enter the loss.

5

Practice

  • RLHF Book Chapter 6: masked aggregation script

    Implementation, Loss Aggregation Tradeoffs: run the masked_mean and masked_sum script on the 4-token and 7-token masks and match the printed masked_mean, masked_sum and token-level results

    Then repeat on your own rollout-shaped tensors. The section mini-project tests the same masks on your rollout records.

You're done when

Your mask code reproduces the hand-derived sum and mean on a padded batch, and you can predict the ranking flip between summed and mean scores.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 8 more in the section
  • RLHF Book - Introduction, Training Overview and Instruction TuningNathan Lambert · primary

    Study Chapter 1 (introduction), Chapter 3 (training overview: problem formulation and canonical recipes), Chapter 4 (instruction tuning: chat templates and implementation details) and Appendix A (definitions) at https://rlhfbook.com/c/. Map every RLHF component into the track trajectory schema, then implement assistant-only sequence log probabilities and completion masks against hand examples.

  • Build a Reasoning Model (From Scratch) - Chapters 2 to 5Sebastian Raschka (Manning) · support

    Use Chapter 2 (loading Qwen3 0.6B and a minimal generation function), Chapter 4 (temperature, top-p and self-consistency) and Chapter 5 (token probabilities to log probabilities and sequence scores) as a code companion for log-probability, mask and inference-policy oracles. Chapters 2 to 5 run on a CPU.

Also in this section

  • RLHF Book Course - Lectures 0 and 1Nathan Lambert · required

    Watch Lecture 0 (the ML foundations of post-training, including KL) and Lecture 1 (overview of Chapters 1 to 3), with slides under https://rlhfbook.com/teach/course/. Produce a component and state-ownership diagram tied to executable tests, not a second set of general notes.

  • Training Language Models to Follow Instructions with Human FeedbackOpenAI · required

    Study the demonstration, comparison, reward-model and PPO pipeline plus evaluation design. Reconstruct the data and policy dependencies and state which results cannot be inferred from the paper at small scale.

  • KL Estimators - Schulman's Note and the RLHF Book CodeJohn Schulman; Nathan Lambert · required

    Read John Schulman's note "Approximating KL Divergence" (on joschu.net, linked from the code) for the three Monte Carlo estimators , , and their bias and variance, then the approx_kl1, approx_kl2 and approx_kl3 functions in this file at commit 1042143. Compute all three on sampled tokens from two small policies whose exact KL you know, and say which one each library you use reports.

  • Berkeley CS 185/285 Deep Reinforcement Learning (Spring 2026) - LLM RLUC Berkeley · support

    Slides are public at https://rail.eecs.berkeley.edu/deeprlcourse/static/slides/lec-N.pdf; current videos are not, and the public Fall 2023 playlist numbers lectures differently. Study Lecture 14 (LLM RL) for the language-model-as-policy formulation and how it maps onto the policy-gradient lectures.

  • Stanford CS224R 2026 LLM RL Default ProjectStanford University · support

    Read Sections 1.1 through 1.4 for the Countdown task, distinct SFT, preference and verifier datasets, objective boundaries and evaluation. Use it as a design specification and write independent code; do not submit, copy or publish Stanford course solutions.

  • Hands-on Modern RL - Chapter 13 RLHF PipelineWalking Labs · support

    Use the base-model-to-assistant page and the PPO-RLHF loop page for the pipeline and the token-level ratio, clip and KL order of operations. Its KL sketch is the simple log-ratio difference; audit masks and log probabilities independently and defer scale engineering to RL-12. Pin commit 9231bab of walkinglabs/hands-on-modern-rl; its code/chapterNN folders do not follow the site chapter numbers.

  • LLM Post-Training Laboratory - Baseline and State ContractRoadmap-Final · required

    Build or reuse the laboratory frozen base, SFT and evaluation baseline plus immutable tokenizer, template, model, policy and rollout manifests. Complete fixed log-probability, mask and state-identity tests only in this stage.

  • TRL GRPO Trainer - KL estimation and lossHugging Face · reference

    Read Estimating the KL divergence for the k3 formula with the reference-over-policy ratio, and the default KL-coefficient note. Use it as the correct-ratio reference beside the RLHF Book code estimators.