Skip the value function. Nudge the policy itself toward the actions that paid off. One identity turns that idea into a gradient you can estimate from rollouts, and one subtraction keeps the estimate steady.
Pick how to weight each push, then press Train. Watch the purple bell, the policy, slide toward the yellow peak of reward. Then we build, piece by piece, the objective, the trick, the theorem, REINFORCE, and the two fixes for its noise.
You need the chain rule, what a probability is and a little Python. The MDP from Lectures 5 and 7 helps. We build the rest from zero.
Lecture 9 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Before: Lecture 8, Q-Learning. Next: Lecture 10, Actor-Critic.
Illustrative toy. The policy is a bell curve over the push with a spread of 0.5 N. Each update samples 8 pushes and steps the centre with learning rate 0.04. Reward is 25 minus the squared miss from 2 N, so every reward is large and positive. The baseline is the average reward of the batch.
Chapter 0
See why a max over actions breaks for a robot arm, and watch a policy improve with no value table at all
Lecture 8 taught the value recipe. Learn Q(s, a), the expected return of taking action a in state s. Then act by picking the action with the largest Q.
With four joystick buttons, that is easy: compare four numbers. A robot arm's action is seven joint torques, each any real number. There is no list to scan. The max becomes its own optimization problem, solved inside every decision, fifty times a second.
The lecture asks: why learn a value function when the robot only uses a policy? The linear quadratic regulator (LQR), the classic problem with linear dynamics and quadratic cost, makes the case. Its best value function is a quadratic bowl over the state. Its best policy is one line: action = −K × state, for one gain matrix K.
A policy gradient method changes the policy's parameters directly, in the direction that raises the average reward. Here is the smallest one. One state, three actions, and only the middle action pays.
Purple bars are the policy's probabilities. Press Step: the policy samples one action (blue dot). If it paid, its probability goes up.
Illustrative toy. Softmax policy over three logits, learning rate 0.5. Each step adds 0.5 × reward × (1 for the sampled action, else 0, minus its probability) to every logit.
Work the first step. The policy starts at (0.34, 0.33, 0.33). It samples action 1, which pays 1. Its logit rises by 0.5 × 1 × (1 − 0.33) = 0.335, and the others fall. Its probability goes from 0.33 to 0.45. A sample that pays 0 moves nothing.
Failure. A value-based controller for a continuous arm grids the torques to take the max.
Symptom: jerky motion, or a decision that misses its 20 ms budget. Measure: time each decision and count the grid points. Fix: let a policy output the torque directly.
Three reasons to optimize the policy directly:
Chapter 1
Define the one number to raise, write how likely a whole run is, and estimate the number by rolling out
Run a robot twice with the same policy and you get two different runs. The policy rolls dice to pick actions. The world adds its own noise. So "how good is this policy" must be an average.
Name the parts. The policy πθ(a | s) gives a probability to each action a in state s, set by parameters θ (the network weights). One run is a trajectory τ = (s0, a0, s1, a1, …). Its return R(τ) is the sum of its rewards. The quantity to raise is the average return, J(θ).
J of theta equals the expected value, over tau drawn from p-theta, of R of tau.
Run the policy many times. Write down each run's return R of tau. Their average, over runs drawn from this policy, is J of theta.
With made-up numbers: three runs return 4, 7 and 1. The estimate of J(θ) is (4 + 7 + 1)/3 = 4. More runs give a better estimate.
How likely is one trajectory? Call the start chance p(s0) and the world's chance of the next state p(st+1 | st, at). Multiply every step's chances.
p-theta of tau equals p of s-zero, times the product over t of pi-theta of a-t given s-t, times p of s-t-plus-one given s-t and a-t.
Take the start chance p of s-zero. For each step, multiply by the policy's chance of the action and the world's chance of the next state. The result is p-theta of tau.
With made-up numbers, two steps: start 1, policy 0.5, world 0.9, policy 0.8, world 1. pθ(τ) = 1 × 0.5 × 0.9 × 0.8 × 1 = 0.36.
Only the π factors contain θ. Chapter 3 uses this fact. First, try the estimate.
The teal robot takes 4 steps. Forward pays +1, back pays −1. Set the policy's chance of forward, then roll out and watch the yellow estimate find J.
Illustrative toy. The true value is J = 4 × (2 × π(forward) − 1). Moving the slider clears the rollouts, because they came from the old policy.
Failure. You change θ and keep averaging the old rollouts.
Symptom: the estimate lags the policy. Measure: compare it with a fresh batch. Fix: sample new rollouts after every change of θ.
Chapter 2
Turn the gradient of a probability into an average you can sample, and meet the score
We want ∇θJ, the gradient: the direction in θ that raises J fastest. J is an average weighted by pθ(τ). The gradient lands on that probability. No rollout hands you "the gradient of a probability". One identity fixes this.
Take any positive function f(θ). The chain rule says the gradient of log f is ∇f divided by f. Multiply both sides by f.
Grad-theta of f equals f, times grad-theta of log f.
To get the gradient of f, take the gradient of log f and multiply it by f. With f a probability, the f in front turns the gradient into an average, and rollouts estimate averages.
With made-up numbers: f(θ) = θ² at θ = 3. Directly, ∇f = 2 × 3 = 6. By the trick, log f has gradient 2/θ = 2/3, and f × 2/3 = 9 × 2/3 = 6. Both give 6.
The piece the trick produces for one action has a name. The score ∇θ log πθ(a | s) is the direction in θ that makes action a more likely in state s. Make it concrete with a two-action policy and one knob θ. Let σ be the logistic function, σ(θ) = 1/(1 + e−θ), and set π(left) = σ(θ).
Grad-theta of log pi-theta of left equals one minus sigma of theta.
The score of left is the chance of not taking left, 1 minus sigma of theta. It is positive: raise θ to make left likelier. The score of right is minus sigma of theta, negative: lower θ to make right likelier.
At θ = 0.5, σ(θ) = 0.62. The score of left is 1 − 0.62 = +0.38. The score of right is −0.62. The rarer action has the bigger score.
The bars are π(left) and π(right). The arrows are their scores: right-pointing means "raise θ to make me likelier". Slide θ.
Exact values for the two-action logistic policy. The arrow length is the score.
Failure. A hand-written score has the wrong sign.
Symptom: the policy runs away from reward. Measure: compare with a finite-difference gradient (the lab in Chapter 3). Fix: compute log π and let autodiff take its gradient.
Chapter 3
Derive the policy gradient in three lines and watch every term you cannot know fall away
The lecture derives the gradient on the board. It takes three steps, and none is harder than the chain rule.
Put step 3 into step 2. That is the policy gradient theorem.
Grad-theta of J equals the expected value, over tau drawn from p-theta, of the sum over t of grad-theta log pi-theta of a-t given s-t, times R of tau.
For one run, add up the scores of every action it took. Multiply by the run's return R of tau. Average that over runs. Good runs push their actions up hard.
With made-up numbers: a two-step run has scores +0.5 and −0.3, so the sum is 0.2. Its return is 2. This run contributes 0.2 × 2 = 0.4 to the average.
The dynamics vanished. That is why policy gradient is model-free: it learns from what physics did, without a model of physics.
Warm chips are physics, purple chips are the policy. Step through product, log, gradient. Then make the floor icy and see which number stays the same.
Illustrative numbers. The policy picks the three actions with chances 0.6, 0.7 and 0.5, each a logistic of θ, so the scores are 0.4, 0.3 and 0.5. Logs are natural logs.
Now check the theorem in code. The lab computes the gradient of J two ways on a bandit: by the theorem, and by nudging θ and measuring J. They must agree.
Failure. In autodiff code, the return R still carries a gradient.
Symptom: the update differentiates through R and points the wrong way. Measure: check R.requires_grad. Fix: detach R. The theorem treats it as a fixed number.
Chapter 4
Replace the expectation with an average over N rollouts, step uphill, and throw the old data away
The theorem is an average over runs. Roll out N runs and take their average instead. That is REINFORCE (Williams, 1992). Call the i-th run τi and the estimate ĝ ("g-hat").
g-hat equals one over N, times the sum over i of R of tau-i, times the sum over t of grad-theta log pi-theta of a-t-i given s-t-i.
For each run i, add up its scores and multiply by its return R of tau-i. Average over the N runs. That is g-hat. Then step: θ becomes θ + η × g-hat, where η ("eta") is the learning rate.
With made-up numbers: run 1 returns 3 with score sum 0.4; run 2 returns 1 with score sum −0.2. ĝ = (3 × 0.4 + 1 × (−0.2))/2 = 0.5. With η = 0.1, θ moves up by 0.05.
Step 4 throws data away because the average is over runs of the current policy. After the step, the old runs came from a different policy. REINFORCE is on-policy. Q-learning is off-policy and can replay old transitions.
A two-armed bandit with noisy rewards: arm 1 pays 1 on average, arm 0 pays 0.5. Three runs train for 40 updates. Change the batch size and the learning rate.
Illustrative toy. Each reward adds noise with standard deviation 1. The policy picks arm 1 with chance σ(θ), starting at θ = 0. Each run uses its own seed.
Now build the estimator yourself. The lab gives you the sampled actions and their scores. You add the reward weighting.
Failure. The learning rate is too large for the batch.
Symptom: J jumps around or falls after a good start. Measure: plot J over updates for three seeds. Fix: lower η or raise N.
Chapter 5
Read the update as trial and error, then compute one full step by hand
Each action's score gets the weight of its run's return. The update pushes an action in a high-return run up hard. It pushes an action in a low-return run up weakly, or down. The lecture's phrase: REINFORCE formalizes trial and error.
Write one action's term without the log. Since ∇ log π = ∇π / π, the term is the return times ∇π divided by π.
The chance π sits below the line. A rare action that paid off divides by a small number, so it gets a bigger push. That is a built-in pull toward good actions the policy seldom tries.
One state, two actions, θ = 0, so π(left) = π(right) = 0.5. From Chapter 2, the score of left is +0.5 and the score of right is −0.5. Four one-step episodes come back:
| Episode | Action | Score | Return | Return × score |
|---|---|---|---|---|
| 1 | left | +0.5 | 1 | +0.5 |
| 2 | left | +0.5 | 1 | +0.5 |
| 3 | right | −0.5 | 0 | 0 |
| 4 | right | −0.5 | 0 | 0 |
The estimate is the average of the last column: ĝ = (0.5 + 0.5 + 0 + 0)/4 = +0.25. With η = 1, θ moves from 0 to 0.25. So π(left) goes from 0.50 to σ(0.25) = 0.56. Left paid, and left became likelier.
Each chip is one episode. Tap it to switch its return between 0 and 1. The bars show return × score. Make right the paying action and watch the sign flip.
The same four episodes as the table. A highlighted chip has return 1; a plain chip has return 0. Learning rate η = 1.
Failure. Every return is positive, so the update pushes every action up.
Symptom: the policy improves slowly and wobbles. Measure: count the episodes with a negative weight; here there are none. Fix: subtract a baseline (Chapter 8).
Chapter 6
See why REINFORCE is right on average but often wrong on one batch
REINFORCE is unbiased: the average of many estimates equals the true gradient. It also has high variance: one estimate can land far from that average. The lecture says it bluntly: what is wrong with REINFORCE? It has high variance.
Three things make it worse:
Work the third one. Take Chapter 5's bandit at θ = 0, with left paying 1 and right paying 0. One sample of return × score is +0.5 or 0, half the time each. Its mean is 0.25 and its standard deviation is 0.25.
Now add 10 to both rewards. The sample is 11 × 0.5 = 5.5 or 10 × (−0.5) = −5. The mean stays 0.25. The standard deviation becomes 5.25, 21 times larger. A batch of N divides the variance by N, so you need 441 samples to get back to 0.25.
Each blue dot is one REINFORCE estimate from a batch of N samples. Red dots point the wrong way. Shrink N, or shift every reward by 10.
Illustrative toy: a two-armed bandit at θ = 0.3, arm 1 pays 1 and arm 0 pays 0. Each dot is a real REINFORCE estimate from sampled actions; 150 dots per setting.
Failure. The batch is too small for the reward scale.
Symptom: a jagged learning curve that sometimes drops. Measure: compute estimates from several independent batches and compare their spread with their mean. Fix: a larger batch costs rollouts; the next two chapters cut variance for free.
Chapter 7
Credit each action only with the rewards that came after it, and lose noise without losing accuracy
In REINFORCE, the action at step t gets the whole return, including rewards that arrived before it. An action cannot cause an earlier reward. Those earlier rewards add noise and no credit.
So weight each action by the reward-to-go: the sum of rewards from its own step to the end. Call the reward at step t′ rt′.
g-hat equals one over N times the sum over i, of the sum over t, of grad-theta log pi-theta of a-t given s-t, times the sum over t-prime from t onward of r-t-prime.
For each step t, multiply the score of a-t by the rewards from step t onward. Add over steps, then average over runs. Rewards before step t no longer touch a-t.
With made-up numbers: rewards 1, 0, 2 and scores 0.5, −0.2, 0.4. Full return: 3 × (0.5 − 0.2 + 0.4) = 2.1. Reward-to-go: 0.5 × 3 + (−0.2) × 2 + 0.4 × 2 = 1.9.
Dropping the past terms keeps the estimate unbiased. Given the past, a score averages to zero over the policy's actions. Chapter 8 proves it. So a past reward times a score also averages to zero. The inner sum is also a one-run estimate of Q(st, at). Replace it with a learned Q and you get actor-critic, Lecture 10.
Bars are the rewards of a six-step run. Pick the step of an action. Yellow bars are its reward-to-go. Grey bars came earlier, so it could not cause them.
Illustrative rewards: 0.2, −0.1, 0.5, 0.3, −0.2, 0.8. No discount.
Failure. An off-by-one: the code sums rewards from t + 1, so it drops the action's own reward.
Symptom: one-step tasks never learn. Measure: on a one-step bandit, reward-to-go must equal the full return. Fix: start the sum at t′ = t.
Chapter 8
Prove that subtracting a state's usual return leaves the gradient alone, and watch it shrink the noise
Suppose every run scores between 99 and 101. Raw REINFORCE pushes every action up, then sorts them by tiny differences. Subtract the usual return, 100. Now runs score −1 to +1: better than usual goes up, worse goes down.
The number you subtract is a baseline b(s): any function of the state alone, not of the action. Why is that allowed? Because a baseline's term in the gradient averages to zero.
The expected value, over a drawn from pi-theta, of b of s times grad-theta log pi-theta of a given s, equals zero.
Pull b of s out, since it does not depend on the action. What is left is the average score, and the average score is zero. So subtracting b of s changes no average.
With made-up numbers: two actions at 0.5 each, scores +0.5 and −0.5, b = 100. Average: 0.5 × 100 × 0.5 + 0.5 × 100 × (−0.5) = 25 − 25 = 0.
Why is the average score zero? Undo the log trick, and sum over actions:
The chances always add up to 1, a constant, and a constant has zero gradient.
Now the noise. Take θ = 0 again, with left returning 101 and right 99. A raw sample is 101 × 0.5 = 50.5 or 99 × (−0.5) = −49.5. The mean is 0.5 and the standard deviation is 50. Subtract b = 100: both samples become +0.5. Same mean, standard deviation 0.
The usual choice is b(s) = V(s), the state's average return. Then Q(s, a) − V(s) is the advantage A(s, a): how much better this action was than usual. Every modern policy gradient method weights the score by an advantage.
Top row: raw estimates. Bottom row: the same samples with the baseline subtracted. Raise the offset added to every reward.
Illustrative toy: the bandit of Chapter 6 at θ = 0.3, 12 samples per estimate, 150 estimates per row. The baseline is the exact average reward V under the current policy.
Measure it yourself. The lab draws thousands of estimates with and without a baseline and compares their means and variances.
Failure. The baseline depends on the action, for example b = Q(s, a) itself.
Symptom: the weights are all zero and the policy never moves. Measure: check that b takes only the state as input. Fix: use V(s) or another state-only function.
Chapter 9
Keep the terms, the numbers, the core code and the next steps on one page
Policy gradient raises the average return J(θ) by gradient ascent. The log-derivative trick makes the gradient an average of score times return. The dynamics drop out, so it is model-free. REINFORCE estimates the average from fresh rollouts. Reward-to-go and a state-only baseline cut the noise and keep it unbiased.
| Term | What it is | Number from this page |
|---|---|---|
| Objective J(θ) | Average return over runs of πθ | Returns 4, 7, 1 give J ≈ 4 |
| Score | ∇θ log πθ(a | s): the way to make a likelier | θ = 0.5: left +0.38, right −0.62 |
| Policy gradient | E[ (Σt score) × R(τ) ] | Scores 0.5, −0.3 and R = 2 give 0.4 |
| REINFORCE step | θ ← θ + η ĝ, then fresh rollouts | ĝ = 0.25 moves π(left) 0.50 to 0.56 |
| Reward shift | Same task, much noisier estimate | +10 makes the spread 21 times larger |
| Reward-to-go | Credit an action with rewards from its step on | 2.1 becomes 1.9 |
| Baseline b(s) | Subtract a state-only number; no bias | Returns 101 and 99: spread 50 becomes 0 |
| Advantage | A(s, a) = Q(s, a) − V(s) | Better than usual: positive |
| Property | Q-learning | Policy gradient |
|---|---|---|
| Learns | Q(s, a); the policy is the argmax | πθ directly |
| Continuous actions | Awkward: a max inside every decision | Natural: output the action |
| Data | Off-policy: replays old transitions | On-policy: fresh rollouts |
| Main weakness | Unstable with function approximation | High variance, many samples |
pythonimport torch def reinforce_loss(logp, rewards, baseline): # logp: [T] log pi(a_t|s_t) with grad; rewards: [T]; baseline: [T] V(s_t), no grad rtg = torch.flip(torch.cumsum(torch.flip(rewards, [0]), 0), [0]) # reward-to-go, from t adv = (rtg - baseline).detach() # a fixed weight: no gradient through it return -(logp * adv).sum() # minus, because optimizers descend # one update: roll out N episodes with the CURRENT policy, then # loss = mean of reinforce_loss over episodes; loss.backward(); opt.step(); discard the episodes
This lecture sits between the value methods of Lecture 8 and the critic of Lecture 10. Actor-critic keeps the score and replaces the noisy reward-to-go with a learned value. PPO and SAC, which run many real robots, grow from that.
Now press Present or Teach and derive the policy gradient on a blank page. Cover the objective, the trick, the three steps, REINFORCE and the two fixes. Then go back to the hero and train with and without the baseline. Say which chapter explains each wobble.
This lesson re-teaches Lecture 9 of CMU 16-831, Introduction to Robot Learning (Spring 2024), taught by Guanya Shi. The course site is 16-831-s24.github.io, with slides on the lectures page. REINFORCE is from R. J. Williams (1992). The explanations, toys and devices here are our own.