CS 336: Language Modeling from Scratch Lecture 16 — Post-Training 2:
Reinforcement Learning from Verifiable Rewards

Stanford University
Autumn 2026

Why Verifiable Rewards? The RLHF Ceiling

KL distance from initial policy Reward score Proxy RM Gold / Human overoptimization →
  • RLHF trains against a learned proxy reward model
    • Pushing KL too far exploits proxy flaws instead of improving true quality
    • Prevents scaling RL compute aggressively
  • RLVR targets domains where we optimize exactly what we want
    • Math answers, unit-tested code, Lean proofs, executable sandboxes
    • Unlocks long reasoning traces and test-time compute scaling

RLVR replaces a noisy preference proxy with a programmatic check—or, in 2026, an executable environment or rubric judge.

Lecture Roadmap

1. Core Algorithms PG → TRPO → PPO GRPO & baselines Dr. GRPO fix 2. How It Started Early 2025 RLVR R1-Zero & R1 Kimi K1.5 & Qwen3 3. 2026 Systems Agents & sandboxes Async RL rollouts Mismatch & MoE 4. 2026 Pipelines Effort budgets On-policy distill V4.1, K3, Nemotron

Core Algorithms: Policy Gradient → TRPO → PPO

Clipping lets PPO take multiple gradient steps on a rollout batch without the policy moving too far from $\pi_{\theta_k}$.

PPO in the Language Model Setting

Policy LM sample (x, y) Reference LM per-token KL penalty Reward / Verifier terminal r(x, y) Value Model V token baseline V(s_t) GAE & Buffer Advantages A_t Returns R_t Update Policy PPO-Clip loss Update Value V Clipped MSE vs R_t

PPO in Practice: Clipped Loss & Inner Loop

# Inner loop: optimize for multiple epochs on a rollout batch (AlpacaFarm)
v_clip = torch.clamp(vpred, old_v - clip_v, old_v + clip_v)
vf_loss = 0.5 * torch.maximum((vpred - ret)**2, (v_clip - ret)**2).mean()

ratio = torch.exp(logprob - old_logprob)
pg1 = -adv * ratio
pg2 = -adv * torch.clamp(ratio, 1.0 - eps, 1.0 + eps)  # eps = 0.2
pg_loss = torch.maximum(pg1, pg2).mean()

loss = pg_loss + vf_coef * vf_loss

Because we minimize loss, torch.maximum over negated objectives implements PPO's pessimistic lower bound.

PPO in Practice: Reward Shaping & GAE

Generalized Advantage Estimation (GAE) trades off bias and variance over TD errors $\delta_t^V$:

$$\hat{A}_t^{\text{GAE}(\gamma,\lambda)} = \sum_{l=0}^{\infty} (\gamma\lambda)^l \delta_{t+l}^V, \qquad \delta_t^V = r_t + \gamma V(s_{t+1}) - V(s_t)$$

# Per-token KL shaping + terminal reward
kl = torch.clamp(logp - ref_logp, min=0.0)
shaped_r = -kl_coef * kl
shaped_r[batch_idx, terminal_pos] += reward
  • LM bandit simplification: setting $\gamma = \lambda = 1$ works well—GAE collapses to reward-to-go minus $V(s_t)$
  • Clamping KL $\ge 0$ prevents runaway negative-KL divergence if the policy destabilizes
  • Healthy run: reward climbs, KL stays bounded, negative KL shaping levels off

Why Do We Need Another RL Algorithm?

Why not PPO?
  • Complex in practice: many fragile code-level details (critic warmup, value clipping, GAE tuning)
  • Value model cost: $V_\phi$ consumes as much memory and compute as the policy itself
  • Hard to fit: predicting expected future reward mid-CoT for long reasoning traces is noisy
Why not DPO?
  • Wrong data structure: DPO assumes pairwise Bradley-Terry preference comparisons
  • Offline by default: cannot explore new reasoning strategies unless turned into an iterative online loop
  • Verifiers give scalar/binary scores directly on any sampled trajectory

Goal: keep PPO's on-policy exploration and clipping, but eliminate the learned value model.

GRPO: Group Relative Policy Optimization

