Velamuvi AIAcademy

Lesson 11 of 12 · Deep RL

Actor-Critic Methods

Learn actor-critic reinforcement learning: the advantage, A2C and A3C, PPO's clipped objective, SAC, a NumPy actor-critic and Stable-Baselines3 code.

  • 17 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Explain what the actor and the critic each learn, and what the advantage measures
  • Train a one-step actor-critic in NumPy, with the TD error as the advantage
  • Describe A2C and A3C, and explain how PPO's clipped objective keeps every update small
  • Say what SAC adds, and train PPO or SAC with Stable-Baselines3
  • Choose a sensible first algorithm for a new problem

The idea in plain words

Policy Gradients ended with a trade-off. REINFORCE learns a policy directly, but it judges every action by the whole return that followed, so its updates are noisy and it has to wait for the end of each episode. Q-learning learns from every single step by bootstrapping, but it learns values, and its policy is an afterthought. Actor-critic methods use both. The actor is a policy, trained with a policy gradient as in REINFORCE. The critic is a value function, trained with TD learning as in Q-Learning. After every step, the critic tells the actor whether its action turned out better or worse than expected.

Picture a trainee chef and a head chef. The trainee (the actor) cooks. The head chef (the critic) tastes every dish as it leaves the kitchen and says "better than usual" or "worse than usual". The trainee doesn't wait for the restaurant's review at the end of the year, which is the return; they adjust after every dish. Meanwhile the head chef's sense of "usual" keeps improving too.

Most deep RL algorithms in use today are actor-critics, including A2C, PPO and SAC. This lesson builds the simplest one in NumPy, then tours the big ones and shows how to run them with a library.

The advantage

What should the critic tell the actor? Not how good the state is, and not just how good the action is, but how much better the action is than the policy's usual behaviour in that state. That's the advantage. The baseline in Policy Gradients already pointed this way: G_t − V(s_t) is one estimate of it. The critic can provide others, each less noisy than the last but more dependent on the critic being right:

advantage        A(s, a) = Q(s, a) − V(s)          positive: better than the policy's average in s

ways to estimate it, from the noisiest to the most reliant on the critic:
whole return     G_t − V(s_t)                      REINFORCE with V as the baseline
n steps          r_(t+1) + γ × r_(t+2) + … + γ^(n−1) × r_(t+n) + γ^n × V(s_(t+n)) − V(s_t)
one step         δ = r + γ × V(s′) − V(s)          the TD error; just r − V(s) if s′ ends the episode

The one-step version is the TD error from Q-Learning, now with V: the critic's surprise. If the critic's values are right, the average of r + γ × V(s′) over what can happen next is exactly Q(s, a), so the average TD error is exactly the advantage. It uses one real reward instead of a whole noisy future, so it's far less noisy than G_t. The price is a bias while the critic is still wrong. The simplest actor-critic uses it after every step:

after every step (s, a, r, s′):
δ     =  r + γ × V(s′) − V(s)                      the critic's surprise
V(s)  ←  V(s) + α_critic × δ                       the critic learns: TD learning
θ     ←  θ + α_actor × δ × ∇ log π_θ(a | s)        the actor learns: REINFORCE, with δ in place of G_t − b

A one-step actor-critic in NumPy

Here's the grid from Q-Learning again, with its random move costs. The actor keeps four preferences in every cell and turns them into probabilities with a softmax, as in Policy Gradients. The critic keeps one value per cell. Both learn after every move, with α = 0.1 for each and γ = 0.9. The agent never sees the rules: it only sees what step returns.

Try it yourselfPython
import numpy as np

GRID = ["...G",      # the grid from Q-Learning: G +10, T -10, # wall, start in S
        ".#.T",      # a move costs a random amount between 0 and 2 (1 on average)
        "....",
        "S..."]
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]          # up, right, down, left

def step(state, action, rng):
    row, col = divmod(state, 4)
    r2, c2 = row + MOVES[action][0], col + MOVES[action][1]
    if not (0 <= r2 < 4 and 0 <= c2 < 4) or GRID[r2][c2] == "#":
        r2, c2 = row, col                            # bumped into the edge or the wall
    if GRID[r2][c2] == "G":
        return r2 * 4 + c2, 10.0, True
    if GRID[r2][c2] == "T":
        return r2 * 4 + c2, -10.0, True
    return r2 * 4 + c2, -rng.uniform(0, 2), False

