RL practicum: labs from Q-learning to agentic GRPO
Read first: RL course map: which lecture or chapter to use at each stage · Proximal Policy Optimization (PPO) · DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models · DAPO: An Open-Source LLM Reinforcement Learning System at Scale
TL;DR. This optional companion teaches how to inspect RL implementations and diagnose experiments. You can learn its core ideas without running anything: work through the baseline calculation, trace the clipped loss and masks, compare the loss-normalisation weights, and critique the example dashboards. Five optional labs provide ways to test those predictions. Labs 1–2 run on a laptop CPU, lab 3 uses CS285’s GRPO homework on one H100, and labs 4–5 cover search-agent RL and diagnosing failing runs. The estimated 22 active hours describes the proposed implementation route, not a prerequisite for understanding RL or finishing the track; minutes (60) covers only the reading-and-reasoning route.
How to use this page (and what to skip on a first read)
Section titled “How to use this page (and what to skip on a first read)”Reading-only route: do the worked example, read the four PPO metrics and the loss-aggregation table, then answer the masking and failure-diagnosis questions. Treat the commands as implementation references. Optional execution: pick one lab that answers a question you care about; the large-model and search-agent routes need separate hardware planning. If you do run several labs, go in order and keep the debugging checklist open. On a first read, skip: lab 3’s option B (the TRL and verl toggles), all of lab 4, and the frontier-report rows of lab 5. The cited full reproduction configurations use multi-GPU hardware; understanding their mechanisms does not. Time estimates marked est. are my own for a part-time learner. Run times and expected numbers come from the cited handouts and papers.
Key idea: one loop, five scales
Section titled “Key idea: one loop, five scales”Every lab runs the same loop. Sample behaviour with the current policy, score it, turn scores into advantages (how much better than expected), update the policy, and log enough to know whether it worked. The labs change only the scale: a 2-state toy, CartPole (balance a pole on a cart), a 1.5B language model, then a multi-turn search agent.
The update you will implement or configure in labs 2–5 is PPO’s clipped surrogate (PPO is Proximal Policy Optimization; GRPO, Group Relative Policy Optimization, uses the same surrogate with a different advantage). Some labs use unclipped policy gradients; PPO and GRPO instead clip an incentive in the sampled surrogate. With positive advantage, that term stops rewarding increases once ; with negative advantage, it stops rewarding decreases once . Movement in the harmful direction remains penalised. Clipping is not a constraint on the final policy ratio or KL (Kullback–Leibler divergence): shared parameters and other loss terms can move probabilities farther, which is why CleanRL also offers an optional target_kl early stop.
Here is the policy being trained and the policy that generated the data. is an action (a CartPole push, or one token) taken in state . is its advantage, and is the importance ratio. and are the lower and upper clip widths; they are equal in PPO, and DAPO raises the upper one. is the normaliser, and choosing it is lab 3’s loss-aggregation ablation.
No-run clipping example. With , and , the surrogate contributes and is locally flat in . With at the same ratio, it contributes and still pushes back. This is why a high out-of-band fraction is not the same as a high fraction of zero gradients.
IR analogy: the ratio is a target-to-logging-policy importance weight. Its denominator plays the logging-propensity role familiar from counterfactual learning to rank from click logs; a bare inverse propensity is , without the target-policy numerator. Both techniques trade bias against unstable weighting, but PPO’s advantage-dependent minimum is not simply symmetric clipping of IPS weights. Lab 5 asks what happens when “the logging policy” is a different engine or several updates old.
The labs at a glance
Section titled “The labs at a glance”| Lab | Backs these pages | Hardware | Starter | Minimal route (est.) |
|---|---|---|---|---|
| 1. Tabular TD vs MC, REINFORCE variance | MDP, Bellman, MC/TD/Q, REINFORCE | laptop CPU | your own ~100 lines of Python | 4 h |
| 2. Policy gradient → PPO on CartPole | GAE, PPO | laptop CPU | CS285 HW2, CleanRL ppo.py | 7 h |
| 3. GRPO on a small LM with a verifier | InstructGPT, DPO, GRPO, R1, DAPO, Dr. GRPO, GSPO | 1× H100 (Modal) | CS285 HW4; option B: TRL / verl | 8 h + ≈8 GPU-h |
| 4. Multi-turn search agent | Search-R1, long-horizon tool agents, verl/HybridFlow | 8 GPUs | Search-R1 repo | full route only |
| 5. Systems and failure diagnosis | Missing old logits, RL infra, ScaleRL, reward hacking, reasoning boundary | your lab 2–3 logs | TRL / verl metrics | 3 h |
Lab 1: tabular TD vs Monte Carlo, and REINFORCE variance (laptop)
Section titled “Lab 1: tabular TD vs Monte Carlo, and REINFORCE variance (laptop)”Goal. See bootstrapping and baselines with numbers small enough to check by hand. Setup. Plain Python or numpy, no framework. Use the site’s search-or-answer toy from the course map. From s₀ (“no evidence”), answer earns +1 with probability 0.2, and search costs −0.1 and moves to s₁ (“evidence in context”). From s₁, answer earns +1 with probability 0.9. Answering ends the episode. Use γ = 1.
Implement. (i) Monte Carlo (MC) and TD(0) evaluation of the policy “50/50 at s₀, answer at s₁”. The true values are V(s₁) = 0.9 and V(s₀) = 0.5·0.8 + 0.5·0.2 = 0.5. (ii) Q-learning with ε-greedy exploration (pick a random action with probability ε). It should find Q(s₀, search) = 0.8 and Q(s₀, answer) = 0.2. (iii) REINFORCE with π(search | s₀) = σ(θ), with and without a baseline. Sample many single-episode gradients at θ = 0 and compute their mean and variance. Then reproduce two textbook figures listed on the Sutton & Barto page: Example 6.2 (the random walk, where TD beats MC on error per episode) and Figure 13.2 (the short corridor, where the baseline speeds REINFORCE up).
Measure and look for. On the toy, the gradient mean should match the exact value 0.15 with or without the baseline, while the variance drops about 3×. The worked example below derives this. Plot TD and MC error against episodes for several step sizes α. The textbook’s claim is that TD wins on the random walk; check whether your curves agree.
Worked example: the baseline, by hand
Section titled “Worked example: the baseline, by hand”Intuition first. REINFORCE nudges θ by (return − baseline) × (how θ changes the log-probability of what you did). A good baseline does not change the average nudge. It removes the part of each nudge that only says “this episode was lucky”, and that part is noise.
At θ = 0, π(search) = p = 0.5. The score is for search and for answer. The episode return G is:
| Branch (prob.) | Return G (prob.) | g = G·s, no baseline | g = (G − 0.5)·s |
|---|---|---|---|
| search (0.5) | 0.9 (0.9), −0.1 (0.1) | 0.45, −0.05 | 0.20, −0.30 |
| answer (0.5) | 1 (0.2), 0 (0.8) | −0.50, 0 | −0.25, +0.25 |
Mean. Without a baseline: 0.5·(0.9·0.45 − 0.1·0.05) + 0.5·(−0.2·0.5) = 0.20 − 0.05 = 0.15. With b = 0.5: 0.5·(0.18 − 0.03) + 0.5·(−0.05 + 0.20) = 0.15. This equals the exact gradient p(1 − p)·(0.8 − 0.2) = 0.15.
Variance. Because s² = 0.25 for both actions, E[g²] = 0.25·(Var G + (E G − b)²), with E G = 0.5 and Var G = 0.215. With b = 0, E[g²] = 0.116 and the variance is 0.116 − 0.0225 = 0.094. With b = 0.5, E[g²] = 0.054 and the variance is 0.031. A simulation of 200,000 episodes gave 0.094 and 0.031. In lab 2 the baseline becomes a learned value network, and in lab 3 it becomes the group mean reward. Group centring has the same comparative intuition, but not the identical unbiasedness proof. A fixed or state-only baseline is independent of the sampled action. A group mean includes each completion’s own reward; even without standard-deviation scaling, this scales the expected score-function gradient by for independent samples. Reward scaling and response-length normalisation add further differences.
Lab 2: from policy gradient to PPO on CartPole (laptop)
Section titled “Lab 2: from policy gradient to PPO on CartPole (laptop)”Goal. Build the actor–critic pieces yourself, then read a reference PPO and learn its four dashboard metrics. Part A, CS285 HW2 (repo, handout). You fill in the TODOs in pg_agent.py: return estimators (full return and reward-to-go), a neural-network baseline, generalized advantage estimation (GAE), and advantage normalisation. The handout says each run takes from “a few seconds to a few (up to ten) minutes” on a laptop CPU, and the README notes that training was faster on a laptop CPU than on Modal. Do Experiment 1: eight CartPole runs that cross reward-to-go (-rtg), advantage normalisation (-na) and batch size (-b 1000 vs -b 4000). A verified example is uv run src/scripts/run.py --env_name CartPole-v0 -n 100 -b 1000 -rtg -na --exp_name cartpole_rtg_na. Then do Experiment 3, the GAE λ sweep on LunarLander-v2 with λ ∈ 1. The handout’s bar is a best CartPole return of 200 and a best LunarLander run above 150. It also notes that advantage normalisation is “technically biased” yet often removes the need for a baseline in its simple environments. HW2 has no PPO clipping, so Part B supplies it.
Part B, CleanRL. Run uv run python cleanrl/ppo.py --seed 1 --env-id CartPole-v0 --total-timesteps 50000 (from the CleanRL README) and view it with uv run tensorboard --logdir runs. The script falls back to CPU when no GPU is present. Read the whole file next to the “37 implementation details of PPO” blog. Then ablate one setting at a time from the defaults (gae_lambda 0.95, clip_coef 0.2, norm_adv on, update_epochs 4): λ ∈ 1, clip 0.1 vs 0.4, normalisation off, and 10 epochs. Run --help for the exact switch name that turns a boolean off.
The four metrics, in plain words.
losses/approx_klis how far the policy moved during this update. CleanRL uses the estimator (r − 1) − log r, which is never negative. For r = 1.2 it gives 0.2 − 0.182 = 0.018. The naive −log r gives −0.18, a negative “KL” that is still unbiased on average; CleanRL logs it asold_approx_kl.losses/clipfracis the share of samples whose ratio left the [1 − ε, 1 + ε] band. If it is high, your steps are too large: too many epochs or too high a learning rate.losses/explained_varianceis how much of the return the critic predicts. Near 1 is good. Near 0 or negative means the baseline is not helping.losses/entropyis how random the policy still is. A fast drop to zero means exploration is over.
Lab 3: GRPO on a small language model with a verifier (one GPU)
Section titled “Lab 3: GRPO on a small language model with a verifier (one GPU)”Option A (minimal route): CS285 HW4 (repo, handout). The model is Qwen/Qwen2.5-Math-1.5B-Instruct with LoRA (low-rank adapters, so only small added matrices are trained). Every run is configured for an H100 on Modal. The handout says the work “can in fact be completed with about 8 H100 hours”. Outside the course you pay for Modal yourself, and running the launcher elsewhere is untested here. You implement, in order: per-token log-probs, the completion mask and the approximate KL; minibatching; group advantages; Reinforce.update (GR-REINFORCE, one on-policy pass); and GRPO.update (PPO-style epochs with clipping). Two tasks are provided:
- format_copy is a debugging task: copy an integer into XML. The reward is +1 for the right integer, +0.2 for an answer tag and +0.1 for strict XML, so 1.3 is the maximum. Each run takes about 5 minutes, and reward usually reaches about 1.3. Debug if final eval exact match is materially below 0.8.
- math_hard uses level-5 MATH problems with a boxed-answer verifier. Before RL, eval is about 0.23. GR-REINFORCE (201 steps, about 2 h) ends near 0.31, and you should debug below 0.27. GRPO (501 steps, about 5 h) ends with eval above 0.37, and you should debug below 0.35.
- Then run the required ablation: at least five extra format_copy runs varying PPO epochs, a smaller and a larger KL coefficient, the clip ε, and
grad_accum_steps=1. Watch the KL-to-reference metric, the clipped-token fraction, the gradient norm and the sampled generations. The handout warns that rollout reward “is expected to fluctuate a lot”, so compare runs on the eval curves.
Option B (full route): DAPO-style toggles in TRL. The GRPOTrainer docs (v1.17.1) quickstart trains Qwen/Qwen2.5-0.5B-Instruct on trl-lib/DeepMath-103K with trl.rewards.accuracy_reward (install with pip install 'trl[math_verify]'). The docs say this takes about a day across 8 GPUs. Shorten max_steps for ablations and measure your own run times. Defaults have moved, so check them. loss_type now defaults to "dapo" and beta (KL weight) to 0.0.
| Change | TRL option | What it tests | Watch |
|---|---|---|---|
| Loss aggregation | loss_type: grpo / dr_grpo / dapo | per-response vs per-token weight (question 2) | completions/mean_length |
| Std normalisation | scale_rewards: "group" / "batch" / "none" | Dr. GRPO’s difficulty bias | reward_std |
| Clip-higher | epsilon=0.2, epsilon_high=0.28 | DAPO’s entropy argument | entropy, clip_ratio/high_mean |
| Overlong | mask_truncated_completions=True | cut-off answers as noise | completions/clipped_ratio |
| Reuse / staleness | num_iterations (μ), steps_per_generation | off-policy drift inside a step | clip_ratio/region_mean |
| Sequence ratio | importance_sampling_level="sequence" | sequence-ratio ablation; combine with loss_type="grpo" for GSPO-style per-sequence aggregation | clip ratio, stability |
Holding the default loss_type="dapo" with sequence-level ratios keeps length-weighted aggregation and is a different objective (TRL warns about this); reproducing a paper also requires its other hyperparameters.
Normalisers without a run. For a synthetic two-completion minibatch with lengths 10 and 1,000, fixed , and no auxiliary losses, grpo weights each short token 0.05 and each long token 0.0005. dapo weights every token 1/1010. dr_grpo with length cap 1,024 weights every token 1/2048. Equal per-token weighting and equal per-response weighting answer different questions, and changing the denominator also changes the update scale.
TRL has no dynamic sampling. Watch frac_reward_zero_std (groups where every completion scored the same, which carry no signal). For the real filter use verl’s DAPO recipe: algorithm.filter_groups.enable, plus actor_rollout_ref.actor.clip_ratio_low/high and actor_rollout_ref.actor.loss_agg_mode (token-mean, seq-mean-token-sum, seq-mean-token-mean). Dynamic sampling is provided by the separate DAPO recipe and entrypoint (main_dapo.py). algorithm.filter_groups.enable alone does not turn an ordinary GRPO trainer into that recipe; also configure the filtering metric (filter_groups.metric) and the maximum generation attempts (filter_groups.max_num_gen_batches). For the overlong penalty, the current verl-recipe/dapo/config/dapo_trainer.yaml sets reward.reward_manager.name=dapo and configures reward.reward_kwargs.overlong_buffer_cfg.{enable,len,penalty_factor} together with reward.reward_kwargs.max_resp_len. The older documentation’s reward_model.overlong_buffer.* belongs to the historical recipe, and some shell examples still show it; check the config you actually launch. verl’s own Qwen2.5-32B reproductions reach 52% on AIME 2024 with DAPO, 50% without dynamic sampling, and 44% without token-level loss and dynamic sampling. These are historical reproductions at verl commit 4f80e4 on 16×8 H800 GPUs (the 44% row on 16×8 H20 with a different image), not a controlled one-GPU ablation or a guaranteed current result. IR analogy: loss aggregation is the choice between weighting each query equally or each judged document equally in a ranking loss. Long lists dominate under the second, and long answers dominate under dapo.
Lab 4: a multi-turn search agent (full route, 8 GPUs)
Section titled “Lab 4: a multi-turn search agent (full route, 8 GPUs)”Goal. Train an agent that interleaves reasoning, search calls and an answer, and measure what masking and retrieval settings do. Setup (Search-R1 repo). The README’s steps are: download the e5 index and the wiki-18 corpus, run python scripts/data_process/nq_search.py, launch the retriever with bash retrieval_launch.sh, then train. Treat this as a historical, pinned environment: use Search-R1’s own environment and bundled verl fork, not a current generic verl installation. Its README specifies Python 3.9, vLLM 0.6.3 and an editable install of the repository, with a separate retriever environment; do not “modernise” it by substituting the latest vLLM. In the inspected train_grpo.sh, DATA_DIR is defined but the parquet paths use TRAIN_DATA_DIR and TEST_DATA_DIR. From the repository root, run export TRAIN_DATA_DIR="$PWD/data/nq_search" and export TEST_DATA_DIR="$PWD/data/nq_search" before bash train_grpo.sh; otherwise those paths become /train.parquet and /test.parquet. A BM25 launcher is at example/retriever/retrieval_launch_bm25.sh. The train_grpo.sh script uses 8 GPUs and Qwen/Qwen2.5-3B, with actor_rollout_ref.actor.state_masking=true, max_turns=2, retriever.topk=3, groups of n_agent=5, and max_obs_length=500. The script currently requests 1,005 steps; the paper trained on 8×H100 for 500 steps, a different configuration.
Ablate and compare with the paper. Turn state_masking off. The paper (PPO) reports average exact match (EM) falling from 0.431 to 0.343 on Qwen2.5-7B base and from 0.303 to 0.262 on 3B. Sweep retriever.topk across 1, 3 and 5; the paper reports 0.375, 0.431 and 0.400 on 7B. Also sweep max_turns, which has no published number, so predict first. Swap e5 for BM25. That is where your IR expertise counts, because the retriever is the environment.
Lighter alternatives, with caveats. Pass tools=[...] to TRL’s GRPOTrainer, and set the iteration limit in its GRPOConfig, for example args=GRPOConfig(max_tool_calling_iterations=2). In its source, tool-result tokens are zeroed out of the loss mask, but no documented switch turns that off, so the masking ablation needs Search-R1. Trace one sequence: prompt → generated query → retrieved passage → generated answer. The query and answer have policy-loss mask 1; prompt, passage and padding have mask 0. The passage remains visible as context for later generated tokens. Check the per-token loss mask directly: TRL’s num_tokens includes prompt tokens and therefore cannot be equated to the number of trained tokens. verl’s search-tool guide now requires you to supply the tool class yourself. Its corpus is a 60–70 GB download, and its example was tested on 8×H20 for about 27 h.
Lab 5: systems and failure diagnosis
Section titled “Lab 5: systems and failure diagnosis”Goal. Learn to tell an algorithm problem from an infrastructure problem. Minimal route: fill in the checklist below from your lab 2–3 logs, and deliberately break one format_copy run (for example, many PPO epochs). Full route: measure the following in TRL or verl.
- Sampler–trainer mismatch. The fast inference engine (vLLM) and the training framework compute slightly different log-probs for the same tokens. Your π_old is then not the policy that actually sampled. In TRL,
sampling/sampling_logp_difference/{mean,max}andsampling/importance_sampling_ratio/{min,mean,max}are logged only when bothuse_vllm=Trueandvllm_importance_sampling_correction=True(the default; modesequence_mask). The docs say a growing logp difference indicates “a widening train-inference mismatch”. Turning correction off also removes these built-in logs, so for a correction-on/off study add a common diagnostic logger or use verl’s metrics-only configuration. The logged ratios are already masked or clipped: insequence_maskmode a minimum of zero can mean rejection rather than a naturally tiny ratio. Their extrema do not reveal the uncorrected tail or prove effectiveness; report the raw log-ratio distribution, the retained or masked fraction and held-out performance with a common logging path. In verl, setactor_rollout_ref.rollout.calculate_log_probs: trueand readrollout_corr/kl,rollout_corr/k3_klandrollout_corr/log_ppl_abs_diff;RolloutCorrectionConfig.disabled()logs metrics only. verl names precision, backend and staleness as the sources. Missing old logits explains why this biases the update. - Separate two off-policy gaps. TRL’s PPO ratio compares the current training policy with cached training-engine probabilities from generation time. Its additional vLLM correction compares those cached probabilities with the actual sampler probabilities. Increasing
num_iterationsgrows the first gap while reusing the second correction, so the sampling-logp-difference metric need not grow with each reuse. Use policy and rollout version information and current-versus-cached ratios to diagnose reuse. For asynchronous verl (fully async), compare actual rollout log-probs with a named training snapshot, and state whether you use decoupled correction or bypass mode.async_training.staleness_threshold=0means synchronous, but a synchronous collection baseline also needsasync_training.trigger_parameter_sync_step=1; setting only the threshold to zero can still leave several training updates per parameter synchronisation. IR analogy: this is off-policy learning to rank from logs of a ranker several versions old. The ratio corrects it only while the two policies overlap. - Mixture-of-experts (MoE) models add routing mismatch. The MoE handbook reports that routing replay cut train–inference KL from 1.5e-3 to 7.5e-4 on Qwen3-30B-A3B. The frontier fixes are reports to read, not labs: DeepSeek-V3.2 (off-policy sequence masking; TRL exposes
off_policy_mask_threshold), GLM-5 (double-sided ratio masking), MiMo-V2.6 (routing and top-p mask replay) and Kimi K3 (token-level log-ratio mask; K3 inherits this policy optimisation from Kimi K2.5, which spells out the formula). - Reward-hacking probes. In HW4 math_hard, +0.1 is paid just for containing the boxed-answer prefix. Log how often that bonus is paid while the answer is wrong, and keep a stricter held-out checker. IR analogy: a rubric or verifier reward is nugget evaluation, and a policy can learn to mention nuggets without being right. See rubrics as rewards and METR’s examples.
Debugging checklist
Section titled “Debugging checklist”| Symptom | Likely cause | What to log or check |
|---|---|---|
| Gradient estimates swing wildly (lab 1–2) | no baseline, tiny batch | per-batch gradient variance; add baseline or -na, larger -b |
explained_variance near 0 or negative | critic not learning | value loss; value learning rate; return scale |
approx_kl and clipfrac high, return collapses | steps too large | fewer epochs, lower learning rate; CleanRL target_kl |
| Entropy falls to ~0 early, reward plateaus | collapse, no exploration | entropy, clip_ratio/high_mean; try epsilon_high; see entropy mechanism |
frac_reward_zero_std high | prompts too easy or too hard | pass-rate histogram; filter groups or re-balance data |
completions/clipped_ratio high, length rising | truncation; grpo length bias | loss_type, mask_truncated_completions, overlong penalty |
| Train reward up, held-out eval flat | reward hacking or noise | eval curves, sampled completions, bonus-only reward rate |
sampling_logp_difference growing | engine, precision or MoE mismatch | IS correction on; rollout_corr/*; bf16 vs fp32 |
| Agent stops calling the tool | tool failures or no credit | tools/call_frequency, tools/failure_frequency; masking |
| Loss nonzero on prompt or tool tokens | mask bug | tokens in loss vs tokens generated, per sample |
Optional execution budgets—not reading time
Section titled “Optional execution budgets—not reading time”| Route | Labs | Hands-on (est.) | Compute |
|---|---|---|---|
| Minimal | 1 (4 h), 2 Parts A–B (7 h), 3 option A (8 h), 5 checklist (3 h) | ≈22 h | laptop + ≈8 H100-h (HW4 handout) |
| Full | minimal + HW2 Exp. 2 and 4 (3 h), 3 option B (12 h), 4 (15 h), 5 full (6 h) | ≈58 h | + 8-GPU node for lab 4 |
These hours count active work: coding, launching, reading plots and writing notes. Unattended GPU time is excluded, because the 2 h and 5 h math_hard runs can overlap with reading. The 22-hour estimate is optimistic for a first implementation and assumes the environments, cloud account and starter dependencies already work; the two textbook-figure reproductions in lab 1 are optional extras. Neither 22 nor 58 hours is a completion promise: budget setup and debugging separately and record your actual time. The TRL full quickstart alone reports roughly 8 GPUs × 1 day ≈ 192 GPU-hours, and the verl search example roughly 8 × 27 ≈ 216 GPU-hours; ablations multiply these costs, and neither belongs in the eight-H100-hour homework estimate. minutes (60) covers only the reading-and-reasoning route. Rubric: F1, since it is a practicum and teaches no new method. S2, since TRL and verl are what 2025–26 recipes run on. L2, since it fills the implementation-inspection and failure-diagnosis gap. T2, since its core is CS285 homework. Q2, since every starter is a maintained course or library. R2, since it is the only hands-on page on the site.
Caveats
Section titled “Caveats”- Libraries move. TRL’s defaults changed (
loss_type="dapo",beta=0.0), verl removed its in-tree search tool, and HW4 is tied to Modal. Re-check option names against the docs on the day you run. - The time estimates are mine. The run times and target numbers come from the HW2 and HW4 handouts, the verl DAPO page and the Search-R1 paper.
- Small-model results may not transfer. The reasoning-boundary page and ScaleRL show that conclusions depend on scale and on how you evaluate (pass@1 vs pass@k).
- Expected outcomes on this page are what the sources reported. Treat unsourced predictions (marked “predict first”) as hypotheses to test.
You should now be able to…
Section titled “You should now be able to…”- compute a REINFORCE gradient and its variance by hand, and explain why a baseline keeps the mean while cutting the variance;
- read approx KL, clip fraction, explained variance and entropy on a PPO dashboard and say what each implies;
- trace GRPO’s log-probabilities, masks, group advantages and clipped update, and identify which invariant a failing implementation violates;
- predict how
loss_type,scale_rewards,epsilon_highand truncation masking change length and entropy, then test it; - explain why tool or retrieved tokens must be masked, and quote the Search-R1 ablation;
- diagnose a failing run from its metrics using the checklist, separating algorithm bugs from sampler–trainer mismatch and staleness.
Connections
Section titled “Connections”- Course map gives the reading order and the toy MDP. This is the course map’s optional implementation-literacy companion. Reading it or running its labs is not required to complete Stage 2.
- CS285 maps the lectures behind HW2 and HW4. Spinning Up is an alternative PPO reference implementation.
- RL infra has a one-GPU verl PPO quickstart on GSM8K, which is a bridge between labs 3 and 4. Async RLHF and AReaL cover the staleness trade-off that lab 5 measures.
- On-policy distillation and MOPD reuse the same sample–score–update loop with a teacher’s log-probs as the reward. Lab 3’s code is the natural place to try them.
- Reward over-optimization scaling explains why lab 5’s held-out checker matters once a learned reward model replaces the verifier.
- Agent Lightning and RAGEN are alternative stacks for lab 4’s multi-turn setting.
Questions to think through
These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.
- Derive / compute
On the search-or-answer toy (γ = 1, π(search | s₀) = σ(θ) at θ = 0, always answer from s₁), the worked example gets a single-episode REINFORCE gradient variance of 0.094 with no baseline and 0.031 with b = 0.5. Redo it for b = 0.9, show that the mean is still 0.15, and find the constant baseline with the lowest variance. Why is "use the mean return" exactly optimal here but not when π(search | s₀) ≠ 0.5?
What a strong answer covers
- Per-episode gradient g = (G − b)·s, with score s = +0.5 for search and −0.5 for answer. So s² = 0.25 always, and E[g²] = 0.25·E[(G − b)²].
- E[G] = 0.5 and Var(G) = 0.465 − 0.25 = 0.215. So Var(g) = 0.25·(0.215 + (0.5 − b)²) − 0.15².
- For b = 0.9: 0.25·(0.215 + 0.16) − 0.0225 = 0.07125. The mean stays 0.15 because E[s] = 0 under π, so the b·E[s] term vanishes.
- The minimum is at b = E[G] = 0.5, with variance 0.03125, a 3× cut from b = 0.
- In general the best constant is E[s²G] / E[s²]. When p ≠ 0.5 the two actions have different s² ((1 − p)² vs p²), so their returns are weighted unequally and the plain mean return is no longer the minimiser.
- What if…
In lab 3 you switch TRL's loss_type between grpo, dapo and dr_grpo. A synthetic diagnostic minibatch (not a complete reward-normalised group) holds two completions with frozen advantages +1 and lengths 10 and 1,000 tokens. Assume one device, one accumulation step, r = 1, no auxiliary losses, no masking and max_completion_length = 1,024. Derive each token's gradient weight under each setting. Explain why this calculation alone cannot predict a mean-length curve, and design an ablation that separates length weighting from update scale.
What a strong answer covers
- grpo averages within each completion, then over the batch of 2: short-answer tokens get 1/(2×10) = 0.05 each and long-answer tokens 1/(2×1000) = 0.0005 each. Each completion has total weight 0.5.
- dapo divides by all active tokens: 1/1010 ≈ 0.0009901 per token for both, so the long completion carries about 99.01% of the total weight.
- dr_grpo divides by the constant 2×1024 = 2048: ≈ 0.0004883 per token for both. Its total gradient scale here is about 0.4932 of dapo's.
- A complete centred two-response group cannot have two positive advantages. The frozen advantages isolate aggregation from reward estimation.
- dapo reduces the original per-response length bias but keeps a data-dependent token denominator (TRL docs: it does not eliminate it completely). Fixed-denominator dr_grpo removes that normalisation effect, not every cause of changing length: reward, truncation, update scale and sampling also matter.
- Hold prompts, rollouts, rewards, clipping, scale_rewards and truncation fixed; inspect gradient norms and the lengths of correct and incorrect answers separately. Distinguish a fixed-learning-rate comparison from a separately retuned practical comparison.
- Mechanism
The lab 4 Search-R1 script sets actor_rollout_ref.actor.state_masking=true. Explain which loss terms disappear when retrieved passages are masked, and why training on those tokens is wrong in the policy-gradient view (whose action is a retrieved token?). Say what the Search-R1 masking ablation reported and what you would log to catch a masking bug in your own agent loop.
What a strong answer covers
- Retrieved passages come from the environment (the retriever), not from π. They are observation, not action, so they have no ∇log π term in the policy gradient.
- Without the mask, the loss pushes up (or down) the probability of reproducing retrieved text in proportion to the trajectory's advantage. That trains corpus prediction, not query and answer choice. The importance ratio on those tokens is also meaningless, because π never sampled them.
- Search-R1 (PPO) reports average EM with vs without the mask: 0.431 vs 0.343 for Qwen2.5-7B base, and 0.303 vs 0.262 for 3B.
- Check the explicit mask against token provenance: only policy-generated query, reasoning and answer tokens should carry actor loss, while retrieved text stays in the attention context. TRL multiplies completion and tool masks, but its num_tokens also counts prompt tokens, so it is not a loss-token counter. Check any KL term's mask as well.
- IR view: the passages are like the documents a ranker displays. The agent's action is the query and the answer, so credit belongs to those tokens.
- Critique
A colleague says their lab 3 GRPO run on a 0.5B model "works" because train reward rose from 0.3 to 0.7 in 200 steps. You also see entropy falling toward zero, frac_reward_zero_std climbing to 0.8, completions/clipped_ratio at 0.4 and a flat held-out eval. Critique the claim and give the likely causes and checks, using the debugging table.
What a strong answer covers
- Rollout reward is weak evidence. HW4 warns that it fluctuates and says to compare on eval curves. A flat eval with rising train reward points to reward hacking or overfitting to training prompts.
- frac_reward_zero_std = 0.8 means 80% of samples sit in groups where every completion got the same reward. Their group-relative advantage is zero, so only about one fifth of samples carry nonzero reward advantages (separate KL or entropy terms may still contribute). Inspect all-success versus all-failure groups first: filtering (verl filter_groups) improves useful-batch composition but may keep rejecting hard prompts, so compare it against a changed curriculum or reward.
- Falling entropy means the policy is nearly deterministic, so groups stop disagreeing, which feeds the zero-std problem. Treat entropy collapse as a hypothesis: compare token entropy, clip_ratio/high_mean, group success histograms and representative outputs. A larger epsilon_high (such as 0.28) or an explicit entropy bonus is an ablation, not a guaranteed cure.
- clipped_ratio = 0.4 means 40% of completions hit max_completion_length and were cut off. Check whether the reward gain comes from a format bonus. Try mask_truncated_completions or a longer limit.
- Read sampled completions (log_completions) for degenerate patterns before trusting any aggregate metric.
- Design
Design two separate lab 5 experiments: (A) TRL rollout reuse via num_iterations, and (B) asynchronous verl rollout lag with correction disabled, token-level correction and sequence-level correction. Name the policies in each ratio, specify a genuinely fresh-collection baseline, make sure the same diagnostics exist in every arm, and state what result would falsify the claim that correction improves learning at a fixed rollout budget.
What a strong answer covers
- In TRL distinguish πθ/πold, the PPO ratio that changes during reuse, from πold/πsampler, the generation-time engine correction. The cached sampler diagnostics do not measure later policy drift.
- For verl start with staleness_threshold = 0 and trigger_parameter_sync_step = 1. Vary the former while fixing the latter, the resource allocation, the partial-rollout setting and the correction mode.
- Enable actual rollout log-prob recording (calculate_log_probs) and name the training snapshot used for comparison. RolloutCorrectionConfig.disabled() gives a metrics-only arm; TRL with correction off loses its sampling diagnostics, so add a common logger.
- Use the same prompts, rewards, seeds, decoding and rollout or token budget. Changing reuse also changes optimisation work, so report optimizer updates separately.
- Report raw log-ratio tails, rejected or retained fractions, effective sample size where available, and held-out success. Masked or clipped ratio extrema alone are not evidence that correction worked.
- Correction helps only if held-out performance or stability improves at comparable cost across seeds; it need not reduce the raw mismatch. No improvement, or too much discarded data, falsifies the claimed benefit in that setting.
- Research idea
Lab 4 treats the retriever as a fixed part of the environment. Propose a research question for your group where IR expertise is an edge, using lab 4 as the testbed. Give the hypothesis, the ablation grid, the metrics and one confound, grounded in the Search-R1 top-k result.
What a strong answer covers
- Search-R1 (7B, average EM) reports top-k = 1 → 0.375, 3 → 0.431 and 5 → 0.400. Retrieval breadth is a non-monotone environment variable, so it is worth studying.
- Example hypothesis: retriever quality (the default e5 dense retriever vs BM25) changes which search behaviour the policy learns (call count, query reformulation), not just final EM.
- Grid: retriever (BM25, e5) × top-k (1, 3, 5) × max_turns, with state masking on and model, steps and seeds fixed.
- Metrics: held-out EM, calls per episode, response length, and an IR-native one: recall of gold passages for the queries the agent issues.
- Confounds: higher top-k means more observation tokens and a tighter max_obs_length budget. Cross training-time and evaluation-time retrievers and top-k where feasible, or a better test retriever can masquerade as better learned search. Control passage tokens and search calls, and state a falsifier, such as no change in query behaviour or EM once retrieval quality and context budget are matched.