LLM RL IV: Online Policy Optimization
Online LLM RL samples from a changing policy, scores trajectories and updates from sparse, noisy or verifiable rewards. This stage transfers REINFORCE, PPO, RLOO and group-relative estimators into token space while making masks, policy lag, normalization and compute-matched controls testable.
Section 11 of 12 · 12 units · about 50 hours
By the end you can Implement and hand-check one value-based and one critic-free language-policy estimator, run a tiny verifiable online study, and show whether its gain survives matched SFT, direct-preference, rejection or best-of-N controls and reward-hacking tests.
Units
- On-policy generation and the sequence policy gradient4h
- Terminal rewards, per-token loss assignment and token-space REINFORCE4h
- PPO-style RLHF with a value critic, and critic cost versus group sampling5h
- Leave-one-out baselines and RLOO3h
- Grouped sampling, group-relative advantages, GRPO and degenerate groups5h
- Within-prompt and batch normalization, reward scaling and comparability3h
- Token log probabilities, importance ratios, clipping and loss aggregation5h
- Reference KL penalties, masks, truncated completions and length incentives4h
- Multiple gradient steps, off-policy drift, rollout freshness and policy lag4h
- Entropy collapse, KL spikes, invalid outputs, zero-signal groups and prompt balancing4h
- Fixed-rollout estimator, ratio, clipping and gradient tests3h
- SFT, DPO, rejection and best-of-N controls, matched budgets and training traces6h
Build it
Mini project · about 14 to 18 hours
Online policy optimization with versioned rollouts
Build critic-based and critic-free policy updates on frozen rollouts in policylab, prove freshness handling, then run a tiny online study with matched controls. The versioned collector and traces feed reasoning agents and the capstone evidence pack.
- 1Build the rollout collector in
llm/with an exact sequence-gradient oracle and a written generation-policy contract, implement terminal-reward REINFORCE with detached rewards, and prove padding invariance with hand-gradient tests intests/. - 2Implement the value-based fixed-rollout estimator with a critic-target oracle in
llm/, compare critic state and fitting cost against group sampling inledger/, and check RLOO baselines with prompt-regrouping tests and exact expected-gradient enumeration. - 3Normalize fixed prompt groups with both standard-deviation conventions in
llm/, handle degenerate and singleton groups explicitly, and ablate reward transforms with matched gradient reductions, passing the free TensorTonic group-advantage cases. - 4Implement detached token ratios with sign-dependent clipping in
llm/, check first-step equivalence with REINFORCE by autodiff, compare sequence, token and constant-denominator reductions on unequal lengths, and enumerate reference KL with EOS, padding and truncation tests, passing the free TensorTonic surrogate and length-normalization cases. - 5Assemble value-based and critic-free estimator suites on frozen rollouts in
tests/, inject ratio, mask and version defects that must fail, freeze behavior scores inschema/, and simulate queue age on CPU with stale-score injection and drift traces. - 6Replay zero-signal and verifier-failure batches with prompt-slice diagnostics, separate mastery from breakage and contraction, and enforce a bounded refill cap with all attempts and costs retained in
ledger/. - 7Run a CPU online update with matched SFT, direct-preference, rejection and best-of-N controls under a stated budget, and defend held-out quality with reward, KL, entropy, length and validity traces plus a reward-hacking pack across seeds, moving to a decoder only if your GPU fits it.
What you hand in
- The
llm/rollout and estimator package with oracles and regression tests. - Normalization, clipping and freshness studies with drift and slice evidence.
- Bounded online study with matched controls, traces and hacking pack.
How to check it
- Self-grade with the rubric below
- TensorTonic: Normalize GRPO Group Advantages
Pass population cases; add sample-convention and degenerate tests.
- TensorTonic: Compute a Clipped GRPO Surrogate
Pass public cases; add autodiff and aggregation checks.
- TensorTonic: Compare Sequence and Token Length Normalization
Pass reduction cases; add KL and boundary extensions.
- RLHF Book policy-gradient losses at pinned commit
Differential-test fixed rollouts with KL disabled first.
How it's graded
Estimator correctness
Pass: Frozen-rollout losses and gradients match hand oracles with ratio, mask and version defects caught.
Great: A constant-ratio defect passes loss equality yet fails the gradient check.
Freshness honesty
Pass: Behavior scores stay immutable and stale-score injection fails with drift metrics recorded.
Great: A queue-age simulation names the reuse limit where correction breaks down.
Signal diagnosis
Pass: Zero-signal and verifier-failure replays carry distinct flags with bounded refill accounting.
Great: A verifier outage is shown to survive sampling fixes and routes to a data repair.
Control discipline
Pass: Budgets reconcile across tokens, calls and updates with negative evidence retained across seeds.
Great: The verdict separates learned change from selection, length and evaluator effects.
Resources
- RLHF Book - Policy Gradients and RegularizationNathan Lambert
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.
- RLHF Book Course - Lectures 3 and 4Nathan Lambert
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.
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
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
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.
- LLM Post-Training Laboratory - Online RLRoadmap-Final
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.
- DAPO: An Open-Source LLM Reinforcement Learning System at ScaleYu et al. (2025)
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.
- Understanding R1-Zero-Like Training: A Critical Perspective (Dr. GRPO)Liu et al. (COLM 2025)
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)
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
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
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
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
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.