def softmax(h):
    e = np.exp(h - h.max())
    return e / e.sum()

rng = np.random.RandomState(0)
H = np.zeros((16, 4))                                # the actor: 4 preferences in every cell
V = np.zeros(16)                                     # the critic: one value per cell
alpha_actor, alpha_critic, gamma = 0.1, 0.1, 0.9
rewards, lengths = [], []
print("episodes   average reward   average steps   V(S)")
for episode in range(1, 301):
    s, total = 12, 0.0                               # start in S, cell 12
    for t in range(100):
        pi = softmax(H[s])
        a = rng.choice(4, p=pi)                      # the actor chooses
        s2, r, done = step(s, a, rng)
        delta = (r if done else r + gamma * V[s2]) - V[s]    # the TD error: better or worse than expected?
        V[s] += alpha_critic * delta                 # the critic learns, as in TD learning
        grad_log = -pi                               # the gradient of log pi(a): one-hot(a) - pi
        grad_log[a] += 1
        H[s] += alpha_actor * delta * grad_log       # the actor follows the critic's verdict
        s, total = s2, total + r
        if done:
            break
    rewards.append(total)
    lengths.append(t + 1)
    if episode % 50 == 0:
        print(f"{episode - 49:>3}-{episode:<3} {np.mean(rewards[-50:]):13.2f} {np.mean(lengths[-50:]):14.1f} {V[12]:9.2f}")

print("\ncritic: V in every cell     actor: most likely move, and its probability")
for row in range(4):
    cells = range(row * 4, row * 4 + 4)
    values = " ".join(f"{GRID[row][c % 4]:>5}" if GRID[row][c % 4] in "GT#" else f"{V[c]:5.1f}" for c in cells)
    moves = " ".join(f"{GRID[row][c % 4]:>6}" if GRID[row][c % 4] in "GT#" else
                     f"{'↑→↓←'[H[c].argmax()]} {softmax(H[c]).max():.2f}" for c in cells)
    print(values + "      " + moves)
Output
episodes   average reward   average steps   V(S)
  1-50          -7.45           16.2     -4.55
 51-100          4.26            6.6      0.36
101-150          4.97            6.1      1.25
151-200          5.20            6.1      1.89
201-250          4.91            6.1      1.74
251-300          5.14            6.0      2.04

critic: V in every cell     actor: most likely move, and its probability
 -2.5   1.2  10.0     G      → 0.44 → 0.86 → 1.00      G
 -4.0     #   8.0     T      ↑ 0.36      # ↑ 0.99      T
 -2.1   4.4   5.9  -2.7      → 0.75 → 0.99 ↑ 0.99 ← 0.42
  2.0   3.1  -0.5  -3.1      → 0.98 ↑ 0.99 ↑ 0.78 → 0.40
  • The learning curve. By episodes 51 to 100, the agent needs 6.6 moves on average, and from episode 101 on about 6, the shortest route. The average reward settles around 5, the best possible: 10 for the goal, minus about 1 for each of the other five moves. Q-learning's settled lower on the same grid, around 4, because ε-greedy kept forcing random moves. The actor needs no ε: it explores less and less by itself as its probabilities sharpen.
  • The critic. Along the route the actor uses (right, up, right, up, up, right), the critic's values are 2.0, 3.1, 4.4, 5.9, 8.0 and 10.0, close to the optimal values from Value Functions: 1.8, 3.1, 4.6, 6.2, 8.0 and 10.0. V(S) wobbles around the true 1.81 because the costs are random. Off the route, the values are low and stale: the critic learned them while the actor still wandered, and then the actor stopped going there.
  • The actor. On its route, the actor is almost certain, with probabilities from 0.98 to 1.00. Where it rarely goes, it's still unsure: in the top-left cell, its favourite move has a probability of only 0.44. Like Q-learning, it learns well only where it acts. It also chose a different route from value iteration's up-up-up-right-right-right, and both take six moves.

A2C and A3C: many workers at once