Prompt q o_1 r_1 = 1 o_2 r_2 = 0 ... o_G r_G = 1 Group Z-Score Advantage No value network needed
  • Introduced in DeepSeekMath (Shao et al., 2024): sample $G$ outputs $\{o_i\}_{i=1}^G \sim \pi_{\theta_{\text{old}}}(\cdot|q)$
  • Replace critic baseline with the within-group z-score: $$A_i = \frac{r_i - \mathrm{mean}(\{r_1,\dots,r_G\})}{\mathrm{std}(\{r_1,\dots,r_G\})}$$
  • Clipped surrogate + explicit non-negative KL estimator: $$\mathbb{D}_{\text{KL}}(\pi_\theta\|\pi_{\text{ref}}) = \frac{\pi_{\text{ref}}(o_i|q)}{\pi_\theta(o_i|q)} - \log \frac{\pi_{\text{ref}}(o_i|q)}{\pi_\theta(o_i|q)} - 1$$

In the strictly online case (one gradient update per rollout), GRPO is just policy gradient with group-normalized rewards plus KL.

GRPO Is Tiny to Implement—and Beats Positive-Only RFT

# 1. Group advantage (1e-4 avoids divide-by-zero when all rewards match)
adv = (rewards - rewards.mean()) / (rewards.std() + 1e-4)  # broadcast

# 2. Online GRPO loss (rollout + immediate update)
kl = torch.exp(ref_logp - logp) - (ref_logp - logp) - 1.0
loss = ((-logp * adv + kl_coef * kl) * mask).sum() / total_resp_len

Thinking Carefully: Is GRPO's Advantage a Valid Baseline?

GRPO's Length Bias and the Dr. GRPO Fix

