Lecture 16 · Reinforcement Learning I: Fundamentals

Advanced Natural Language Processing · Lecture 16。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 16 (03/12), “Reinforcement Learning I: Fundamentals”; slides anlp-s2026-16-rl.pdf; course code 16_rl/pg.ipynb and 16_rl/pg_vf.ipynb. Readings: A. Karpathy, Deep Reinforcement Learning: Pong from Pixels (blog, 2016); OpenAI, Spinning Up in Deep RL (Parts 1 and 3, Vanilla Policy Gradient, PPO). Additional: J. Schulman et al., Proximal Policy Optimization Algorithms (2017); J. Schulman et al., High-Dimensional Continuous Control Using Generalized Advantage Estimation (ICLR 2016). The slides draw on J. Schulman’s 2016 tutorial and D. Silver’s 2015 lectures. Sources: the public slides and notebooks, the readings, and the papers cited in each section. Every number labelled “measured” comes from code/lecture16/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, one CPU thread). Code: code/lecture16/ — four demos, each under two minutes. Reading time: ~90 minutes for the prose; ~20 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Name the three problems of supervised fine-tuning that reinforcement learning addresses: task mismatch, data mismatch, exposure bias.
  2. Formalize a problem as a Markov decision process: states, actions, transitions, rewards, policies, episodes, returns. Distinguish the environment’s state, the agent’s observation and the agent’s own state.
  3. Derive the policy gradient from the score-function identity and turn it into the REINFORCE algorithm.
  4. Explain why policy-gradient estimates are noisy, and how reward-to-go, discounting, baselines, advantages, TD residuals and GAE trade variance against bias.
  5. Explain why large updates are dangerous, and how PPO’s clipped objective lets an agent reuse a batch of experience safely.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 1, demo 05: a policy as a softmax over actions, learned from rewards (REINFORCE in miniature).
    • Lecture 12: the score-function estimator vs the reparameterization trick.
    • Lecture 8: supervised fine-tuning (SFT).
    • Lecture 14: seeds and error bars.
  • Scope: policy-gradient methods, the family used for language models.
  • Not in scope:
    • Value-based methods (Q-learning, DQN) and model-based RL, beyond a paragraph.
    • Off-policy actor-critic methods.
    • Exploration bonuses.
    • Applications to LMs: RLHF, RLVR and GRPO are Lecture 17; agents are Lecture 18.

0.3 Section → code map

SectionIdeaDemo in code/lecture16/
§2.1–2.3an MDP that reads text; sparse rewards; imitation vs the optimum01_mdp.py Parts A, C
§2.4state vs observation, and memory01_mdp.py Part D
§2.5returns, discounting, value functions01_mdp.py Part B
§3the policy gradient: 13 estimators vs the exact gradient02_policy_gradient.py Part A
§3.4, §4.5the course notebooks on CartPole, 8 seeds03_cartpole.py
§4.3baselines and reward offsets02_policy_gradient.py Parts B, C
§5reusing a batch; PPO’s clip04_ppo.py

0.4 Notation

