Unit 6 of 11 · about 5 hours · implement
Immutable rollout metadata, policy freshness, lag and off-policy importance weights
A loss can pass its arithmetic tests while training on the wrong distribution. The research artifact must preserve which policy actually produced each action, including failed and filtered work.
You'll be able to
- Collect immutable language rollouts bound to prompt, sampler, policy, reference, verifier and RNG identities.
- Implement a bounded rollout-update-evaluation cycle and detect overwritten old log probabilities.
- Derive trajectory importance weights and explain what token clipping cannot correct.
Covers
Read
In this order, only the parts listed
0 of 3 done
- CS336 Spring 2026 Assignment 5: live step and stale dataCS336 Assignment 5 - Alignment and Reasoning RL
Section 4.2.4,
grpo_train_step_standard_on_policy; Sections 6.1 and 6.2.1, importance reweighting and token-level surrogatesDo not run the two-GPU vLLM recipe. Use the small synchronous substitute described below; read asynchronous execution as a source of lag, not infrastructure to build.
- RLHF Book code: rollout ownershipRLHF Book Code - Policy Gradients and Rejection Sampling
RolloutEngine._generate_experience: generation configuration, action mask, rewards,log_probs_old,log_probs_refandExperienceconstructionTrace the data flow only. Add immutable version and outcome records yourself; the example's tensor buffer is not a complete experiment manifest.
- LLM Post-Training Laboratory: identity contractLLM Post-Training Laboratory - RL and Reasoning
Architecture constraints; Milestone C; Milestone D stale-log-probability, ratio-direction and policy-lag injections
Focus on
- Bind token IDs, prompt split and template, policy and reference hashes, verifier version, sampling settings, RNG state, action masks, raw reward components and stopping reasons. Stored old scores must survive later parameter changes unchanged.
- Start the live study on your existing roughly 10M-parameter decoder and short string-reversal task, on CPU or your GPU. Use PyTorch 2.14.1, a character tokenizer, a small SFT initialization, groups of 4, at most 8 generated tokens and an initial 10-update budget. Keep the model config and starting checkpoint hash.
- Choose the assignment's one-update on-policy variant explicitly: inclusive group mean, sample standard deviation plus
1e-6, response-mean loss, no KL optimization term. Keep a frozen reference for diagnostics. Use temperature 1 without probability truncation, disable dropout, and regenerate after each update. - Collect, verify, update and externally evaluate fresh held-out outputs. Count prompts, attempts, generated and training tokens, verifier calls and failures separately. Later minibatches become stale after an optimizer step; asynchronous version lag is another mismatch.
Common mistakes · 3
- Recording raw-model scores after sampling through temperature or truncation. The actual behavior distribution includes those transformations; removed support cannot be restored by importance weights.
- Calling a token ratio exact trajectory correction. It leaves old prefix visitation in place; the full trajectory weight is a product of token ratios.
- Overwriting sampler scores with learner scores from a newer checkpoint. If scoring backends differ, retain both sets at the same old checkpoint under separate names.
Try it yourself
Closed-book, before checking anything
[0.5, 0.5], current probabilities [0.75, 0.25] at both positions. For sequences '00', '01', '10', '11', trajectory weights are [2.25, 0.75, 0.75, 0.25]. Weighting the behavior probabilities by these recovers the current joint distribution. Implement this oracle, then inject an old-score overwrite into a collected batch and require the identity check to fail before an update.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Do importance weights recover actions given zero behavior probability?Answer
No. Exact correction requires behavior support wherever the target distribution contributes.
2.Why are first-update ratios near 1 rather than necessarily bit-identical to 1?Answer
Matching weights and distributions imply equality mathematically, but different kernels, precision or dropout can change computed scores. Test under a declared tolerance and fixed scoring mode.
3.Does clipping a huge importance weight preserve unbiasedness?Answer
Generally no. It trades bias for reduced influence of extreme weights, and does not repair missing support or wrong metadata.
Practice
- CS336 Assignment 5:
grpo_train_step_standard_on_policytest_grpo_train_step_standard_on_policy: loss and updated-parameter snapshot with two accumulation microbatches and a final cleared-gradient assertionUse the public fixture on CPU and keep solutions private. It tests a supplied-response update, not on-policy collection or generalization. The mini-project supplies the actual small rollout-update-evaluation cycle and immutable manifest.
You're done when
The train-step snapshot passes, the old-score overwrite is rejected, and one bounded live run records fresh rollouts, updates, reference diagnostics and independent held-out evaluation without losing failed attempts.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 17 more in the section
- CS336 Assignment 5 - Alignment and Reasoning RLStanford University · primary
Do Sections 3 to 5: prompting and grading baselines,
baseline_calcs, then the Section 4.2 functions (tokenization, response log probabilities, rollout rewards, group-normalized rewards, loss aggregation, the on-policy GRPO step) until the GRPO and metrics tests pass on CPU. The handout runs OLMo-2 1B with a two-GPU vLLM loop; run a small GRPO on a model and task that fit your GPU instead, with one normalization ablation and one preserved failure. - RLHF Book Code - Policy Gradients and Rejection SamplingNathan Lambert · support
Run
policy_gradients/train.pywith the REINFORCE, RLOO or GRPO config and the rejection-sampling selection controls (top_per_promptagainstrandom_per_prompt). Defaults use Qwen3-1.7B and a 7B scorer, so shrink the model, rollouts and tokens to fit your GPU. Sweep one variable and keep an unstable or hacked run. - LLM Post-Training Laboratory - RL and ReasoningRoadmap-Final · support
Use the rollout, objective, policy-version, reward-hacking and compute-normalized evaluation requirements as the persistent artifact for this and later stages.
Also in this section
- RLHF Book - Policy Gradients, Reasoning and Rejection SamplingNathan Lambert · required
Read Chapter 6 (policy gradients: REINFORCE, RLOO, PPO, GRPO and loss aggregation), Chapter 7 (reasoning), Chapter 9 (rejection sampling), Chapter 12 (distillation) and Chapter 15 (regularization). Do the Suggested Experiments in Chapters 6 and 9. Derive only the estimator used in your experiment, then use Chapters 14 and 15 to design the reward-hacking tests.
- DeepSeek-R1 Technical ReportDeepSeek AI · required
Read v2 Sections 2 and 3 (R1-Zero with rule-based rewards and GRPO, then cold-start SFT, RL and distillation) and the limitations (language mixing, the length jump). Separate evidence in the report from your tiny experiment and list the scale, data and infrastructure differences that block reproduction; read Dr. GRPO alongside it.
- DeepSeekMath, Section 4 (Group Relative Policy Optimization) (Shao et al., 2024)DeepSeek-AI · required
Read Section 4: GRPO drops the critic and uses the group mean and standard deviation as the baseline, averages within each sequence, then over the group, and adds a KL term. Section 5 relates RFT, DPO, PPO and GRPO. TRL 1.15.0 defaults differ (
loss_type="dapo",beta=0.0). - Understanding R1-Zero-Like Training: A Critical Perspective (Liu et al., 2025)Sea AI Lab · support
Read Sections 1 and 3 and Figure 1: dividing by response length favors long wrong answers, and dividing by the group standard deviation reweights questions by difficulty. Dr. GRPO removes both.
- DAPO: An Open-Source LLM Reinforcement Learning System at Scale (Yu et al., 2025)ByteDance Seed and Tsinghua · support
Read Sections 2 and 3: asymmetric clipping, no KL term, token-level loss averaging, dynamic sampling of mixed-outcome groups and overlong reward shaping. It keeps the standard deviation that Dr. GRPO drops; treat the disagreement as open.
- Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs (Ahmadian et al., 2024)Cohere · support
Read Sections 2 to 4: REINFORCE with a leave-one-out baseline over k samples, and why PPO's extra machinery may not pay off in their on-policy LLM setting.
- Self-Consistency Improves Chain of Thought Reasoning in Language Models (Wang et al., 2023)Google Research · support
Read Sections 2 and 3: sample several reasoning paths and take the majority answer. It is the no-training baseline any RL result must beat at matched samples and tokens.
- Scaling LLM Test-Time Compute Optimally can be More Effective than Scaling Model Parameters (Snell et al., 2024) with Large Language Monkeys (Brown et al., 2024)UC Berkeley and Google DeepMind; Stanford · support
Read Snell Sections 2 and 3 (proposer, verifier and compute-optimal allocation), Section 5 (best-of-N and search against a verifier) and Section 6 (revisions), and Large Language Monkeys Sections 2 to 4 (coverage grows with repeated sampling; precision depends on the verifier, https://arxiv.org/abs/2407.21787). Report tokens and verifier calls, not only sample counts.
- Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model? (Yue et al., 2025)Tsinghua University · support
Read Sections 2 to 4: compare base and RL models at matched sampling with pass@k. The finding is debated; use its control matrix, not its verdict.
- Let's Verify Step by Step (Lightman et al., 2023)OpenAI · support
Read Sections 2 and 3: outcome versus process supervision on MATH and the PRM800K labels. Define step boundaries before you train any step-level verifier.
- STaR: Bootstrapping Reasoning With Reasoning (Zelikman et al., 2022) with Rejection Sampling Fine-Tuning (Yuan et al., 2023)Stanford; Alibaba · support
Read STaR Section 3 (rationalization with the answer as a hint, then fine-tuning) and Yuan et al. Sections 3.3 and 4.1 (keep only correct sampled paths and refit, https://arxiv.org/abs/2308.01825). Neither is RL; both are the self-training controls an RL claim needs.
- Build a Reasoning Model (From Scratch), Chapters 4 to 7Sebastian Raschka / Manning · support
Use Chapter 4 (temperature, top-p and self-consistency, pp. 94-135), Chapter 6 (GRPO on Qwen3-0.6B, pp. 179-224) and Chapter 7 (clipping, KL and metrics, pp. 225-266). Listing 6.13 is the unclipped policy gradient; clipping and KL arrive in Sections 7.4 and 7.5. Its advantage uses
torch.std, which is the unbiased estimator. - Tulu 3, Section 6 (Reinforcement Learning with Verifiable Rewards)Allen Institute for AI · support
Read Sections 6.1 to 6.4: RLVR data, recipe findings, infrastructure and results, plus the appendix on IFEval over-optimization. It ships data and configs you can inspect.
- TRL GRPO TrainerHugging Face · reference
Read after your scratch loss passes. In TRL 1.15.0 the defaults are
loss_type="dapo"(token mean),beta=0.0(no reference model loaded) andscale_rewards="group"; setloss_type="grpo"andbetaabove zero to approach the DeepSeekMath objective, and state the choice beside any comparison. - TensorTonic - RLVR SetTensorTonic · 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). Add rollouts with unequal active lengths, and cross-check against the CS336 tests. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution. - Modern LLM Notebook - Reasoning and On-Policy DistillationWalking Labs · support
Use
notebooks-en/part4-frontiers/28-cot-thinking.ipynband31-opd.ipynbto compare CoT, inference-time search and on-policy distillation; notebook 28 needs API keys for some cells. Count tokens and verifier calls so selection is not confused with learning. - Berkeley CS285 - LLM Reinforcement LearningUC Berkeley · reference
Read Lecture 14 "LLM RL", PDF pages 13 to 39: Part 2 (language models as policies), Part 3 (baselines, regularization and GRPO, pages 25 to 30) and Part 4 (Bradley-Terry, RLHF and verifier rewards, pages 31 to 39). Use it to repair RL prerequisites; HW4 needs Modal H100 credit and is not required.