---
title: "Why Policy Gradients Need Baselines and Trust Regions"
subtitle: "CMU Advanced NLP · Lecture 15: Reinforcement Learning Fundamentals"
author: "Chao Ma"
date: "2026-12-03"
categories: [NLP, Reinforcement Learning, Policy Gradient, PPO, Baselines]
description: "How Markov decision processes, the REINFORCE score-function estimator, temporal discounting, learned value baselines, and PPO surrogate clipping turn non-differentiable rewards into stable policy updates."
toc: true
lightbox: true
format:
html:
code-fold: false
include-in-header:
text: |
<style>
.math.display { display:block; max-width:100%; overflow-x:auto; overflow-y:hidden; padding:.35em 0; }
main p, main li { overflow-wrap:anywhere; }
</style>
execute:
enabled: false
image: anlp15-assets/cartpole-baseline-convergence.png
resources:
- anlp15-assets/create_figures.py
- anlp15-assets/manifest.json
---
<iframe width="100%" height="500" src="https://www.youtube.com/embed/CmyrQAV-vdY" title="CMU Advanced NLP Fall 2025 (15): Reinforcement Learning Fundamentals" frameborder="0" allowfullscreen></iframe>
Supervised fine-tuning teaches a language model to imitate tokens in a static dataset, not to optimize whether an entire generated response passes unit tests, solves a math problem, or avoids harmful content. When the evaluation criterion lives at the end of a trajectory—and may not even be differentiable—we need a learning rule that directly optimizes expected reward over the model's own rollouts.
Sean Welleck's Lecture 15 on the [CMU Advanced NLP Fall 2025 schedule](https://cmu-l3.github.io/anlp-fall2025/) ([slides PDF, 50 pp.](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf); course code in [`15_rl`](https://github.com/cmu-l3/anlp-fall2025-code/tree/main/15_rl); [Fall 2025 lecture recording on YouTube](https://www.youtube.com/watch?v=CmyrQAV-vdY), 68m10s, posted Oct 21, 2025) builds the mathematical and algorithmic foundations of policy-gradient reinforcement learning before turning to LLM post-training in [Lecture 16](cmu-advanced-nlp-lecture-16-reinforcement-learning-for-llms.qmd):
1. **From maximum likelihood to interaction ([slides, pp. 2–13](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=2)):** Diagnosing three limits of supervised fine-tuning—task mismatch, data mismatch, and exposure bias—and reframing training around model-generated trajectories scored by a reward function.
2. **Markov Decision Processes (MDPs) and RL formulations ([slides, pp. 14–26](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=14)):** Formalizing states, actions, transition dynamics, rewards, policies, trajectories, and value functions, with concrete groundings in Pong, robotics, and autoregressive math reasoning.
3. **REINFORCE and the score-function estimator ([slides, pp. 28–34, 48–50](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=28)):** Deriving why differentiating expected return produces log-probability updates weighted by future returns—without differentiating the environment.
4. **Stabilizing updates and comparing saved CartPole runs ([slides, pp. 35–46](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=35)):** Weighting gradients via discounting, state baselines, TD residuals, and Generalized Advantage Estimation (GAE), curbing excessive update incentives via PPO surrogate clipping, and inspecting the single saved `CartPole-v1` runs in [`pg.ipynb`](https://github.com/cmu-l3/anlp-fall2025-code/blob/main/15_rl/pg.ipynb) and [`pg_vf.ipynb`](https://github.com/cmu-l3/anlp-fall2025-code/blob/main/15_rl/pg_vf.ipynb).
{fig-alt="Two-panel chart titled Saved CartPole Runs Solved in 572 vs. 1,141 Episodes. Panel A plots running EMA reward against episode index on CartPole-v1 from single saved notebook runs: REINFORCE without baseline (terracotta line) fluctuates and crosses the 475 solved threshold at episode index 1,140 (1,141 episodes), while REINFORCE with a learned value baseline (blue line) reaches the threshold at inferred episode index 571 (572 episodes), labeled 49.9% fewer episodes. Panel B plots Slide 38 prompt weights with a bold zero baseline: Summarize (R=0.80, b=0.75) moves from +0.80 raw to +0.05 advantage; Summarize (R=0.30, b=0.75) flips from +0.30 raw to -0.45 advantage; Prove (R=0.30, b=0.10) stays positive from +0.30 raw to +0.20 advantage."}
## Why supervised fine-tuning hits a ceiling
Given an instruction-following dataset $\mathcal{D} = \{(x^{(i)}, y^{(i)})\}_{i=1}^N$, supervised fine-tuning (SFT) minimizes token-level negative log-likelihood ([slides, pp. 2–3](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=2)):
$$
\mathcal{L}_{\text{MLE}}(y_{1:T} \mid x) = -\sum_{t=1}^{T} \log p_\theta(y_t \mid y_{<t}, x).
$$
SFT excels at teaching response format and imitating curated demonstrations, yet [slides, pp. 4–7](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=4) identify three structural mismatches when we deploy the model on downstream tasks:
| Failure mode | Supervised MLE objective | Downstream task requirement | Concrete lecture example ([slides, pp. 4–7](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=4)) |
|---|---|---|---|
| **Task mismatch** | Matches token likelihood $p(\text{probable response} \mid \text{prompt})$ | Satisfies a sequence-level criterion | A probable answer need not be helpful or non-offensive; probable code need not pass test cases |
| **Data mismatch** | Learns every behavior present in $\mathcal{D}$ | Requires scarce task-specific behaviors | Pretraining text contains toxic comments and buggy code, while high-quality chains of thought are scarce |
| **Exposure bias** | Conditions only on gold prefixes $y_{<t}$ during training | Must recover from its own errors at test time | Making an arithmetic slip mid-solution or clicking the wrong page while shopping online |
Reinforcement learning resolves all three mismatches through three shifts ([slides, pp. 8–12](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=8)):
1. **Direct task optimization:** The task criterion is encoded directly in a scalar reward function rather than approximated by next-token likelihood.
2. **On-policy data generation:** The model generates its own candidate trajectories (for example, `2 + 3 = 23` vs. `2 + 3 = 5`), so it experiences its own mistakes during training.
3. **Any evaluable trajectory provides signal:** As long as a reward function or verifier can score a complete trajectory, both successes and failures drive gradient updates.
## Formalizing interaction as an MDP
Lecture 15 models sequential interaction as a **Markov Decision Process (MDP)** $\mathcal{M} = (\mathcal{S}, \mathcal{A}, E, R)$ ([slides, pp. 14–20](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=14)):
- **State space $\mathcal{S}$ and observation boundary ([slide 23](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=23)):** Formally, the environment maintains a private internal state $s_t^E$ and emits an observation $o_t$ visible to the agent; before selecting $a_t$, the agent constructs its working state $s_t = f(o_0, a_0, r_1, \dots, a_{t-1}, r_t, o_t)$ (or simply $s_t = o_t$ in Markov settings; *note: Slide 23 prints $a_t, o_t$ inside $f(\dots)$*).
- **Action space $\mathcal{A}$:** Discrete or continuous choices available to the agent (Atari buttons, joint torques, CartPole `LEFT`/`RIGHT`, or vocabulary tokens $y_t \in \mathcal{V}$).
- **Environment transition kernel $E(s_{t+1} \mid s_t, a_t)$:** Distribution over next states given the current state and action.
- **Reward function $R(s_t, a_t) \to \mathbb{R}$:** Scalar feedback emitted at each transition ($r_{t+1} = R(s_t, a_t)$).
- **Policy $\pi_\theta(a_t \mid s_t)$:** Parameterized conditional distribution over actions given agent state.
Using consistent 0-based indexing matching [slide 20](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=20) and [slide 31](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=31), rolling out policy $\pi_\theta$ from an initial state $s_0 \sim E$ across $T$ actions ($t = 0, \dots, T-1$) until terminal state $s_T$ produces an **episode** (or **trajectory**) $\tau_{0:T} = (s_0, a_0, r_1, s_1, \dots, a_{T-1}, r_T, s_T)$ drawn from trajectory distribution $d_{\tau_\pi}$. The undiscounted episodic objective is to maximize expected return:
$$
J(\theta) = \mathbb{E}_{\tau \sim d_{\tau_{\pi_\theta}}}\!\left[\sum_{t=1}^{T} r_t\right],
$$
where the **value function** $v^\pi(s_t) = \mathbb{E}\!\left[\sum_{t'=t+1}^{T} r_{t'} \;\middle|\; s_t\right]$ measures expected future return starting from state $s_t$ ([slide 25](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=25)). Across the lecture and course notebooks, the exact same MDP formalism grounds three distinct domains (written with 0-based transitions $(s_t, a_t) \to (s_{t+1}, r_{t+1})$ for $t = 0, \dots, T-1$):
| Domain | State $s_t$ | Action $a_t$ | Transition $E(s_{t+1} \mid s_t, a_t)$ | Reward $r_{t+1}$ |
|---|---|---|---|---|
| **Pong** ([slides, pp. 21–22](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=21)) | Game screen frames | Paddle move (`up`, `down`, `stay`) | Game physics updates screen | $0$ for $t < T-1$; $+1$ win or $-1$ loss at $r_T$ ($s_T$) |
| **LLM Math** ([slides, pp. 18, 24](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=18)) | Prompt + prefix $(x, y_{<t})$ | Next token $y_t \in \mathcal{V}$ | Deterministic append $(x, y_{<t} \circ y_t)$ | $0$ for $t < T-1$; $r(x, y_{0:T-1}) \in \{0, 1\}$ verifier at $r_T$ |
| **CartPole-v1** ([`pg.ipynb`](https://github.com/cmu-l3/anlp-fall2025-code/blob/main/15_rl/pg.ipynb)) | $(x, \dot{x}, \theta_{\text{pole}}, \dot{\theta}_{\text{pole}}) \in \mathbb{R}^4$ | `0` (`LEFT`) or `1` (`RIGHT`) | Rigid-body cart-pole dynamics | $+1.0$ per upright step (max `500` steps) |
## Deriving REINFORCE: why environment dynamics drop out
Because trajectories depend on $\theta$ through the sampling distribution $p(\tau \mid \theta)$—and both the environment transition $E$ and reward $R(\tau)$ are typically non-differentiable or unknown—we cannot backpropagate $\nabla_\theta R(\tau)$ directly ([slide 28](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=28)). Instead, Williams (1992) **REINFORCE** uses the **score-function gradient estimator** (log-derivative identity $\nabla_\theta p_\theta(x) = p_\theta(x)\nabla_\theta \log p_\theta(x)$ on [slide 29](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=29)):
$$
\nabla_\theta \mathbb{E}_{x \sim p_\theta(x)}[f(x)]
= \sum_x \nabla_\theta p_\theta(x)\, f(x)
= \sum_x p_\theta(x)\, \nabla_\theta \log p_\theta(x)\, f(x)
= \mathbb{E}_{x \sim p_\theta(x)}\!\left[f(x)\,\nabla_\theta \log p_\theta(x)\right].
$$
For a single draw $\hat{x} \sim p_\theta$, $\hat{g}_{\text{REINFORCE}} = f(\hat{x})\,\nabla_\theta \log p_\theta(\hat{x})$ is an unbiased Monte Carlo gradient estimator (assuming $p_\theta$ is differentiable with respect to $\theta$ and differentiation can interchange with the sum or integral).
### Factorizing the trajectory gradient (Appendix Slides 48–50)
Applying the score-function estimator to the trajectory distribution $p(\tau \mid \theta)$ under episodic return $R(\tau) = \sum_{k=1}^T r_k$ ([slides, pp. 48–49](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=48)), using 0-based action indices $t = 0, \dots, T-1$ to match $\tau_{0:T}$ and Slide 31 *(note: Slides 30 and 49–50 shift to 1-based $t=1,\dots,T$ indexing in their sums and products)*:
$$
p(\tau \mid \theta) = E(s_0)\prod_{t=0}^{T-1}\Big[\pi_\theta(a_t \mid s_t)\, E(s_{t+1} \mid s_t, a_t)\Big].
$$
Taking logarithms turns the product into a sum, and differentiating with respect to $\theta$ **eliminates both the initial state distribution $E(s_0)$ and every environment transition term $E(s_{t+1} \mid s_t, a_t)$**:
$$
\nabla_\theta \log p(\tau \mid \theta)
= \nabla_\theta \log E(s_0) + \sum_{t=0}^{T-1} \nabla_\theta \log \pi_\theta(a_t \mid s_t) + \sum_{t=0}^{T-1} \nabla_\theta \log E(s_{t+1} \mid s_t, a_t)
= \sum_{t=0}^{T-1} \nabla_\theta \log \pi_\theta(a_t \mid s_t).
$$
Substituting into the score-function expectation gives $\nabla_\theta \mathbb{E}_\tau[R(\tau)] = \mathbb{E}_\tau\!\left[R(\tau)\sum_{t=0}^{T-1} \nabla_\theta \log \pi_\theta(a_t \mid s_t)\right]$. Next, applying **causality** ([slide 50](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=50)): an action $a_t$ taken at or after step $k$ ($t \ge k$) cannot influence an earlier reward $r_k$ (which depends only on steps $0, \dots, k-1$), so $\mathbb{E}_\tau[r_k \nabla_\theta \log \pi_\theta(a_t \mid s_t)] = 0$ for all $t \ge k$. Summing over $k = 1, \dots, T$ and collecting coefficients of $\nabla_\theta \log \pi_\theta(a_t \mid s_t)$ replaces total trajectory return $R(\tau)$ with the **reward-to-go** $R_t$ *(note: Slide 50 writes $\sum_{t'=t}^T r_t$ as a minor subscript typo for $r_{t'}$, drops $\nabla_\theta$ inside its middle equation, and omits $\mathbb{E}_\tau$ in its final display line)*:
$$
\nabla_\theta \mathbb{E}_\tau[r_k] = \mathbb{E}_\tau\!\left[r_k \sum_{t=0}^{k-1} \nabla_\theta \log \pi_\theta(a_t \mid s_t)\right]
\;\implies\;
\nabla_\theta \mathbb{E}_{\tau \sim \pi_\theta}[R(\tau)]
= \mathbb{E}_\tau\!\left[\sum_{t=0}^{T-1} R_t\,\nabla_\theta \log \pi_\theta(a_t \mid s_t)\right], \quad R_t = \sum_{k=t+1}^{T} r_k.
$$
In PyTorch ([slide 31](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=31)), we implement gradient ascent on $J(\theta)$ by minimizing the surrogate **policy-gradient loss** over sampled trajectories (where $R_t$ is treated as a constant weight detached from $\theta$):
$$
\mathcal{L}_{\text{PG}}(\theta) = -\sum_{t=0}^{T-1} R_t \log \pi_\theta(a_t \mid s_t), \qquad \nabla_\theta \mathcal{L}_{\text{PG}}(\theta) = -\sum_{t=0}^{T-1} R_t \nabla_\theta \log \pi_\theta(a_t \mid s_t).
$$
When $R_t > 0$, gradient descent on $\mathcal{L}_{\text{PG}}$ weights $\nabla_\theta \log \pi_\theta(a_t \mid s_t)$ positively; when $R_t = 0$, that step contributes zero gradient; when $R_t < 0$, it weights $\nabla_\theta \log \pi_\theta(a_t \mid s_t)$ negatively ([slide 30](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=30); note that in a multi-step sum, the combined parameter update can still shift any individual action probability in either direction).
{fig-alt="Three-stage horizontal architecture diagram titled Policy Gradients Differentiate Action Log-Probs, Not Environment Transitions. Stage 1 MDP Interaction Loop shows Agent/Policy pi_theta(a_t | s_t) sending action a_t to Environment E(s_{t+1} | s_t, a_t), receiving s_{t+1} and r_{t+1}, and defining trajectory probability p(tau | theta) = E(s0) prod_{t=0}^{T-1} [pi_theta(a_t|s_t) E(s_{t+1}|s_t,a_t)]. Stage 2 Score-Function Cancellation shows grad log p(tau | theta) = sum_{t=0}^{T-1} grad log pi_theta(a_t|s_t) + 0 because grad log E = 0, followed by causality reduction to g_hat_t = A_hat_t grad log pi_theta(a_t|s_t). Stage 3 Loss and Two Groundings shows surrogate objective L_PG and PPO gain clipping, CartPole-v1 (s_t in R^4, gamma=0.99, single saved runs: 1,141 episodes for PG vs 572 episodes for PG+VF), and LLM Math RLVR (s_t=(x,y_<t), a_t=y_t, terminal 0/1 verifier), connected by a dashed bottom feedback update loop."}
## Stabilizing learning: discounting, baselines, and advantages
Vanilla REINFORCE suffers from high variance because single-trajectory returns $R_t$ conflate the effect of action $a_t$ with all subsequent stochastic rewards and transitions ([slides, pp. 35–36](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=35)). Lecture 15 groups stabilization into two strategies: **re-weighting the gradients** (discounting, baselines, advantages) and **controlling step size** (PPO).
### Strategy 1A: Temporal discounting ([slide 37](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=37))
When rewards arrive many steps after an action, multiplying a reward by $\gamma \in (0, 1]$ per step down-weights distant outcomes under the 0-based discounted return-to-go:
$$
R_t = \sum_{t'=t+1}^{T} \gamma^{t' - t - 1} r_{t'}.
$$
*(Note on objective matching: When the notebooks multiply log-probs by discounted $R_t$ without an outer $\gamma^t$ factor—i.e., using discounted gradient weighting rather than the exact gradient of $J_\gamma(\theta) = \mathbb{E}[\sum_{t=0}^{T-1}\gamma^t r_{t+1}]$, whose episodic policy gradient weights step $t$ by $\gamma^t R_t$—they trade exact discounted-objective fidelity for reduced variance on distant rewards.)*
In Slide 37's 6-action example ($a_1, \dots, a_6$) where only the final transition delivers $+1$ and $\gamma = 0.9$, the exact weights $\gamma^{6-t}$ are `[0.59049, 0.6561, 0.729, 0.81, 0.9, 1.0]` (printed to two decimals on the slide as `0.59, 0.66, 0.73, 0.81, 0.9, 1`). Author evaluations of that same terminal-only 6-step example show that shorter discount factors ($\gamma = 0.5$) decay early credit rapidly to `0.03125` at $a_1$, whereas `CartPole-v1`'s $\gamma = 0.99$ leaves $a_1$ at `0.951` (though CartPole itself pays `+1` at every step, not just at termination).
### Strategy 1B: State baselines and unbiased centering ([slides, pp. 38–39](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=38))
When rewards in a task are non-negative (such as Slide 38's `0` to `1` scores, or `+1` per CartPole step), vanilla REINFORCE gives every positive-return action a non-negative score-gradient weight—relying solely on better actions receiving larger positive weights than worse ones. Subtracting a state-dependent **baseline** $b(s_t)$ centers the gradient weight:
$$
\hat{g}_t = \big(R_t - b(s_t)\big)\,\nabla_\theta \log \pi_\theta(a_t \mid s_t).
$$
Why does subtracting $b(s_t)$ keep the estimator unbiased? Because $b(s_t)$ does not depend on action $a_t$, its expected contribution given $s_t$ is identically zero:
$$
\mathbb{E}_{a_t \sim \pi_\theta(\cdot \mid s_t)}\!\left[b(s_t)\,\nabla_\theta \log \pi_\theta(a_t \mid s_t)\right]
= b(s_t) \sum_{a_t} \pi_\theta(a_t \mid s_t)\,\frac{\nabla_\theta \pi_\theta(a_t \mid s_t)}{\pi_\theta(a_t \mid s_t)}
= b(s_t)\,\nabla_\theta \underbrace{\sum_{a_t}\pi_\theta(a_t \mid s_t)}_{= 1}
= 0.
$$
Although the expectation is unchanged for *any* state-only baseline $b(s_t)$, variance reduction depends on the choice of $b(s_t)$ (a poorly matched baseline can even increase variance). Choosing $b(s_t) \approx v^\pi(s_t)$ ([slide 39](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=39)) centers updates around expected return from $s_t$. On Slide 38's prompt table *(note: the slide prints `"B - R"` as the column header, whereas the signed green/red entries compute $R - b(s)$)*:
| Prompt ([slide 38](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=38)) | Reward $R$ | Baseline $b(s)$ | Centered advantage $R - b(s)$ | Gradient effect |
|---|---|---|---|---|
| `"Summarize this paper: ..."` (good) | `0.80` | `0.75` | `+0.05` | Slightly reinforce (already an easy prompt) |
| `"Summarize this paper: ..."` (poor) | `0.30` | `0.75` | `-0.45` | Strongly penalize (worse than expected) |
| `"Prove this theorem: ..."` (solid) | `0.30` | `0.10` | `+0.20` | Reinforce (outperforms a hard prompt) |
Without a baseline, both the poor summary and the solid proof carry identical weight `+0.30`. With $b(s_t) \approx v^\pi(s_t)$, the poor summary flips sign to `-0.45`.
### Strategy 1C: Advantage estimators ([slide 40](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=40))
Writing the general gradient estimator as $\hat{g}_t = \hat{A}_t\,\nabla_\theta \log \pi_\theta(a_t \mid s_t)$, three common advantage estimators trade off bias and variance:
1. **Monte Carlo baseline advantage:** $\hat{A}_t = R_t - v(s_t)$ (unbiased when $v$ depends only on $s_t$, higher variance across long episodes).
2. **One-step Temporal Difference (TD) residual** (Sutton & Barto, 1998): $\hat{A}_t = \delta_t^v = r_t + \gamma v(s_{t+1}) - v(s_t)$ (low variance, biased if $v \neq v^\pi$; under the 0-based notation of Slide 31 where transitioning from $(s_t, a_t)$ emits $r_{t+1}$, write $r_{t+1}$ in place of $r_t$).
3. **Generalized Advantage Estimation (GAE)** (Schulman et al., 2015): $\hat{A}_t = \sum_{l \ge 0} (\gamma \alpha)^l \delta_{t+l}^v$ *(printed with parameter $\alpha$ on Slide 40, corresponding to $\lambda \in [0, 1]$ in Schulman et al. 2015)*, which interpolates between one-step TD ($\alpha = 0$) and Monte Carlo baseline ($\alpha = 1$, provided terminal states satisfy $v(s_T) = 0$ so the finite-episode sum telescopes to $R_t - v(s_t)$).
## Controlling step size: PPO surrogate clipping
Even with advantages, a noisy batch can push $\pi_\theta$ too far from the policy $\pi_{\theta_{\text{old}}}$ that generated the rollouts, collapsing performance on subsequent iterations ([slide 41](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf#page=41)). **Proximal Policy Optimization (PPO)** (Schulman et al., 2017) dampens destructive updates by clipping one branch of the per-sample surrogate objective using the probability ratio:
$$
\text{ratio}(x, y) = \frac{p_\theta(y \mid x)}{p_{\theta_{\text{old}}}(y \mid x)},
\qquad
L_{\text{PPO}}(\theta) = \min\!\Big(\text{ratio}(x, y)\,A(x, y),\; \operatorname{clip}\!\big(\text{ratio}(x, y),\, 1-\epsilon,\, 1+\epsilon\big)\,A(x, y)\Big).
$$
Crucially, PPO clipping removes the optimization **incentive** for further movement in the favorable direction outside $[1-\epsilon, 1+\epsilon]$—it does **not** impose a hard constraint preventing $\text{ratio}$ from leaving $[1-\epsilon, 1+\epsilon]$ across updates. Note the asymmetric behavior shown in Panel B below (evaluated by the author on Slide 41's formula at $\epsilon = 0.2$ and $A \in \{+1, -1\}$):
- **When $A(x, y) > 0$:** Increasing the action probability ($\text{ratio} > 1$) raises the surrogate objective only up to $\text{ratio} = 1 + \epsilon = 1.2$; beyond $1.2$, $\operatorname{clip}$ holds $L_{\text{PPO}}$ flat at its maximum $+1.2 A$, removing any extra reward for over-concentrating probability mass in one step.
- **When $A(x, y) < 0$:** Decreasing the action probability ($\text{ratio} < 1$) gives $L_{\text{PPO}} = -\max(\text{ratio}, 0.8)|A|$, so the objective stays **flat at $-0.8|A|$** (its maximum value for $A < 0$) whenever $\text{ratio} \le 0.8$, removing any incentive to push $\text{ratio}$ further below $0.8$. Meanwhile, *increasing* a negative-advantage action's probability ($\text{ratio} > 1.2$) remains unclipped and linearly penalized ($\min$ picks $\text{ratio}\cdot A < -1.2|A|$).
{fig-alt="Two-panel chart titled Discounting Weights Future Rewards; PPO Clips Surrogate Gain. Panel A has a zero baseline and plots discounted return R_t across actions a1 through a6 for a +1 reward at a6: gamma=0.99 (green dashed, author evaluation) stays near 0.95 to 1.00; gamma=0.90 (blue solid, Slide 37) rises across 0.59, 0.66, 0.73, 0.81, 0.90, 1.00; gamma=0.50 (terracotta dotted, author evaluation) rises from 0.03 to 1.00. Panel B is an author evaluation of PPO surrogate objective L_PPO against probability ratio r from 0.4 to 1.6 with shaded clip band [0.8, 1.2] at epsilon=0.2: the A=+1 blue curve rises linearly until r=1.2 then stays flat at +1.20, while the A=-1 terracotta curve stays flat at -0.80 (its maximum for A=-1) for r<=0.8 and decreases linearly for r>0.8."}
## Empirical verification on CartPole (`pg.ipynb` vs. `pg_vf.ipynb`)
The two official Fall 2025 course notebooks ([`pg.ipynb`](https://github.com/cmu-l3/anlp-fall2025-code/blob/main/15_rl/pg.ipynb) and [`pg_vf.ipynb`](https://github.com/cmu-l3/anlp-fall2025-code/blob/main/15_rl/pg_vf.ipynb)) provide single saved runs of Vanilla REINFORCE and REINFORCE with a learned value-function baseline on `CartPole-v1` (`discount_gamma = 0.99`, `Adam lr = 1e-3`, running reward EMA $\bar{R}_{\text{new}} = 0.05\,R_{\text{ep}} + 0.95\,\bar{R}_{\text{old}}$ initialized at `10`, solved threshold `475.0`):
- **Policy network $\pi_\theta(a \mid s)$:** `Linear(4, 128) -> ReLU -> Linear(128, 2) -> Softmax(dim=1)` mapping `[cart pos, cart vel, pole angle, pole angular vel]` to probabilities over `{LEFT, RIGHT}`.
- **Value network $v_\phi(s)$ (`pg_vf.ipynb` only):** `Linear(4, 128) -> ReLU -> Linear(128, 1)`, trained with a separate `Adam` optimizer (`lr = 1e-2`) on MSE loss $\mathcal{L}_{\text{VF}} = \text{MSE}(v_\phi(s_t), R_t)$.
- **Important gradient-detachment detail:** In `pg_vf.ipynb`, `adv` is copied as a detached tensor (`adv[i] -= v.item()`) so `policy_loss = -(log_probs * adv).sum()` updates only $\theta$, while `vf_loss` updates only $\phi$.
- **Slide vs. notebook distinction:** Note that Slides 32–34 show a different CartPole implementation (`Dropout(p=0.6)` on Slide 32, standardized episode returns `(R - R.mean()) / (R.std() + eps)` on Slide 33, and a training plot ending near ~360 episodes on Slide 34), whereas the saved Fall 2025 `pg.ipynb` notebook omits dropout and uses unstandardized discounted returns.
- **RNG & baseline comparison caveat:** Each notebook presents a **single saved run** without direct gradient-variance measurements or matched random-number-generator state across runs (both call `env.reset(seed=42)` and `torch.manual_seed(42)` in Cell 3, but `pg.ipynb` subsequently initializes a demonstration `Policy()` and calls `env.reset()` before creating its training `Policy()`, whereas `pg_vf.ipynb` initializes training `Policy()` and `VF()` directly, and neither re-seeds `env.reset()` inside the episode loop).
Reading the saved execution outputs in both notebooks shows how the two single runs progressed (with `pg_vf.ipynb`'s final solve index `571` reconstructed from the `Ep 570` checkpoint `474.47`, the final `500`-step solve message `475.750287` since $0.05\times 500 + 0.95\times 474.473986 = 475.750287$, and the saved matplotlib plot's x-axis):
| Saved single run | Policy & VF hyperparameters | Last 10-ep checkpoint | Episode solved (`> 475.0`) | Final running reward |
|---|---|---|---|---|
| **Vanilla REINFORCE (`pg.ipynb`)** | $\pi_\theta$ `lr = 1e-3`, no baseline ($\gamma = 0.99$) | `Ep 1140`: last `500.00`, avg `475.14` | `i_episode = 1140` (`1,141` episodes) | `475.14` (`500` steps) |
| **REINFORCE + Value Baseline (`pg_vf.ipynb`)** | $\pi_\theta$ `lr = 1e-3`, $v_\phi$ `lr = 1e-2` ($\gamma = 0.99$) | `Ep 570`: last `500.00`, avg `474.47` | `i_episode = 571` (`572` episodes, inferred) | `475.75` (`500` steps) |
In these saved runs, the value-baseline run reached the solved threshold in `572` episodes compared to `1,141` for Vanilla REINFORCE (`49.9%` fewer episodes) and avoided the sharp mid-training EMA drop visible in the vanilla run (falling from `452.13` at Episode `850` down to `164.27` at Episode `940`).
## Bridging fundamentals to LLM post-training
Slides 44–46 preview how these exact building blocks transfer directly to [Lecture 16: Reinforcement Learning for LLMs](cmu-advanced-nlp-lecture-16-reinforcement-learning-for-llms.qmd):
- **RLHF** (Ziegler et al., 2019; Stiennon et al., 2020; Ouyang et al., 2022): Slides 44–45 frame RLHF using the same policy-gradient + preference-reward + PPO loop where state $s_t = (x, y_{<t})$ and action $a_t = y_t$ (with the KL anchor to the reference policy added in those papers and covered in Lecture 16).
- **RLVR / GRPO** (DeepSeek-AI, 2025): Slide 46 introduces RL with verifiable rewards as a 1-step MDP with a `0/1` rule-based reward and PPO using an output-average baseline (`"GRPO"`; DeepSeek-R1 Eq. 3 further normalizes that centered reward by the group standard deviation, and token-level MDPs can also use terminal-only rewards).
## Practical takeaways
*(Author synthesis across Lecture 15 slides and course notebooks:)*
1. **Use policy gradients when task criteria or trajectories are non-differentiable.** Factoring $p(\tau \mid \theta)$ removes $\nabla_\theta \log E$, letting a model learn from unit tests, math verifiers, or discrete simulator rewards.
2. **Center returns with a well-chosen baseline.** Subtracting any state-only baseline $b(s_t)$ keeps the score-function gradient unbiased, and approximating $v^\pi(s_t)$ aligns update signs with relative quality—consistent with the saved CartPole runs solving in `572` vs. `1,141` episodes.
3. **Separate advantage estimation from surrogate clipping.** Discounting, baselines, and GAE shape credit assignment and reduce variance; PPO's clipped surrogate removes the optimization incentive for oversized ratio moves between rollout batches.
## Primary sources and verification
- **Course slides:** Sean Welleck, *CS11-711 Advanced NLP (Fall 2025) — Lecture 15: Reinforcement Learning*, 50 pp. ([PDF](https://cmu-l3.github.io/anlp-fall2025/static_files/anlp-f2025-15-rl.pdf)).
- **Instructor's lecture recording:** Sean Welleck, *CMU Advanced NLP Fall 2025 (15): Reinforcement Learning Fundamentals* ([YouTube](https://www.youtube.com/watch?v=CmyrQAV-vdY), 68m10s, posted Oct 21, 2025).
- **Course code:** [`15_rl`](https://github.com/cmu-l3/anlp-fall2025-code/tree/main/15_rl) (`pg.ipynb` and `pg_vf.ipynb`).
- **Main readings on syllabus:** Andrej Karpathy (2016), [*Deep Reinforcement Learning: Pong from Pixels*](https://karpathy.github.io/2016/05/31/rl/); OpenAI [*Spinning Up in Deep RL*](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html).
- **Additional references on syllabus:** Schulman et al. (2015), *High-Dimensional Continuous Control Using Generalized Advantage Estimation* ([arXiv:1506.02438](https://arxiv.org/abs/1506.02438)); Schulman et al. (2017), *Proximal Policy Optimization Algorithms* ([arXiv:1707.06347](https://arxiv.org/abs/1707.06347)).
- **Figure generation & numerical verification:** [`create_figures.py`](anlp15-assets/create_figures.py) and [`manifest.json`](anlp15-assets/manifest.json).