Actor-Critic Methods

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.

Score the actor three ways

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

Why the Policy Gradient Needs a Critic

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.

Count how often luck wins

Teal bars are the returns after right. Grey bars are the returns after left. Drag the luck and watch them overlap.

±2

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.

The road

  1. Value, Q and the advantage: how good a state is, how good an action is, and the gap.
  2. A learned value steadies the gradient: baselines, and the three scores of the hero.
  3. Discount factors: why late rewards count less.
  4. Fitting the critic: Monte Carlo against bootstrapped targets.
  5. The TD error: a one-step advantage that blames the right step.
  6. n-step returns and GAE: the knob between the two targets.
  7. The actor-critic loop: train three learners side by side.
  8. Batches, workers and network shapes: many samples per update.
  9. The field guide: numbers, code, links and credit.
Right is the better first action. Why can an episode that went right earn less than one that went left?

Chapter 1

Value, Q and the Advantage

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.

QuestionNameOn 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.

Say it aloud

A-pi of s and a equals Q-pi of s and a, minus V-pi of s.

Aπ(s,a)
A-pi of s and a the advantage: how much better action a is than the policy's usual choice in state s.
Qπ(s,a)
Q-pi of s and a the reward you expect from s if you take a first, then follow the policy.
Vπ(s)
V-pi of s the reward you expect from s if you follow the policy from the start.
π
pi the policy: the actor's probability for each action in each state.
In plain words

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.

With numbers

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.

Move the policy and watch the value move

Purple bars are the two Q values. The line is the value. Blue arrows are the advantages. Drag the chance of right.

30%

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.

The policy picks right with chance 0.3 and left with 0.7. Q(right) = 5 and Q(left) = 2. What is A(right)?

Chapter 2

A Learned Value Steadies the Gradient

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.

Say it aloud

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.

∇θJ(θ)
grad-theta of J the direction to move θ that raises the expected return J fastest.
(1/N) Σi
one over N, sum over i the average over N sampled episodes.
Σt
sum over t one term for each step t of the episode.
∇θ log πθ(a | s)
grad-theta log pi-theta of a given s the direction that makes action a more likely in state s.
Â
A-hat the score for that action. The hat means an estimate.
In plain words

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.

With numbers

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.

ScoreWhat it isSpread of the pushPushes the right way
Full returnR, every reward of the episode2.1638%
Return minus baselineR − 2.9, the average return1.1973%
Critic advantager + V̂(s′) − V̂(s)0.55100%

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.

Why a baseline does not move the average

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.

Slide the baseline

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.

0.0

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.

Why does subtracting a baseline b(s) leave the average policy gradient unchanged?

Chapter 3

Discount Factors

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.

Say it aloud

G-t equals the sum over k from zero to infinity of gamma to the k, times r of t plus k.

Gt
G-t the discounted return from step t.
Σk=0∞
the sum over k from zero to infinity one term for each step ahead, from now (k = 0) on.
γk
gamma to the k the discount: gamma multiplied by itself k times.
rt+k
r of t plus k the reward k steps after step t.
In plain words

Take each future reward. Multiply it by gamma once for each step of delay. Add them up. The total is G-t.

With numbers

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.

Slide gamma and watch the horizon

Each bar is the weight of a reward k steps away. The dashed line is the effective horizon. Drag gamma.

0.90

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.

With γ = 0.99, about how many steps ahead does the agent look?

Chapter 4

Fitting the Critic

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.

Say it aloud

y-t equals r-t plus gamma times V-hat-phi of s t plus one.

yt
y-t the target for the critic at step t.
rt
r-t the reward the agent got at step t.
γ
gamma the discount factor, between 0 and 1.
V̂φ(st+1)
V-hat-phi of s t plus one the critic's current guess of the value of the next state.
In plain words

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.

With numbers

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.

Say it aloud

L of phi equals one half the sum over t of V-hat-phi of s-t minus y-t, squared.

L(φ)
L of phi the critic's loss. Lower is better.
½ Σt
one half, sum over t add over every visited step. The half cancels when you take the gradient.
V̂φ(st)
V-hat-phi of s-t the critic's output for the state at step t.
yt
y-t the target, held fixed during the update.
In plain words

Square the gap between each output and its target. Add the squares. Move phi a little downhill on that sum.

With numbers

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.

Compare the two targets

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.

+1.00

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.

PropertyMonte CarloBootstrapped (TD)
Biasnonethe critic's error
Variancehigh: every later rewardlow: one reward
Needs the episode to endyesno

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.

The critic's guesses are 3 points too high in every state. Which target inherits that error?

Chapter 5

The TD Error Is a One-Step Advantage

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).

Say it aloud

