Preferences H start at 0, so every arm starts with probability 1/10.
Introduction to Reinforcement LearningPart 4 · Beyond value functions
Lecture 10Policy gradients and actor-critics
Forget values for a while and learn the policy directly: why stochastic policies help, the score-function trick, the policy gradient theorem, REINFORCE and baselines, actor-critics, trust regions, and continuous actions.
Key ideas, one per episode
- Ep. 38Sometimes the best policy is simpler than the world.
- Ep. 39Weigh ∇log π by the reward, minus a baseline.
- Ep. 40Policy gradients never need the dynamics.
- Ep. 41The critic judges; the actor follows the TD error.
- Ep. 42Let a distribution do the exploring.
Based on: Lecture 9: Policy Gradients and Actor Critics, DeepMind × UCL Reinforcement Learning Lecture Series (2021), by Hado van Hasselt. The slides follow that order of topics, in our own words, figures and examples; they are not official material of the original course.
Watch
5 short episodes of ACML Explains for this lecture. Pick one from the list, and open the transcript to read along: each timestamp plays the episode from there. The narration is generated with a voice clone of Teddy, used with his permission.
Episode 38 · 5:12
Why learn the policy?
What's the best way to beat a casino? Don't play. Sometimes the best policy is simpler than the world.
Sometimes the best policy is simpler than the world.
TranscriptEpisode 38
The long way around
Module ten: policy gradients and actor critics. Quick recap. So far we always took the long way around. Learn values, then read a policy off them. Or learn a model, plan with it, and get a policy. Even the question of which policy is better, we answered with values. Policy pi beats policy pi prime if its value is at least as high in every state. And remember the flips? A tiny error in the values, and the greedy policy suddenly jumps to a completely different action. So today, a new idea. Why not learn the policy directly?
Three roads
There's a lovely line from Vladimir Vapnik: do not solve a more general problem as an intermediate step. Three roads lead to the same place, the optimal policy. Model-based, value-based, and policy-based. Sometimes the model is the easy part. If the dynamics are simple, a few samples teach you how the world moves. And sometimes the dynamics are a nightmare, but the best policy is simple. Always move forward, for example.
Beat the casino
A well known joke in statistics. What's the best way to beat a casino? Don't play. It sounds silly, but statistically it's the right answer. The expected value of every casino game is against the player. Poker, roulette, pick your favourite. The dynamics are anything but simple. The optimal policy? Whatever the state, do nothing. Complex world, trivial policy. In a case like that, learning a model or every value is a lot of work for
Pros and cons
nothing. The advantages. First, we optimise the true objective. For the first time, we learn exactly the thing we wanted to learn. It extends easily to huge or continuous action spaces. It can learn stochastic policies. And sometimes the policy is just simpler. The disadvantages. It can get stuck in a local optimum. The knowledge it learns can be very specific. And on its own, it doesn't squeeze every drop of information out of the data. Sound familiar? Gradient descent with backpropagation has exactly the same problems. They come from optimising over functions, not from reinforcement learning.
A policy, directly
A policy, written directly: the probability of taking action a in state s, given parameters theta. If the policy is deterministic, those probabilities are zero or one. If it's stochastic, anything in between. The same notation covers both. Now, in a fully observed MDP, there's always an optimal deterministic policy. So why would we ever want randomness? Because most problems aren't fully observed. Board games, maybe. Almost everything else, no. And with function approximation, states blur together all the time. Randomness also makes the landscape smooth, so gradients can work. And it explores for free while we learn.
The aliased corridor
Here's a small world. A corridor of five cells. Gold below the middle one, and a skull below each end. The agent only feels the walls around it. And the two grey cells feel exactly the same: a wall above, a wall below, open on both sides. A deterministic policy must do the same thing in both grey cells. Say it always goes right. From the left half, great, you reach the gold. From the right half, you step right, the corner sends you back left, and you bounce between those two cells forever. We simulated it. From a random start, the deterministic policy reaches the gold sixty percent of the time. The other forty percent, it walks back and forth until we stop it.
Flip a coin
Now flip a coin in the grey cells. Fifty percent left, fifty percent right. What's the chance you go left ten times in a row? One half to the power of ten. About one in a thousand. Left forever? Zero. In our runs, the coin-flip policy reached the gold every single time, in about three point eight steps on average. And this isn't random tie-breaking. When we learn the policy directly, the probabilities can be anything, not just fifty fifty. Whatever works best.
What we maximise
So what exactly are we maximising? Imagine you love diving. I give you a policy: every minute, go down one more metre, no matter what. Good policy? At some point you die. Call that minus infinity. Not a great dive. For episodes like a dive, we judge a policy by its expected total return from the start. That's the value of the start state. Where do we start? From a start state distribution, d zero. In chess, it's a single board. In blackjack, it's every pair of cards for you and the dealer. A lot. For tasks that never end, we use the average reward per step instead. Physicists will tell you the world isn't really continuous. The computer certainly isn't. There's always a discretisation somewhere.
The pawn nobody meets
One more strange thing. Remember the white pawn on the first row? A legal board you can never reach. A value table would eventually meet that state and learn it. This objective never will. It only sees what the start distribution can reach. In theory, that's a gap. In practice? If I want to make you the best chess player in the world, do I care that you can't solve an impossible position? No. Next time: how do we actually climb this objective? With one beautiful trick.
Climbing J
Policy gradients turn reinforcement learning into an optimisation problem. Find the theta that makes J of theta as large as possible. We'll use stochastic gradient ascent. It's gradient descent, just walking uphill. Simple, and it plays nicely with deep networks. There are other ways. Hill climbing. Simulated annealing. Genetic algorithms, which I love, and evolution strategies. More robust sometimes, but they cost more. Gradients need a smooth landscape. And stochastic policies help with exactly that. Nudge a probability a little, and the expected return changes a little.
Smooth
What does smooth mean, mathematically? A function you can differentiate as many times as you like, at every point. Polynomials are smooth. Keep differentiating, you hit zero, and zero differentiates forever. Sine is smooth too: sine, cosine, minus sine, minus cosine, and back to sine. A loop-de-loop. If you can only differentiate once, the linear approximations behave, but the way they change can go wild. Smooth means nothing explodes, anywhere. We'll ask for a bit less: differentiable almost everywhere. Everywhere except a set of size zero, like a finite or countable bunch of points. You had four years for this to settle in. Why does that matter? A gradient is a promise about the neighbourhood. If the function jumps around, the promise is worthless.
The problem
Now the problem. We want the gradient of the expected reward with respect to theta. How does that expectation even depend on theta? Only indirectly. Theta picks the actions, and the actions bring the rewards. And you can't sample a reward and differentiate it. A reward is just a number. It doesn't depend on theta at all. In module two, we already met one answer: the gradient bandit. Today, we see where it actually comes from.
The trick
Here's the trick. The score function trick. Write the expectation as a sum over actions: probability of the action times its reward. Theta lives only in the probabilities. Take the gradient. Then multiply and divide by the probability. The gradient of pi divided by pi is just the gradient of log pi. And what's left is an expectation again. The gradient of the expected reward equals the expected reward times the gradient of log pi. An expectation is something we can sample. Take an action, see the reward, multiply. That's REINFORCE, from Ronald Williams, nineteen ninety two.
Why log π is easy
Why can we compute the gradient of log pi? Because pi returns a probability. A single number. It comes straight out of theta, so you know exactly how it moves when theta moves. A log of a number, and a derivative. Nothing scary. Intuition for the update: increase the probability of actions that got high rewards. Decrease the rest. In expectation, that's the true gradient. It's a trick worth stealing, by the way. It shows up all over machine learning, whenever you need a gradient through a random choice.
Our check
We checked it. A three armed bandit with a softmax policy. We know the exact gradient, so we can compare. With ten samples, the estimate is a mess. Two of the three components even point the wrong way. With a hundred, it's in the neighbourhood. With a thousand, close. With a hundred thousand, it's off by only a few thousandths. Unbiased, but noisy. That's the story of this whole module. Right on average, and all over the place on any single try.
Softmax
A softmax policy: each action gets a preference, and the probability is proportional to e to the preference. The gradient of its log is neat: the gradient of the chosen action's preference, minus the average gradient over all actions. So the chosen action goes up, and everything else shares the cost. Scaled by how good the reward was. Notice something. If every reward is positive, the chosen action always goes up, even a bad one. The good ones just go up faster.
Baselines
Now a gift from the maths. Subtract any baseline b that doesn't depend on the action, and the expected gradient doesn't change. Why? The baseline times the sum of all the probability gradients. And the probabilities always sum to one, so their gradients sum to zero. Does that matter? Scores of eight and nine, or eight hundred and nine hundred, rank the actions the same. Only relative scores count. But the noise is very different. Our run: a ten armed bandit where every reward sits around plus four. Two thousand runs, a thousand steps each. Without a baseline, after a thousand steps, it picks the best arm forty nine percent of the time. With the running average as a baseline: eighty three percent. Same gradient on average. Far less noise. When every action looks great, the baseline asks the right question: better than usual, or worse?
REINFORCE
So: REINFORCE. Sample an action, weigh the gradient of log pi by the reward, minus a baseline, and step uphill. It doesn't need a model. It doesn't need the reward function. It only needs samples, and a policy you can differentiate. The price: one sample is one noisy vote. You need a lot of votes. Calming that noise is what the next episodes are about. Next time: from a single step to a whole episode. The policy gradient theorem.
From bandits to episodes
Last time, one step: a bandit. Today, whole episodes, where every action changes what comes next. The idea carries over. Replace the immediate reward with the long-term return, G t, or with the action value, q. There are actually two policy gradient theorems, from Sutton and colleagues in two thousand. One for the average return per episode, and one for the average reward per step. The episodic one says: the gradient is the expected sum, over every step, of three things multiplied together: gamma to the t, q, and the gradient of log pi at that step.
A trajectory
Here's why it works. Take a whole trajectory: a start state, an action, a reward, a next state, an action, and so on. Its probability is a long product. The chance of the start state, times pi of the first action, times the chance of the next state, times pi of the next action. The score function trick still holds for whole trajectories. The gradient of the expected return is the expected return times the gradient of the log of that probability. And the log of a product is a sum of logs. That's what makes everything fall apart nicely. Products are painful to differentiate. Sums are easy. Every step gets its own little term.
The dynamics drop out
Look at the terms. The start state probability. The transition probabilities. Do any of them depend on theta? No. Their gradients are zero. Only the policy terms survive. The gradient becomes the return times the sum of the gradients of log pi along the way. So policy gradients don't need to know the dynamics. A little surprising, right? Shouldn't we know how our actions move the world? Remember from the very first lecture: the reward is not part of the dynamics. Dynamics is physics. We want the ball in the basket. Physics doesn't care what we want.
From t onwards
All the dependencies in a sequential problem hide inside the dynamics. Once those terms drop out, what's left separates, step by step, for a fixed policy. One more step of algebra. An action at time t can't change rewards that came before it. So each step only needs the return from that step onwards: G t. And the expected G t, given the state and action, is exactly q. That's the theorem.
100 candies
In practice, we sample. Play a whole episode, then for every step, nudge theta by G t times the gradient of log pi. Notice we use the real G t here, not an estimate. We played to the end, so we know it. Why guess when you know the answer? It's like someone telling you: there are a hundred candies in this bag. And you say, no, no, I'd rather guess how many. No matter where we wander in this course, we come back to the same building blocks. With one step, this looks like TD. With the full return, it's Monte Carlo. For the record: if a stranger in the street offers you a bag of candies, better not take it. That's what they taught me.
Dropping γᵗ
Typically, people also drop the gamma to the t factor. In long episodes, it shrinks the signal from later steps almost to nothing. That's okay-ish. It's like pretending, at every step, that the episode could have started right there. Or, if you prefer, a slightly biased gradient. Many implementations you'll find do exactly this: keep the discount inside the return, and drop it from the update.
The short corridor
Let's run it. The short corridor, a little example from Sutton and Barto. Three cells, then the goal. Minus one for every step. All three cells look the same to the agent. And in the middle one, the actions are switched. Right takes you left, and left takes you right. We computed every policy exactly. Go right with probability ninety five percent, and it takes forty four steps on average. Go mostly left: eighty two. The best policy goes right fifty nine percent of the time, and needs about eleven point seven steps. Stochastic again. No deterministic policy comes close.
REINFORCE learns it
Now REINFORCE, learning that probability from scratch. A hundred runs, a thousand episodes each, starting from a poor policy that goes right nineteen percent of the time. In the first fifty episodes, it needs twenty three steps on average. By the last hundred episodes: thirteen point four. Close to the best possible, eleven point seven. Slow, but steady. Every episode is a noisy, unbiased vote for a slightly better policy. And notice what it never needed: the rule that switches the middle cell. And it never knew which cell it was in, either. To the agent, all three cells were the same. One probability had to work for all of them.
Average reward
The average reward version looks similar, with one change: subtract the global average reward, rho. Only the distance from the average matters. Rewards of eight and nine, or eight hundred and nine hundred, rank actions the same way. What hurts is the spread around the average. That's where the flips come from. So: policy gradients work on whole trajectories, without a model, using only what the policy itself controls. Next time: the noise problem. And a critic that helps the actor.
The noise
Policy gradients are unbiased. And very noisy. Let's talk about that noise. Two levers. One pays a hundred dollars now and then, and zero the rest of the time. The other pays one dollar, every single time. Pull each three times. One gave you three dollars. The other gave you zeros. Pull once more, and you might get the hundred. With so few samples, your estimates jump around. And a jump in the estimates means a jump in the policy. The flips again.
A baseline: q − v
The fix we met last time: a baseline. And the most common baseline is the value of the state, v of s. Then each step is weighted by q minus v. What does that measure? The contribution of my specific action, compared to how good the state already was. If my action is plain vanilla, q minus v is tiny, the gradient is tiny, and the policy barely moves. The update goes where the action actually mattered. And it pushes the policy, indirectly, toward states that are good in themselves. Good states tend to be stable states. And because the baseline depends only on the state, the expected gradient stays exactly the same. Variance reduction for free.
Is low variance good?
Is low variance always what you want? Not always, but often. Another bandit. Arm A pays ten dollars, every time. Arm B costs you ten dollars, but once in a thousand pulls, it pays a million. In expectation, arm B wins, by a lot. But if you walk in with a hundred dollars in your pocket, which one do you pick? Arm A. So reducing variance is sometimes a choice, not a law. But for learning, it's almost always worth it.
The critic
Where does v come from? A critic. A value function, learned by policy evaluation. Monte Carlo, or temporal differences. Nothing new. For evaluating, it doesn't even matter how the policy is represented. It does its hocus pocus, you sample it, and you average the returns. So why keep theta around? Because the other half of the system, the actor, needs it. The actor is the one doing policy learning. You can go one step further and bootstrap: use the reward plus the next state's value, instead of the full return. Even less variance, at the price of a little bias.
Actor critic
Put them together: actor critic. The critic updates its weights w by TD. The actor updates theta by a policy gradient. Take an action from the policy. See the reward and the next state. Compute the TD error: reward, plus gamma times the next value, minus the current value. The critic moves its value toward the target, exactly like TD zero. That part is value-based learning, the same as always. The actor moves theta by the same TD error, times the gradient of log pi. If the action turned out better than expected, do it more often.
Everything moves
And it's a loop. A new theta changes which actions we sample. That changes the states and rewards we see. That changes the TD error. Which changes both updates. Everything moves at once. Like Sarsa, in spirit. A bit dizzying, and in practice, it's what most modern reinforcement learning uses. If one of them moves too fast, the other is chasing a moving target. So usually the critic learns a bit faster than the actor.
Our corridor runs
Back to the short corridor. Same start, a poor policy. A hundred runs, a thousand episodes, three methods. REINFORCE on its own: twenty three steps per episode at the start, thirteen point four by the end. With a learned baseline: seventeen and a half at the start, eleven point nine by the end. One-step actor critic: fourteen point six at the start, eleven point nine by the end. The critic helps most early on, when the policy is still bad. A fair warning: each method has its own step sizes, and we didn't tune them to the bone. The ordering is the point, not the decimals.
Trust regions
One more danger. In supervised learning, the data doesn't care about your model. Here, a bad policy collects bad data. Not wrong data. It's part of the dynamics, it has every right to exist. It just doesn't help you. So we don't want to step too far. A popular idea: limit how much the policy changes between updates, measured by the KL divergence, a distance between distributions. Maximise J, minus some penalty times that divergence. That's the idea behind trust region methods like TRPO and PPO. Our run: a three armed bandit. With a step size of five, almost a quarter of the runs had locked onto a worse arm by the end. With point two, none did. Big steps learn fast when they're right, and badly when they're wrong. A trust region is a seat belt.
Recap
So: the critic learns values, the actor learns the policy, and the TD error connects them. Keep the steps small enough that bad data can't take over. And remember, there are many variants. The papers are cute and readable. Chef's recommendation. Next time: what happens when there are infinitely many actions?
A car picks a speed
Picture an autonomous car. The action: how fast to drive, anywhere between zero and a hundred. That's a continuous action. Infinitely many choices. And for value-based methods, that's a headache. How do you even store q for every speed? And how do you find the maximum over infinitely many actions, at every single step? Philosophically, by the way, no engine gives you an infinitely fine throttle. In practice, everything is discrete. But it's continuous enough to hurt. Why not just discretise? Zero to a hundred in steps of one is a hundred and one actions. Now add steering, and braking. It explodes quickly.
A distribution over speeds
With policy gradients, continuous actions are much easier. The policy just has to output a distribution over speeds. Careful with words: the policy isn't Gaussian. It's a function. The distribution it returns over actions can be. So say the action is drawn from a normal distribution, with a mean mu that depends on the state, and a fixed spread, sigma. And here's the cheat. A gradient over an infinite set of actions just became a gradient over two numbers. Mu and sigma. How do you feel about infinite vectors? Not fun. Vectors of size two? Much better. So instead of a value for every possible speed, we learn where to aim, and how much to wobble around it.
The Gaussian gradient
For a Gaussian, the gradient of log pi is simple: the action minus the mean, divided by sigma squared, times the gradient of the mean. Plug that into REINFORCE with a baseline. If the return was better than expected, move the mean toward the action you just tried. If it was worse, move the mean away. The exploration comes for free, from the spread. And sigma can be learned too. Start wide, explore a lot, and narrow down as you become more confident.
Our speed toy
A toy run. The car must pick a speed, and somewhere there's a best speed, sixty three. The closer, the better the reward. The car doesn't know any of this. It starts with a mean of twenty and a spread of ten. Two hundred runs. After about three hundred tries, the average mean is within two of sixty three. By the end, it sits right on it.
Approximately right
The price: we assumed the distribution has a nice parametric shape. That's usually not exactly true. Approximately true, often. If you noticed, this course started perfect. Everything with proofs. And then it went downhill. Approximately here, roughly there. A student once told me it's like cooking or painting. It doesn't need to be perfect. I'm a mathematician. Mathematics is the only profession where things are perfect. We live in a purer world. In practice, you compare against the state of the art, not against the theoretical optimum. Unless you're a student in my lab. Then you compare against the theoretical optimum. Just kidding. A model that's right ninety percent of the time, or one that's right ninety five percent? You take the ninety five, even though both are sometimes wrong.
Climb q
Policy gradients don't lean on the critic very much. If values generalise well, maybe we can lean on them more. Learn q with something like Sarsa. Let the actor output one action, deterministically. Then move the actor up the slope of q, in the direction of better actions. This idea has had many names over the years. Today it's mostly known as the deterministic policy gradient. And it's a form of policy iteration again.
Cacla
One more, and I like it a lot: Cacla. The continuous actor critic learning automaton. It measures the error in action space, not in parameter space. The actor proposes an action. You explore around it, and try a slightly different one. The critic computes the TD error, and updates its value as usual. If the TD error is positive, move the actor toward the action you tried. If it's zero or negative, don't touch the actor at all. Two nice things. It never pushes away from bad actions. And the size of the update doesn't depend on how big the rewards are. If the try was worse, you don't really know which direction is better. So Cacla does nothing, and waits for a good surprise.
The queen, ×100
Why not push away from bad actions? Chess. Sometimes you sacrifice your queen, and a few moves later, you checkmate. Losing the queen looks terrible right away. With Cacla, that moment doesn't teach the actor anything. The win afterwards does. So it doesn't learn never sacrifice a queen. It learns sacrifice, then mate, is a good idea. We tested the second property on our speed toy. Multiply every reward by a hundred, and keep the step size. The Gaussian policy gradient blew up in all two hundred runs. Cacla didn't even notice: the same three hundred tries to reach sixty three.
Module ten, done
That's module ten. Learn the policy directly. Climb the gradient with the score function trick, and calm the noise with a baseline and a critic. Keep your steps small. And when actions are continuous, let a distribution do the exploring, or let Cacla follow the good surprises. Next module: learning about many things at once. General value functions.
5:12Episode 38Why learn the policy?Sometimes the best policy is simpler than the world.
5:19Episode 39The score-function trickWeigh ∇log π by the reward, minus a baseline.
5:12Episode 40The policy gradient theoremPolicy gradients never need the dynamics.
5:07Episode 41Actor and criticThe critic judges; the actor follows the TD error.
5:08Episode 42Infinitely many actionsLet a distribution do the exploring.
Interactive lab
Policy-gradient bandit lab
Learn a softmax policy directly with the gradient-bandit (REINFORCE) update, with or without a baseline. Shift every reward up by a constant and see why the baseline matters.
Ten arms, each paying a noisy reward around its own hidden mean. The policy is a softmax over preferences H, and each pull moves H along the score-function gradient: H(a) += α (R − b)(1[a = A] − π(a)). The setup follows Sutton and Barto (Section 2.8).
Learn the policy, not the values
Ten arms. Arm a pays a reward drawn around its hidden mean q*(a), with spread 1; the means are drawn around the reward offset.
Raise the arm you pulled if its reward beat the baseline b, lower the others, and the reverse if it did worse.
Any b leaves the expected gradient unchanged, but a good b cuts its variance. With b = 0 and rewards around +4, every pulled arm gets pushed up.
A fresh bandit: every arm has probability 0.10.
Policy over the arms
Bar height: π(a). Under each bar, the hidden mean q*(a); the best arm is green.
How often it picks the best arm
Your run: share of the last 50 pulls that went to the best arm.
Play
A game that goes with this lecture, and what to look for while you play.
Echo Heist
Teach a little robot. Steal back a city.
In this lecture: Echo Heist can train a policy-gradient learner too: a policy that is learned directly, with no value table behind it.
Choose what your partner Echo senses, which actions it can take and what success means, then let a real learner train in your browser: tabular, planning, policy-gradient, deep-RL or imitation. When the door opens, the policy is frozen and Echo runs with what it learned.