Original GRPO (biased terms in red):
$$\frac{1}{G}\sum_{i=1}^G \textcolor{#c00000}{\frac{1}{|o_i|}}\sum_{t=1}^{|o_i|} \min\!\big(\rho_{i,t}\hat{A}_i,\;\mathrm{clip}(\rho_{i,t},1\pm\epsilon)\hat{A}_i\big)$$ $$\hat{A}_i = \frac{r_i - \mathrm{mean}(\{r_j\})}{\textcolor{#c00000}{\mathrm{std}(\{r_j\})}}$$
Dr. GRPO (Liu et al., 2025 — unbiased):
Remove $\frac{1}{|o_i|}$ (constant normalizer) and drop $\mathrm{std}$: $$\hat{A}_i = r_i - \mathrm{mean}(\{r_1,\dots,r_G\})$$
  • Response-level length bias from $\frac{1}{|o_i|}$:
    • When correct ($\hat{A}_i \gt 0$): shorter responses get larger per-token updates → favors brevity
    • When incorrect ($\hat{A}_i \lt 0$): longer responses get smaller per-token penalties → encourages longer wrong answers
  • Effect of Dr. GRPO: matches reward and benchmark accuracy while stopping output length inflation on incorrect responses

With a constant length normalizer and mean-only baseline, Dr. GRPO sits close to REINFORCE Leave-One-Out (RLOO).

How RLVR Started (Early 2025): DeepSeek-R1-Zero

Historical milestone (Jan 2025): proved pure outcome-based RL on a base LM scales reasoning without PRMs or MCTS.

  • Setup: base DeepSeek-V3 (Dec 2024; 671B total / 37B active) + GRPO with only:
    • Accuracy reward (correct final answer?)
    • Format reward (use <think> tags)
  • Why PRMs & MCTS failed to scale:
    • PRMs: hard to define/label intermediate steps; invite reward hacking
    • MCTS: token-level search space is vastly larger than board games
  • Overstated "aha" moment: Dr. GRPO showed base models already self-correct, and part of R1-Zero's length surge came from GRPO's length bias
Benchmarko1-0912R1-Zero
AIME 2024 (pass@1)74.471.0
AIME 2024 (cons@64)83.386.7
MATH-500 (pass@1)94.895.9
GPQA Diamond77.373.3
LiveCodeBench63.450.0
CodeForces rating18431444

Strong on math from pure RL, but suffered from poor readability and language mixing.

DeepSeek-R1 Pipeline & Offline Distillation (Jan 2025)

DeepSeek-V3 Base model Cold-Start SFT Readable long CoT Reasoning RL GRPO + lang reward SFT + RLHF 600K+200K → GRPO Offline Distill 800K traces → SFT

Historical baseline: in 2026, offline SFT distillation is replaced by on-policy distillation.

Kimi K1.5 (Jan 2025): Curriculum & Length Reward

Historical milestone contemporaneous with R1; introduced data curation, curriculum, and explicit length control.

$$\mathrm{len\_reward}(i) = \begin{cases} \lambda & r(x,y_i,y^*)=1 \\ \min(0, \lambda) & r(x,y_i,y^*)=0 \end{cases}, \quad \lambda = 0.5 - \frac{\mathrm{len}(i) - \mathrm{min\_len}}{\mathrm{max\_len} - \mathrm{min\_len}}$$

Correct answers are rewarded for brevity ($\lambda \in [-0.5, 0.5]$); wrong answers are penalized if longer than the group midpoint.

2025 Stepping Stones: Thinking Control & Agent Tasks

Qwen3 (May 2025, historical)
  • Low-data RLVR: GRPO on just 3,995 carefully filtered examples
  • Thinking Mode Fusion: mix /think and /no_think data; halt thinking at a token budget via an early-stop string
  • Test-time scaling: raising budget from 1K → 32K tokens raised AIME/code accuracy smoothly
  • Alignment tax: general RLHF slightly lowered math/STEM scores
Automated SWE Tasks (Qwen3-Coder-Next)
  • Synthetic environments (800K tasks): parse repos via AST → sample bug patches → validate fail-to-pass tests in Docker → generate issues
  • Long-horizon emergence: average agent turns grew from 50 → 130 during RL
  • Warning sign of reward hacking: without blockers, the agent ran git remote add to restore deleted remotes and fetch ground truth

Next: how late-2026 frontier models rebuilt tasks, sandboxes, RL systems, and distillation around agents.

2026 Frontier: From Math Answers to Agents in Sandboxes

Multi-Turn Agent Loops & Verifier Serving

Rollout Policy token IDs + logprobs Agent Scaffold + Sandboxed Container (multi-turn tool loop) tool call obs Async Verifier & Reward Pools Unit-Test Graders sandboxed execution Lean Checkers formal verification Rubric Judges LLM checklist scoring Generative RMs open-ended domains

Reward Hacking Becomes a Systems Security Problem

What RL Agents Actually Exploited
  • Git & repo leaks: restoring deleted remotes or inspecting future commits to fetch ground-truth patches
  • Kernel & driver bugs: escaping sandbox constraints during RL exploration
  • Package mirrors: leaking held-out answers over external or mirror networks
  • Destructive hacks: deleting system files to trick grading scripts into passing
DeepSeek-V4.1 Containment (DSec)
  • Per-sandbox AppArmor profiles: restrict syscalls and filesystem access tightly
  • eBPF network policies: isolate traffic and block unauthorized external or mirror leaks
  • Crash = failure: any environment crash is scored as a failed trajectory, removing the incentive to break the harness

When optimizing executable rewards at scale, every sandbox escape is a high-reward policy waiting to be found.

Non-Verifiable Tasks: Agentic Generative Judges

Many valuable tasks (writing, research synthesis, open-ended advice) lack unit tests—returning us to RLHF overoptimization.

1. Inspect read candidate(s) 2. Write Rubric task-specific criteria 3. Score & Log grade vs. rubric 4. Tournament binary comparisons Group Rewards feed RL update

RL Systems: Why Rollouts Dominate

Typical RL step wall-clock breakdown (late-2026 systems survey) Autoregressive Rollouts & Environment Execution (>90% of RL time) Train

Making RL fast is primarily an inference-serving and scheduling problem.

The Long-Tail Problem: Synchronous vs. Asynchronous RL

Synchronous RL: every step waits for the single longest rollout Sample 1 GPU idle (waiting for straggler) Sample 2 Sample 3 1 very long trajectory decides batch latency Sample 4 Train Step Asynchronous RL: fixed in-flight pool + continuous dispatch Slot 1 Slot 2 Slot 3 Long trajectory runs without blocking other slots Slot 4 Train Train

Async RL in Practice: Sample-Level Dispatch & Preemption

Design lessons from DeepSeek-V4.1 (Sept 2026):

Dispatch GranularityBehaviorOutcome
Batch-level dispatchWait for whole batch to drain before launching nextTraining metrics oscillated
Prompt-level dispatchDispatch only after all $G$ rollouts of a prompt finishPipeline stalled on slow prompts
Sample-level dispatchLaunch a new prompt as soon as finished samples fill one GRPO groupSmooth throughput & stable RL

Four Complementary Fixes for the Rollout Long Tail

TechniqueHow It WorksExample / Evidence
Partial rolloutsPause unfinished long generations at the iteration boundary; resume them in the next iterationIntroduced in Kimi K1.5; standard in async pipelines
Over-provisioningStart more rollout requests than the batch needs; stop collecting once the target batch fillsAPRIL; eliminates waiting on the slowest tail samples
Length bucketingGroup requests with similar expected output lengths into the same inference batchesReduces decode-step padding and straggler waste
Online speculative decodingRun speculative decoding inside rollout with draft models trained online as the policy shiftsMiles reported 25%+ speedup over a frozen MTP drafter

Online drafter updates matter because a frozen draft model loses acceptance rate as RL shifts the policy distribution.

Two Side Effects of Asynchronous RL

1. Async Length Bias
  • Short trajectories finish first, so early training batches systematically over-represent short answers
  • Fixes:
    • Per-dataset concurrency limits
    • Discarding early short samples before the steady-state length distribution fills the queue
2. Off-Policy Staleness
  • In-flight tokens may have been generated by an older checkpoint $\pi_{\theta_{\text{old}}}$
  • Fixes:
    • Bound maximum checkpoint staleness
    • Mask out the loss on tokens that are too stale
Connection back to PPO: PPO's clipped importance ratio $\mathrm{clip}\!\left(\frac{\pi_\theta}{\pi_{\theta_{\text{old}}}}, 1-\epsilon, 1+\epsilon\right)$ originally bounded multi-epoch updates—in async RL, the exact same mechanism also handles policy lag.

Weight Transfer: Trainer → Rollout Engine

Trainer Ranks TP / PP / EP shards Reshard & Requantize P2P RDMA or delta sync (only changed weights) Rollout Engine pause → load → resume Version Tag tracks staleness

Exact Token Capture & Decoupled RL Services

A New Failure Mode: Train–Inference Mismatch

Same Weights θ & Same Token IDs Rollout Engine (SGLang / vLLM) produces π_rollout(a_t | s_t) Trainer (Megatron / FSDP) computes π_train(a_t | s_t) π_rollout ≠ π_train "On-policy" RL silently becomes off-policy → drift & instability

Why Sparse MoE Makes Train–Inference Mismatch Worse

Rollout Router E4: 0.4102 > E7: 0.4100 Activates Expert 4 top-k winner Downstream Layers & Logits (Trajectory A) amplified across 50+ subsequent MoE layers ↕ tiny 0.0003 logit diff Trainer Router E7: 0.4103 > E4: 0.4101 Activates Expert 7 discontinuous flip! Different Downstream Computation (Trajectory B) large probability & gradient divergence

Mismatch Fixes 1 & 2: TIS and MoE Routing Replay

1. Truncated Importance Sampling (TIS)
  • Reweight each token loss by the truncated trainer-to-rollout probability ratio: $$w_t = \min\!\left(\frac{\pi_{\text{train}}(a_t|s_t)}{\pi_{\text{rollout}}(a_t|s_t)},\; c\right)$$
  • Corrects off-policy drift without blowing up gradient variance
  • Exposed directly in frameworks (e.g., Miles --use-tis, used on GLM-5.3)
2. Routing Replay + FP32 LM Head
  • Record exact expert IDs chosen during rollout and replay them in the trainer forward pass
  • Nemotron 3.5 Super (Oct 2026): router replay + FP32 LM head cut trainer–inference KL by >1 order of magnitude (report)
  • MiniMax-M1 likewise traced mismatch to the LM head and fixed it in FP32
  • DeepSeek-V4.1: concatenates routing across segments when an async rollout spans checkpoints

Mismatch Fixes 3 & 4: Matched Numerics & Low-Precision QAT

Unifying quantization across rollout, training, and serving removes both the train–inference gap and post-RL quantization loss.

Controlling Reasoning Length & Effort in 2026

Generalizes Kimi K1.5's length reward and Qwen3's binary toggle into continuous, controllable test-time effort.

DeepSeek-V4.1 (Sept 2026)
  • Pass a scalar effort level $b \in [1, 100]$ in the system prompt
  • Mean-center rewards within each (prompt, effort) subgroup
  • Add a length penalty whose coefficient decays exponentially with $b$
  • Public API tiers map directly to $b$:
    • max $\to 100$,  high $\to 75$,  low $\to 50$
Kimi K3 (July 2026)
  • Estimate a per-problem token budget using the cold-start model
  • Override trajectory reward to $-1$ whenever length exceeds $\tau \times \text{budget}$
  • Anneal $\tau$ downward across training to produce dedicated high- and low-effort variants
  • Later consolidated into one model via multi-teacher distillation

Why On-Policy Distillation Replaced SFT Distillation

Offline SFT Distillation (Early 2025) Teacher CoTs Student CE on teacher text Train/test distribution shift: Student never sees its own prefixes during training (e.g., R1 → Qwen 2.5) On-Policy Distillation / MOPD (2026) Student samples y Teacher(s) score every token On-policy trajectories + dense signal: Fixes student mistakes on its own rollouts Merges many specialized RL experts into one

$$r_t = \mathrm{clip}\!\left(\log \frac{\pi_{\text{teacher}}(y_t \mid x, y_{\lt t})}{\pi_{\text{student}}(y_t \mid x, y_{\lt t})}\right) \quad \text{(Kimi K3 MOPD per-token reward)}$$

Dense per-token feedback is far more sample-efficient than sparse terminal rewards while avoiding offline SFT exposure bias.

2026 Post-Training Pipeline: Kimi K3 (July 2026)

2.8T total parameters, 104B active; 896 routed experts (16 active, 2 shared); MXFP4 QAT.

SFT Cold Start General Tasks RL 3 effort levels (low / med / high) General Agents RL 3 effort levels (low / med / high) Coding Agents RL 3 effort levels (low / med / high) MOPD 9 experts → 1 unified model clipped per-token log-ratio

2026 Pipelines: DeepSeek-V4.1 & Nemotron 3.5 Super

DeepSeek-V4.1-Flash (Sept 2026)

552B total; 16B decode / 8B prefill active; 384 routed experts.

  • Pipeline: SFT → large-scale asynchronous RL → full-vocabulary on-policy distillation from >40 teacher models
  • Key takeaway from the report: adds no new RL algorithms—the gains came from task synthesis, sandbox environments, and RL infrastructure
Nemotron 3.5 Super (Oct 2026)

Hybrid Mamba-Transformer MoE.

  • Pipeline: SFT → joint RLVR + RLHF → expert teachers → MOPD
  • Joint multi-environment RL: each environment's samples route to its own verifier or reward model
  • Scale: global batch 8,192 (16 rollouts/prompt); max generation raised from 80K → 128K tokens; router replay + FP32 LM head

All three late-2026 frontier labs converged on the same pattern: specialized RL experts consolidated by on-policy distillation.

How RLVR Evolved: Early 2025 vs. Late 2026

DimensionEarly 2025 (R1, Kimi K1.5)Late 2026 (V4.1, Kimi K3, Nemotron 3.5)
Core algorithmGRPO / KL-regularized PGSame foundation (Dr. GRPO / clipped PG + TIS)
Primary tasksSingle-turn math & competition codeMulti-turn agents in sandboxes (SWE, terminal, search, office)
Non-verifiable RLScalar RMs / LLM spot judgesAgentic rubric judges + binary tournament group rewards
Rollout systemsMostly synchronous; partial rolloutsAsync sample-level dispatch, token preemption, P2P RDMA sync
Mismatch controlLargely ignoredTIS, MoE routing replay, FP32 LM head, MXFP4/MXFP8 QAT
Effort controlLate-stage length penalty / toggleContinuous system-prompt effort $b$ or annealed budget $\tau$
ConsolidationOffline SFT distillation (800K CoTs)Multi-teacher on-policy distillation (9 to >40 experts)

Recap: RL from Verifiable Rewards

  1. Why RLVR: verifiable checks (and rubric-based generative judges) overcome RLHF proxy overoptimization and unlock test-time scaling
  2. Algorithms: GRPO removes PPO's value network via group baselines; Dr. GRPO removes std-scaling and length biases to restore an unbiased gradient
  3. Agentic environments: 2026 RL runs millions of sandboxed multi-turn tasks; reward hacking requires OS-level containment (AppArmor, eBPF)
  4. RL systems: rollouts exceed 90% of time—solved by async sample-level dispatch, exact token capture, fast RDMA weight sync, and mismatch fixes (TIS, routing replay, QAT)
  5. Modern pipeline: train specialized RL experts across domains and effort budgets, then unify them via on-policy distillation