Maps to: CMU 11-711 Spring 2026, Lecture 16 (03/12), “Reinforcement Learning I: Fundamentals”; slides
anlp-s2026-16-rl.pdf; course code16_rl/pg.ipynband16_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 fromcode/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:
- Name the three problems of supervised fine-tuning that reinforcement learning addresses: task mismatch, data mismatch, exposure bias.
- 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.
- Derive the policy gradient from the score-function identity and turn it into the REINFORCE algorithm.
- Explain why policy-gradient estimates are noisy, and how reward-to-go, discounting, baselines, advantages, TD residuals and GAE trade variance against bias.
- 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
| Section | Idea | Demo in code/lecture16/ |
|---|---|---|
| §2.1–2.3 | an MDP that reads text; sparse rewards; imitation vs the optimum | 01_mdp.py Parts A, C |
| §2.4 | state vs observation, and memory | 01_mdp.py Part D |
| §2.5 | returns, discounting, value functions | 01_mdp.py Part B |
| §3 | the policy gradient: 13 estimators vs the exact gradient | 02_policy_gradient.py Part A |
| §3.4, §4.5 | the course notebooks on CartPole, 8 seeds | 03_cartpole.py |
| §4.3 | baselines and reward offsets | 02_policy_gradient.py Parts B, C |
| §5 | reusing a batch; PPO’s clip | 04_ppo.py |
0.4 Notation
| Symbol | Meaning |
|---|---|
| , , | state, action, reward at step ; an episode |
| the policy, with parameters | |
| , | the environment’s transitions and reward function (the slides’ notation) |
| the return of an episode; the reward-to-go from step | |
| the objective: expected return | |
| , , | value, action value, advantage |
| , | discount factor; GAE’s mixing parameter |
| , | PPO’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:
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:
- The task criterion is optimized directly, through the reward (“is 2 + 3 = 5?”, “is this response offensive?”).
- 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.
- 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:
| agent | observation | action | reward | |
|---|---|---|---|---|
| Atari | the player | the screen | button presses | the game score |
| robotics | the robot | camera images, joint angles | joint torques | balance, reaching a target |
| text generation | the language model | the text generated so far | the next token | is the final answer correct? |
2.2 Markov decision processes
The formalism is a Markov decision process :
- is the state space;
- is the action space;
- gives the environment’s transitions;
- is the reward.
The agent acts with a policy . An episode (trajectory) runs from until a terminal state:
The goal is a policy that maximizes the expected return .
“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, ;
- 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: . Autograd through that computation gives the exact policy gradient, against which every estimator in this lecture is measured.
Measured (demo 01, Part C):
| policy | = P(door opened within 10 actions) |
|---|---|
| uniformly random | 0.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 optimum | 0.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 : the environment’s private representation;
- the observation : what the agent sees;
- the agent state : whatever information the agent uses to pick its next action, some function 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:
| agent | distinct agent states | best |
|---|---|---|
| sees the full state (inventory in the text) | 13 | 0.9950 |
| sees only the current text, no inventory | 8 | 0.1144 |
| current text + memory of having taken the key | 13 | 0.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: . The slides’ example has six actions, +1 after the last, and . The discounted return seen after each action is (demo 01, Part B):
| action | a1 | a2 | a3 | a4 | a5 | a6 |
|---|---|---|---|---|---|---|
| discounted return | 0.59 | 0.66 | 0.73 | 0.81 | 0.90 | 1.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 is the expected return from a state. It satisfies the Bellman equation, .
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 | 0.2014 | 0.2785 | 0.3886 | 0.5261 | 0.6472 | 0.7989 | 0.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 value function;
- a model of the environment .
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 with gradient ascent. But what is ? The return depends on 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 and function :
using . The right-hand side can be estimated by sampling: draw and use . No derivative of 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
Take the log. The environment’s terms do not depend on , so they vanish from the gradient: . We never need to know or differentiate the environment. Therefore
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 (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):
- Collect an episode with .
- Compute the returns .
- Form the loss , whose gradient is the estimate above.
- Update with SGD or Adam.
3.4 Measured: the estimate is right on average and noisy per episode
At the SFT policy (), 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 ). Dividing the variance by 0.01 gives the number of episodes needed for a gradient estimate within 10% of the truth:
| weight of | relative bias | relative variance | episodes for 10% error |
|---|---|---|---|
| , the whole return | 0.028 (noise 0.032) | 20.8 | 2,083 |
| , reward-to-go | 0.028 (noise 0.032) | 20.8 | 2,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 , Adam , 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 , with a different weight . 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 () 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):
| weight | relative bias | cosine with the exact gradient | relative variance |
|---|---|---|---|
| 0.028 (noise) | 1.000 | 20.8 | |
| 0.198 | 0.990 | 13.4 | |
| 0.347 | 0.962 | 9.0 | |
| 0.552 | 0.866 | 4.7 |
The course notebooks use on CartPole. There every step earns +1, so the discount mostly limits the effective horizon to about steps.
4.2 Baselines
Subtract from the return a baseline that does not depend on the action:
Still unbiased, because .
Intuition (the slides’ table):
| prompt | reward | baseline | reward − baseline |
|---|---|---|---|
| “Summarize this paper: …” | 0.8 | 0.75 | +0.05 |
| “Summarize this paper: …” | 0.3 | 0.75 | −0.45 |
| “Prove this theorem: …” | 0.3 | 0.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, .
Measured: when do baselines help?
- With Key Quest’s 0/1 rewards, barely. A constant baseline 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 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 offset | no baseline | leave-one-out baseline (groups of 16) | exact value baseline |
|---|---|---|---|
| 20.8 | 23.5 | 18.4 | |
| 288.7 | 23.5 | 18.4 | |
| 5845.1 | 23.5 | 18.4 |
Without a baseline the variance grows like (281× at ); 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):
| method | after 10 updates | 25 | 100 |
|---|---|---|---|
| REINFORCE | 0.763 | 0.950 | 0.978 |
| leave-one-out baseline | 0.738 | 0.951 | 0.986 |
| learned critic () | 0.737 | 0.952 | 0.986 |
| REINFORCE, reward + 1 | 0.432 | 0.711 | 0.948 |
| leave-one-out, reward + 1 | 0.738 | 0.951 | 0.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 : 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: , with an actual return;
- TD residual (Sutton & Barto): . 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): . gives the TD residual, and gives (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 episodes | relative bias | cosine | relative variance |
|---|---|---|---|
| (TD residual) | 0.717 | 0.700 | 4.0 |
| 0.610 | 0.811 | 4.4 | |
| 0.242 | 0.982 | 11.5 | |
| () | 0.029 (noise) | 1.000 | 21.0 |
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.99 with a well-trained critic.
4.4 A learned value function on CartPole
pg_vf.ipynb adds a value network , trained by regression on observed returns, and uses as the weight. Measured over eight seeds (demo 03):
| recipe | episodes to solve (8 seeds) | median | median environment steps |
|---|---|---|---|
REINFORCE (pg.ipynb) | 644 to >1,000 (2 unsolved) | 771.5 | 197,222 |
+ value baseline (pg_vf.ipynb) | 370–541 | 469 | 120,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 , not the current . The correction is to weight each action by the probability ratio and maximize the surrogate . Its gradient at 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 batch | 1 | 2 | 4 | 8 | 12 | 16 |
|---|---|---|---|---|---|---|
| plain surrogate: | 0.258 | 0.314 | 0.411 | 0.488 | 0.432 | 0.335 |
| plain: KL to the old policy | 0.004 | 0.015 | 0.058 | 0.205 | 0.399 | 0.612 |
| PPO-clip: | 0.258 | 0.314 | 0.399 | 0.449 | 0.428 | 0.414 |
| PPO-clip: KL | 0.004 | 0.015 | 0.040 | 0.066 | 0.078 | 0.091 |
With the plain surrogate, 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 , a trust region, which requires second-order optimization. PPO (Schulman et al., 2017) gets most of the effect with a first-order trick:
How it behaves, case by case:
| advantage | ratio | what the min picks | gradient |
|---|---|---|---|
| (good action) | push up | ||
| , a constant | none: no reward for going further | ||
| (bad action) | push down | ||
| , a constant | none |
The min makes the objective a pessimistic bound. It never pays for moving a ratio beyond in the direction the advantage favors, but it still corrects moves in the wrong direction.
Measured on the same batches (the table above, ):
- 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;
- 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:
| method | after 5 updates | 10 | 40 | worst seed at 40 | largest KL in one update |
|---|---|---|---|---|---|
| REINFORCE (1 step per batch) | 0.498 | 0.738 | 0.975 | 0.971 | 0.00 |
| 4 steps per batch, plain | 0.889 | 0.967 | 0.987 | 0.982 | 0.06 |
| 4 steps per batch, PPO-clip | 0.855 | 0.951 | 0.985 | 0.974 | 0.05 |
| 16 steps per batch, plain | 0.603 | 0.752 | 0.601 | 0.000 | 4.43 |
| 16 steps per batch, PPO-clip | 0.818 | 0.856 | 0.950 | 0.787 | 0.15 |
| 4 steps, plain, lr 0.3 | 0.874 | 0.891 | 0.895 | 0.000 | 0.42 |
| 4 steps, PPO-clip, lr 0.3 | 0.912 | 0.970 | 0.992 | 0.990 | 0.15 |
- Reuse buys sample efficiency. Four steps per batch reach –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 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):
- Collect trajectories with the current policy.
- Compute advantages: a baseline, a value function, discounting, GAE.
- Compute the loss: the policy-gradient loss or PPO’s clipped loss (plus a value loss if there is a critic).
- 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
- Why RL: SFT imitates; RL optimizes the task criterion directly, learns from the model’s own samples, and lets it practice recovering from mistakes.
- 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.
- 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).
- Policy gradient: ; the environment drops out.
- Measured: unbiased, but ~2,000 episodes for one 10%-accurate gradient in a 13-state problem.
- 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 );
- advantages and TD residuals: 4.7× less variance with exact values;
- GAE: trades a critic’s bias for variance.
- On CartPole, the learned value baseline solved every seed (median 469 vs 771.5 episodes).
- Step size: reusing a batch is efficient but can collapse the policy (KL 4.43, ). PPO’s clip removes the incentive to move ratios beyond : 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. 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
-
The score function, by hand. A one-step policy picks action 1 with probability and action 0 otherwise; the reward is , . Compute 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$. -
Baselines are free. Prove . Why may 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.) -
The optimal constant baseline. Write with . Show that the variance (trace) is minimized by . Use it to explain why 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. -
GAE’s limits. Show that equals at and at (with 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. -
PPO’s gradient. With : what is the gradient of one action’s PPO term when (a) , ; (b) , ; (c) , ; (d) , ?
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. -
Why reuse eventually hurts. In demo 04 the plain surrogate’s peaked after 8 steps on a batch and then fell, while the KL kept growing. Explain using importance sampling.
Answer
The 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. -
Discounting in the notebooks. CartPole gives +1 per step and the notebooks use . 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).
Related assignment (concepts only)
- 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 | 样本效率 / 策略坍缩 |