Deep RL versions of the actor-critic change three things. The actor and the critic become neural networks, often one network with two outputs: the action probabilities and a single value. The advantage looks n steps ahead instead of one, which balances noise against bias. And many copies of the environment run at once. Consecutive steps from one environment are nearly identical, the problem that Deep Q-Networks solved with a replay memory. Actor-critics are on-policy, so instead they learn from many environments in different situations at the same time.

  • A3C, the Asynchronous Advantage Actor-Critic (DeepMind, 2016), gives every worker its own copy of the environment and of the network. Each worker plays a few steps, computes its gradients and applies them to shared parameters without waiting for the others. It beat the best Atari results of its time in half the training time, on one multi-core CPU instead of a GPU.
  • A2C is the synchronous version: it waits for all the workers, averages their gradients and makes one update. It's simpler and makes better use of a GPU, and OpenAI found it learned at least as well as A3C. Libraries today usually offer A2C.

Both add an entropy bonus, a small reward for keeping the policy random, which stops it from collapsing onto one action too early:

actor loss    =  −average of  A_t × log π_θ(a_t | s_t)   −  β × average entropy of π_θ
critic loss   =  average of  (n-step return − V(s_t))²
entropy       =  −Σ over a of  π(a) × log π(a)        largest when every action is equally likely

PPO: small, safe steps

The biggest danger in a policy gradient method is a step that's too large. One bad update can wreck a good policy, and because the policy collects its own data, a wrecked policy collects bad data and may never recover. Proximal Policy Optimization (PPO), from OpenAI in 2017, keeps every update close to the policy that collected the data, so it can safely squeeze several passes of gradient steps out of each batch.

PPO collects a batch of steps with the current policy, now called the old policy, estimates their advantages with the critic, and then improves the policy for several passes over the batch. For each step, the probability ratio compares how likely the new policy makes the action with how likely the old one made it. Multiplied by the advantage, the ratio gives an objective whose gradient, before the policy has changed, is exactly the actor's update from above: A × ∇ log π. PPO clips the ratio to between 1 − ε and 1 + ε, with ε = 0.2 as a rule, and takes the smaller of the clipped and unclipped values. Once an action's probability has moved 20% in the helpful direction, the objective goes flat, so there's nothing more to gain from pushing further. Moves in the harmful direction are never clipped away, so mistakes still count in full.

ratio          r(θ) = π_θ(a | s) ÷ π_old(a | s)          1 means the policy hasn't changed for this action
PPO objective  L(θ) = average over the batch of  min( r(θ) × A,  clip(r(θ), 1 − ε, 1 + ε) × A )

with ε = 0.2, so clip(...) keeps the ratio between 0.8 and 1.2:
A = 2,  r = 1.5:   min(3.0, 2.4)   =  2.4     past 1.2: no more credit for raising a good action
A = −1, r = 0.5:   min(−0.5, −0.8) = −0.8     past 0.8: no more credit for lowering a bad one
A = −1, r = 1.5:   min(−1.5, −1.2) = −1.5     a bad action made more likely: the full penalty counts

PPO usually estimates advantages with GAE, generalised advantage estimation, which blends the n-step estimates for every n, and it adds the critic loss and an entropy bonus to the clipped objective. It's popular because it's simple, works for discrete and continuous actions, runs well in parallel and is forgiving about its settings.

SAC: off-policy and deliberately random

Soft Actor-Critic (SAC), published in 2018, is an off-policy actor-critic for continuous actions: like DQN, it learns Q-values from a replay memory, and its actor maximises the reward plus the entropy of its own policy, so it succeeds while staying as random as it can. Reusing old experience makes it far more sample-efficient than PPO, which is why it's a favourite for real robots, where every second of experience is expensive.

The same algorithms in Stable-Baselines3

In practice you rarely write PPO or SAC yourself. Stable-Baselines3 is a widely used library of reliable PyTorch implementations of A2C, PPO, SAC, DQN and more, all with the same interface. This code doesn't run in the browser: it needs a local install with pip install stable-baselines3, which also installs PyTorch and Gymnasium, and it takes a few minutes on a laptop.

import gymnasium as gym
from stable_baselines3 import PPO, SAC
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.evaluation import evaluate_policy

# PPO on CartPole: 4 numbers in, 2 discrete actions. 4 copies of the game run side by side.
env = make_vec_env("CartPole-v1", n_envs=4, seed=0)
model = PPO("MlpPolicy", env, seed=0)              # the defaults include clip_range=0.2, n_epochs=10
model.learn(total_timesteps=100_000)
mean, std = evaluate_policy(model, model.get_env(), n_eval_episodes=20)
print(f"PPO on CartPole: {mean:.0f} ± {std:.0f}   (the maximum is 500)")
model.save("ppo_cartpole")                          # load it again with PPO.load("ppo_cartpole")

