A policy gradient scores each action by what happened after it, and luck makes that score noisy. On the toy chain below, the full return points the update the right way in only 38 of 100 episodes. A critic's one-step advantage gets all 100 right, with the same average.
Pick the score the actor gets, then press Sample. Each dot is the push one episode gives the actor. Then we build, piece by piece, the value function, the critic, the targets it learns from and the loop that trains both.
You need the policy gradient (the actor makes actions that did well more likely; see Policy Gradients) and a little Python. We build the rest from zero.
Based on Lecture 4, Actor-Critic Methods, of Stanford CS 224R: Deep Reinforcement Learning, taught by Chelsea Finn (slides PDF). GAE comes from Schulman et al. (arXiv 1506.02438) and A3C from Mnih et al. (arXiv 1602.01783). The explanations, toys and devices here are our own.
An illustrative toy. The actor picks right with probability 0.3. Right pays 1, then 2 per step; left pays 0, then 1 per step; luck adds −2, 0 or +2 at each later step. The critic here is exact. Exact over all outcomes: the push has spread 2.16, 1.19 and 0.55 for the three scores, and average 0.63 for all three.
Chapter 0
See how one episode's luck hides which action was good
A robot does a task three steps long. At the first step it picks right or left. Right earns 1 point now and leads to a stretch that pays 2 points a step. Left earns 0 and leads to a stretch that pays 1 point a step. At each later step, luck adds or takes away up to 2 points.
The policy gradient scores each action with the return, the sum of the rewards after it. Then it makes actions with high scores more likely. The return mixes two things: the effect of the choice, and luck from steps the choice did not control.
Teal bars are the returns after right. Grey bars are the returns after left. Drag the luck and watch them overlap.
The toy chain of the hero. Luck adds −k, 0 or +k at each of the two later steps, with equal chance. Percentages are exact over all 81 pairs of episodes.
With luck of 2 points a step, a left episode beats a right episode in 15 of 81 pairs, 19% of the time. Each such pair teaches the actor the wrong lesson. More samples average the luck away, but each sample costs robot time.
Symptom: the learning curve jumps from batch to batch, and the policy drifts the wrong way for a while.
Measure: sample the gradient several times from the same policy. If the signs disagree often, the score is too noisy.
Fix: a better score. That is this lesson.
The fix is a second network, the critic, that learns how much reward to expect from each state. We score the policy, now called the actor, against that expectation. The critic knows the average, so luck from later steps stops counting against the action.
Chapter 1
Name how good a state is, how good an action is, and the gap between them
Stand at the start of the chain with the current policy. Ask three questions. How much reward do I expect from here? How much if I go right first? How much better is right than my usual habit?
The value of a state is the reward you expect from it if you follow the policy from there on. The Q value of a state and an action is the reward you expect if you take that action first, then follow the policy. Both are averages over many episodes, so luck cancels out.
| Question | Name | On the chain, policy picks right 30% of the time |
|---|---|---|
| How good is right here? | Q(s0, right) | 1 + 2 + 2 = 5 |
| How good is left here? | Q(s0, left) | 0 + 1 + 1 = 2 |
| How good is this state? | V(s0) | 0.3 × 5 + 0.7 × 2 = 2.9 |
The value is the Q values averaged with the policy's own probabilities. The gap between an action's Q value and the state's value is the advantage.
A-pi of s and a equals Q-pi of s and a, minus V-pi of s.
Take the reward you expect after action a. Subtract what you expect from state s on average. Positive A beats the habit; negative A falls short.
On the chain, A(s0, right) = 5 − 2.9 = 2.1 and A(s0, left) = 2 − 2.9 = −0.9. Weighted by the policy, 0.3 × 2.1 + 0.7 × (−0.9) = 0.
Purple bars are the two Q values. The line is the value. Blue arrows are the advantages. Drag the chance of right.
The toy chain. The Q values stay fixed because the later steps do not depend on the policy here.
Push the chance of right up and the value climbs toward Q(right). The advantage of right shrinks. Once the actor mostly goes right, right is no longer much better than the habit.
Symptom: the advantages in one state are all positive, or all negative.
Measure: average them with the policy's weights. The result should be near zero.
Fix: if it is not, the value estimate is out of date. Refit it on fresh episodes.
Chapter 2
Swap the noisy return for an advantage and keep the average the same
The policy gradient is a recipe for nudging the actor. At each step, find the direction that makes the chosen action more likely. Scale it by a score for that action. Average over all steps.
Name the parts first. The actor's weights are θ (theta). The chance of action a in state s is pi-theta of a given s. The expected return is J. The score is an estimate of the advantage, A-hat.
Grad-theta of J is about one over N, times the sum over i and t, of grad-theta log pi-theta of a given s, times A-hat.
At every step, push θ toward the action taken, as hard as A-hat says. Positive A-hat makes the action more likely; negative makes it less likely. Average the pushes.
The chain's actor has one weight, and grad-log-pi is 1 − 0.3 = 0.7 after right. One episode went right with A-hat = 2.1, so the push is 0.7 × 2.1 = 1.47. A step of size 0.5 moves the chance of right from 0.30 to 0.47.
Three scores fit in the place of A-hat. All three have the same average push, 0.63. Their spread, the standard deviation over episodes, differs a lot.
| Score | What it is | Spread of the push | Pushes the right way |
|---|---|---|---|
| Full return | R, every reward of the episode | 2.16 | 38% |
| Return minus baseline | R − 2.9, the average return | 1.19 | 73% |
| Critic advantage | r + V̂(s′) − V̂(s) | 0.55 | 100% |
A baseline is a number that depends on the state but not on the action. Subtracting it keeps the average push the same, because the pushes toward every action, weighted by the policy, cancel.
The average push from a baseline b is b times the policy-weighted sum of grad-log-pi. That sum is zero, because the probabilities always add to one:
Σa π(a|s) ∇ log π(a|s) = Σa ∇π(a|s) = ∇ 1 = 0
On the chain: 0.3 × 0.7 + 0.7 × (−0.3) = 0.
The curve is the spread of the push for each baseline. The average stays at 0.63 everywhere. Drag the baseline and find the bottom.
Exact over all 18 outcomes of the toy chain. The lowest spread for a fixed number is at 4.1, near the value 2.9 but not on it.
So the value is not the lowest-noise baseline. It is close, easy to learn, and turns the score into the advantage. The critic also replaces the luck of later steps with their expected value, so its line sits lower still.
Symptom: learning needs huge batches before it moves at all.
Measure: the spread of the gradient across repeated batches from one policy.
Fix: subtract V̂(s), then switch to the critic's advantage.
Chapter 3
Shrink late rewards so sums stay finite and the critic sees a shorter future
A walking robot gets a reward every step, for hours. Add up every future reward and the sum grows without limit. The value of every state becomes infinite, and the critic has nothing to learn.
The fix is to count a reward less the longer you wait for it. Call the reward at step t r-t. Pick a number γ (gamma) between 0 and 1, the discount factor. Multiply a reward k steps away by gamma to the k.
G-t equals the sum over k from zero to infinity of gamma to the k, times r of t plus k.
Take each future reward. Multiply it by gamma once for each step of delay. Add them up. The total is G-t.
Five rewards of 1 with γ = 0.9: G = 1 + 0.9 + 0.81 + 0.73 + 0.66 = 4.10. With γ = 0.99 it is 4.90; with γ = 0.5 it is 1.94.
Each bar is the weight of a reward k steps away. The dashed line is the effective horizon. Drag gamma.
Pure arithmetic, no toy model. The horizon 1/(1 − γ) is the sum of all the weights.
The weights add up to 1/(1 − γ). That number is the effective horizon: about how many steps ahead the agent looks. Gamma 0.9 gives 10 steps; 0.99 gives 100. Another reading: gamma is the chance the episode goes on one more step.
Discounting trades bias for variance, like the critic does. Far rewards are the noisiest part of a return, and gamma shrinks them. The price is a slightly different goal that cares less about the far future. Every later chapter carries gamma.
Symptom: the agent grabs a small reward now and ignores a big one later.
Measure: compare the delay to the big reward with 1/(1 − γ).
Fix: raise gamma until the horizon covers the delay. 0.99 is a common default.
Chapter 4
Train the value network on Monte Carlo or bootstrapped targets, and choose between noise and bias
The critic is a network V-hat-phi with weights φ (phi). It takes a state and outputs one number. We train it like any regression: show it a state and a target y, then shrink the squared gap. The open question is where the targets come from.
Name the parts of the bootstrapped target. The reward at step t is r-t. The next state is s of t plus 1. The critic's current guess for it is V-hat-phi of that state.
y-t equals r-t plus gamma times V-hat-phi of s t plus one.
Take the reward you saw. Add the critic's guess for where you landed, shrunk by gamma. That is the label for the state you left.
Made-up numbers, γ = 0.9: the agent goes from A to B and gets r = 1. The critic says V̂(B) = 5, so y(A) = 1 + 0.9 × 5 = 5.5.
L of phi equals one half the sum over t of V-hat-phi of s-t minus y-t, squared.
Square the gap between each output and its target. Add the squares. Move phi a little downhill on that sum.
Made-up: V̂(A) = 2 with y = 5.5, and V̂(B) = 5 with y = 10.2. L = ½ × (12.25 + 27.04) = 19.6. A table critic with step size 0.1 moves V̂(A) from 2 to 2.35.
Each dot is one target for V(s0) from one episode. The dashed line is the true value, 2.9. Drag the critic's error.
The toy chain. The critic's guess for both next states is off by the error. The bars are exact over all outcomes: squared bias plus variance.
| Property | Monte Carlo | Bootstrapped (TD) |
|---|---|---|
| Bias | none | the critic's error |
| Variance | high: every later reward | low: one reward |
| Needs the episode to end | yes | no |
On this chain, TD wins until the critic is off by 2.3. Early in training the critic is poor; later it is good.
Symptom: the critic's loss falls, but its values creep up and never settle.
Measure: compare V̂ with Monte Carlo returns on a few held-out episodes.
Fix: TD targets chase the critic's own errors. Take smaller steps, use longer targets (Chapter 6), or compute targets from a slowly updated copy of the critic.
Chapter 5
Score each action by the surprise it caused, at the step where it happened
A robot walks a hallway of five steps. Each step costs 1 point and the last step pays 10. At step 2 the floor is wet: one walk in five slips there, scores −5 and ends. The critic has learned the values under this policy.
The actor needs A = Q − V, but we only fit the value. One sampled step gives a cheap Q: the reward you got plus the value of where you landed. Subtract the value of where you were. The result is the TD error δ (delta).
Delta-t equals r-t plus gamma V-hat of s t plus one, minus V-hat of s-t.
Add the reward to the shrunk value of the next state. Subtract the value of the state you left. Positive delta means the step went better than the critic expected.
In the hallway γ = 1 and V̂(s2) = 5.4. A slip gives r = −5 and no next state: δ = −5 + 0 − 5.4 = −10.4. A safe step gives δ = −1 + 9 − 5.4 = 2.6.
Warm numbers are rewards; purple numbers are the critic's values. Blue bars are the score each step's action gets. Pick a walk and a score, then step.
A toy hallway, γ = 1. The values 3.4, 4.4, 5.4, 9 and 10 are exact for a robot that walks forward and slips at step 2 one time in five.
With the return-to-go score, a slip gives steps 0, 1 and 2 all −10.4. The actor learns to avoid its first two steps, which did nothing wrong. With delta, steps 0 and 1 score 0, because they went as expected. Only step 2 gets −10.4.
With an exact critic, delta is a fair sample of the advantage: averaged over what happens next, r + γV(s′) is Q(s, a). With a learned critic, delta carries the critic's error, the trade of Chapter 4.
Symptom: delta stays large and keeps one sign after many updates.
Measure: average delta over a batch. It should hover near zero.
Fix: the critic lags the actor. Give the critic more updates or a larger step size.
Chapter 6
Use n real rewards before you trust the critic, and blend every n with one knob
Monte Carlo trusts all the rewards. TD trusts one reward and then the critic. Between them sits a family: take n real rewards, then add the critic's guess for the state n steps later.
y-t-n equals the sum over k from zero to n minus one of gamma to the k r of t plus k, plus gamma to the n V-hat of s t plus n.
Add the next n rewards, each shrunk per step of delay. Add the critic's guess for the state you reach. n = 1 is TD; n to the end is Monte Carlo.
Made-up: rewards 1, 1, 1; critic values 5, 6, 7, 8 along the way; γ = 0.99. One-step: 1 + 0.99 × 6 = 6.94. Two-step: 1 + 0.99 + 0.98 × 7 = 8.85.
Generalized advantage estimation (GAE, Schulman et al.) averages all n-step advantages at once. Each extra step's weight falls by a factor λ (lambda). The result is a sum of TD errors.
A-hat-t GAE equals the sum over l from zero to infinity of gamma-lambda to the l, times delta of t plus l.
Take delta now, plus the next delta shrunk by gamma-lambda, plus the one after shrunk twice. Lambda 0 keeps only delta-t; lambda 1 gives the Monte Carlo return minus V-hat.
Same numbers, λ = 0.95, so γλ = 0.9405. The deltas are 1.94, 1.93, 1.92. From the end: 1.92; 1.93 + 0.9405 × 1.92 = 3.74; 1.94 + 0.9405 × 3.74 = 5.45.
Top: how much each term counts. Bottom: squared bias, variance and their sum. Move n or lambda, then change the critic's error.
Toy model: γ = 0.9, reward noise with standard deviation 1 per step, and the critic off by the same amount in every state. Real errors are messier.
A good critic favours small n; a poor critic favours long returns. Switch to GAE: there the best lambda often lands in the middle, because a little lambda cuts the bias at once while the variance barely moves. The critic also starts poor and gets better, so a middle setting is a safe hedge. The lecture notes that n between 1 and the episode length often works best. The PPO paper used γ = 0.99 and λ = 0.95 on its robot tasks.
Symptom: advantages swing wildly in long episodes.
Measure: the spread of A-hat across a batch.
Fix: lower lambda, or n, to lean more on the critic.
Chapter 7
Run the actor, fit the critic, score with the critic, push the actor, and repeat
The batch version, the lecture's full algorithm, waits for whole episodes:
The online version updates after every step:
One online step with made-up numbers: V̂(s) = 2, r = −1, V̂(s′) = 4, γ = 0.95. Delta is −1 + 3.8 − 2 = 0.8. A critic step of 0.2 moves V̂(s) to 2.16. With a 50% chance of the action and an actor step of 0.1, θ moves by 0.1 × 0.8 × 0.5 = 0.04.
A corridor of six cells: the goal pays 10, each step costs 1. The three learners share the actor and its step size and differ only in the score. Press Train.
An illustrative toy: γ = 0.95, a table actor and a table critic (one number per cell), actor step 0.1, episodes capped at 20 steps. Reward-to-go learners update after each episode; the actor-critic updates every step. The best possible return is 4.44. The first run is one where the reward-to-go learners get stuck; New run shows others.
Press New run several times. Most runs of all three learners reach the goal. Some reward-to-go runs get stuck: an unlucky early stretch drives the policy to always go left, where its gradient is almost zero. Over 60 runs at noise 4, return to go got stuck in 7 and minus average in 10. The actor-critic got stuck in none, because each delta carries one step's noise.
Now set the critic step to 0.01. The actor-critic starts slowly, because its scores lean on a critic that has not learned yet. At 0 the critic never learns, and 26 of 30 runs fail.
Symptom: the return climbs, then collapses.
Measure: plot the critic's loss and the average delta next to the return.
Fix: if the critic lags, raise its step size or give it more updates per actor update. If the actor jumps, shrink its step size.
Chapter 8
Get many unrelated samples per update, and decide what the actor and critic share
Online actor-critic learns from one step at a time. Consecutive steps of one episode look alike: the same room, almost the same pose. A batch of eight steps from one robot carries less news than eight steps from eight robots. A neural network trained on such similar samples drifts toward whatever it saw last.
The fix is parallel workers: N copies of the environment, each running the actor at the same time.
| Way | How it works | Cost |
|---|---|---|
| Synchronous | Every worker takes one step. The N transitions form one batch and one update. | Waits for the slowest worker. |
| Asynchronous (A3C) | Each worker computes its own update and applies it when ready. | Each update uses weights a few versions old. |
Each lane is a worker and each dot a transition. Watch how updates gather them. Drag the number of workers and switch the mode.
The spreads assume consecutive steps of one worker share a correlation of 0.6 and separate workers are independent. Illustrative.
With 8 independent workers, the spread of the averaged update falls to 1/√8, which is 35% of one step's spread. Eight steps from one worker with correlation 0.6 fall only to √((1 + 7 × 0.6) / 8), which is 81%.
| Choice | What it is | For it | Against it | Seen in |
|---|---|---|---|---|
| Separate | one network for the actor, one for the critic | each learns its own features; stable | twice the weights and compute | PPO on its robot tasks |
| Shared | one trunk with two heads | features learned once; cheaper | the critic's gradient can disturb the actor's features | A3C; PPO on Atari |
With a shared trunk, the training loss is a sum: the actor's loss plus a weight times the critic's squared error. That weight is one more knob to tune. With separate networks, each has its own step size, and the critic often needs to learn at least as fast as the actor.
Symptom: training is unstable even with a good critic.
Measure: count how many different episodes each update sees.
Fix: add workers, or collect a longer batch before each update.
Chapter 9
Keep the terms, the numbers, a checklist and the core code on one page
Actor-critic is a policy gradient with a learned score. The critic learns the value of each state from Monte Carlo, TD or n-step targets. The actor's score is the TD error or GAE, which keeps the average push and cuts the noise. Gamma sets how far ahead both look. Parallel workers give each update many unrelated samples.
| Term | Meaning |
|---|---|
| Actor | The policy network πθ. It acts, and it is what you deploy. |
| Critic | The value network V̂φ. It scores the actor during training. |
| Value V(s) | Expected discounted return from state s under the policy. |
| Q value Q(s, a) | Expected return if you take a first, then follow the policy. |
| Advantage A(s, a) | Q(s, a) minus V(s): how much better a is than the habit. |
| Baseline | A number that depends on the state only. Subtracting it cuts noise and keeps the average. |
| Bootstrapping | Using your own estimate inside your training target. |
| TD error δ | r + γV̂(s′) − V̂(s): the critic's one-step surprise. |
| GAE | A sum of TD errors with weights (γλ) to the l. |
| Effective horizon | 1/(1 − γ): about how far ahead the agent looks. |
| What | Number | Why it matters |
|---|---|---|
| Hero chain: spread of the push | 2.16, 1.19, 0.55 | Full return, minus baseline, critic advantage; same average 0.63 |
| Hero chain: right-way pushes | 38%, 73%, 100% | The critic removes the luck of later steps |
| Best fixed baseline on the chain | 4.1 (value 2.9) | The value is close to the best baseline, not equal |
| Effective horizon | γ 0.9: 10; 0.99: 100 | Pick gamma to cover the delay to the reward |
| TD against Monte Carlo, chain | TD wins while the critic is off by under 2.3 | Bias against variance, stated as a number |
| PPO paper defaults, robot tasks | γ 0.99, λ 0.95 | A common starting point for GAE |
| 8 workers | spread 35% of one step | Independent samples average down as 1/√N |
pythonimport torch, torch.nn.functional as F def gae(r, v, done, gamma=0.99, lam=0.95): # r, done: [T]; v: [T+1] critic values adv, last = torch.zeros_like(r), 0.0 for t in reversed(range(len(r))): keep = 1.0 - done[t] # no value after the episode ends delta = r[t] + gamma * v[t+1] * keep - v[t] # the TD error last = delta + gamma * lam * keep * last # A_t = delta_t + gamma*lam*A_{t+1} adv[t] = last return adv def update(actor, critic, opt_a, opt_c, obs, act, r, done, last_obs): v = critic(torch.cat([obs, last_obs[None]])).squeeze(-1) # [T+1] adv = gae(r, v.detach(), done) target = adv + v[:-1].detach() # critic target: GAE return critic_loss = 0.5 * F.mse_loss(v[:-1], target) opt_c.zero_grad(); critic_loss.backward(); opt_c.step() adv = (adv - adv.mean()) / (adv.std() + 1e-8) # normalize per batch logp = actor(obs).log_prob(act) # [T] actor_loss = -(logp * adv).mean() # minus, because optimizers go downhill opt_a.zero_grad(); actor_loss.backward(); opt_a.step()
Now press Present or Teach and explain from memory: V, Q and the advantage, the two critic targets, the TD error, GAE and the loop. Then go back to the hero and say why each score spreads as it does.
This lesson re-teaches Lecture 4, Actor-Critic Methods, of Stanford CS 224R, Deep Reinforcement Learning, taught by Chelsea Finn. The course site is cs224r.stanford.edu and the slides are the lecture 4 PDF; the lecture credits its discount slides to Sergey Levine. GAE is from Schulman et al., High-Dimensional Continuous Control Using Generalized Advantage Estimation, and A3C from Mnih et al., Asynchronous Methods for Deep Reinforcement Learning. The toys, numbers and devices are our own.