Unit 7 of 12 · about 5 hours · derive, implement
Token log probabilities, importance ratios, clipping and loss aggregation
A correct ratio can still feed the wrong estimator. Token clipping and loss reduction control different parts of the update and must be tested separately.
You'll be able to
- Implement detached old-policy token ratios and the sign-dependent clipped surrogate.
- Derive the distinction between token surrogates and exact sequence importance weights.
- Compare sequence means, token means and constant-denominator reductions on one frozen batch.
Covers
Read
In this order, only the parts listed
0 of 2 done
- RLHF Book: token ratios and loss reductionsRLHF Book - Policy Gradients and Regularization
Chapter 6, Proximal Policy Optimization (PPO), Understanding the PPO Objective, and Loss Aggregation Tradeoffs (page read 2026-10-14)
Reuse the earlier PPO clipping derivation. Clipping is a surrogate plateau, not a hard constraint on the updated policy. Compare reductions with identical token terms; the chapter's comparison script computes
masked_mean_token_levelonratioalone, without the advantages its other two reductions use. - DAPO: asymmetric clipping and token aggregationDAPO: An Open-Source LLM Reinforcement Learning System at Scale
arXiv:2503.14476v2, Sections 3.1 and 3.3, equations 10 and 12
Read the equations and weighting argument only. The paper's probability bounds describe clipping plateaus, not guaranteed bounds after an optimizer step.
Focus on
- Compute on identical sampled tokens and prefixes. Old log probabilities and advantages stay detached.
- Maximize . A positive advantage plateaus above the upper bound; a negative advantage plateaus below the lower bound. Other out-of-range cases still have gradients.
- Exact trajectory reweighting uses . A token ratio leaves the old prefix distribution in place; token PPO is a local surrogate, not exact off-policy correction of terminal sequence reward.
- Name the denominator: response length then response mean, total valid tokens, or a fixed batch-size times generation limit. If group sizes vary, specify whether prompts or completions get equal weight. Accumulated token sums need a shared denominator to match a full-batch token mean.
Common mistakes · 3
- Clamping the ratio and discarding the minimum. This incorrectly removes corrective gradients on the wrong side of the interval.
- Using reference log probabilities as old log probabilities. The reference anchor need not have generated the rollout.
- Averaging token means from unequal minibatches. It does not recover the full-batch token mean unless token counts are equal or correctly weighted.
Try it yourself
Closed-book, before checking anything
torch.float64, use ratios [0.5, 1.5, 0.5, 1.5], detached advantages [2., 2., -2., -2.] and clip width 0.2. The maximized terms are [1., 2.4, -1.6, -3.]; the negative mean loss is 0.3 and its gradients with respect to current selected log probabilities are [-0.25, 0., 0., 0.75]. Separately reduce token terms [1., 1., 1., 1., 10.] and [1., 1., 1., 1., 1., 1., 1., 1., 1., 10.]: sequence mean 2.35, token mean 2.2, constant denominator 20 gives 1.65.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Can every token ratio be inside the clip interval while the sequence ratio is outside?Answer
Yes. Two ratios of 1.1 multiply to 1.21, outside an interval with upper bound 1.2.
2.Does a clipped token have no influence on any parameter update?Answer
Its active clipped outcome term has zero derivative away from a boundary. Other tokens, KL and shared parameters can still move its probability.
3.Does TRL's dapo loss type select the complete DAPO recipe?Answer
No. It selects a reduction. Reward scaling, clipping bounds, KL and sampling need separate configuration.
Practice
- Compute a Clipped GRPO Surrogate
Language Modeling from Scratch plan, Compute a Clipped GRPO Surrogate: statement and public examples
The problem reports out-of-range ratios, not the sign-dependent active plateau fraction. The section mini-project adds autodiff checks and unequal-length aggregation tests.
You're done when
Both advantage signs match hand values and gradients, all three reductions match the frozen terms, and your minibatch reduction matches its stated full-batch objective.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 11 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.
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. - 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. - 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.