Stanford Online
AI-assisted summary of Stanford CME295 Transformers & LLMs | Autumn 2026 | Lecture 4 - Reinforcement Learning with LLMs — original source. Check the original for full context.
Source published:
Key ideas
- Post-training alignment for LLMs bifurcates into RLHF via Bradley-Terry preference modeling for subjective outputs and RLVR via programmatic verification for deterministic tasks. (9:32)
- Proximal Policy Optimization stabilizes training using ratio clipping and a token-level critic, but demands high memory and compute to train the value network concurrently with the policy. (40:34)
- Group Relative Policy Optimization eliminates the auxiliary value function by estimating advantages relative to empirical group statistics, though uncorrected variants introduce length bias pathologies. (67:16)
- On-Policy Distillation and Self-Distillation sidestep reward modeling entirely by enforcing dense, token-level reverse KL penalties from capable or context-privileged teacher passes. (88:51)
Detailed notes
## Background Published on YouTube by Stanford Online on October 19, 2026, this video captures Lecture 4 of Stanford University's Autumn 2026 course CME295 (Transformers & LLMs), taught by Adjunct Professors Afshine Amidi and Shervine Amidi. Accompanying the university's graduate curriculum, the lecture provides an in-depth mathematical treatment of reinforcement learning algorithms used in large language model post-training.
## TL;DR The lecture covers the mathematical foundations and systems engineering of reinforcement learning for LLM alignment and reasoning. The instructors trace the progression from classical RL and vanilla policy gradients (REINFORCE) to Proximal Policy Optimization (PPO), detailing advantage estimation, ratio clipping, and KL penalties. They analyze the memory efficiencies and length-bias pitfalls of critic-free approaches like Group Relative Policy Optimization (GRPO) along with its variants DAPO and Dr. GRPO. The session concludes by demonstrating how On-Policy Distillation (OPD) uses dense token-level reverse KL supervision from frozen teachers or self-generated privileged context to bypass credit assignment issues and auxiliary model overhead.
## Atmosphere & style The presentation carries the polished, rigorous, and highly structured tone of an advanced graduate engineering lecture. The Amidi brothers establish an engaging tag-team teaching cadence, shifting smoothly between formal chalkboard-style calculus derivations and pragmatic systems considerations like GPU VRAM bottlenecks and paper notation quirks. The mood is collaborative and intellectually grounded, making heavy mathematical concepts feel accessible through intuitive analogies while demystifying the actual mechanics running inside state-of-the-art AI labs.
## Bulletin - [09:32](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=572s) Post-training alignment for LLMs bifurcates into RLHF via Bradley-Terry preference modeling for subjective outputs and RLVR via programmatic verification for deterministic tasks. - [40:34](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=2434s) Proximal Policy Optimization stabilizes training using ratio clipping and a token-level critic, but demands high memory and compute to train the value network concurrently with the policy. - [01:07:16](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4036s) Group Relative Policy Optimization eliminates the auxiliary value function by estimating advantages relative to empirical group statistics, though uncorrected variants introduce length bias pathologies. - [01:28:51](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5331s) On-Policy Distillation and Self-Distillation sidestep reward modeling entirely by enforcing dense, token-level reverse KL penalties from capable or context-privileged teacher passes.
## Key takeaways - [06:35](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=395s) In token-level LLM reinforcement learning, the prompt acts as the state, the vocabulary distribution acts as the policy, and each generated token represents an action. - [17:12](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=1032s) The policy gradient derivation relies on the log-derivative trick to compute parameter gradients over expected rewards without differentiating through non-differentiable text sampling. - [33:22](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=2002s) Vanilla REINFORCE suffers from high gradient variance and an absence of intermediate token credit assignment when driven by completion-level scalar rewards. - [53:03](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=3183s) PPO addresses off-policy instability during rollout reuse by clipping the importance sampling ratio within a [1 - epsilon, 1 + epsilon] boundary to establish zero-gradient update plateaus. - [59:25](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=3565s) The beta hyperparameter governing KL divergence penalties against the frozen reference model in PPO corresponds mathematically to the scaling parameter beta in Direct Preference Optimization. - [01:07:16](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4036s) GRPO drops the auxiliary value model required by PPO, deriving baseline expectations and standard deviations from a sampled group of completions per prompt. - [01:18:25](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4705s) Standard GRPO creates an unintended length bias pathology because per-sequence length normalization penalizes incorrect long answers far less severely than incorrect short answers. - [01:22:41](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4961s) Architectural variants such as DAPO and Dr. GRPO resolve length bloat and prompt distortion by modifying token normalization and removing group standard deviation divisors. - [01:25:20](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5120s) Outcome supervision forces identical terminal rewards onto every token in a trajectory, accidentally reinforcing incorrect intermediate reasoning steps in sequences that reach correct answers. - [01:30:41](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5441s) On-Policy Distillation optimizes reverse KL divergence, which triggers mode-seeking behavior in student models and imposes steep penalties on hallucinated tokens deemed implausible by the teacher. - [01:39:15](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5955s) On-Policy Self-Distillation removes external teacher dependencies by utilizing privileged context conditioning—such as ground-truth answers—during parallel teacher-forcing forward passes. - [01:40:55](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=6055s) Commercial AI labs frequently adopt tiered architectures, utilizing compute-heavy RLVR/GRPO for frontier models while compressing capabilities into lightweight deployment tiers via multi-teacher OPD.
## Detailed walkthrough ### [00:06](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=6s) Introduction, Disclaimers, and the LLM Training Pipeline Recap
The lecture opens with an acknowledgment that Lecture 4 marks a shift in technical depth: reinforcement learning (RL) methods have rapidly become central to post-training modern large language models, but understanding them requires confronting more mathematical rigor than previous sessions demanded. Addressing the audience's potential apprehension, the instructor sets expectations directly: “The reason why today's session is a little bit special is because contrary to the previous ones there's going to be a little bit math involved which is why last time we said all the RL based methods we will just reserve them for today.” To manage this complexity, students are urged not to be intimidated by large equations, but rather to follow a three-step approach: first grasp the intuitive reason why an operation is needed, review any unfamiliar mathematical notation, and finally interpret formulas from first principles.
A major source of confusion in reading RL literature is inconsistent notation across papers. To prevent ambiguity, the lecture establishes clear conventions: - **Rewards vs. Ratios:** Rewards are denoted by $R$, while probability ratios are strictly denoted by $\rho$ (rho), avoiding papers that overload $R$ for both. - **Policies:** Distinctions must be maintained between the active policy $\pi_\theta$, the reference policy $\pi_{\text{ref}}$, and the old roll-out policy $\pi_{\text{old}}$. - **Objective Direction:** Machine learning literature traditionally minimizes a loss $\mathcal{L}$, but reinforcement learning typically maximizes expected return; papers often reuse $\mathcal{L}$ for an objective meant to be maximized.
To contextualize where RL fits, the instructor recaps the full LLM training pipeline: - **Pre-training:** Teaches foundational language and code comprehension across trillions of tokens drawn from curated mixtures of web text, books, and code. It relies on standard next-token prediction penalized by cross-entropy loss across the entire sequence, augmented recently by emerging phases like mid-training (using higher-quality filtered data) and long-context training. - **Supervised Fine-Tuning (SFT):** Adapts the base model into a helpful conversational assistant. The loss remains cross-entropy next-token prediction, but applies exclusively to output tokens rather than the prompt. - **Preference Tuning & Reasoning:** The frontier post-training stages that adjust model behavior according to human values (tone, safety, style) or enhance chain-of-thought problem-solving abilities. Both heavily leverage reinforcement learning.
```mermaid flowchart LR accTitle: LLM Post-Training Pipeline accDescr: Sequential stages from pre-training through supervised fine-tuning, preference tuning, and reasoning. subgraph Pre["Pre-Training"] A["Trillions of Tokens<br/>(Web, Books, Code)"] --> B["Base Model<br/>(Cross-Entropy Loss)"] end subgraph SFT["Supervised Fine-Tuning"] B --> C["Instruction Data"] C --> D["Helpful Assistant<br/>(Output-Only Loss)"] end subgraph Post["RL Post-Training"] D --> E["Preference Tuning<br/>(RLHF / DPO)"] D --> F["Reasoning Enhancements<br/>(RLVR / Math & Code)"] end ```
[06:35](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=395s) Mapping Classical Reinforcement Learning to LLMs
Classical reinforcement learning is framed as an agent interacting sequentially with an environment: the agent observes an environmental state $s$, selects an action $a$ governed by its policy $\pi_\theta(a \mid s)$, transitions to a subsequent state, and receives a scalar reward $r$. The overarching objective is finding parameters $\theta$ that maximize the cumulative expected reward.
When translating this classical framework to language modeling, the mapping can be understood at two distinct granularities: - **Token-Level Formulation:** The LLM acts as the agent, the input context or prompt constitutes the initial state, and generating each subsequent token is an individual action. The policy $\pi_\theta$ represents the conditional probability distribution over the model's vocabulary given the preceding token sequence. - **Sequence-Level Formulation:** Because designing dense, meaningful token-by-token rewards is exceedingly difficult in natural language generation, the problem is more effectively formulated at the completion level. The prompt serves as the state, the complete generated text sequence (completion) represents a single macroscopic action, and $\pi_\theta$ denotes the conditional probability of outputting that entire response. A scalar reward is then assigned once to the whole completion.
As the instructor highlights: “So the agent here is the LLM that takes some input as a state and tries to decide what to do next. So what token to sample next. So the action is a token and in order to decide what token to go next to, what it does is it relies on the probability distribution that it outputs given an input.”
[09:32](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=572s) Reward Design: Subjective Human Feedback (RLHF) vs. Verifiable Rewards (RLVR)
Evaluating the quality of a model's generated response falls into two broad structural categories depending on whether ground truth exists:
1. **Subjective Tasks without Ground Truth (RLHF):** Many language tasks have no single correct answer; quality depends on nuance, tone, harmlessness, and clarity. In this paradigm—Reinforcement Learning from Human Feedback—human annotators compare pairs of candidate responses given a prompt. These pairwise preference judgments are modeled using the Bradley-Terry formulation to optimize a separate reward model. Once trained, this frozen reward model supplies scalar evaluation scores to guide policy updates. 2. **Deterministic and Verifiable Tasks (RLVR):** For domains such as mathematics and software engineering, answers can be verified algorithmically against known ground-truth results or unit test suites. This paradigm—Reinforcement Learning with Verifiable Rewards—bypasses noisy learned reward models in favor of deterministic execution feedback (e.g., whether code passes compiler checks and test assertions, or whether a final numerical solution matches the target).
The instructor clarifies: “You have a deterministic way to check whether your answer is correct or not. And so these methods you will also find them under the name RLVR, reinforcement learning with verifiable rewards, and these are typically in the field of reasoning, so math problems and coding problems.”
| Reward Paradigm | Primary Application | Ground Truth | Reward Source | Key Methodology | |:--- |:--- |:--- |:--- |:--- | | **RLHF** | Preference tuning, chat tone, safety, helpfulness | Subjective / non-existent | Learned, frozen Reward Model | Bradley-Terry pairwise comparisons | | **RLVR** | Formal reasoning, mathematics, code generation | Objective / exact | Deterministic execution, test cases, or exact match | Verifiable outcome checks |
[12:23](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=743s) Aligning Policy Parameters via Expected Reward Optimization
Having defined reward signals, the operational challenge becomes adjusting the parameters $\theta$ of the LLM policy to maximize the expected reward collected across tasks. The high-level optimization workflows for both preference tuning and verifiable reasoning share an identical structure, differing primarily in the evaluation block:
In preference tuning, a prompt is sampled from a dataset, and the active LLM generates a response candidate. The prompt and candidate completion are piped together into the frozen reward model, which evaluates the pair and outputs a scalar score. That score is fed back into the optimization objective to nudge parameter weights $\theta$ toward higher-scoring generations.
In verifiable reasoning, the LLM processes a problem prompt, outputs a reasoning trace, and produces a final conclusion. A programmatic verifier inspects the final output against ground truth. The resulting discrete or continuous verification score updates the policy parameters. In both paradigms, the central goal is establishing a mathematical gradient of the expected reward with respect to model parameters:
```mermaid flowchart TD accTitle: Policy Reward Optimization Loop accDescr: Prompt fed to LLM generating completion evaluated by reward model or verifier to update model parameters. subgraph Generation["Policy Rollout"] P["Prompt (State)"] --> LLM["LLM Policy $\pi_\theta$"] LLM --> C["Generated Completion (Action)"] end subgraph Evaluation["Feedback Mechanism"] P --> RM{"Reward Mechanism"} C --> RM RM -->|"Preference Tuning"| RM1["Frozen Reward Model<br/>(Scalar score)"] RM -->|"Reasoning"| RM2["Deterministic Verifier<br/>(Unit tests / Exact match)"] end subgraph Optimization["Parameter Update"] RM1 --> OPT["Policy Gradient Update<br/>$\nabla_\theta \mathbb{E}[R]$"] RM2 --> OPT OPT -.->|"Update $\theta$"| LLM end ```
The instructor encapsulates the guiding loop: “Depending on how the reward model responds you would tweak the parameters of your LLM in order to maximize the rewards, the expected rewards that it is generating.”
[13:51](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=831s) Questions on Log Probabilities and Human Feedback
Before delving into the formal mathematics of policy gradients, the instructor addresses two student questions clarifying fundamental practicalities of reinforcement learning with language models.
First, a student asks whether the probability assigned to a full multi-token sequence is exceptionally small. The instructor confirms that it is indeed extremely low, which is precisely why practitioners take the logarithm of the sequence probability to ensure numerical stability during training.
Second, another student asks whether a human evaluator must inspect and score every single generated completion. The instructor explains that having humans in the evaluation loop at training time would be impossible:
> “You're training it at human preferences. And the reason why you're doing that is because you don't want to have a human in the loop every time you generate a completion.”
Instead, a reward model is pre-trained on human preference data beforehand. Once trained, that frozen reward model evaluates any newly generated model responses on the fly, eliminating the need for active human participation during the reinforcement learning phase.
- **Numerical Stability**: Working in log-probability space avoids floating-point underflow caused by multiplying long sequences of token probabilities together. - **Frozen Reward Model**: Acts as a proxy judge for human preferences, scoring completions automatically and scalably.
---
[15:02](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=902s) Optimization Objective and Gradient Refresher
Transitioning to the formal setup, the overarching objective is defined as finding model parameters $\theta$ that maximize the expected reward under the distribution of trajectories generated by the policy $\pi_\theta$. In mathematical notation, this is expressed as:
$$\max_\theta \mathbb{E}_{\tau \sim \pi_\theta} [r(\tau)]$$
Because machine learning algorithms rely on gradient-based updates to optimize parameters, the central challenge is determining how to take the gradient of this expectation when the sampling distribution itself depends on $\theta$.
To ensure the class shares a consistent mathematical baseline, the instructor offers an intuitive refresher on gradients. Geometrically, the gradient of a multivariable function provides both the direction and the magnitude of the steepest increase. In a one-dimensional setting with an input $x \in \mathbb{R}$, if the derivative $f'(x)$ is positive, the function increases as $x$ increases; if negative, it increases as $x$ decreases. The multi-dimensional analogue for $x \in \mathbb{R}^n$ is the gradient $\nabla f(x)$, consisting of the vector of partial derivatives with respect to each input coordinate.
---
[17:12](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=1032s) Derivation of the Policy Gradient
Returning to the blackboard, the instructor proceeds with the mathematical derivation for computing the gradient of the expected reward with respect to the policy parameters $\theta$:
$$\nabla_\theta J(\theta) = \nabla_\theta \mathbb{E}_{\tau \sim \pi_\theta} [r(\tau)] = \nabla_\theta \int r(\tau) \pi_\theta(\tau) \, d\tau$$
Assuming standard regularity conditions that allow exchanging differentiation and integration, the gradient operator passes inside the integral. The instructor points out that the reward function $r(\tau)$ is not a function of $\theta$—it is frozen—leaving only $\pi_\theta(\tau)$ to be differentiated:
$$\nabla_\theta \int r(\tau) \pi_\theta(\tau) \, d\tau = \int r(\tau) \nabla_\theta \pi_\theta(\tau) \, d\tau$$
To convert this expression back into an expectation that can be approximated via sampling, the instructor uses the log-derivative trick:
$$\nabla_\theta \log f(\theta) = \frac{\nabla_\theta f(\theta)}{f(\theta)} \implies \nabla_\theta f(\theta) = f(\theta) \nabla_\theta \log f(\theta)$$
Substituting $\pi_\theta(\tau)$ for $f(\theta)$ yields:
$$\nabla_\theta \pi_\theta(\tau) = \pi_\theta(\tau) \nabla_\theta \log \pi_\theta(\tau)$$
Plugging this back into the integral produces:
$$\int r(\tau) \left( \nabla_\theta \log \pi_\theta(\tau) \right) \pi_\theta(\tau) \, d\tau = \mathbb{E}_{\tau \sim \pi_\theta} [r(\tau) \nabla_\theta \log \pi_\theta(\tau)]$$
A student asks where the logarithm comes from, and the instructor reiterates that it arises strictly from the mathematical identity relating the gradient of a function to the gradient of its log. Addressing a follow-up question about the tilde notation ($\tau \sim \pi_\theta$), the instructor explains that it signifies that trajectories are drawn from the probability distribution defined by policy $\pi_\theta$.
The core takeaway of the derived formula is intuitive:
> “So what you can take away from this formula is that if the reward is positive, the gradient will incentivize your model to increase the probability of such actions and it will incentivize your model to decrease the probability of actions that have a negative reward.”
```mermaid flowchart LR accTitle: Policy Gradient Derivation Flow accDescr: Step-by-step mathematical flow deriving the policy gradient log trick. subgraph Step1["1. Integral Form"] A["Maximize E[r(τ)]"] --> B["∫ r(τ) ∇π_θ(τ) dτ"] end subgraph Step2["2. Log Trick"] B --> C["∇π_θ = π_θ ∇log π_θ"] end subgraph Step3["3. Policy Gradient"] C --> D["∫ r(τ) ∇log π_θ(τ) π_θ(τ) dτ"] D --> E["E_τ~π_θ [r(τ) ∇log π_θ(τ)]"] end ```
---
[23:50](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=1430s) The REINFORCE Algorithm for LLMs
The instructor contextualizes the trajectory formulation for LLMs. Rather than generic trajectories $\tau$, LLM reinforcement learning operates over a dataset of prompts $X$ and model-generated completions $Y$ sampled from the policy: $Y \sim \pi_\theta(\cdot \mid X)$. While the blackboard proof condensed notation to single trajectories $\tau$, full expectations are taken over prompts and the conditional responses generated by the model.
In the standard REINFORCE update scheme: 1. Sample a prompt $X$. 2. Generate completion $Y \sim \pi_\theta(\cdot \mid X)$ token-by-token. 3. Compute the scalar reward $r(X, Y)$ using the reward model. 4. Compute the policy gradient estimator: $r(X, Y) \nabla_\theta \log \pi_\theta(Y \mid X)$. 5. Update model parameters via gradient ascent: $\theta \leftarrow \theta + \alpha \nabla_\theta J(\theta)$, where $\alpha$ is the learning rate.
The instructor highlights a crucial distinction: while pre-training and supervised fine-tuning (SFT) train on static, pre-collected datasets using parallelized teacher forcing, RL is inherently on-policy. The model must roll out new tokens autoregressively every time an update is performed. Because generation is sequential—each token must be sampled before predicting the next—this generation step cannot be parallelized across the time dimension, rendering rollout collection computationally bottlenecked and expensive.
---
[25:51](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=1551s) Importance Sampling Ratio
To avoid the extreme computational cost of generating brand-new rollouts for every single gradient step, the instructor introduces importance sampling. Instead of re-sampling trajectories from the updated policy $\pi_\theta$ after each tiny parameter modification, one can collect rollouts using a reference, frozen policy ($\pi_{\theta_{\text{fixed}}}$ or $\pi_{\theta_{\text{old}}}$) and reuse those completions over multiple gradient steps.
The transformation proceeds by multiplying and dividing the integrand by the reference policy probability distribution:
$$\mathbb{E}_{\tau \sim \pi_\theta}[r(\tau)] = \int r(\tau) \pi_\theta(\tau) \, d\tau = \int r(\tau) \frac{\pi_\theta(\tau)}{\pi_{\theta_{\text{fixed}}}(\tau)} \pi_{\theta_{\text{fixed}}}(\tau) \, d\tau$$
Expressed as an expectation under the fixed sampling policy:
$$\mathbb{E}_{\tau \sim \pi_\theta}[r(\tau)] = \mathbb{E}_{\tau \sim \pi_{\theta_{\text{fixed}}}} \left[ r(\tau) \frac{\pi_\theta(\tau)}{\pi_{\theta_{\text{fixed}}}(\tau)} \right]$$
The scalar fraction:
$$\frac{\pi_\theta(\tau)}{\pi_{\theta_{\text{fixed}}}(\tau)}$$
is called the **importance sampling ratio**. It re-weights the reward of each sampled trajectory to correct for the distribution mismatch between the policy that actually generated the text ($\pi_{\theta_{\text{fixed}}}$) and the current policy being optimized ($\pi_\theta$).
A student raises an immediate objection: if the model still needs to compute $\pi_\theta(\tau)$, where is the computational savings? The instructor clarifies that computing token probabilities for a full, already-generated sequence in a single forward pass is drastically faster and fully parallelizable across the sequence length, whereas generating a rollout autoregressively step-by-step is an expensive sequential process.
[30:19](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=1819s) Generation vs. Evaluation: Autoregressive Rollouts vs. Parallel Forward Passes
The lecture begins by contrasting the computational cost of generating text against evaluating an already generated sequence. When performing a rollout during reinforcement learning, the model must generate text autoregressively: it takes the initial prompt tokens to generate the very first output token, feeds that generated token back in to produce the next token, and repeats this loop step by step until the sequence finishes. This sequential autoregression makes text generation intrinsically expensive.
```mermaid flowchart TD accTitle: Generation vs Evaluation in Decoder LLMs accDescr: Autoregressive token-by-token generation compared to parallelized evaluation across full sequences.
subgraph GEN["Autoregressive Generation (Expensive)"] direction LR G1["Token 1 In"] --> G2["Token 1 Out"] G2 --> G3["Token 2 In"] G3 --> G4["Token 2 Out..."] end
subgraph EVAL["Evaluation Forward Pass (Cheap)"] direction LR E1["All Input Tokens<br/>(Full Completion Known)"] --> E2["Masked Self-Attention<br/>(Parallel Computation)"] E2 --> E3["All Output Probabilities<br/>Computed at Once"] end ```
In contrast, evaluation is computationally cheap. Addressing a question from the audience asking for more detail on why evaluation is considered cheap, the instructor clarifies that during evaluation, the full sequence of completion tokens is already known in advance. In a standard decoder-only large language model, masked self-attention allows each token position to attend simultaneously to itself and all preceding tokens in parallel. Rather than decoding one token at a time, the entire prompt and completion can be passed through the model in a single forward pass to compute all token probabilities at once. When an audience member asks about the expensive generation step with fixed parameters $\theta$, the instructor notes that while rollouts are indeed expensive, one can generate rollouts once and reuse those generated trajectories across multiple training updates instead of regenerating them at every step.
---
[33:22](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=2002s) Challenges of Vanilla Policy Gradients: Variance, Credit Assignment, and Policy Drift
Moving beyond the computational trade-offs, the discussion turns to the core failure modes of vanilla policy gradient methods (such as REINFORCE) when applied to LLMs. The instructor outlines three central challenges:
1. **High Variance from Lack of a Baseline:** Vanilla policy gradients update model parameters proportionally to the scalar reward $R$ multiplied by the score function $\nabla_\theta \log \pi_\theta$. If rewards are strictly positive and lack a relative baseline, both good and bad answers receive positive parameter updates. For example, if a good answer receives a reward of $101$ and a bad answer receives a reward of $100$, both values are large. The gradient updates will push the model to make both answers appear more frequently, differing only slightly in step magnitude. Over many iterations this creates high-variance, oscillating gradient trajectories. Introducing a baseline representing the expected reward for a state (e.g., an expected value of $100.5$, yielding $+0.5$ for the good answer and $-0.5$ for the bad answer) dramatically lowers gradient variance by directly contrasting an action against expectations. 2. **Lack of Token-Level Credit Assignment:** Completion-level rewards evaluate the trajectory as a monolithic whole (e.g., binary correct/incorrect). The instructor illustrates this with a reasoning prompt: - *Prompt:* A teddy bear is placed in a sealed box, and the box is moved to the kitchen. Where is the teddy bear? - *Faulty Chain-of-Thought:* “Step one, Teddy climbs out of the box. Step two, Teddy walks to the kitchen. And step three, answer kitchen.” Although the final answer (“kitchen”) is correct, the intermediate reasoning step (“Teddy walks to the kitchen”) is physically invalid. Under completion-level rewards, every single token in the generated chain of thought is reinforced equally, rewarding hallucinated reasoning steps alongside the correct final answer. 3. **Policy Drift and Reward Hacking:** LLMs entering the RL phase have already gone through costly pre-training and supervised fine-tuning (SFT), placing them in an already capable state. If an RL objective is applied without constraints, the policy can drift far from the reference model, leading to catastrophic forgetting of previous capabilities. Furthermore, learned reward models are imperfect approximations of human intent. The instructor humorously compares this to optimizing teaching quality based on audience applause:
> “So if I were to only optimize for that then that would not be ideal because maybe I would just spend hour or two hours making jokes that are not related to the class. I would still receive clubs maybe, but it would not be aligned with my objective.”
When reward models are imperfect, unconstrained optimization leads directly to reward hacking, where the LLM games the scoring model without actually satisfying the underlying objective.
---
[40:34](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=2434s) Proximal Policy Optimization (PPO) and Advantage Estimation
To address these three challenges, modern RL pipelines turn to Proximal Policy Optimization (PPO). PPO modifies the vanilla policy gradient objective in two fundamental ways: - It replaces raw completion rewards with an **advantage** function that evaluates actions relative to a learned baseline. - It enforces a **proximity constraint** to ensure the updated policy $\pi_\theta$ does not deviate excessively from the reference policy $\pi_{\text{ref}}$ (giving PPO its "Proximal" name).
The advantage function shifts the optimization question from “*how good is this answer with respect to the prompt?*” to “*compared to what we would expect for this prompt, how good is this response?*”
To compute token-level advantages, the framework introduces a value function that estimates the expected final return from any intermediate state. Given a prompt like “Teddy is in a box. Where is Teddy?” and a partial completion, the value function estimates the expected final reward if the remaining tokens were sampled under the current policy:
| Partial Sequence Stage | Tokens Evaluated | Estimated Expected Final Reward | |:--- |:--- |:--- | | Initial state / first token | `in` | $0.60$ | | Subsequent token | `the` | $0.70$ | | Pivotal token | `box` | $0.95$ | | Final state | `.` (End of sequence) | $1.00$ |
By tracking the change in expected value across token transitions, the model performs explicit token-level credit assignment. For the pivotal token `"box"`, the simplest one-step advantage calculation contrasts the value after producing the token ($0.95$) with the expected value prior to producing it ($0.70$):
$$\text{Advantage}(\text{"box"}) = 0.95 - 0.70 = +0.25$$
This baseline allows the training signal to explicitly isolate and reward the exact tokens that improved the likelihood of a successful final outcome, rather than distributing credit uniformly across the entire response.
[45:00](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=2700s) Token-Level Value Functions and Generalized Advantage Estimation
The discussion turns to the value function, which is defined strictly at the token level rather than across an entire sequence. The underlying mathematical formula aims to estimate the expected future rewards if decoding begins with a given prompt input and a partial completion, then continues by sampling tokens directly from the current policy $\pi_\theta$. Because the value estimate depends on where the policy itself would take the generation, the value model cannot be static; it must be trained alongside the policy, leveraging the policy's evolving parameters. It acts as a token-by-token baseline:
```mermaid flowchart LR accTitle: Token Advantage Computation accDescr: Sequence diagram showing how advantage is extracted by subtracting the value of the prefix from the current prefix plus token. subgraph Context ["Token Evaluation"] A["Prompt + Prefix: x, y_<t"] --> V1["V(x, y_<t)"] B["Prompt + Token: x, y_<=t"] --> V2["V(x, y_<=t)"] end V2 --> Diff{"Subtract"} V1 --> Diff Diff --> Adv["Advantage: A_t"] ```
To determine the baseline advantage of an individual token, one computes the difference between the value up to that token and the value of the prefix immediately preceding it:
$$\text{Advantage}_t \approx V(x, y_{\le t}) - V(x, y_{< t})$$
Subtracting the baseline isolates the marginal impact of that specific token choice. However, the instructor cautions that treating advantage simply as this immediate single-step difference is an oversimplification, calling it "quote unquote" accurate. Generating a specific token may not only increase the likelihood of securing an immediate reward; it can also set up future tokens to be far more effective:
> "You teaching the concepts may lead to your friend acing the math exam. So, that's your short-term reward. But you can also assume that the fact of them succeeding the exam is also placing them on a good path for succeeding later exams and maybe being successful at work and then starting a company, being a CEO, being a billionaire. So you cannot completely attribute you teaching the concept to your friend as being the sole reason for them being successful in the future. But there is some part of it that should be attributed to that and that is the idea behind the generalized advantage estimation paper which is not part of the exam."
The Generalized Advantage Estimation (GAE) framework formalizes this long-term credit assignment by evaluating how future values perform and propagating a portion of that signal backward to credit the original token.
[49:25](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=2965s) Joint Training and Value Function Mechanics
A student in the lecture asks about the relationship and potential coupling between the value function and the policy network. The instructor clarifies that while they are two separate conceptual models, in standard practice they are trained jointly using a single unified loss function that penalizes both policy errors and value prediction errors:
> "The reward model is trained beforehand and the value model is trained at the same time as when you're training your policy. And the main reason why you want to do that this way is because the definition of your value model is to determine the expected rewards if you were to continue according to the policies that you're training."
Although their objective functions are distinct, the two heads often share an underlying transformer backbone parameterization ($\theta$). Importantly, the value function is an auxiliary critic used strictly during optimization—its scalar predictions are never fed back into the policy as generative token inputs.
- The reward model is frozen before RL training begins. - The value model must update concurrently with $\pi_\theta$ to reflect what the current policy can realistically achieve. - The shared loss contains both an LLM policy loss term and a value prediction loss term.
[51:04](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=3064s) Reusing Rollouts and the Importance Sampling Ratio
Shifting focus to the optimization objective, the goal is not merely to optimize the raw expected reward, nor is it simply taking the direct expectation of advantages. Generating full auto-regressive completions from large models is computationally expensive, making it prohibitive to re-sample fresh completions for every single parameter update step.
To improve sample efficiency, training pipelines generate a single batch of rollout completions using the current policy parameters, denoted $\pi_{\text{old}}$, and then execute multiple gradient update steps over that identical batch. Once parameters update to $\pi_\theta$, the rollout data no longer reflects samples pulled from the live policy. To adjust for this off-policy mismatch, an importance sampling ratio is introduced:
$$\rho_t(\theta) = \frac{\pi_\theta(y_t \mid x, y_{<t})}{\pi_{\text{old}}(y_t \mid x, y_{<t})}$$
Instead of optimizing $\mathbb{E}[A_t]$, the objective optimizes $\mathbb{E}[\rho_t(\theta) \cdot A_t]$. The instructor notes that while many RL papers write this ratio as $r_t(\theta)$, CME295 explicitly denotes it with the Greek letter rho ($\rho$) to prevent confusing the probability ratio with scalar reward values ($R$).
```mermaid flowchart TD accTitle: Policy Rollout Reuse Cycle accDescr: Cycle illustrating how a single rollout batch is reused across gradient steps by applying the importance sampling ratio rho. A["Generate Rollout Batch with pi_old"] --> B["Compute Importance Ratio: rho = pi_theta / pi_old"] B --> C["Scale Advantage: rho * A"] C --> D["Gradient Update to Policy Parameters theta"] D -->|"Multi-step reuse"| B ```
[53:03](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=3183s) PPO Ratio Clipping and the Zero-Gradient Region
Allowing updates using the raw importance sampling ratio $\rho$ introduces severe training instability. If the policy update changes $\theta$ so drastically that $\pi_\theta$ diverges wildly from $\pi_{\text{old}}$, the ratio blows up, leading to catastrophic policy collapse. The optimization requires an explicit constraint to keep $\rho$ reasonably close to 1.
Before analyzing the analytical formula, the instructor sketches the objective function $J(\theta)$ on the blackboard as a function of $\rho$, demonstrating how the unclipped objective behaves linearly with respect to the ratio:
``` Unclipped J(θ) PPO Clipped Objective (for Advantage > 0) (for Advantage > 0)
J ↑ / J ↑ /---------- (slope = 0) │ / │ / │ / │ / │ / │ / │ / │ / └────┼──────────→ └────┼────┼─────→ ρ=1 ρ ρ=1 1+ε ρ ```
When the calculated advantage $A$ is positive, the objective encourages the model to increase the probability of that action, driving $\rho$ higher than 1. Without modification, the gradient remains constant and non-zero everywhere, providing an unbounded incentive to push $\rho$ arbitrarily high:
> "So what you want to do is to break that incentive and clip that function in order for you to have a zero gradient region where if you were to let's say perform an update to your policy and it would become here you would have no incentive to increase $\rho$ and this is exactly what is on the slides."
By capping the objective at $1 + \epsilon$ when $A > 0$, the function enters a flat plateau with zero gradient, preventing excessive updates. Conversely, when the advantage is negative ($A < 0$), the unclipped objective constantly pushes $\rho$ toward zero; clipping at $1 - \epsilon$ eliminates the incentive to drive probabilities dangerously low once a sufficient adjustment has been made.
[57:45](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=3465s) Constraining Policy Drift via KL Penalty
Responding to a student who asks why KL divergence cannot be used instead of ratio clipping, the instructor points out that PPO architectures often combine mechanisms: ratio clipping limits step-to-step changes from the rollout distribution, while a Kullback-Leibler (KL) divergence penalty anchors the model over longer trajectories.
The KL divergence operator between two probability distributions $P$ and $Q$ evaluates divergence under the expectation that $P$ represents the true distribution:
$$D_{\mathrm{KL}}(P \parallel Q) = \sum_i P(i) \log \left(\frac{P(i)}{Q(i)}\right)$$
In an LLM alignment loss, the KL divergence provides a soft constraint penalizing the active policy $\pi_\theta$ whenever it drifts too far from the original supervised fine-tuned (SFT) base model. The instructor highlights the critical distinction between policy notations:
| Policy Symbol | Role in Pipeline | Description | |:--- |:--- |:--- | | $\pi_\theta$ | Current Policy | The live model undergoing gradient updates. | | $\pi_{\text{old}}$ | Rollout Policy | The fixed snapshot used to generate the current training batch of completions. | | $\pi_{\text{ref}}$ | Reference Policy | The frozen base/SFT model used in the KL penalty to prevent long-term policy collapse. |
> "So typically what people do is they actually penalize your current policy from being too different from your SFT policy from your base policy your reference policy which is why I want you to pay attention to the subscripts of every $\pi$ that you see out there. So here it's $\pi_\theta$ with respect to $\pi_{\text{ref}}$. $\pi_{\text{ref}}$ is reference as in the base policy and this contrasts with $\pi_{\text{old}}$ which is the policy that you use to generate the completions."
[59:25](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=3565s) Connecting PPO Policy Dynamics to the DPO Objective
The training dynamic of PPO relies on managing three distinct policies. The training loop starts with a fixed base reference model, $\pi_{\text{ref}}$, which remains untouched throughout the training process. The model generates a batch of responses using its current policy, which then becomes fixed as $\pi_{\text{old}}$. Several gradient updates are performed on the active policy $\pi_\theta$, after which a new batch is generated, resetting $\pi_{\text{old}}$ to the newly updated policy. Through all these iterations, $\pi_{\text{ref}}$ stays fixed as the absolute anchor against which deviations are evaluated.
```mermaid flowchart TD accTitle: Policy Dynamics in PPO accDescr: Three policy versions involved in PPO training and their roles. subgraph Policies["PPO Policy Roles"] Ref["π_ref: Base Reference Policy<br/>(Permanently fixed)"] Old["π_old: Rollout Policy<br/>(Fixed per batch generation)"] Theta["π_θ: Active Policy<br/>(Updated via gradient steps)"] end Ref -->|"KL Divergence Anchor"| Theta Old -->|"Probability Ratio Baseline"| Theta Theta -->|"Periodically updates into"| Old ```
This setup connects directly to the formulation seen in Direct Preference Optimization (DPO), derived from the Bradley-Terry preference model:
$$\mathcal{L}_{\text{DPO}} = -\mathbb{E} \left[ \log \sigma \left( R(y_w) - R(y_l) \right) \right]$$
Here, the implicit reward is expressed as $R(y) = \beta \log \frac{\pi(y|x)}{\pi_{\text{ref}}(y|x)}$, and $\sigma$ represents the standard sigmoid function $\sigma(x) = \frac{1}{1 + e^{-x}}$, which evaluates to $0.5$ at $x=0$, approaches $1$ as $x \to +\infty$, and approaches $0$ as $x \to -\infty$. The parameter $\beta$ is identical to the coefficient used in the KL divergence penalty in reinforcement learning with LLMs. As the speaker explains:
> “The beta that is actually penalizing for your model being too different from your reference model is actually the same beta.”
The mathematical consequence of this equivalence lies in the steep region of the sigmoid curve. When $\beta$ is large, even a minuscule deviation in probability ratio relative to $\pi_{\text{ref}}$ makes the input argument to the sigmoid large enough to reach the flat saturation region near 1. Consequently, a large $\beta$ provides lower incentive to stray far from $\pi_{\text{ref}}$, whereas a small $\beta$ demands a much wider divergence between the winning response $y_w$ and losing response $y_l$ before saturation is achieved.
[01:04:05](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=3845s) Audience Q&A: Dual Constraints, Vocabulary-Scale KL, and PPO Notation Pitfalls
Addressing questions from the audience, the instructor clarifies how multiple policy references operate during optimization:
- **The Three Policies:** $\pi_\theta$ is the active parameterized policy undergoing optimization; $\pi_{\text{old}}$ is the frozen policy that generated the trajectories in the current batch; and $\pi_{\text{ref}}$ is the fixed pre-trained/SFT base model. - **Dual Constraints:** To prevent drift both locally and globally, implementations typically enforce both constraints simultaneously: the probability ratio $r_t(\theta) = \frac{\pi_\theta(a_t|s_t)}{\pi_{\text{old}}(a_t|s_t)}$ is clipped around 1 to avoid large single-iteration updates, while a KL penalty $\mathbb{D}_{\text{KL}}(\pi_\theta \parallel \pi_{\text{ref}})$ penalizes absolute drift away from the base model. - **Computing KL over Large Vocabularies:** Because summing over an entire LLM vocabulary at every token step is computationally prohibitive, practitioners rely on sample-based KL estimators instead of exact full-distribution sums.
The instructor also warns students about confusing notation in the original Proximal Policy Optimization literature:
> “And I wanted to have a dedicated slide to say if you were to read the PPO paper, please be careful. $L$ is not a loss. It is an objective function. You want to maximize that quantity. You don't want to minimize. And the second one is you will see $r$ for the ratio. Be careful. It is not a reward. It is a ratio.”
- Gradients in naive policy gradients are noisy, but introducing a value-function baseline yields advantages that reduce variance while enabling token-level credit assignment. - Ratio clipping and KL regularization terms prevent destabilizing updates relative to $\pi_{\text{old}}$ and $\pi_{\text{ref}}$, respectively.
[01:07:16](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4036s) The Motivation Behind GRPO: Eliminating the Critic
While PPO addresses the core challenges of policy gradient methods, it introduces a massive engineering and computational burden: training an auxiliary value network (critic). The speaker underlines this drawback directly:
> “The big problem with this approach is that you need to train a value function. That is a lot of hassle.”
To eliminate this burden, Group Relative Policy Optimization (GRPO) has gained widespread prominence. GRPO maximizes policy advantages without training or maintaining a value function network at all:
> “GRPO stands for group relative policy optimization, and what it does is it tries to maximize advantages, but without a value function.”
Instead of using a separate critic model to approximate expected future returns from every token state, GRPO samples a group of candidate outputs for each prompt and estimates advantages empirically across the group:
1. **Group Sampling:** Given an input prompt, the model samples a group of $G$ distinct responses by setting a positive temperature parameter ($T > 0$). 2. **Group Scoring:** Each output in the group is evaluated by a reward mechanism (either a learned reward model or a deterministic rule-based checker). 3. **Reward Standardization:** The group-relative advantage for each response is computed by subtracting the group's empirical reward mean $\mu$ and dividing by the standard deviation $\sigma$: $$A_i = \frac{r_i - \text{mean}(\{r_j\}_{j=1}^G)}{\text{std}(\{r_j\}_{j=1}^G)}$$ 4. **Constrained Optimization:** The standard policy gradient objective is applied using these group advantages, retaining both ratio clipping against $\pi_{\text{old}}$ and a KL divergence penalty relative to $\pi_{\text{ref}}$.
[01:09:42](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4182s) Architectural Comparison: GRPO vs. PPO
The computational footprint of GRPO is significantly smaller than that of standard PPO because it reduces the number of models required in GPU memory.
```mermaid flowchart TD accTitle: Architectural Comparison Between GRPO and PPO accDescr: Flow diagram contrasting GRPO group sampling with PPO actor-critic pipeline. subgraph GRPO["GRPO Pipeline"] direction TB PromptG["Prompt x"] --> ModelG["Policy Model π_θ"] ModelG -->|"Sample G outputs (T > 0)"| OutG["Responses: y_1, y_2,..., y_G"] OutG --> ScoreG["Reward Evaluator (Learned or Verifiable)"] ScoreG --> NormG["Standardize: A_i = (r_i - μ) / σ"] NormG --> LossG["Clipping + KL vs π_ref (No Value Model)"] end subgraph PPO["PPO Pipeline"] direction TB PromptP["Prompt x"] --> ModelP["Policy Model π_θ"] ModelP -->|"Sample 1 output"| OutP["Response y"] OutP --> RewardP["Reward Model + KL Penalty"] ModelP --> CriticP["Value Model (Critic)"] CriticP --> AdvP["Token-Level Advantage Estimation (e.g., GAE)"] AdvP --> LossP["Clipping + Policy Update"] end ```
In GRPO, the training system only requires the policy model $\pi_\theta$, a reference model $\pi_{\text{ref}}$ for the KL constraint, and an evaluation mechanism. Furthermore, in reasoning, mathematics, or code generation tasks, the learned reward model can be replaced entirely with programmatic verifiable rewards (such as test cases or formal logic checkers).
| Component / Trait | Proximal Policy Optimization (PPO) | Group Relative Policy Optimization (GRPO) | |:--- |:--- |:--- | | **Responses per prompt** | Typically generates a single response ($G = 1$) per rollout step. | Samples a group of $G$ responses ($G \ge 2$) using $T > 0$. | | **Value Function / Critic** | **Mandatory:** Requires an auxiliary value model to predict expected returns and compute advantages. | **None:** Completely omits the value network, substantially reducing GPU memory and complexity. | | **Advantage Calculation** | Calculated at the token level via the value function baseline (e.g., Generalized Advantage Estimation). | Computed across the sampled group via empirical standardization: $\frac{r_i - \mu_{\{r\}}}{\sigma_{\{r\}}}$. | | **Drift Regularization** | Clips importance ratio $r_t(\theta)$ with respect to $\pi_{\text{old}}$; applies KL penalty versus $\pi_{\text{ref}}$ (often embedded directly in rewards). | Retains importance ratio clipping relative to $\pi_{\text{old}}$ and KL divergence penalty against $\pi_{\text{ref}}$. | | **Reward Mechanism** | Typically requires a dedicated neural reward model (unless verifiable). | Compatible with standard reward models or purely verifiable, deterministic programmatic verifiers. |
In PPO, the policy generates an output, feeds it into a reward model, and concurrently queries a value network to obtain per-token baseline predictions of future return to assemble advantage estimates. In GRPO, group-level normalization replaces token-level critic queries, providing a clear relative baseline without ever training a critic.
[01:12:47](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4367s) Models in Training: PPO vs. GRPO
Computing advantages can be done in a completely vanilla fashion by taking the difference between value functions, but standard practice relies on Generalized Advantage Estimation (GAE). Once calculated, that advantage scales the gradient used to update the policy. Looking at the full system architecture, several distinct models interact during alignment:
```mermaid flowchart TD accTitle: Model Architecture in PPO vs GRPO Training accDescr: Diagram contrasting frozen models against active training models in PPO and GRPO pipelines.
subgraph Frozen["Frozen / Pre-trained Components"] Ref["Reference Model<br/>(Frozen baseline)"] RM["Reward Model<br/>(Optionally pre-trained)"] end
subgraph Active["Actively Trained Models"] Pol["Policy Model π_θ<br/>(Trained in both PPO & GRPO)"] Val["Value Model V_φ<br/>(Trained jointly ONLY in PPO)"] end
Ref -.->|"KL penalty check"| Pol RM -.->|"Scoring"| Pol Val <-->|"Must stay in sync"| Pol ```
The reference model is kept fixed to anchor the original behavior, and any reward model used to evaluate outputs is pre-trained beforehand rather than updated on the fly. The policy model is always trained. In Proximal Policy Optimization (PPO), however, an additional value model must be trained jointly with the policy. Because the value model estimates the expected rewards of following the current policy—a target that moves continuously as the policy updates—both models must stay synchronized. The instructor points out: “And that is the core reason why PPO is a hassle because you need to have all the bandwidth to to host the value model training.”
[01:14:41](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4481s) Comparing Mathematical Formulations: PPO vs. GRPO
While the complete mathematical objectives can appear intimidating, breaking them down reveals clear structural parallels alongside two critical divergences:
| Component | Proximal Policy Optimization (PPO) | Group Relative Policy Optimization (GRPO) | |:--- |:--- |:--- | | **Importance Sampling Ratio** | Ratio of current policy probability $\pi_\theta$ to data-generating old policy probability $\pi_{\theta_{\text{old}}}$ | Ratio of current policy probability $\pi_\theta$ to data-generating old policy probability $\pi_{\theta_{\text{old}}}$ | | **Policy Ratio Clipping** | Clipped within $[1 - \epsilon, 1 + \epsilon]$ to prevent destructive steps | Clipped within $[1 - \epsilon, 1 + \epsilon]$ to prevent destructive steps | | **KL Penalty Location** | Typically integrated directly into the token-level advantage calculation | Expressed explicitly as a regularizer term within the overall loss function | | **Advantage Computation Level** | Token level ($t$), leveraging an actively trained token-level value function $V_\phi$ | Completion/output level ($i$), though formally indexed as $A_{i,t}$, computed relative to group mean and standard deviation |
Although the advantage notation in the GRPO formula includes both the completion index $i$ and token index $t$ ($A_{i,t}$), practitioners almost universally treat it as a function of completion $i$ alone. Differentiating individual token contributions without an explicit value model is difficult, so the reward of the entire completion is compared to the group:
$$\hat{A}_i = \frac{R_i - \text{mean}(\mathbf{R})}{\text{std}(\mathbf{R})}$$
When addressing a student question about whether the KL divergence belongs in the loss or the advantage, the instructor notes that while slides often contrast specific design choices, implementations frequently vary across papers: “And by the way it's a common thing. Every paper has a different way of implementing this. So yeah, don't be surprised.”
[01:18:25](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4705s) The Length Bias Pathology in GRPO
When GRPO was evaluated on complex mathematics and reasoning benchmarks, the training process successfully incentivized the model to generate chains of thought before outputting a final answer, yielding marked performance improvements. However, empirical evaluation revealed an unintended phenomenon: the average response length steadily climbed throughout training, continuing to expand even after task accuracy reached a plateau.
This bloat stems from the token-level normalization factor in the objective function, specifically the term $\frac{1}{|o_i|}$, where $|o_i|$ is the completion length in tokens: - When a response is short ($|o_i|$ is small), $\frac{1}{|o_i|}$ is large, amplifying the per-token gradient contribution. - When a response is long ($|o_i|$ is large), $\frac{1}{|o_i|}$ is small, attenuating the per-token gradient contribution.
Because the update direction depends on whether the completion advantage is positive or negative, this scaling produces asymmetric behavior:
```mermaid flowchart TD accTitle: GRPO Token Normalization Dynamics accDescr: Flowchart illustrating how completion length scales gradient updates for positive and negative advantages.
Length{"Response Length"}
Length -->|"Short (|o| small → 1/|o| large)"| Short["Amplified Updates"] Length -->|"Long (|o| large → 1/|o| small)"| Long["Dampened Updates"]
Short -->|Advantage > 0| SPos["Strong upward push (+)"] Short -->|Advantage < 0| SNeg["Severe downward penalty (--)"]
Long -->|Advantage > 0| LPos["Mild upward push (+)"] Long -->|Advantage < 0| LNeg["Weak downward penalty (-)"] ```
When generating an incorrect response (where advantage is negative), a short response receives a massive downward gradient penalty, whereas a long response receives only a mild penalty. Consequently, when faced with problems it cannot solve correctly, the model exploits this asymmetry: “...relatively speaking, the model will prefer a bad answer that is longer compared to a bad answer that is shorter.” The model learns that prolonging an erroneous response minimizes the training penalty, explaining why response lengths continue to balloon even after benchmark performance plateaus.
[01:22:41](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4961s) Post-GRPO Refinements: DAPO, Dr. GRPO, and Credit Assignment
Several follow-up methods address the structural vulnerabilities of vanilla GRPO: - **DAPO (Decoupled Advantage Policy Optimization):** Eliminates the per-sample length skew by normalizing across the aggregate token count of the entire batch rather than dividing each response by its own sequence length, ensuring uniform token weighting. - **Dr. GRPO (GRPO Done Right):** Dispenses with the sequence-length normalization factor entirely. - **Standard Deviation Bias Removal:** Normalizing completion advantages by the standard deviation of group rewards introduces distortion across inputs of varying difficulty; questions with low reward variance artificially inflate advantage magnitudes. Removing the standard deviation divisor resolves this inconsistency. - **Asymmetric Clipping Bounds:** Using a symmetric clipping threshold $\epsilon$ (such as $0.2$) restricts low-probability actions disproportionately. An action with a base probability of $0.001$ has almost no margin to expand under symmetric bounds, choking off exploration and diversity. Employing distinct upper and lower clipping bounds ($\epsilon_{\text{low}} \neq \epsilon_{\text{high}}$) affords underrepresented tokens a viable margin to emerge.
In wrapping up GRPO before passing the floor to Shervine Amidi, the instructor notes that while baseline GRPO produces lower-variance gradients via group baselines and controls update sizes using clipping and KL penalties, it abandons fine-grained temporal resolution: “We don't have a value function anymore, but we don't have token level credit assignments and that's not good.” Addressing that lack of token-level credit assignment motivates the next paradigm in the lecture: On-Policy Distillation.
[01:25:20](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5120s) The Credit Assignment Flaw in Outcome-Supervised GRPO
Returning to the running example of a teddy bear sealed inside a box, Shervine Amidi revisits the limitations of Group Relative Policy Optimization (GRPO) paired with verifiable rewards. In an outcome-supervised setup, the reinforcement learning algorithm cares exclusively about the final answer, remaining completely blind to the intermediate reasoning steps. When generating $G$ candidate completions, some reasoning chains contain steps that go well, some contain steps that go completely wrong, and others mix both sound and flawed deductions.
```mermaid flowchart TD accTitle: Outcome Supervision vs Process Credit Assignment accDescr: Diagram contrasting end-of-sequence reward attribution with per-step token evaluation.
subgraph Outcome["Outcome Supervision (GRPO)"] direction TB A["Step 1: Sound premise"] --> B["Step 2: Flawed deduction"] B --> C["Final Answer (Correct by chance)"] C ==>|"Uniform Reward / Advantage"| A C ==>|"Uniform Reward / Advantage"| B end
subgraph Process["Process Supervision Challenge"] direction TB D["Step-level evaluation"] --> E["Token-level ambiguity"] E --> F["Need dense step/token reward models"] end ```
Under the standard GRPO objective, every token in a completion is assigned the exact same sequence-level advantage scalar based entirely on the terminal outcome. If an intermediate reasoning step is utterly nonsensical but the final answer accidentally matches the ground truth, those faulty tokens are still reinforced with a positive advantage. Shervine notes that while one could hope that random intermediate errors average out across massive sample sizes so the model eventually uncovers valid behavior, relying on that long horizon is fundamentally inefficient: “So each of your terms of your loss functions might not be correctly rewarding the right things.”
Even if one pivots toward process supervision where the advantage is written explicitly as a function of the token position $t$, dense step-level or token-level labels become strictly necessary. Relying on human or automated process labels introduces recursive ambiguity: if the student generates the step "Teddy walks to the kitchen," it is unclear whether the penalty belongs to the action of walking or to the kitchen destination itself. Resolving this down to individual tokens would require training and maintaining separate token-level reward models—the exact computational overhead and multi-model complexity that motivated abandoning standard PPO in favor of GRPO in the first place.
- In outcome supervision, every token receives the identical end reward, causing local noise and severe credit assignment misattribution. - Process supervision requires granular step-level labeling, which risks falling into a recursive ambiguity down to individual words. - Training auxiliary reward models to score each token reintroduces the multi-model memory footprint of PPO that practitioners seek to avoid.
---
[01:28:51](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5331s) The Case for Distillation Without Extra Models
To establish an ideal training paradigm, Shervine recaps the properties researchers want to preserve. First, the objective must remain strictly on-policy, meaning the network trains directly on the generations sampled from its own current weights rather than off-policy static datasets. Second, the supervision signal should credit tokens locally rather than relying on noisy sequence-level terminal rewards. Third, the system must avoid training any additional critic, value, or reward models.
When Shervine prompts the room for a machine learning paradigm that provides dense next-token prediction signals from a stronger pre-existing network without training separate critic weights, a student immediately volunteers distillation. Shervine confirms the intuition: “Yeah, exactly. Because distillation is about next token prediction, transfer of information from one model to the other.” However, rather than standard offline distillation over static teacher outputs, the objective must adapt to an on-policy regime where the student generates completions and a frozen, capable teacher provides token-by-token supervision.
- Desideratum 1: Stay strictly on-policy to avoid distribution shift and train on the student's actual generation distribution. - Desideratum 2: Provide dense, token-by-token feedback instead of sparse, delayed terminal rewards. - Desideratum 3: Eliminate auxiliary trainable networks like critic or value models to minimize compute and memory overhead.
---
[01:30:41](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5441s) Reverse KL Divergence and Mode-Seeking Behavior
Before detailing On-Policy Distillation (OPD), Shervine reviews the mechanics of Kullback–Leibler (KL) divergence between probability distributions $P$ and $Q$. Because KL divergence is non-symmetric ($D_{\mathrm{KL}}(P \parallel Q) \neq D_{\mathrm{KL}}(Q \parallel P)$), the order of arguments fundamentally dictates the optimization behavior. Shervine summarizes the directional meaning in plain terms: “So the way I propose we interpret this so KL of P and Q is in a world governed by P. How bad is it to approximate with Q?”
In classical offline distillation, the world is governed by the teacher $T$, placing $T$ as the first argument: $D_{\mathrm{KL}}(T \parallel S)$. But because on-policy training evaluates actions sampled under the student distribution $S$, the objective flips to the reverse KL divergence, $D_{\mathrm{KL}}(S \parallel T)$:
$$D_{\mathrm{KL}}(S \parallel T) = \sum_i S(i) \log \left( \frac{S(i)}{T(i)} \right)$$
This formulation yields distinctive mathematical characteristics: 1. **Zero-avoidance for teacher support:** If a token has non-zero probability under the teacher ($T(i) > 0$) while the student places negligible probability on it ($S(i) \approx 0$), the outer weighting term $S(i)$ pulls the term toward zero. The loss is thus forgiving when the student fails to cover parts of the teacher's distribution. 2. **Heavy penalty on student hallucinations:** Conversely, if the teacher assigns near-zero probability to a token ($T(i) \approx 0$) but the student assigns it positive probability ($S(i) > 0$), the ratio $S(i)/T(i)$ explodes, producing a massive penalty.
Because a compact student model lacks the capacity and degrees of freedom to capture the full multi-modal spread of a massive teacher, reverse KL drives mode-seeking behavior. The student prioritizes focusing its probability mass tightly on the sharpest peaks of the teacher distribution rather than smoothing its mass across the entire distribution (mode-covering). While the earliest distillation papers experimented with combinations of forward and reverse penalties, modern on-policy distillation relies heavily on this reverse KL formulation.
---
[01:34:15](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5655s) On-Policy Distillation in Practice: The Teddy Bear Example
Shervine illustrates the operational mechanics of on-policy distillation using the sealed teddy bear problem. The student model autoregressively samples its own tokens conditioned on the input prompt. At every single newly generated token, the frozen teacher inspects the prefix context and evaluates the probability of that student token under its own distribution.
```mermaid flowchart LR accTitle: On-Policy Distillation Step-by-Step Flow accDescr: The student autoregressively samples tokens while the teacher scores each token under the accumulating context.
subgraph Sampling["On-Policy Generation"] P["Prompt: Teddy in sealed box"] --> S1["Student outputs: 'Teddy'"] S1 --> S2["Student outputs: 'climbs'"] S2 --> S3["Student outputs: 'walks'"] end
subgraph Evaluation["Teacher Verification (Reverse KL)"] T1["Teacher: Context allows 'Teddy' (Loss: ~0)"] T2["Teacher: 'climbs' impossible in sealed box! (Large penalty)"] T3["Teacher: 'Teddy climbs' in context allows 'walks' (Loss: ~0)"] end
S1 -.-> T1 S2 -.-> T2 S3 -.-> T3 ```
When the student initiates its answer with "Teddy", the teacher's distribution finds that plausible and incurs negligible penalty. However, when the student follows with "Teddy climbs", the teacher flags "climbs" as extremely improbable within a sealed container: “So let's say the sentence starts with Teddy. So Teddy makes sense to the teacher. I would generate also Teddy. But then the student says Teddy climbs and the teacher would say okay wait climbs is not a high probability token in my distribution.” The reverse KL loss penalizes this token heavily.
Shervine then highlights an intriguing quirk in the toy example: in a second output branch where the student generated "climbs" earlier and then generated "walks", the word "walks" is not flagged with a red penalty. When asked why, an audience member suggests the teacher might now treat the teddy bear anthropomorphically. Shervine confirms this insight: because language models operate conditionally on the entire running context, once the hallucinated premise "Teddy climbs" has been accepted into the prompt prefix, subsequent human-like verbs such as "walks" become high-probability continuations under the teacher's distribution.
---
[01:36:30](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5790s) Dense Token-Level Supervision and Parameter Efficiency
Shervine summarizes the structural advantages that distinguish On-Policy Distillation from standard supervised fine-tuning (SFT) and standard RL:
1. **Dense Supervision:** Feedback arrives at every single token rather than as a single delayed scalar at the terminal token. 2. **On-Policy Alignment:** Unlike standard SFT, which conditions exclusively on external, ground-truth text demonstrations, OPD forces the model to evaluate and correct errors occurring within its own self-generated completion trajectories: “and contrary to SFT it's as the name suggests on policy meaning that you're training the model to be better at with respect to its own completions”. 3. **Compute Efficiency:** For a fixed training budget, practitioners obtain significantly stronger reasoning performance per FLOP compared to pure outcome-supervised RL.
Shervine highlights an ablation study published in a Thinking Machines blog post evaluating parameter-efficient fine-tuning under strict rank constraints. When tuning low-rank LoRA adapters, standard SFT leaves a noticeable performance gap across different parameter ranks. Applying on-policy distillation substantially closes the performance delta between lower-rank and higher-rank configurations, demonstrating that dense on-policy teacher signals maximize the utility of constrained model architectures. Furthermore, because OPD operates purely through forward passes over a frozen teacher network without fitting an auxiliary reward model or estimating trajectory returns, the pipeline avoids the instability and memory footprint of multi-model reinforcement learning.
[01:38:04](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5884s) Limitations of On-Policy Distillation
The discussion opens with an inherent benefit of on-policy distillation: because training directly optimizes toward matching the teacher distribution, there is fundamentally nothing in the reward structure to exploit or hack. As the speaker explains, “if on-policy decision wants to bring the loss down to zero, then you would align with the teacher distribution, which is a good edge case.” However, this setup presents two severe limitations.
First, standard on-policy distillation strictly requires having an external teacher model readily available. If an organization is actively developing a state-of-the-art frontier model, an external superior guide might not exist at all: “Maybe you're the best. So there is no one that could teach you.” Second, unlike reinforcement learning approaches such as Group Relative Policy Optimization (GRPO)—where updates are anchored directly against ground-truth labels and verified correctness—on-policy distillation relies solely on comparing student outputs against the probability distributions emitted by a teacher. A teacher model is not inherently flawless; its output distributions can be imperfect, hallucinated, or lack domain coverage over specialized topic areas that the practitioner needs to target.
- **Absence of reward hacking**: Driving distillation loss to zero purely forces alignment with the target teacher distribution. - **The frontier boundary limitation**: When training the world's most capable model, no external teacher model exists to serve as an authority. - **Imperfect and incomplete targets**: Teacher distributions may contain errors or have sparse domain coverage compared to ground-truth labels.
---
[01:39:15](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=5955s) On-Policy Self-Distillation (OPSD)
To eliminate the strict dependency on an external teacher model, the speaker introduces a mechanism that appears counterintuitive at first: “I know it's it's not obvious, but once we're going to see it, it sounds magical.” The key lies in understanding how token probability distributions are extracted during the training phase. When generating responses, a student model samples autoregressively, but during evaluation and training, modern architectures operate via teacher forcing: the entire prompt combined with the generated student tokens is fed in parallel to compute next-token prediction distributions.
Because teacher forcing allows full control over the context window, practitioners can inject extra guidance directly into the prompt. The teacher pass can be supplied with the prompt, the full ground-truth answer, and the complete chain of reasoning leading up to that answer. The model is then asked to predict the response conditioned on having that privileged context. This enables the exact same underlying model to play both roles: an unassisted student version generates raw completions, while an omniscient, privileged version of that identical model acts as the teacher to yield refined probability distributions for the loss calculation.
```mermaid flowchart TD accTitle: On-Policy Self-Distillation Prompt and Inference Flow accDescr: Diagram showing how a single model functions as both student and teacher through prompt conditioning. subgraph StudentPass ["Student Path (Unprivileged)"] SPrompt["Prompt"] --> SModel["Base Model (Student)"] SModel --> STokens["Generated Student Tokens"] end
subgraph TeacherPass ["Teacher Path (Privileged Context)"] PrivInput["Prompt + Ground-Truth Answer & Reasoning + Student Tokens"] --> TModel["Same Base Model (Teacher)"] TModel --> TDist["Target Probability Distribution"] end
STokens --> DistillLoss["On-Policy Distillation Loss"] TDist --> DistillLoss ```
- **Teacher-forcing context injection**: Any helpful context—including final answers and scratchpad derivations—can be prepended to the teacher's input context. - **Single-model setup**: The same network weights act as both the unconditioned student generating tokens and the privileged teacher evaluating them. - **Loss optimization**: The student learns to match distributions that were conditioned on having access to the answer, pulling its unassisted generation capability closer to the privileged performance.
---
[01:40:55](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=6055s) Industry Applications and Tiered Model Architectures
In response to a student question about when on-policy distillation yields the largest practical payoff, the speaker breaks down where the method fits inside commercial AI laboratories. For an absolute frontier model setting the state of the art, distillation from an external system yields diminishing returns. However, the technique remains useful even for top-tier systems to prevent catastrophic forgetting: “The like GLM-5 paper that we saw last week is one example where you would use it to calibrate the fact that you do not lose knowledge that you have learned in the past.” In that scenario, an evolving model distills against its own previous checkpoints to retain established competencies.
More commonly, leading AI organizations maintain a tiered product suite consisting of larger, flagship systems alongside smaller, low-latency variants (such as a "Pro" and a "Flash" series). Distillation methods provide the greatest leverage when compressing capabilities down to the faster tiers:
| Tier / Model Class | Primary Training Strategy | Core Objectives & Characteristics | |:--- |:--- |:--- | | **Frontier / Pro Tier** | Foundational GRPO, RL with ground-truth labels | Compute-heavy post-training using hardcore ground-truth verification; acts as the primary capability boundary. | | **Efficient / Flash Tier** | On-Policy Distillation (OPD) | Rapidly transfers capabilities from larger frontier models into compact, high-throughput architectures. | | **Continual Updates / Self-Retention** | Self-Distillation (OPSD) | Calibrates updates against prior model iterations to safeguard previously acquired knowledge against forgetting. |
As the speaker summarizes the production trade-off: “maybe on-policy distillation would be what you use on your flash series and then your pro series might be more foundational GRPO and then like these core techniques that might need more compute but that are based off like hardcore labels.”
---
[01:42:09](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=6129s) Multi-Teacher On-Policy Distillation
The final architectural challenge stems from the fact that a single teacher model is intrinsically bounded by its own strengths and blind spots across diverse subjects. Trying to rely on a single catch-all teacher across mathematics, programming, natural science, and humanities risks inconsistent supervision signals and catastrophic forgetting.
To overcome this, modern pipelines deploy Multi-Teacher On-Policy Distillation. Domain-specific models are trained using verifiable rewards tailored to each distinct vertical (such as formal math proofs or deterministic code execution). When the student model is updated, its on-policy outputs are distilled against the specific domain-expert teacher for that given topic rather than a single monolithic model:
- **Domain-expert allocation**: Sub-specialized models are trained against verifiable domain rewards and serve as authorities only within their respective specialties. - **Mitigating interference and forgetting**: As the speaker cautions, “empirically if you do this post-training RL on just a single one you might have things like forgetting that happens and you might use a given set of parameters towards multiple objectives.” - **Superior training stability**: Distilling distinct skills from focused expert teachers prevents conflicting parameter updates across disparate task objectives, concluding the lecture's overview of reinforcement learning and distillation mechanics.
## Notable quotes > [01:07:16](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=4036s) GRPO stands for group relative policy optimization, and what it does is it tries to maximize advantages, but without a value function.
> [49:25](https://www.youtube.com/watch?v=3Vaj0Oka_t4&t=2965s) The reward model is trained beforehand and the value model is trained at the same time as when you're training your policy. — Instructor
## Mentioned Stanford University, Afshine Amidi, Shervine Amidi, Bradley-Terry model, RLHF, RLVR, REINFORCE, Proximal Policy Optimization (PPO), Generalized Advantage Estimation (GAE), Direct Preference Optimization (DPO), Group Relative Policy Optimization (GRPO), DAPO, Dr. GRPO, On-Policy Distillation (OPD), On-Policy Self-Distillation (OPSD), Thinking Machines, LoRA, GLM-5
## Video description For more information about Stanford’s graduate programs, visit: https://online.stanford.edu/graduate-education
To follow along with the course schedule and syllabus, visit: https://cme295.stanford.edu/syllabus/
Chapters: 00:00:00 Introduction 00:06:35 RL setup 00:09:32 Reward design 00:12:23 Policy gradient 00:17:12 Derivation of the gradient 00:23:50 REINFORCE 00:25:51 Importance sampling ratio 00:33:22 Challenges of policy gradients 00:40:34 Proximal Policy Optimization (PPO) 00:42:49 Value function and advantage 00:51:16 Policy ratio 00:53:03 Ratio clipping 00:57:45 KL Penalty 00:59:48 Connection with DPO 01:07:29 Group Relative Policy Optimization (GRPO) 01:09:42 Comparison of GRPO and PPO 01:18:25 Limitations of GRPO 01:22:41 DAPO, Dr. GRPO 01:25:17 On-Policy Distillation (OPD) 01:39:32 Self (OPSD) and Multi-Teacher (OPD) variants
Afshine Amidi is an Adjunct Professor at Stanford University.
Shervine Amidi is an Adjunct Professor at Stanford University.
Follow the playlist: https://youtube.com/playlist?list=PLakGfbKCei80&si=HF2tNywj7nXIQq8X
[Source](https://www.youtube.com/watch?v=3Vaj0Oka_t4)