Actor-critic methods: advantages, GAE, A2C and soft actor-critic
Before this lesson: the policy gradient theorem, baselines and the advantage (lesson 07); TD errors, -step returns and the λ-return (lesson 04); DQN, target networks and replay buffers (lesson 06); the maximization bias (lesson 05); entropy (information theory 01); the reparameterization trick (calculus 12). Time: about 85 minutes, plus the notebook.
Why this matters #
Almost every deep RL algorithm used today is an actor-critic method.
- PPO (lesson 09) is an actor-critic method with GAE (usually ). It trains robots in simulation, game agents such as OpenAI Five, and language models in RLHF, where the critic is a "value head" on the language model.
- SAC and TD3 are standard for continuous control from raw experience: robot locomotion and manipulation in MuJoCo and on real robots, where data is expensive and reuse matters.
- AlphaGo and AlphaZero (lesson 10) have a policy head and a value head, the same two parts.
- The maximum-entropy view of SAC returns in RL for language models: the KL-regularized objective of RLHF has the same soft-greedy optimum, (lesson 09).
1. Predict first #
2. The picture #
The actor and the critic #
From lesson 07, the policy gradient is , and REINFORCE estimates the advantage by . An actor-critic method learns a value function with parameters (the critic) and uses it in two ways: as the baseline, and to replace most of the sampled return by a prediction.
The simplest estimate uses one real reward and then the critic. This is the TD error of lesson 04:
If the critic were exact (), then . So is an advantage estimate that uses only one random reward and one random next state.
The two parts help each other. The critic gives the actor a low-variance signal after every step, without waiting for the episode to end. The actor changes the policy, and the critic follows it. But a wrong critic gives the actor a wrong signal: this is the bias of actor-critic methods.
Press "1 step (slow)" a few times, then "100 steps". The robot vacuum of lesson 01: the boxes show the actor's policy (orange bars) and the critic's values (blue bars) in the states H and L. The slow step shows the five phases of one update. The charts show and against the optimal values (dashed), and the probabilities of the optimal actions. Watch in the first 100 steps: the critic starts at , so "clean" (reward 1 now) looks better than "charge" (reward 0 now) until the critic learns that is large.
Short or long: k-step advantage estimators #
Between (one real reward) and (all real rewards) there is a family. The -step advantage estimator uses real rewards and then the critic:
- : . Low variance (one random reward), but biased when .
- (to the end of the episode): . This is REINFORCE with the baseline : no bias in the policy gradient for any , but high variance.
Where does the bias come from? Write the critic as , with an error . Then
The last term, , depends only on the state, so it acts like a baseline and does not bias the policy gradient (lesson 07). The middle term is the real bias: the critic's error at the state where we bootstrap, discounted by . More real rewards push the bootstrap point further away and shrink this term, but each real reward adds noise.
Move the critic error and the reward noise , then find the best . A chain of 20 steps, each with a reward , . The critic is wrong by in every state. The top chart shows the error of 40 sampled estimates (the orange dots are at the current setting) and their mean, the bias. The bottom chart shows bias², variance and their sum, the mean squared error, for every . Switch to "k-step" to see the same trade-off for . A perfect critic favours small ; a bad critic and quiet rewards favour near 1.
The figure measures the error of as an estimate of . This removes the harmless baseline term , and it is the same quantity as the error of the value target that trains the critic.
A critic gives and . At step 0 the reward is , , and the episode does not end. What is ?
. The answer forgets the discount on , and forgets to subtract . A positive tells the actor that the action did better than the critic expected.
3. Definitions and main results #
Generalized advantage estimation #
The λ-return of lesson 04 averages -step returns with weights . GAE (Schulman et al., 2016) does the same with the -step advantage estimators.
Theorem (GAE). For and a critic ,
In particular, gives , and gives .
Proof.
1. Telescoping. For every ,
In the second sum, each cancels the next term's ; only is left.
2. Insert step 1 into the definition: .
3. Swap the two sums. The term appears for every . Its total weight is
for . So .
4. : only is left (with ), so .
5. (defined by the right-hand side, the limit of the left): is the telescoping sum of step 1 with . The boundary term is 0 after the episode ends (and tends to 0 when and is bounded), so the sum is .
If the episode ends steps after , every with is the same full estimate , so all the remaining weight lands on it, exactly as for the λ-return. And is the λ-return with the critic as the bootstrap: the usual value target for the critic.
With an exact critic every is unbiased. If , then , and for , because later actions also follow . So for every . With an imperfect critic, a smaller means more bias and less variance.
In GAE, what are the estimates for and for ?
With only the first term of survives: the one-step TD error (low variance, biased by the critic). With the TD errors telescope to the Monte Carlo return minus the baseline (unbiased policy gradient, high variance). The first option swaps them; it is the most common slip.
Computing GAE: the backward recursion #
The sum satisfies . So one backward pass over a rollout computes all advantages. A rollout of steps (it may contain several episodes) has:
- rewards and critic values ;
- done flags : means the episode ended with step ( is terminal);
- the bootstrap value , the critic's value of the state after the last step.
for . The value targets are . The factor does two jobs: no bootstrapping from a terminal state, and no advantage flows back across the end of an episode into the previous one.
Termination or truncation. An episode can stop for two different reasons.
- Termination: the task really ended (the robot fell, the game was won). The value after it is 0. Set .
- Truncation: we stopped collecting data (a time limit, or the end of the rollout buffer). The next state is a normal state with a nonzero value. Do not cut the return to 0: bootstrap with of the real next state.
The end of every rollout buffer is a truncation; that is what the bootstrap value is for. Gymnasium
reports the two cases separately (terminated and truncated); only terminated should become .
Press "Step back" until all steps are computed. The data is the worked example below: rewards, values, done flags, and the bootstrap value on the right. Each step shows and in violet; the violet arrow carries back, and it is cut at a dashed line where an episode ends. Click a done flag to toggle it. Make the last step terminal: is no longer used.
Your rollout buffer has 128 steps, and the episode is still running at the last step. How should GAE treat step 127?
The episode did not end; only our data collection stopped. The return after step 127 is not 0, and the best guess for it is . Setting treats a truncation as a termination: every advantage near the end of the buffer is then biased downward (for positive rewards), and the critic learns that states near the cut have low value.
and have different jobs. is part of the objective: it decides how much the agent cares about later rewards (an effective horizon of about steps). Even with a perfect critic, a smaller changes which policy is best. is only part of the estimator: with a perfect critic, every gives an unbiased advantage for the same objective. With an imperfect critic, trades its bias against the variance of the rewards. Common choices are and .
A2C and A3C #
A3C (asynchronous advantage actor-critic, Mnih et al., 2016) runs many actor-learners in parallel threads. Each one collects a few steps, computes -step advantages and sends gradients to shared parameters. A2C is the synchronous version: copies of the environment step together, the rollout has transitions, and one batched update follows. A2C uses the GPU better and works as well as A3C.
The policy and the critic often share a network body with two heads. A2C minimizes one loss over the batch:
where is an -step or GAE advantage, treated as a constant, and is the value target. Typical weights are and . The entropy bonus keeps the policy from becoming deterministic too early. Many implementations also normalize the advantages in each batch (subtract the mean, divide by the standard deviation); a constant shift is a baseline, and the scaling only changes the step size.
A2C is on-policy: the policy gradient needs data from the current policy, so each batch is used once and then thrown away. PPO (lesson 09) reuses each batch for a few epochs, carefully.
Continuous actions and off-policy learning: DDPG and TD3 #
A replay buffer (lesson 06) reuses every transition many times. For continuous actions the max over actions of Q-learning is a hard optimization problem, so DDPG (Lillicrap et al., 2016) learns a deterministic actor that does the max: it moves the action uphill on the critic. By the deterministic policy gradient theorem (Silver et al., 2014),
the chain rule through the critic. The critic learns with the target and target networks; exploration comes from noise added to the action.
DDPG overestimates , for the same reason as Q-learning (the actor finds the errors of the critic, a maximization bias, lesson 05). TD3 (Fujimoto et al., 2018) adds three fixes:
- Clipped double Q-learning. Learn two critics and use the smaller target: . The min fights the overestimation.
- Delayed policy updates. Update the actor (and the target networks) once every 2 critic updates, so the actor follows a critic that has settled.
- Target policy smoothing. with : the target averages over a small region, so the actor cannot exploit a narrow, wrong peak of the critic.
TD3 and SAC compute the critic target with of two critics. What problem does this fight?
The actor maximizes the critic, so it is drawn to actions where the critic is too high: the maximization bias of lesson 05. Bootstrapping then spreads this error. The min of two independently trained critics is a pessimistic estimate that cancels much of the upward bias (it may underestimate a little, which is much less harmful).
Soft actor-critic: maximum-entropy RL #
SAC (Haarnoja et al., 2018) changes the objective. Besides the reward, the agent is paid for the entropy of its policy in every state it visits:
Here is the temperature (in this section is not a step size). With this is the usual objective. The entropy bonus makes the policy explore, makes it robust (it learns several good ways to act, not one), and makes training more stable.
Soft value functions. With the bonus, the Bellman equations of lesson 01 become
The second equation says: the soft value is the expected plus times the entropy.
The soft-greedy policy. In a state with action values , which policy maximizes ? For discrete actions:
Theorem (Gibbs policy). Let and . For every distribution over the actions,
with equality exactly when . So the best policy is , and the soft value is .
Proof.
- From the definition of : , so .
- Insert this into the left side: .
- Since , this is .
- , with equality only for (information theory 03).
The soft value is a smooth maximum ("log-sum-exp"). As it tends to and becomes greedy; as , becomes uniform.
Move the temperature . The blue bars are the action values , the orange bars the soft-greedy policy . The violet line is the soft value , the dashed line is . The chart shows the entropy of (it rises to ) and how far is above . The readout checks . Edit the values to see that only their differences, divided by , shape .
SAC in practice (continuous actions). SAC is an off-policy actor-critic method with a replay buffer.
- Critics: two soft Q-networks with target networks (Polyak averaging) and the clipped double-Q target with a fresh .
- Actor: a Gaussian whose sample is squashed by into the action range. It minimizes , a KL projection of onto . The gradient uses the reparameterization trick (calculus 12): with , so the gradient flows through the critic into , with much lower variance than the score function.
- Temperature: a good depends on the scale of the rewards. The second SAC paper (Haarnoja et al., 2018b) tunes it automatically: keep the entropy near a target (often ) by minimizing . When the entropy is below the target, this raises ; when it is above, it lowers .
The tanh correction in the log-probability
The actor samples from a Gaussian and outputs . By the change-of-variables formula (calculus 10), the density of is the density of divided by :
Forgetting the second term makes the entropy estimate wrong, and the temperature tuning then fails. Code uses the stable form .
On-policy or off-policy?
| A2C, PPO (on-policy) | DDPG, TD3, SAC (off-policy) | |
|---|---|---|
| Data | fresh rollouts of the current policy | a replay buffer of old transitions |
| Policy | stochastic (softmax or Gaussian) | deterministic (DDPG, TD3) or stochastic (SAC) |
| Critic | , targets from GAE | (two in TD3 and SAC), TD targets |
| Actor gradient | score function × advantage | through the critic: (TD3) or reparameterization (SAC) |
| Actions | discrete or continuous | mainly continuous (SAC also has a discrete version) |
| Sample efficiency | lower | higher (each transition is reused) |
| Typical use | parallel simulators, RLHF for language models | robots and expensive simulators |
Answers to section 1. (1) Bootstrap with of the next state: the episode did not end, only the data did. Using 0 treats a truncation as a termination and biases the targets. (2) No. only changes how we estimate the advantage; with an exact critic every is unbiased. is part of the objective. (3) gives the usual objective and a greedy policy . A very large makes the entropy dominate: the policy becomes almost uniform, whatever the rewards.
4. Worked example #
(a) GAE with an episode end. Three steps, , , so .
| 0 | 1 | 0 | 1.0 |
| 1 | 1 | 1 | 0.5 |
| 2 | 0 | 0 | 1.0 |
The episode ends with step 1; step 2 is the first step of a new episode. The rollout stops after step 2 while that episode is still running, so we bootstrap with . Go backward:
- : , so bootstrap. . There is nothing after it in the rollout (), so .
- : , so no bootstrap and no carry. , and .
- : . , and .
Advantages ; value targets .
Check with the theorem. The episode of step 0 ends after two steps, so and every longer estimator equals (that is, ). The weights are on and the rest, , on the full estimate: ✓.
What if step 1 were not an episode end? Then and : the advantage of step 2 now flows back.
(b) The soft-greedy policy. One state, three actions with .
- : , sum . So and . Check: and , so ✓. The soft value is above because of the entropy bonus.
- : ; the policy is almost greedy, , and .
- : ; , almost uniform, and . Now is most of the value.
5. In code #
NumPy checks both parts of the worked example. The GAE function works for one environment; the notebook extends it to many parallel environments.
import numpy as np
def gae(rewards, values, dones, last_value, gamma, lam):
T = len(rewards)
adv = np.zeros(T)
next_adv, next_value = 0.0, last_value
for t in reversed(range(T)):
nonterminal = 1.0 - dones[t]
delta = rewards[t] + gamma * nonterminal * next_value - values[t]
next_adv = delta + gamma * lam * nonterminal * next_adv
adv[t] = next_adv
next_value = values[t]
return adv, adv + values
r = np.array([1.0, 1.0, 0.0]); d = np.array([0, 1, 0]); v = np.array([1.0, 0.5, 1.0])
adv, targets = gae(r, v, d, last_value=2.0, gamma=0.9, lam=0.8)
print(adv.round(4), targets.round(4)) # [0.81 0.5 0.8 ] [1.81 1. 1.8 ]
print(gae(r, v, d, 2.0, 0.9, 0.0)[0].round(4)) # lambda = 0: the TD errors [0.45 0.5 0.8 ]
print(gae(r, v, d, 2.0, 0.9, 1.0)[0].round(4)) # lambda = 1: G_t - V(s_t) [0.9 0.5 0.8]
# soft-greedy policy and soft value for Q = (1, 2, 0)
Q = np.array([1.0, 2.0, 0.0])
for alpha in (0.1, 1.0, 10.0):
z = Q / alpha
pi = np.exp(z - z.max()); pi /= pi.sum()
V = alpha * (z.max() + np.log(np.exp(z - z.max()).sum()))
H = -(pi * np.log(pi + 1e-300)).sum()
print(alpha, pi.round(3), round(V, 4), np.isclose(V, pi @ Q + alpha * H))
# 0.1 [0. 1. 0.] 2.0 True
# 1.0 [0.245 0.665 0.09 ] 2.4076 True
# 10.0 [0.332 0.367 0.301] 12.0194 True
CleanRL's ppo.py contains the same GAE loop (note that its dones array is shifted by one step: there,
dones[t] says whether is the first state of a new episode). The log-sum-exp form of subtracts the
maximum first, so it does not overflow for small .
6. Where it shows up #
- PPO for robots, games and language models. GAE with , the critic fitted to , advantage normalization and an entropy bonus are the defaults of PPO (lesson 09). In RLHF the critic is a value head on a copy of the language model; critic-free methods such as GRPO replace it with the mean score of several answers to the same prompt.
- Continuous control. SAC and TD3 are standard baselines on MuJoCo and DeepMind Control tasks, and SAC has learned locomotion and grasping directly on real robots, where its sample efficiency matters.
- Game agents at scale. A3C showed that strong Atari agents can be trained on one multi-core CPU; IMPALA (Espeholt et al., 2018) scales the actor-critic idea to many machines with an off-policy correction (V-trace).
- ML for science and engineering. An actor-critic agent controls the shape of the plasma in a tokamak fusion reactor (Degrave et al., 2022; trained with the actor-critic method MPO in a simulator). Similar agents are studied for chemical process control and particle accelerator tuning, where actions are continuous and simulators are expensive.
7. Common mistakes #
- Truncation treated as termination. A time limit is not an end of the task. Set only for real terminations; at a time limit, bootstrap with of the real next state. With auto-resetting vector environments, the returned observation is already the first state of the next episode; use the final observation that the environment reports separately.
- No reset at episode ends. Without the factor , GAE leaks advantages from one episode into the previous one.
- Gradient through the advantage or the target. and are constants in the losses. Detach them; otherwise the policy loss also changes the critic, and the value loss chases a moving target.
- "λ is a second discount." changes the objective; only changes the estimator.
- One critic, no target network, off-policy. Off-policy actor-critic methods overestimate without clipped double Q and target networks; this is the deadly triad of lesson 06 with an actor that exploits it.
- Forgetting the entropy term in SAC's targets. The soft target contains ; without it the critic learns ordinary values, and the actor's objective no longer matches.
- A fixed temperature across tasks. The right depends on the reward scale. Tune it automatically or scale the rewards.
8. Check yourself #
- Write the actor and critic updates of one-step actor-critic.
Answer
; critic ; actor . - The critic is wrong by . Which part of the error of biases the policy gradient, and which part does not?
Answer
The error at the bootstrap state biases it. The term depends only on the current state, so it acts like a baseline and adds no bias. - Show in one line that .
Answer
. - Compute GAE for one step with , , , , when (a) the episode terminates after the step, (b) the rollout is truncated and .
Answer
(a) . (b) . With one step, plays no role. - Two actions with and . Give the soft-greedy policy and the soft value.
Answer
, so and . Check: and , sum . - Name TD3's three changes to DDPG and the problem each one solves.
Answer
Clipped double Q (the min of two critics) against overestimation; delayed actor updates so the actor follows a settled critic; target policy smoothing (clipped noise on the target action) so the actor cannot exploit narrow errors of the critic.
Write the TD error used by the critic and the actor.
.
Write the one-step actor-critic updates.
Critic ; actor .
Write GAE as a sum of TD errors.
.
Write the backward recursion of GAE with done flags.
, , with .
What do and give in GAE?
: (low variance, biased by the critic). : (unbiased policy gradient, high variance).
What is the difference between the roles of and ?
is part of the objective (how much later rewards count). only mixes estimators; it trades the critic's bias against variance.
A rollout stops at a time limit. What value follows the last step in GAE?
The critic's value of the real next state (bootstrap), not 0: a truncation is not a termination.
Name the three terms of the A2C loss.
Policy term , value loss , entropy bonus .
Write SAC's maximum-entropy objective.
, with temperature .
Give the soft-greedy policy and the soft value for discrete actions.
and .
9. Interview angle #
- "Explain GAE and ." — An exponentially weighted average of -step advantage estimators, equal to ; trades the critic's bias against Monte Carlo variance. Give the two ends.
- "How do you handle time limits?" — Bootstrap at truncation, not at termination; keep
terminatedandtruncatedapart, and use the final observation, not the reset one. - "Why two critics in TD3 and SAC?" — The actor exploits overestimation; the min of two critics is a pessimistic target (clipped double Q), like double Q-learning.
- "SAC or PPO?" — SAC: off-policy, sample efficient, continuous actions, needs a replay buffer and careful critics. PPO: on-policy, simple and stable, works for discrete and continuous actions and with many parallel simulators, the standard for RLHF.
- "Why the entropy bonus?" — It keeps exploration, avoids early collapse to a deterministic policy, and in SAC gives a smooth (soft) Bellman equation with a Boltzmann policy.
- "Which should learn faster, the actor or the critic?" — Usually the critic. It must track the current policy (the two-timescale analysis of actor-critic methods); a fast actor follows the critic's errors.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
gae(rewards, values, dones, last_value, gamma, lam)for one or many parallel environments, with done flags and a bootstrap value; checked against the worked example, the two ends , and a direct sum.normalize_advantages: zero mean and unit standard deviation over the whole batch.- Bias and variance of GAE with an imperfect critic on a chain, by simulation, for several ; compare with the exact formulas.
- One-step actor-critic (tabular softmax actor, tabular critic) on the 4×4 gridworld; the learned greedy policy takes the shortest path from every cell.
- Soft value iteration on the 4×4 gridworld for several temperatures : the soft values approach as and grow with , and the policy's entropy grows.
11. Watch and read #
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition, free PDF: §13.5 (actor-critic) and §12.1 (the λ-return).
- Schulman, Moritz, Levine, Jordan and Abbeel, High-dimensional continuous control using generalized advantage estimation (ICLR 2016): §2–3.
- Mnih et al., Asynchronous methods for deep reinforcement learning (ICML 2016): A3C.
- Fujimoto, van Hoof and Meger, Addressing function approximation error in actor-critic methods (ICML 2018): TD3.
- Haarnoja, Zhou, Abbeel and Levine, Soft actor-critic (ICML 2018), and Haarnoja et al., Soft actor-critic algorithms and applications (2018): automatic temperature.
- OpenAI Spinning Up: Soft Actor-Critic and TD3, with pseudocode.
- Pardo, Tavakoli, Levdik and Kormushev, Time limits in reinforcement learning (ICML 2018): termination versus truncation.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.