# SAC on Pendulum: 1 continuous action, the torque that swings the pendulum up
model = SAC("MlpPolicy", "Pendulum-v1", seed=0)
model.learn(total_timesteps=20_000)
mean, std = evaluate_policy(model, model.get_env(), n_eval_episodes=10)
print(f"SAC on Pendulum: {mean:.0f} ± {std:.0f}   (the rewards are negative: closer to 0 is better)")

# Use the trained policy: an observation in, an action out
env = gym.make("Pendulum-v1")
obs, info = env.reset(seed=1)
done = False
while not done:
    action, _ = model.predict(obs, deterministic=True)
    obs, reward, terminated, truncated, info = env.step(action)
    done = terminated or truncated

Every algorithm takes the same three steps: create it with a policy type and an environment, call learn, then predict. Swap PPO for A2C, or SAC for TD3, and the rest of the code stays the same. "MlpPolicy" gives the actor and the critic ordinary fully connected networks; "CnnPolicy" is for images. evaluate_policy plays whole episodes with the deterministic policy and returns the mean and standard deviation of their returns.

Choosing an algorithm

Your problemA good first choiceWhy
Few states and actions, and the model is knownValue iterationExact answers without trial and error
Few states and actions, no modelQ-learning or SARSAA table is simple and reliable
Large or image states, a few discrete actionsDQN or PPODQN reuses old data; PPO is easier to tune
Continuous actions, a fast simulatorPPOStable, and runs many simulator copies at once
Continuous actions, expensive real experienceSAC, or TD3Off-policy: reuses every step many times
Many CPU cores and cheap environmentsPPO or A2CParallel workers instead of a replay memory
Fine-tuning a language model from feedbackPPO, or a variant such as GRPOThe usual recipe for RLHF

When in doubt, start with PPO: it's rarely the most sample-efficient, but it works on a wide range of problems with its default settings. If the actions are continuous and every step of experience is expensive, try SAC.

Common mistakes

Practice

Practice exercise

A batch of four steps was collected with the old policy, and a few gradient steps have changed the policy since. Change objective to PPO's clipped objective and print the ratios, the objective for every step and its average. Then look at the output: which steps did the clipping change, and why was the last step, a bad action that became more likely, left alone?

Your solutionPython
import numpy as np

old_probs = np.array([0.50, 0.20, 0.60, 0.40])     # pi_old(a | s) for 4 steps of a batch
new_probs = np.array([0.70, 0.22, 0.30, 0.56])     # pi_theta(a | s) after a few gradient steps
advantages = np.array([1.5, 2.0, -1.0, -0.5])      # the critic's advantage estimates
eps = 0.2

ratio = new_probs / old_probs
objective = ratio * advantages                     # the ordinary objective, with no clipping
# Change objective to PPO's clipped objective: for every step, the smaller of
# ratio x advantage and clip(ratio, 1 - eps, 1 + eps) x advantage

print("ratio:    ", " ".join(f"{r:5.2f}" for r in ratio))
print("objective:", " ".join(f"{o:5.2f}" for o in objective))
print(f"average:   {objective.mean():.3f}")
Knowledge check

What does clipping the probability ratio achieve in PPO?

Summary

  • An actor-critic learns a policy, the actor, and a value function, the critic. The critic's TD error, δ = r + γ × V(s′) − V(s), estimates the advantage: how much better an action was than expected.
  • A one-step actor-critic in NumPy learned the grid from Q-Learning, taking about 6 moves per episode after 100 episodes, with critic values close to the optimal ones along its route.
  • A3C and A2C learn from many environments at once, with n-step advantages and an entropy bonus; A2C is the simpler, synchronous version.
  • PPO clips the probability ratio between 1 − ε and 1 + ε, so it can reuse each batch safely. SAC is an off-policy actor-critic for continuous actions that maximises reward plus entropy.
  • Stable-Baselines3 provides them all behind one interface. Start with PPO, and try SAC when actions are continuous and experience is expensive.

Next: Where RL Is Used.

Finished reading? Tick it off to track your progress.