SymbolMeaning
sts_t, ata_t, rtr_tstate, action, reward at step tt; an episode τ=(s0,a0,r1,s1,… )\tau = (s_0, a_0, r_1, s_1, \dots)
πθ(a∣s)\pi_\theta(a \mid s)the policy, with parameters θ\theta
E(st+1∣st,at)E(s_{t+1} \mid s_t, a_t), R(s,a)R(s, a)the environment’s transitions and reward function (the slides’ notation)
R(τ)=∑trtR(\tau) = \sum_t r_tthe return of an episode; Rt=∑t′≥tγt′−trt′R_t = \sum_{t' \ge t} \gamma^{t'-t} r_{t'} the reward-to-go from step tt
J(θ)=Eτ∼πθ[R(τ)]J(\theta) = \mathbb E_{\tau \sim \pi_\theta}[R(\tau)]the objective: expected return
Vπ(s)V^\pi(s), Qπ(s,a)Q^\pi(s, a), Aπ=Qπ−VπA^\pi = Q^\pi - V^\pivalue, action value, advantage
γ\gamma, λ\lambdadiscount factor; GAE’s mixing parameter
ρ=πθ/πold\rho = \pi_\theta / \pi_{\text{old}}, ϵ\epsilonPPO’s probability ratio and clip range

1. Why reinforcement learning?

1.1 Three problems with imitation

Supervised fine-tuning (Lecture 8) maximizes the likelihood of reference outputs:

L(θ)=−∑tlog⁡pθ(yt∣y<t,x).\mathcal L(\theta) = -\sum_t \log p_\theta(y_t \mid y_{<t}, x).

It teaches the model to imitate, and the slides name three ways that falls short.

  • Task mismatch. We want helpful, non-offensive, correct responses and code that passes the tests. Likelihood rewards probable text. These are different targets: a probable answer to a math problem can be wrong.
  • Data mismatch. The data contains things we don’t want (toxic comments, buggy code) and lacks things we do (worked chains of thought, helpful responses to every possible prompt).
  • Exposure bias. During training the model always sees a correct prefix (teacher forcing, Lecture 3). At test time it conditions on its own outputs. It has never practiced recovering from its own mistakes, such as a wrong step in a proof or a wrong click while shopping online.

1.2 The RL loop

Reinforcement learning replaces “imitate this output” with “generate, get a score, update”:

prompt ──► model ──► output ──► reward ──► update the model
            ▲                                   │
            └───────────────────────────────────┘

The slides list three differences from supervised learning:

  1. The task criterion is optimized directly, through the reward (“is 2 + 3 = 5?”, “is this response offensive?”).
  2. The data is generated by the model. The reward says how to use each sample: push up the good ones, push down the bad ones.
  3. The model can learn from any trajectory whose reward we can evaluate, including its own mistakes, which addresses exposure bias.

The price: the model must discover good outputs on its own, and the learning signal is a single number per attempt. This lecture builds the machinery on two small environments. Lecture 17 applies it to language models.


2. The reinforcement-learning problem

2.1 Agents and environments

An agent interacts with an environment. At each step the agent receives an observation and a scalar reward and executes an action; the environment receives the action and emits the next observation and reward. The agent’s goal is to maximize total reward. RL is at once a problem, a class of solutions, and the field that studies both.

The slides’ examples:

agentobservationactionreward
Atarithe playerthe screenbutton pressesthe game score
roboticsthe robotcamera images, joint anglesjoint torquesbalance, reaching a target
text generationthe language modelthe text generated so farthe next tokenis the final answer correct?

2.2 Markov decision processes

The formalism is a Markov decision process (S,A,E,R)(S, A, E, R):

  • SS is the state space;
  • AA is the action space;
  • E(st+1∣st,at)E(s_{t+1} \mid s_t, a_t) gives the environment’s transitions;
  • R(st,at)R(s_t, a_t) is the reward.

The agent acts with a policy π(at∣st)\pi(a_t \mid s_t). An episode (trajectory) runs from s0∼Es_0 \sim E until a terminal state:

s0, a0∼π(⋅∣s0), s1∼E(⋅∣s0,a0), r1=R(s0,a0), a1∼π(⋅∣s1), …, sT.s_0,\ a_0 \sim \pi(\cdot \mid s_0),\ s_1 \sim E(\cdot \mid s_0, a_0),\ r_1 = R(s_0, a_0),\ a_1 \sim \pi(\cdot \mid s_1),\ \dots,\ s_T .

The goal is a policy that maximizes the expected return J=Eτ∼π[∑trt]J = \mathbb E_{\tau \sim \pi}\big[\sum_t r_t\big].

“Markov” means the next state depends only on the current state and action, not on how we got there.

Pong (Karpathy’s blog) is the slides’ running example:

  • the reward is 0 at every step until the end, then +1 for a win and −1 for a loss;
  • a single number must teach the agent which of hundreds of paddle moves were good. This is the credit-assignment problem.

Math problem solving is the slides’ language example:

  • state: the prompt plus the tokens so far, st=(x,y<t)s_t = (x, y_{<t});
  • action: the next token;
  • transition: append it;
  • reward: 1 at the end if the answer is correct, 0 otherwise.

The policy is the language model itself.

2.3 Key Quest: an MDP that reads text

The demos use Key Quest (quest_world.py), small enough that everything can be computed exactly. The house is six rooms in a 2×3 grid; the cellar connects only to the library. The agent starts in the hall, a key lies in the cellar, and a locked door is in the garden. The agent reads a description and answers with one of six commands.

An expert episode (demo 01):

t=0  You are in the hall. Exits: north, east, west. Your hands are empty.   ->  go west
t=1  You are in the library. Exits: north, east. Your hands are empty.      ->  go north
t=2  You are in the cellar. Exits: south. There is a key here. ...          ->  take key
t=3  You are in the cellar. Exits: south. You carry a key.                  ->  go south
t=4  You are in the library. Exits: north, east. You carry a key.           ->  go east
t=5  You are in the hall. Exits: north, east, west. You carry a key.        ->  go east
t=6  You are in the garden. ... There is a locked door here. You carry a key. -> open door   reward +1

The rules:

  • moves succeed with probability 0.9 (a slippery floor);
  • the only reward is +1 for opening the door, so it is sparse and arrives at the end, like “is the final answer correct”;
  • episodes are cut after 10 actions, and the shortest solution takes 7.

Because the transition probabilities are known, backward induction computes the exact value of any policy: Vt(s)=∑aπ(a∣s) [R(s,a)+∑s′E(s′∣s,a) Vt+1(s′)]V_t(s) = \sum_a \pi(a \mid s)\,[R(s, a) + \sum_{s'} E(s' \mid s, a)\, V_{t+1}(s')]. Autograd through that computation gives the exact policy gradient, against which every estimator in this lecture is measured.

Measured (demo 01, Part C):

policyJJ = P(door opened within 10 actions)
uniformly random0.0001 (exactly 0.000090)
noisy expert (a random action half of the time)0.1734
behavior cloning of 100 of its episodes (“SFT”)0.2014
expert (dynamic programming) = the optimum0.9950
  • A random agent almost never sees a reward. It succeeds once per 11,122 episodes (18 times in 200,000 sampled). An RL algorithm that starts from random behavior has nothing to learn from. This is the exploration problem, and it is why RL for language models starts from a pretrained or fine-tuned model, never from scratch.
  • Imitation is capped by its data. Behavior cloning, SFT in miniature, reproduces its noisy demonstrator (0.20 vs 0.17), not the expert. Going beyond the demonstrations needs a reward.
  • The optimum here was computed by dynamic programming, which needs the transition probabilities. That is a model-based shortcut; an RL agent normally learns from sampled episodes only.

2.4 States, observations, and the agent’s state

The slides distinguish three things:

  • the environment state stEs_t^E: the environment’s private representation;
  • the observation oto_t: what the agent sees;
  • the agent state sts_t: whatever information the agent uses to pick its next action, some function f(o0,a0,r1,…,ot)f(o_0, a_0, r_1, \dots, o_t) of its history. The simplest choice is the current observation.

Demo 01 (Part D) hides the inventory from the text:

with inventory : You are in the library. Exits: north, east. You carry a key.
without        : You are in the library. Exits: north, east.

In the library and the hall, the agent must go west the first time and east the second, and without the inventory the two visits read the same. The best possible agents, found by exact gradient ascent:

agentdistinct agent statesbest JJ
sees the full state (inventory in the text)130.9950
sees only the current text, no inventory80.1144
current text + memory of having taken the key130.9950

When the observation does not determine the state, an agent that reacts only to the current observation can be crippled. Remembering one bit of its own history restores the optimum. For a language-model agent the agent state is the whole context window: everything it has read and written so far. That is one reason LM agents work (Lecture 18), and why what goes into the context matters so much.

2.5 Returns, discounting and value functions

The return is the sum of rewards. Often rewards come late, and we discount them by how far in the future they are: Rt=∑t′≥tγt′−trt′R_t = \sum_{t' \ge t} \gamma^{t' - t} r_{t'}. The slides’ example has six actions, +1 after the last, and γ=0.9\gamma = 0.9. The discounted return seen after each action is (demo 01, Part B):

actiona1a2a3a4a5a6
discounted return0.590.660.730.810.901.00

Earlier actions get less credit for a delayed reward. Discounting also encodes “sooner is better”, and keeps returns finite in endless tasks.

The value function Vπ(s)=Eπ[Rt∣st=s]V^\pi(s) = \mathbb E_\pi[R_t \mid s_t = s] is the expected return from a state. It satisfies the Bellman equation, V(s)=∑aπ(a∣s) [R(s,a)+γ∑s′E(s′∣s,a) V(s′)]V(s) = \sum_a \pi(a \mid s)\,[R(s, a) + \gamma \sum_{s'} E(s' \mid s, a)\, V(s')].

Measured for the SFT policy (demo 01, Part B), along the expert’s route:

state (time)hall, no key (0)library (1)cellar (2)cellar, key (3)library, key (4)hall, key (5)garden, key (6)
exact Vt(s)V_t(s)0.20140.27850.38860.52610.64720.79890.8916

Monte Carlo averages of observed returns agree within sampling error (e.g. 0.5270 ± 0.0088 at “cellar, key”). The value rises along the route: it measures progress toward the goal. §4 uses exactly this to judge individual actions.

2.6 Kinds of RL algorithms

An agent typically contains at least one of:

  • a policy π(a∣s)\pi(a \mid s);
  • a value function;
  • a model of the environment e(rt+1,st+1∣st,at)e(r_{t+1}, s_{t+1} \mid s_t, a_t).

Correspondingly there are policy-based, value-based and model-based methods. Language models are already policies, distributions over the next token, so the methods used for them are policy-gradient methods. Some of these also learn a value function to stabilize training (§4).


3. Policy gradient

3.1 Why not just backpropagate?

We want to maximize J(θ)=Eτ∼πθ[R(τ)]J(\theta) = \mathbb E_{\tau \sim \pi_\theta}[R(\tau)] with gradient ascent. But what is ∇θR(τ)\nabla_\theta R(\tau)? The return depends on θ\theta only through which actions were sampled. Sampling is not differentiable, and the environment, the reward function and the correctness checker are black boxes.

3.2 The score-function estimator (REINFORCE)

The way out (Williams, 1992) moves the gradient from the function to the probability. For any distribution pθp_\theta and function ff:

∇θ Ex∼pθ[f(x)]=∑x∇θpθ(x) f(x)=∑xpθ(x) ∇θlog⁡pθ(x) f(x)=Ex∼pθ[f(x) ∇θlog⁡pθ(x)],\nabla_\theta\, \mathbb E_{x \sim p_\theta}[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}\big[f(x)\, \nabla_\theta \log p_\theta(x)\big],

using ∇log⁡p=∇p/p\nabla \log p = \nabla p / p. The right-hand side can be estimated by sampling: draw x^∼pθ\hat x \sim p_\theta and use g^=f(x^) ∇θlog⁡pθ(x^)\hat g = f(\hat x)\, \nabla_\theta \log p_\theta(\hat x). No derivative of ff is needed.

This is the estimator Lecture 12 compared with the reparameterization trick (and found ~2 million times noisier on a VAE). Here we have no choice: we cannot reparameterize a discrete action or a black-box environment.

3.3 Applied to episodes

The probability of an episode is

p(τ∣θ)=E(s0)∏tπθ(at∣st) E(st+1∣st,at).p(\tau \mid \theta) = E(s_0)\prod_t \pi_\theta(a_t \mid s_t)\, E(s_{t+1} \mid s_t, a_t).

Take the log. The environment’s terms do not depend on θ\theta, so they vanish from the gradient: ∇θlog⁡p(τ∣θ)=∑t∇θlog⁡πθ(at∣st)\nabla_\theta \log p(\tau \mid \theta) = \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t). We never need to know or differentiate the environment. Therefore

∇θJ=Eτ[R(τ)∑t∇θlog⁡πθ(at∣st)]=Eτ[∑tRt ∇θlog⁡πθ(at∣st)].\nabla_\theta J = \mathbb E_\tau\Big[R(\tau) \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\Big] = \mathbb E_\tau\Big[\sum_t R_t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t)\Big].

The second form uses causality: an action cannot affect rewards that came before it, so those terms average to zero, and each action is weighted by the reward-to-go RtR_t (the slides’ appendix).

Intuition. When the return after an action is high, push up the probability of that action in that state; when it is low, push it down.

The vanilla algorithm (REINFORCE; the slides and pg.ipynb):

  1. Collect an episode with πθ\pi_\theta.
  2. Compute the returns RtR_t.
  3. Form the loss LPG=−∑tRtlog⁡πθ(at∣st)\mathcal L_{\text{PG}} = -\sum_t R_t \log \pi_\theta(a_t \mid s_t), whose gradient is the estimate above.
  4. Update θ\theta with SGD or Adam.

3.4 Measured: the estimate is right on average and noisy per episode

At the SFT policy (J=0.2014J = 0.2014), demo 02 draws 20,000 episodes and compares the average of each estimator with the exact gradient (relative bias), and measures the per-episode spread (relative variance E∥g^−gˉ∥2/∥∇J∥2\mathbb E\|\hat g - \bar g\|^2 / \|\nabla J\|^2). Dividing the variance by 0.01 gives the number of episodes needed for a gradient estimate within 10% of the truth:

weight of ∇log⁡π(at∣st)\nabla \log \pi(a_t \mid s_t)relative biasrelative varianceepisodes for 10% error
R(τ)R(\tau), the whole return0.028 (noise 0.032)20.82,083
RtR_t, reward-to-go0.028 (noise 0.032)20.82,083

REINFORCE is unbiased: its average matches the exact gradient up to Monte Carlo noise. But a single episode’s estimate is useless on its own. About 2,000 episodes are needed for one gradient estimate within 10%, and this is a 13-state problem.

Notice that reward-to-go gives identical estimates here. With one reward at the very end, every step’s reward-to-go is the whole return. Reward-to-go helps only when rewards arrive along the way, and in the end-of-sequence reward setting typical of LMs it buys nothing.

On CartPole (the notebooks; demo 03, eight seeds). REINFORCE with γ=0.99\gamma = 0.99, Adam 10−310^{-3}, one episode per update:

  • it reached a running reward above 475 after 644 to more than 1,000 episodes (median 771.5);
  • two of eight seeds had not solved it within 1,000 episodes.

The spread is the noise above, made visible. A single notebook run, the usual way such results are reported, says little about the algorithm: Lecture 14’s seed lottery again.


4. Stabilizing learning, strategy 1: weight the gradients better

All the estimators below have the form g^=∑twt ∇θlog⁡πθ(at∣st)\hat g = \sum_t w_t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t), with a different weight wtw_t. Some keep the expectation exact and lower the variance; some accept a bias for a larger cut in variance.

4.1 Discounting

Weighting by discounted reward-to-go (γ<1\gamma < 1) gives distant rewards less influence. That reduces variance, because fewer random future events enter each weight. But if the objective is the undiscounted return, it is a biased estimate of a different objective, one that prefers fast success. Measured (demo 02):

weightrelative biascosine with the exact gradientrelative variance
RtR_t0.028 (noise)1.00020.8
γ=0.95\gamma = 0.950.1980.99013.4
γ=0.9\gamma = 0.90.3470.9629.0
γ=0.8\gamma = 0.80.5520.8664.7

The course notebooks use γ=0.99\gamma = 0.99 on CartPole. There every step earns +1, so the discount mostly limits the effective horizon to about 1/(1−γ)=1001/(1-\gamma) = 100 steps.

4.2 Baselines

Subtract from the return a baseline b(st)b(s_t) that does not depend on the action:

g^=∑t(Rt−b(st)) ∇θlog⁡πθ(at∣st).\hat g = \sum_t \big(R_t - b(s_t)\big)\, \nabla_\theta \log \pi_\theta(a_t \mid s_t).

Still unbiased, because Ea∼π[∇θlog⁡πθ(a∣s)]=∑a∇θπθ(a∣s)=∇θ1=0\mathbb E_{a \sim \pi}[\nabla_\theta \log \pi_\theta(a \mid s)] = \sum_a \nabla_\theta \pi_\theta(a \mid s) = \nabla_\theta 1 = 0.

Intuition (the slides’ table):

promptrewardbaselinereward − baseline
“Summarize this paper: …”0.80.75+0.05
“Summarize this paper: …”0.30.75−0.45
“Prove this theorem: …”0.30.10+0.20

A score of 0.3 is bad for an easy summarization prompt and good for a hard proof. The baseline says what was expected in that state, so the update rewards actions for doing better than expected. The natural choice is the value function, b(s)=Vπ(s)b(s) = V^\pi(s).

Measured: when do baselines help?

  • With Key Quest’s 0/1 rewards, barely. A constant baseline b=Jb = J gives variance 21.1 vs 20.8 without; the exact value baseline gives 18.4. Rewards that are almost always 0 are already nearly centered.
  • They matter with an offset. Add a constant cc to every episode’s reward, as a reward model with an arbitrary zero point would (demo 02, Part B). The gradient does not change, but the variance does:
reward offsetno baselineleave-one-out baseline (groups of 16)exact value baseline
c=0c = 020.823.518.4
c=1c = 1288.723.518.4
c=5c = 55845.123.518.4

Without a baseline the variance grows like c2c^2 (281× at c=5c = 5); with one it is untouched. The leave-one-out baseline (Kool et al., 2019), the mean return of the other episodes in a group, needs no learned model at all. Lecture 17’s GRPO is built on this idea.

In training (demo 02, Part C; 10 seeds, 16 episodes per update, from the SFT policy):

methodJJ after 10 updates25100
REINFORCE0.7630.9500.978
leave-one-out baseline0.7380.9510.986
learned critic (Rt−V^(st)R_t - \hat V(s_t))0.7370.9520.986
REINFORCE, reward + 10.4320.7110.948
leave-one-out, reward + 10.7380.9510.986

With the offset, plain REINFORCE slows dramatically; the baselined methods are unaffected.

4.3 Advantages, TD residuals and GAE

The best weight is the advantage Aπ(st,at)=Qπ(st,at)−Vπ(st)A^\pi(s_t, a_t) = Q^\pi(s_t, a_t) - V^\pi(s_t): how much better this action was than the policy’s average in this state. It is never known exactly, and the slides list three ways to estimate it:

  • baseline: A^t=Rt−V(st)\hat A_t = R_t - V(s_t), with an actual return;
  • TD residual (Sutton & Barto): A^t=δt=rt+γV(st+1)−V(st)\hat A_t = \delta_t = r_t + \gamma V(s_{t+1}) - V(s_t). This judges an action by what happened immediately after it, using the value function as a stand-in for the rest of the episode;
  • generalized advantage estimation (Schulman et al., 2015): A^t=∑l(γλ)lδt+l\hat A_t = \sum_l (\gamma\lambda)^l \delta_{t+l}. λ=0\lambda = 0 gives the TD residual, and λ=1\lambda = 1 gives Rt−V(st)R_t - V(s_t) (the sum telescopes).

Measured with exact values (demo 02):

  • the exact advantage has relative variance 4.5, against 20.8 for REINFORCE: 4.7× lower, with 447 instead of 2,083 episodes for a 10%-accurate gradient;
  • the TD residual with the exact value function does as well (4.5), and both are unbiased.

In practice the value function is learned (a critic), and its errors bias the TD residual. Demo 02 fits a critic on just 30 episodes:

GAE with a critic from 30 episodesrelative biascosinerelative variance
λ=0\lambda = 0 (TD residual)0.7170.7004.0
λ=0.5\lambda = 0.50.6100.8114.4
λ=0.9\lambda = 0.90.2420.98211.5
λ=1\lambda = 1 (Rt−V^R_t - \hat V)0.029 (noise)1.00021.0

λ\lambda is a dial between trusting the critic (low variance, biased if the critic is wrong) and trusting the observed returns (unbiased, noisy). Schulman et al. use λ≈0.95\lambda \approx 0.95–0.99 with a well-trained critic.

4.4 A learned value function on CartPole

pg_vf.ipynb adds a value network Vϕ(s)V_\phi(s), trained by regression on observed returns, and uses Rt−Vϕ(st)R_t - V_\phi(s_t) as the weight. Measured over eight seeds (demo 03):

recipeepisodes to solve (8 seeds)medianmedian environment steps
REINFORCE (pg.ipynb)644 to >1,000 (2 unsolved)771.5197,222
+ value baseline (pg_vf.ipynb)370–541469120,922

The baseline does not change what is learned, only how noisy each update is. Every seed solved, with 1.6× fewer environment steps. Played greedily, all the final policies balance the pole for (almost) the full 500 steps.

What the critic got wrong (demo 03, Part B). Along the trained policy’s episodes:

  • the critic predicts 88.0 at the start and 75.2 near step 495;
  • the actual discounted return falls from 96.9 to 4.9, because the episode is cut at 500 steps.

The return depends on the time left, which is not part of the state the critic sees. This is §2.4’s lesson again, in a different guise (Pardo et al., 2018, recommend adding the time to the state).


5. Stabilizing learning, strategy 2: control the step size

5.1 The problem with big steps

Each gradient estimate is noisy, and the data was collected by the current policy. A large step can move the policy somewhere the data said nothing about. The next batch is then collected by a bad policy, and training can collapse. Yet collecting episodes is expensive (for an LM: generating text and scoring it), so we would like to take several gradient steps on each batch.

Reusing a batch with importance sampling. After the first step, the batch was drawn from πold\pi_{\text{old}}, not the current πθ\pi_\theta. The correction is to weight each action by the probability ratio ρ=πθ(a∣s)/πold(a∣s)\rho = \pi_\theta(a \mid s) / \pi_{\text{old}}(a \mid s) and maximize the surrogate E[ρ A^]\mathbb E[\rho\, \hat A]. Its gradient at θ=θold\theta = \theta_{\text{old}} is the policy gradient.

Measured: reuse helps, then hurts (demo 04, Part A; 16 Adam steps on one batch of 16 episodes, averaged over 20 batches):

step on the batch12481216
plain surrogate: JJ0.2580.3140.4110.4880.4320.335
plain: KL to the old policy0.0040.0150.0580.2050.3990.612
PPO-clip: JJ0.2580.3140.3990.4490.4280.414
PPO-clip: KL0.0040.0150.0400.0660.0780.091

With the plain surrogate, JJ climbs from 0.201 to 0.488 in 8 steps and then falls back to 0.335. The objective keeps rewarding larger ratios for the batch’s good actions (mean ratio 1.68 after 16 steps), far beyond what 16 episodes can justify.

5.2 Trust regions and PPO’s clip

TRPO (Schulman et al., 2015) maximizes the surrogate subject to an explicit constraint KL(πold ∥ πθ)≤δ\mathrm{KL}(\pi_{\text{old}} \,\|\, \pi_\theta) \le \delta, a trust region, which requires second-order optimization. PPO (Schulman et al., 2017) gets most of the effect with a first-order trick:

LPPO=E[min⁡(ρ A^, clip(ρ,1−ϵ,1+ϵ) A^)].L^{\text{PPO}} = \mathbb E\Big[\min\big(\rho\, \hat A,\ \mathrm{clip}(\rho, 1 - \epsilon, 1 + \epsilon)\, \hat A\big)\Big].

How it behaves, case by case:

advantageratiowhat the min picksgradient
A^>0\hat A > 0 (good action)ρ<1+ϵ\rho < 1 + \epsilonρA^\rho \hat Apush ρ\rho up
A^>0\hat A > 0ρ>1+ϵ\rho > 1 + \epsilon(1+ϵ)A^(1 + \epsilon)\hat A, a constantnone: no reward for going further
A^<0\hat A < 0 (bad action)ρ>1−ϵ\rho > 1 - \epsilonρA^\rho \hat Apush ρ\rho down
A^<0\hat A < 0ρ<1−ϵ\rho < 1 - \epsilon(1−ϵ)A^(1 - \epsilon)\hat A, a constantnone

The min makes the objective a pessimistic bound. It never pays for moving a ratio beyond [1−ϵ,1+ϵ][1-\epsilon, 1+\epsilon] in the direction the advantage favors, but it still corrects moves in the wrong direction.

Measured on the same batches (the table above, ϵ=0.2\epsilon = 0.2):

  • after 16 steps, 48.3% of the batch’s actions are clipped and the mean ratio of good actions sits at 1.20;
  • the KL stays at 0.091;
  • JJ ends at 0.414, below the plain surrogate’s best but far from its collapse.

5.3 Measured: efficiency and stability in training

Demo 04 (Part B) trains from the SFT policy: 10 seeds, 40 updates of 16 episodes, Adam learning rate 0.1 unless stated:

methodJJ after 5 updates1040worst seed at 40largest KL in one update
REINFORCE (1 step per batch)0.4980.7380.9750.9710.00
4 steps per batch, plain0.8890.9670.9870.9820.06
4 steps per batch, PPO-clip0.8550.9510.9850.9740.05
16 steps per batch, plain0.6030.7520.6010.0004.43
16 steps per batch, PPO-clip0.8180.8560.9500.7870.15
4 steps, plain, lr 0.30.8740.8910.8950.0000.42
4 steps, PPO-clip, lr 0.30.9120.9700.9920.9900.15
  • Reuse buys sample efficiency. Four steps per batch reach J≈0.86J \approx 0.86–0.89 after 80 episodes, where one step reaches 0.50.
  • Without a limit, reuse can destroy the policy. With 16 steps, or a larger learning rate, some runs collapse to J=0J = 0 after a single update that moves the policy by KL 4.43. Clipping keeps every run alive.
  • Clipping is not a hard trust region. With 16 steps per batch PPO still made an update of KL 0.15 and let one seed fall to 0.787. Engstrom et al. (2020) and Wang et al. (2019) document this. In practice one also caps the number of epochs, monitors the KL and stops early, and in RLHF adds an explicit KL penalty (Lecture 17).

5.4 Putting it all together

The general loop (the slides):

  1. Collect trajectories with the current policy.
  2. Compute advantages: a baseline, a value function, discounting, GAE.
  3. Compute the loss: the policy-gradient loss or PPO’s clipped loss (plus a value loss if there is a critic).
  4. Update with backpropagation and Adam, possibly several epochs per batch.

Every RL method for language models in Lecture 17 is an instance:

  • RLHF (Ziegler et al., 2019; Stiennon et al., 2020; Ouyang et al., 2022): prompt → response, a learned preference reward, PPO with GAE and a KL penalty.
  • RL with verifiable rewards (DeepSeek-R1): a one-step MDP, a 0/1 rule-based reward, PPO’s loss with the group’s average reward as the baseline. That is “GRPO”.

6. Summary

  1. Why RL: SFT imitates; RL optimizes the task criterion directly, learns from the model’s own samples, and lets it practice recovering from mistakes.
  2. MDPs: states, actions, transitions, rewards, policies, returns. The agent’s state is whatever it keeps from its history.
    • Measured: hiding one bit of state cuts the best memoryless agent from 0.995 to 0.114; memory restores it.
  3. Sparse rewards make learning from scratch hopeless (one success per 11,122 random episodes), so start from imitation, which is capped by its data (0.20).
  4. Policy gradient: ∇J=E[∑twt∇log⁡π(at∣st)]\nabla J = \mathbb E[\sum_t w_t \nabla \log \pi(a_t \mid s_t)]; the environment drops out.
    • Measured: unbiased, but ~2,000 episodes for one 10%-accurate gradient in a 13-state problem.
  5. Variance reduction:
    • reward-to-go: nothing with a single final reward;
    • discounting: less variance, with bias;
    • baselines: unbiased, essential with reward offsets (variance ×281 without one at c=5c = 5);
    • advantages and TD residuals: 4.7× less variance with exact values;
    • GAE: λ\lambda trades a critic’s bias for variance.
    • On CartPole, the learned value baseline solved every seed (median 469 vs 771.5 episodes).
  6. Step size: reusing a batch is efficient but can collapse the policy (KL 4.43, J→0J \to 0). PPO’s clip removes the incentive to move ratios beyond 1±ϵ1 \pm \epsilon: stable, though not a hard trust region.

Common pitfalls

  • Starting RL from a random policy on a sparse-reward task. Nothing to learn from; start from SFT or shape the reward.
  • Expecting reward-to-go to help with end-of-episode rewards. It is identical to the full return there.
  • No baseline with an offset reward. Reward-model scores have arbitrary zero points; the variance grows with the square of the offset.
  • Trusting one seed. Two of eight REINFORCE runs on CartPole did not solve within 1,000 episodes while the others did; report the spread.
  • Forgetting that discounting changes the objective. γ<1\gamma < 1 optimizes “fast” success, which may not be what you want.
  • Too many epochs per batch, or too large a learning rate, without monitoring the KL. Clipping does not stop everything.
  • A critic that cannot see what the return depends on (time left, hidden state). Its errors bias every advantage built on it.

Exercises

  1. The score function, by hand. A one-step policy picks action 1 with probability p=σ(θ)p = \sigma(\theta) and action 0 otherwise; the reward is f(1)=1f(1) = 1, f(0)=0f(0) = 0. Compute ∇θJ\nabla_\theta J exactly and write the REINFORCE estimate for each action. Verify that its mean is the exact gradient and compute its variance.

    Answer$J = p$, so $\nabla J = p(1-p)$. $\nabla \log \pi(1) = 1 - p$ and $\nabla \log \pi(0) = -p$. The estimate is $f(a)\nabla \log \pi(a)$: $1 - p$ if $a = 1$ (probability $p$), and 0 if $a = 0$. Mean: $p(1-p)$ ✓. Variance: $p(1-p)^2 - p^2(1-p)^2 = p(1-p)^3$. With a baseline $b$: the estimate is $(1-b)(1-p)$ or $-(0-b)p = bp$; it is still unbiased, and at $b = p$ the two values are $(1-p)^2$ and $p^2$.
  2. Baselines are free. Prove Ea∼πθ(⋅∣s)[b(s)∇θlog⁡πθ(a∣s)]=0\mathbb E_{a \sim \pi_\theta(\cdot \mid s)}[b(s)\nabla_\theta \log \pi_\theta(a \mid s)] = 0. Why may bb depend on the state but not on the action?

    Answer$\sum_a \pi(a \mid s)\, b(s) \nabla \log \pi(a \mid s) = b(s) \sum_a \nabla \pi(a \mid s) = b(s) \nabla \sum_a \pi(a \mid s) = b(s)\nabla 1 = 0$. If $b$ depended on $a$, it could not be pulled out of the sum, and the term would generally not vanish: the estimator would be biased. (Action-dependent "control variates" exist, but they need a correction term.)
  3. The optimal constant baseline. Write g^=(R−b) s\hat g = (R - b)\, s with s=∑t∇log⁡π(at∣st)s = \sum_t \nabla \log \pi(a_t \mid s_t). Show that the variance (trace) is minimized by b⋆=E[R ∥s∥2]/E[∥s∥2]b^\star = \mathbb E[R\, \|s\|^2] / \mathbb E[\|s\|^2]. Use it to explain why b=J=0.20b = J = 0.20 did not reduce the variance in Key Quest.

    Answer$\mathbb E\|\hat g\|^2 = \mathbb E[R^2\|s\|^2] - 2b\,\mathbb E[R\|s\|^2] + b^2\,\mathbb E\|s\|^2$, minimized at $b^\star$ (the mean term $\|\mathbb E\hat g\|^2$ does not depend on $b$). $b^\star$ is the average return weighted by $\|s\|^2$, the squared size of the episode's score. Failed Key Quest episodes run all 10 steps and have large $\|s\|^2$; successes are short. So $b^\star$ is pulled toward the failures' return, 0, well below $J$. Subtracting 0.20 adds a $-0.20$ weight to every long failure and slightly increases the variance.
  4. GAE’s limits. Show that ∑l≥0(γλ)lδt+l\sum_{l \ge 0}(\gamma\lambda)^l \delta_{t+l} equals δt\delta_t at λ=0\lambda = 0 and Rt−V(st)R_t - V(s_t) at λ=1\lambda = 1 (with V=0V = 0 after the episode ends).

    Answer$\lambda = 0$: only $l = 0$ survives. $\lambda = 1$: $\sum_l \gamma^l(r_{t+l} + \gamma V(s_{t+l+1}) - V(s_{t+l}))$ telescopes. Each $\gamma^{l+1}V(s_{t+l+1})$ cancels the next term's $-\gamma^{l+1}V(s_{t+l+1})$, leaving $\sum_l \gamma^l r_{t+l} - V(s_t) = R_t - V(s_t)$. In between, GAE is a weighted average of $k$-step advantage estimates.
  5. PPO’s gradient. With ϵ=0.2\epsilon = 0.2: what is the gradient of one action’s PPO term when (a) A^=+1\hat A = +1, ρ=1.5\rho = 1.5; (b) A^=+1\hat A = +1, ρ=0.7\rho = 0.7; (c) A^=−1\hat A = -1, ρ=0.7\rho = 0.7; (d) A^=−1\hat A = -1, ρ=1.5\rho = 1.5?

    Answer(a) $\min(1.5, 1.2) = 1.2$, a constant: zero gradient (already pushed far enough). (b) $\min(0.7, 0.8) = 0.7 = \rho\hat A$: gradient $\nabla\rho$, push the good action back up. (c) $\min(-0.7, -0.8) = -0.8$, a constant: zero gradient (already pushed down far enough). (d) $\min(-1.5, -1.2) = -1.5 = \rho\hat A$: gradient $-\nabla\rho$, keep pushing the bad action down. Clipping only removes the incentive to move further in the favored direction; it never blocks a correction.
  6. Why reuse eventually hurts. In demo 04 the plain surrogate’s JJ peaked after 8 steps on a batch and then fell, while the KL kept growing. Explain using importance sampling.

    AnswerThe surrogate $\frac{1}{N}\sum \rho\,\hat A$ is an unbiased estimate of the improvement only for policies near $\pi_{\text{old}}$. As $\pi_\theta$ moves away, the estimate relies on a few samples with large ratios, so its variance explodes. Worse, it says nothing about actions the batch never tried, whose probabilities shrink as the sampled good ones grow. Maximizing a noisy estimate drives the policy toward the batch's accidents, not toward the true optimum (a winner's curse, as in Lecture 14). The KL measures how far outside the data's support the policy has moved.
  7. Discounting in the notebooks. CartPole gives +1 per step and the notebooks use γ=0.99\gamma = 0.99. What is the discounted value of an episode that never ends? Why is the critic’s estimate near the 500-step cutoff wrong, and how could it be fixed?

    Answer$\sum_t 0.99^t = 1/(1 - 0.99) = 100$. Near the cutoff, the true discounted return from step $t$ is $\sum_{k < 500 - t} 0.99^k$ (4.9 at $t = 495$), but the state (position, velocity, angle, angular velocity) is the same as at $t = 0$. A critic of the state alone must average over times and is wrong at both ends. Fixes: add the time left (or $t/500$) to the critic's input; or treat truncation differently from failure, bootstrapping $V(s_{\text{last}})$ instead of 0 at a time-limit cut (Pardo et al., 2018).
  • Assignment 3 (literature review, proposal, baseline reproduction): RL papers are notoriously sensitive to seeds and implementation details (Henderson et al., 2018; Engstrom et al., 2020). If you reproduce one, run several seeds, report the spread and the KL between successive policies, and check your advantage estimates against a setting where the answer is known. These notes do not provide assignment code.

Further reading

  • A. Karpathy, “Deep Reinforcement Learning: Pong from Pixels”, 2016 (course reading); OpenAI, “Spinning Up in Deep RL” (course reading).
  • R. Sutton, A. Barto, Reinforcement Learning: An Introduction, 2nd ed., 2018, chapters 3 and 13; D. Silver, UCL Course on RL, 2015; J. Schulman, “Deep Reinforcement Learning” tutorial, 2016.
  • R. Williams, “Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning”, Machine Learning 1992; R. Sutton et al., “Policy Gradient Methods for Reinforcement Learning with Function Approximation”, NeurIPS 2000; E. Greensmith, P. Bartlett, J. Baxter, “Variance Reduction Techniques for Gradient Estimates in Reinforcement Learning”, JMLR 2004.
  • J. Schulman et al., “Trust Region Policy Optimization”, ICML 2015; “High-Dimensional Continuous Control Using Generalized Advantage Estimation”, ICLR 2016; “Proximal Policy Optimization Algorithms”, 2017 (course readings).
  • W. Kool, H. van Hoof, M. Welling, “Buy 4 REINFORCE Samples, Get a Baseline for Free!”, 2019; A. Ahmadian et al., “Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs”, ACL 2024.
  • L. Engstrom et al., “Implementation Matters in Deep Policy Gradients: A Case Study on PPO and TRPO”, ICLR 2020; Y. Wang et al., “Truly Proximal Policy Optimization”, UAI 2019; P. Henderson et al., “Deep Reinforcement Learning that Matters”, AAAI 2018; F. Pardo et al., “Time Limits in Reinforcement Learning”, ICML 2018.
  • A. Barto, R. Sutton, C. Anderson, “Neuronlike Adaptive Elements That Can Solve Difficult Learning Control Problems”, 1983 (the cart-pole task).

Preview of Lecture 17 — Reinforcement learning II: applications to language models

Lecture 17 puts a language model in the agent’s seat. It treats generation as a one-step MDP (prompt → whole response) or a token-level one, and walks through the slides’ three examples:

  • reversing a string: SFT first (“cold start”), a verifiable 0/1 reward, group-based advantages + the PPO loss = GRPO;
  • solving math problems: DeepSeek-R1;
  • aligning with human preferences: a Bradley–Terry reward model, reward hacking, and a KL penalty with its closed-form optimal policy. DPO skips the reward model.

The demos use a toy LM whose response space can be enumerated, so the KL and the optimal policy are exact.


术语表 (Glossary, English → 中文)

English中文
reinforcement learning (RL)强化学习
task mismatch / data mismatch / exposure bias任务不匹配 / 数据不匹配 / 暴露偏差
agent / environment智能体 / 环境
Markov decision process (MDP)马尔可夫决策过程
state / observation / agent state状态 / 观测 / 智能体状态
action / transition / reward动作 / 转移 / 奖励
policy / episode / trajectory / horizon策略 / 回合 / 轨迹 / 时域
return / reward-to-go / discount factor回报 / 未来回报 / 折扣因子
credit assignment信用分配
sparse reward / exploration稀疏奖励 / 探索
value function / Q-function / advantage价值函数 / 动作价值函数 / 优势函数
Bellman equation / dynamic programming / backward induction贝尔曼方程 / 动态规划 / 逆向归纳
policy-based / value-based / model-based methods基于策略 / 基于价值 / 基于模型的方法
policy gradient / REINFORCE / score-function estimator策略梯度 / REINFORCE / 得分函数估计器
baseline / leave-one-out baseline基线 / 留一基线
variance reduction / bias–variance trade-off方差缩减 / 偏差-方差权衡
temporal-difference (TD) residual时序差分残差
generalized advantage estimation (GAE)广义优势估计
critic / actor-critic评论家(价值网络) / 演员-评论家
importance sampling / probability ratio重要性采样 / 概率比
trust region (TRPO)信赖域(信赖域策略优化)
proximal policy optimization (PPO) / clipped surrogate objective近端策略优化 / 截断替代目标
behavior cloning行为克隆
partial observability / aliasing / time limit部分可观测 / 状态混淆 / 时间限制
sample efficiency / policy collapse样本效率 / 策略坍缩
← 返回课程目录