Delta-t equals r-t plus gamma V-hat of s t plus one, minus V-hat of s-t.

δt
delta-t the TD error at step t: the critic's surprise.
rt
r-t the reward at step t.
γ V̂(st+1)
gamma V-hat of s t plus one the shrunk value of the next state. It is 0 if the episode ended.
V̂(st)
V-hat of s-t the value of the state before the step.
In plain words

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.

With numbers

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.

Step the hallway and compare the blame

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.

In the hallway the robot slips at step 2. Which steps does the TD error blame?

Chapter 6

n-Step Returns and GAE

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.

Say it aloud

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.

yt(n)
y-t-n the n-step target for step t.
Σk=0n−1
the sum over k from zero to n minus one the next n rewards.
γk rt+k
gamma to the k, r of t plus k each real reward, shrunk by its delay.
γn V̂(st+n)
gamma to the n, V-hat of s t plus n the critic's guess for the state n steps later, shrunk n times.
In plain words

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.

With numbers

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.

Say it aloud

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.

ÂtGAE
A-hat-t GAE the advantage estimate for the action at step t.
Σl=0∞
the sum over l from zero to infinity one term for each step ahead.
(γλ)l
gamma-lambda to the l the weight: gamma times lambda, multiplied l times. Lambda is between 0 and 1.
δt+l
delta of t plus l the TD error l steps later.
In plain words

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.

With numbers

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.

Trade bias for spread

Top: how much each term counts. Bottom: squared bias, variance and their sum. Move n or lambda, then change the critic's error.

3
1.5

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.

What does GAE give with λ = 0?

Chapter 7

The Actor-Critic Loop

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:

  1. Run the actor to collect a batch of episodes.
  2. Fit V̂φ to targets from the batch: Monte Carlo, TD or n-step.
  3. Score every step: δ = r + γV̂φ(s′) − V̂φ(s), or GAE.
  4. Push θ along the policy gradient with those scores.
  5. Repeat with fresh episodes from the new actor.

The online version updates after every step:

  1. Take action a in state s. See the reward r and the next state s′.
  2. Compute δ = r + γV̂φ(s′) − V̂φ(s).
  3. Critic: move V̂φ(s) toward r + γV̂φ(s′).
  4. Actor: move θ by its step size, times δ, times grad-log-pi of a given s.

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.

Train three learners side by side

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.

4.0
0.20

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.

In the online loop, what does the actor multiply grad-log-pi by?

Chapter 8

Batches, Parallel Workers and Network Shapes

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.

WayHow it worksCost
SynchronousEvery 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.

Add workers

Each lane is a worker and each dot a transition. Watch how updates gather them. Drag the number of workers and switch the mode.

8

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%.

Shared or separate networks

ChoiceWhat it isFor itAgainst itSeen in
Separateone network for the actor, one for the criticeach learns its own features; stabletwice the weights and computePPO on its robot tasks
Sharedone trunk with two headsfeatures learned once; cheaperthe critic's gradient can disturb the actor's featuresA3C; 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.

Why are eight steps from eight workers better than eight steps from one worker?

Chapter 9

The Field Guide

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.

The terms

TermMeaning
ActorThe policy network πθ. It acts, and it is what you deploy.
CriticThe 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.
BaselineA number that depends on the state only. Subtracting it cuts noise and keeps the average.
BootstrappingUsing your own estimate inside your training target.
TD error δr + γV̂(s′) − V̂(s): the critic's one-step surprise.
GAEA sum of TD errors with weights (γλ) to the l.
Effective horizon1/(1 − γ): about how far ahead the agent looks.

The numbers

WhatNumberWhy it matters
Hero chain: spread of the push2.16, 1.19, 0.55Full return, minus baseline, critic advantage; same average 0.63
Hero chain: right-way pushes38%, 73%, 100%The critic removes the luck of later steps
Best fixed baseline on the chain4.1 (value 2.9)The value is close to the best baseline, not equal
Effective horizonγ 0.9: 10; 0.99: 100Pick gamma to cover the delay to the reward
TD against Monte Carlo, chainTD wins while the critic is off by under 2.3Bias against variance, stated as a number
PPO paper defaults, robot tasksγ 0.99, λ 0.95A common starting point for GAE
8 workersspread 35% of one stepIndependent samples average down as 1/√N

The checklist

The core as code

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()

Keep going

The takeaway. Learn what is good (the critic), then do more of it (the actor). The critic's TD error keeps the policy gradient's average and drops most of its noise.
What is the one change from a policy gradient with a baseline to an actor-critic?

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.

Credit and source

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.

Actor-Critic Methods
CS 224R course site · Lecture 4 slides · GAE paper · Back to Gleams