Unit 8 of 12 · about 4 hours · implement, measure
Reference KL penalties, masks, truncated completions and length incentives
The reference penalty and response boundary are part of the objective. A plausible scalar KL or loss can hide a reversed ratio, a missing stopping action or an uncounted truncated output.
You'll be able to
- Implement a reference-KL estimator with an explicit sampling distribution and reduction.
- Test EOS, padding and length-limit boundaries without silently treating truncation as a completed answer.
- Measure how masks, reward placement and normalization alter length incentives.
Covers
Read
In this order, only the parts listed
0 of 3 done
- RLHF Book: reference KLRLHF Book - Policy Gradients and Regularization
Chapter 15, KL Divergence in RL Optimization, Reference Model to Generations and Implementation Example, equations 2 to 4 (page read 2026-10-14)
Stop before Other Tools to Control Optimization. The example passes two log tensors to
F.kl_divwithoutlog_target=True; correct that and define the token reduction. Its sequence sum also needs a completion mask. - DAPO: truncated samples and length shapingDAPO: An Open-Source LLM Reinforcement Learning System at Scale
arXiv:2503.14476v2, Section 3.4, Overlong Filtering and Soft Overlong Punishment, equation 13
- TRL 1.15.0: KL and truncation configurationTRL GRPO Trainer
Estimating the KL divergence, Loss Types, and
GRPOConfig'sbeta,mask_truncated_completionsanduse_bias_correction_klparametersInspect these contracts only. A sampled KL value and its fixed-rollout gradient are different checks; record any correction for old-policy sampling.
Focus on
- Build on Token entropy, sequence diversity, KL direction and KL estimators. Write instead of relying on forward or reverse labels. For current-policy samples with shared support, and have the same KL expectation.
- A detached rollout log-ratio can shape rewards; an explicit current-policy KL term has its own gradient. Neither estimator's value identity alone proves that fixed-old-sample autodiff equals the exact sequence-KL gradient.
- Include sampled EOS when optimizing complete-sequence likelihood. Mask prompt tokens and post-EOS padding. A length-limit stop has no sampled EOS; retain its reason and choose a specified reward, bootstrap or loss-exclusion policy.
- Per-token KL means and sequence KL sums have different length weighting. Dropping truncated losses changes the training population; log their rewards, lengths and cost even when their loss is masked. Measure length by correctness and validity, not just its overall mean.
Common mistakes · 3
- Using
exp(d) - d - 1on policy samples as the same KL oracle. The probability ratio is reversed. - Interpreting a negative sampled log ratio as impossible KL. Individual log ratios can be negative; the exact expectation is nonnegative.
- Discarding long failures, then reporting success only over the remaining outputs. That changes the evaluation denominator.
Try it yourself
Closed-book, before checking anything
[0.75, 0.25] and reference [0.5, 0.5]. Both the policy-weighted log ratio and the policy-weighted exp(-d) + d - 1 give approximately 0.13081204 nats. Confirm with torch.nn.functional.kl_div(reference.log(), policy.log(), reduction="sum", log_target=True). Then test completion records for immediate EOS, EOS followed by padding and length-limit truncation: only sampled actions enter the sequence likelihood, finite padding changes do not alter loss or gradients, and truncation remains a separate outcome.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Does a format-valid truncated answer necessarily have a terminal outcome reward?Answer
Only if the task contract scores that prefix as a valid answer. A generation cap alone does not establish completion or correctness.
2.What if the policy places mass where the reference probability is zero?Answer
The policy-to-reference KL is infinite. Epsilon floors change that quantity and must not be hidden as exact KL.
3.Does turning off the KL loss make reference-drift monitoring unnecessary?Answer
No. Loss regularization and diagnostic measurement are separate choices. TRL does not log its KL metric when
betais zero, so add an independent diagnostic if needed.
Practice
- Compare Sequence and Token Length Normalization
Language Modeling from Scratch plan, Compare Sequence and Token Length Normalization: statement and public examples
The section mini-project extends this reduction check with reference-KL enumeration and EOS, padding and truncation cases.
You're done when
Your enumerated KL matches the corrected library call, boundary tests pass, and every excluded completion remains visible in the cost and outcome ledger.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- RLHF Book - Policy Gradients and RegularizationNathan Lambert · primary
Study Chapter 6 completely (REINFORCE, RLOO, PPO, GRPO, GSPO, CISPO, loss aggregation, asynchronous systems, truncated importance sampling) and Chapter 15 on KL and regularization. Implement REINFORCE, PPO-style, RLOO and GRPO fixed-rollout losses from the chapter equations, then verify masks, ratios, group baselines and one-gradient-step simplifications.
- DAPO: An Open-Source LLM Reinforcement Learning System at ScaleYu et al. (2025) · support
Read Sections 2 and 3: decoupled clipping bounds, dynamic sampling that drops all-equal groups, the token-level loss and overlong reward shaping, and the removal of the KL term. Compare its token-level aggregation with GRPO's per-sequence mean on a fixed group.
- TRL GRPO TrainerHugging Face · support
After scratch estimator tests pass, inspect the GRPOTrainer for TRL 1.15.0: its reward-function, generation, loss and logging contracts. Its defaults changed across releases (
loss_type="dapo"andbeta=0.0in 1.15.0), so differential-test one batch and record every default you rely on.
Also in this section
- RLHF Book Course - Lectures 3 and 4Nathan Lambert · required
Use Lecture 3 (RL motivation and math, Chapter 6 part 1) and Lecture 4 (RL implementation and practice, Chapter 6 part 2: loss aggregation, asynchronous training). Reproduce the loss on a tiny frozen rollout before using any trainer library.
- Back to Basics: REINFORCE Style Optimization for Learning from Human FeedbackAhmadian et al. · required
Study the RLOO estimator, baseline construction and system simplifications. Compare RLOO with a value-baseline or grouped estimator under matched completions and reward calls.
- DeepSeekMath - GRPODeepSeek AI · required
Study the GRPO method and group-relative advantage construction, not the unrelated pretraining details. Implement all-equal and mixed-reward group tests and separate algorithmic changes from additional sampling.
- Berkeley CS 185/285 Deep Reinforcement Learning (Spring 2026) - LLM RL Lecture and Homework 4UC Berkeley · required
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) and the Homework 4 handout: log probabilities, minibatching, advantage normalization, GR-REINFORCE and GRPO on a format task and a math task, plus a GRPO hyperparameter study. It is configured for H100 GPUs on Modal (about 8 GPU hours), so port the code paths to a tiny model on your GPU or run them on pre-generated rollouts.
- Understanding R1-Zero-Like Training: A Critical Perspective (Dr. GRPO)Liu et al. (COLM 2025) · support
Read Section 3: the response-length bias of per-sequence normalization and the question-difficulty bias of dividing by the group standard deviation. DAPO keeps the standard deviation that Dr. GRPO removes, so treat the choice as open and test both on a fixed group.
- Build a Reasoning Model (From Scratch) - Chapters 6 and 7Sebastian Raschka (Manning) · support
Use Chapter 6 (rollouts, rewards, group advantages, sequence log probabilities and the GRPO loss on Qwen3 0.6B) and Chapter 7 (metrics, clipped ratios, the KL term and a format reward) as the smallest runnable GRPO loop. Listing 6.13 is the unclipped loss; the clipped and KL versions come in Chapter 7. Its advantages use the unbiased
torch.std. - TensorTonic - GRPO ProblemsTensorTonic · support
Solve Normalize GRPO Group Advantages (
cs336-l16-grpo-group-advantages), Compute a Clipped GRPO Surrogate (cs336-l16-clipped-grpo-surrogate) and Compare Sequence and Token Length Normalization (cs336-l16-grpo-length-normalization-audit), free problems in the Language Modeling from Scratch plan, as closed-book checks after your own estimator passes. - Hands-on Modern RL - Chapter 15 GRPO and RLVRWalking Labs · support
Use the GRPO practice and mechanism page and the RLVR page: its group-normalization demo and rule-based reward script run on CPU in seconds. Its TRL examples pin TRL 0.24, whose defaults differ from current releases. Run only a small verifier task and preserve zero-variance, length-hacking and invalid-output cases. Pin commit 9231bab of walkinglabs/hands-on-modern-rl; its
code/chapterNNfolders do not follow the site chapter numbers. - RLHF Book Code - Policy GradientsNathan Lambert · support
Use the
code/policy_gradientspackage at natolambert/rlhf-book at commit 1042143 as a differential reference after the hand implementation passes (loss.pyholds the masked means, the GRPO and PPO losses and the , , KL estimators). Trace every tensor to prompt, completion and policy version and extend the tests with stale-log-prob and mask defects. - LLM Post-Training Laboratory - Online RLRoadmap-Final · required
Complete one PPO-style, RLOO or verifiable group-relative update with immutable rollouts, fixed tests, bounded queues, SFT and direct-preference controls, reward-hacking probes and all failed or filtered samples retained.