Simple Algorithm
Artificial Intelligence · Deep Layer · 28 min

Actor–Critic & Soft Actor–Critic

Combining value estimates with policies.

An actor proposes, a critic evaluates. That division of labor, which goes back to Barto, Sutton and Anderson's pole-balancing learner of 1983, runs from A3C's parallel workers to the deterministic critics that steer simulated robot arms, and to soft actor–critic, which pays the actor for staying random and, in doing so, turns the Bellman max into a log-sum-exp.

What you’ll learn

  • Write the advantage actor–critic loss with nn-step returns and an entropy bonus, and explain how A3C and A2C decorrelate data without replay.
  • State and prove the deterministic policy-gradient theorem, and explain how DDPG and TD3 turn it into off-policy algorithms.
  • Derive the soft Bellman equations and the Boltzmann optimal policy of maximum-entropy RL, and prove that the soft backup is a contraction.
  • Write SAC's critic, actor and temperature losses, including the reparameterization trick and the tanh-squashing correction.

Advantage actor–critic, in parallel: A3C and A2C

An actor–critic keeps two function approximators: the policy πθ\pi_\theta, the actor, and a value estimate VwV_w, the critic, whose job is to turn returns into low-variance advantage estimates. Its deep-learning form is A3C (Mnih et al., 2016), which minimizes, over a short rollout,

L(θ,w)=−∑t[log⁡πθ(at∣st) A^t+β H(πθ(⋅∣st))]+c∑t(G^t−Vw(st))2,A^t=G^t−Vw(st)\loss(\theta,w)=-\sum_t\Big[\log\pi_\theta(a_t\mid s_t)\,\hat A_t+\beta\,\mathcal H\big(\pi_\theta(\cdot\mid s_t)\big)\Big]+c\sum_t\big(\hat G_t-V_w(s_t)\big)^2,\qquad\hat A_t=\hat G_t-V_w(s_t)
G^t=∑k=tt+n−1γk−trk+1+γnVw(st+n)\hat G_t=\sum_{k=t}^{t+n-1}\gamma^{k-t}r_{k+1}+\gamma^nV_w(s_{t+n}) is an nn-step return (A3C used up to 5 steps), A^t\hat A_t is treated as a constant in the policy term, and the entropy bonus, with β=0.01\beta=0.01, keeps the policy from collapsing onto one action too early.

Without replay, consecutive samples from one environment are strongly correlated. A3C's answer was to run many actor–learners in parallel, 16 CPU threads in the paper, each in its own copy of the environment, applying gradients asynchronously to shared parameters. At any moment the workers are in different states, so the combined update is far less correlated, and the data stay on-policy. Mnih et al. reported state-of-the-art Atari results in half the training time of earlier GPU agents, on a single multi-core CPU, and the same method handled continuous control and navigation in 3D mazes.

The synchronous variant A2C waits for all workers and averages their gradients. It uses GPUs better and, in practice, performs at least as well, which suggests that the asynchrony mattered less than the parallel decorrelation. Asynchrony has a cost anyway: workers compute gradients with stale parameters, so their data come from slightly older policies. At larger scale, IMPALA (Espeholt et al., 2018) decouples acting from learning entirely and corrects for the lag with V-trace importance weights (Off-Policy Learning & Importance Sampling).

Deterministic policy gradients: DPG, DDPG and TD3

For continuous actions, a stochastic policy gradient averages over actions, and its variance grows as the policy narrows. Silver et al. (2014) showed that a deterministic policy a=μθ(s)a=\mu_\theta(s) has its own gradient theorem, which needs only the critic's slope in the action.

DerivationProof sketch
  1. ∇θVμ(s)=∇θμθ(s) ∇aQμ(s,a)∣a=μθ(s)+γ∫P(s′∣s,μθ(s)) ∇θVμ(s′) ds′\nabla_\theta V^\mu(s)=\nabla_\theta\mu_\theta(s)\,\nabla_aQ^\mu(s,a)\big|_{a=\mu_\theta(s)}+\gamma\int P\big(s'\mid s,\mu_\theta(s)\big)\,\nabla_\theta V^\mu(s')\,ds'

    Write the value through the critic, Vμ(s)=Qμ(s,μθ(s))V^\mu(s)=Q^\mu(s,\mu_\theta(s)), with Qμ(s,a)=r(s,a)+γ∫P(s′∣s,a) Vμ(s′) ds′Q^\mu(s,a)=r(s,a)+\gamma\int P(s'\mid s,a)\,V^\mu(s')\,ds'. The parameters enter through the action and, at a fixed action, through VμV^\mu at the next state:

  2. ∇θJ=∫∑t≥0γtPr⁡(st=s∣μ)  ∇θμθ(s) ∇aQμ(s,a)∣a=μθ(s) ds\nabla_\theta J=\int\sum_{t\ge0}\gamma^t\Pr(s_t=s\mid\mu)\;\nabla_\theta\mu_\theta(s)\,\nabla_aQ^\mu(s,a)\big|_{a=\mu_\theta(s)}\,ds

    This is the recursion of the stochastic theorem, a local term plus the discounted expected gradient at the next state. Unroll it and average over the start distribution:

No integral over actions appears, so the gradient can be estimated from states in a replay buffer collected by any exploratory behavior: an off-policy actor–critic. (Strictly, averaging over the behavior's states instead of ρμ\rho^\mu gives an approximation of the gradient, as in Degris, White & Sutton's off-policy actor–critic, 2012.) DDPG (Lillicrap et al., 2016) made this deep with DQN's machinery: a replay buffer, target networks updated softly, θ−←τθ+(1−τ)θ−\theta^-\leftarrow\tau\theta+(1-\tau)\theta^- with τ=0.001\tau=0.001, batch normalization, and exploration noise added to the actor's actions.

DDPG is brittle, and TD3 (Fujimoto, van Hoof & Meger, 2018) traced much of the brittleness to the critic's overestimation, the same maximization bias as in Q-learning: an actor that climbs ∇aQ\nabla_aQ seeks out exactly the actions where the critic errs upward. TD3's three fixes:

FixRuleReason
Clipped double Q-learningy=r+γmin⁡i=1,2Qϕi−(s′,a~)y=r+\gamma\min_{i=1,2}Q_{\phi_i^-}(s',\tilde a)an upward error must fool both critics at once; the resulting underestimation is safer, because the actor does not seek it out
Delayed policy updatesupdate the actor and the targets once per 2 critic updateslet the critic's error shrink before the actor exploits it
Target policy smoothinga~=μθ−(s′)+clip⁡(ξ,−c,c)\tilde a=\mu_{\theta^-}(s')+\operatorname{clip}(\xi,-c,c), ξ∼N(0,σ2)\xi\sim\mathcal N(0,\sigma^2)similar actions should have similar values; smoothing denies the actor narrow, spurious peaks of QQ
TD3 used σ=0.2\sigma=0.2 and c=0.5c=0.5 for the target smoothing noise.
Check your understanding

What does the deterministic policy gradient require from the critic that the likelihood-ratio (stochastic) policy gradient does not?

  1. Nothing: both need only sampled returns
  2. The transition model P(s′∣s,a)P(s'\mid s,a)
  3. Importance weights between the behavior and target policies
  4. The gradient of QQ with respect to the action, ∇aQ(s,a)\nabla_aQ(s,a) at a=μθ(s)a=\mu_\theta(s)
Show the answer

D. The gradient of QQ with respect to the action, ∇aQ(s,a)\nabla_aQ(s,a) at a=μθ(s)a=\mu_\theta(s)

The deterministic gradient chains ∇θμθ(s)\nabla_\theta\mu_\theta(s) with ∇aQμ(s,a)\nabla_aQ^\mu(s,a), so it needs a critic that is differentiable in the action; the likelihood-ratio estimator needs only the value of the sampled action. In exchange, DPG avoids integrating over actions and is cheap to estimate off-policy.

Maximum-entropy RL and the soft Bellman equation

Maximum-entropy RL adds the policy's entropy to every reward, J(π)=Eπ[∑tγt(r(st,at)+α H(π(⋅∣st)))]J(\pi)=\E_\pi\big[\sum_t\gamma^t\big(r(s_t,a_t)+\alpha\,\mathcal H(\pi(\cdot\mid s_t))\big)\big], with a temperature α>0\alpha>0 (Ziebart, 2010; Haarnoja et al., 2017). Among policies with similar returns it prefers the most random one, which keeps exploring, resists premature collapse onto one action, and learns several ways of solving a task instead of one.

DerivationWhy a log-sum-exp: the Gibbs variational principle
  1. max⁡π ∑aπ(a)[q(a)−αlog⁡π(a)]\max_\pi\ \sum_a\pi(a)\big[q(a)-\alpha\log\pi(a)\big]

    Fix a state and a vector of action values q(a)q(a). Soft policy improvement maximizes expected value plus α\alpha times entropy:

  2. ∑aπ(a)[q(a)−αlog⁡π(a)]=αlog⁡Z−α DKL(π ∥ πq)\sum_a\pi(a)\big[q(a)-\alpha\log\pi(a)\big]=\alpha\log Z-\alpha\,\KL\big(\pi\,\|\,\pi_q\big)

    Let Z=∑aeq(a)/αZ=\sum_ae^{q(a)/\alpha} and πq(a)=eq(a)/α/Z\pi_q(a)=e^{q(a)/\alpha}/Z. Then q(a)=αlog⁡πq(a)+αlog⁡Zq(a)=\alpha\log\pi_q(a)+\alpha\log Z, and the objective becomes a KL divergence:

  3. max⁡π(Eπq+α H(π))=αlog⁡∑aeq(a)/α → α→0  max⁡aq(a)\max_\pi\big(\E_\pi q+\alpha\,\mathcal H(\pi)\big)=\alpha\log\sum_ae^{q(a)/\alpha}\ \xrightarrow{\ \alpha\to0\ }\ \max_aq(a)

    The maximum is αlog⁡Z\alpha\log Z, attained only at the Boltzmann policy πq\pi_q. The hard max is the limit α→0\alpha\to0. The KL-regularized optimum of RLHF in Fine-Tuning, RLHF & Prompting is the same computation with a reference policy in place of the uniform one.

Predict before you look

A state has two actions, both with Q∗=1Q^*=1, and α=1\alpha=1. What is its soft value V∗(s)=αlog⁡∑aeQ∗(s,a)/αV^*(s)=\alpha\log\sum_ae^{Q^*(s,a)/\alpha}?

Show the answer

1.69

log⁡(e+e)=1+log⁡2≈1.69\log(e+e)=1+\log2\approx1.69. The soft value exceeds every action's value by the entropy of the optimal (here uniform) policy, αlog⁡2\alpha\log2: in maximum-entropy RL, having options is itself worth something. With 10 equally good actions the bonus would be log⁡10≈2.3\log10\approx2.3.

Soft actor–critic

SAC (Haarnoja, Zhou, Abbeel & Levine, 2018) is soft policy iteration with function approximation, run off-policy from a replay buffer. Soft policy evaluation converges to QsoftπQ^\pi_{\text{soft}}, because its backup is an ordinary Bellman backup with an entropy-augmented reward. Soft policy improvement projects the Boltzmann policy of the current critic onto the policy class, πnew=arg min⁡π′∈ΠDKL(π′(⋅∣s) ∥ exp⁡(Qπold(s,⋅)/α)/Z(s))\pi_{\text{new}}=\argmin_{\pi'\in\Pi}\KL\big(\pi'(\cdot\mid s)\,\|\,\exp(Q^{\pi_{\text{old}}}(s,\cdot)/\alpha)/Z(s)\big), which never lowers the soft values. Alternating the two converges to the best policy in Π\Pi, in the tabular case (their Theorem 1).

For continuous actions the actor is a Gaussian squashed by tanh: a=tanh⁡(u)a=\tanh(u) with u=mθ(s)+σθ(s)⊙ξu=m_\theta(s)+\sigma_\theta(s)\odot\xi and ξ∼N(0,I)\xi\sim\mathcal N(0,I). Because aa is a differentiable function of θ\theta and the noise, the actor's loss can be differentiated straight through the critic (the reparameterization trick), usually with much lower variance than the likelihood-ratio estimator. The squashing changes densities, log⁡π(a∣s)=log⁡N(u;m,σ2)−∑ilog⁡(1−tanh⁡2ui)\log\pi(a\mid s)=\log\mathcal N(u;m,\sigma^2)-\sum_i\log(1-\tanh^2u_i). The original SAC already took the minimum of two critics, as TD3 does; a later version dropped its separate state-value network and tuned the temperature automatically, keeping the policy's entropy near a target, −dim⁡A-\dim\mathcal A by default (Haarnoja et al., 2018b).

python
import torch
import torch.nn.functional as F

def sac_losses(batch, actor, q1, q2, q1_targ, q2_targ, log_alpha, gamma=0.99, target_entropy=-6.0):
    s, a, r, s2, done = batch
    alpha = log_alpha.exp()
    with torch.no_grad():                                   # soft Bellman target
        a2, logp2 = actor.sample(s2)                        # reparameterized tanh-Gaussian
        q_next = torch.min(q1_targ(s2, a2), q2_targ(s2, a2)) - alpha * logp2
        y = r + gamma * (1.0 - done) * q_next
    critic_loss = F.mse_loss(q1(s, a), y) + F.mse_loss(q2(s, a), y)
    a_new, logp = actor.sample(s)                           # gradients flow through a_new
    q_new = torch.min(q1(s, a_new), q2(s, a_new))
    actor_loss = (alpha.detach() * logp - q_new).mean()
    alpha_loss = -(log_alpha * (logp.detach() + target_entropy)).mean()
    return critic_loss, actor_loss, alpha_loss

The three SAC losses, each minimized by its own optimizer over its own parameters (critics, actor, log⁡α\log\alpha); the target critics track the critics by Polyak averaging. A target entropy of −6-6 suits a 6-dimensional action space.

AspectDDPGTD3SAC
Policydeterministic μθ(s)\mu_\theta(s)deterministic μθ(s)\mu_\theta(s)stochastic tanh-Gaussian
Explorationnoise added to actionsnoise added to actionsthe policy's own entropy
Critic targetr+γQ−(s′,μ−(s′))r+\gamma Q^-(s',\mu^-(s'))r+γmin⁡iQi−(s′,a~)r+\gamma\min_iQ_i^-(s',\tilde a), smoothed a~\tilde ar+γ(min⁡iQi−(s′,a′)−αlog⁡π(a′∣s′))r+\gamma\big(\min_iQ_i^-(s',a')-\alpha\log\pi(a'\mid s')\big), a′∼πa'\sim\pi
Actor update∇θμθ ∇aQ\nabla_\theta\mu_\theta\,\nabla_aQthe same, every second critic updatereparameterized gradient of E[αlog⁡π−min⁡iQi]\E[\alpha\log\pi-\min_iQ_i]
All three are off-policy actor–critics with replay and target networks; they differ in how they explore and how they guard against overestimation.

Key takeaways

  • Advantage actor–critic (A2C, A3C) combines nn-step advantages, an entropy bonus and a shared critic; parallel workers decorrelate on-policy data without replay, and IMPALA corrects worker lag with V-trace.
  • Deterministic policy gradient: ∇J=Es∼ρμ[∇θμθ(s)∇aQμ(s,a)∣a=μθ(s)]\nabla J=\E_{s\sim\rho^\mu}\big[\nabla_\theta\mu_\theta(s)\nabla_aQ^\mu(s,a)|_{a=\mu_\theta(s)}\big], with no integral over actions, hence off-policy learning from replay; DDPG adds DQN's machinery, and TD3 adds clipped double Q, delayed actor updates and target smoothing.
  • Maximum-entropy RL rewards the policy's entropy; its optimal values satisfy a soft Bellman equation with a log-sum-exp, its optimal policy is Boltzmann (the Gibbs variational principle), and the soft backup is a γ\gamma-contraction.
  • SAC performs soft policy iteration off-policy, with twin soft critics, a reparameterized tanh-Gaussian actor and a temperature tuned toward a target entropy such as −dim⁡A-\dim\mathcal A.
  • Open questions include sample efficiency at scale, loss of plasticity, what entropy really buys, expressive multimodal policies, and theory for deep actor–critics.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why could A3C train deep networks without a replay buffer?

  1. Its entropy bonus decorrelates the samples
  2. It used a target network instead
  3. Parallel workers in different states make each combined update much less correlated, while the data stay on-policy
  4. Its nn-step returns remove the correlation between successive states
Show the answer

C. Parallel workers in different states make each combined update much less correlated, while the data stay on-policy

Replay decorrelates by sampling old transitions, which makes data off-policy. A3C decorrelates across space instead of time: many copies of the environment, each in a different state, contribute to the same parameters.

Question 2

TD3 computes its target with the minimum of two critics. Which problem does this address?

  1. Slow exploration in continuous action spaces
  2. Overestimated action values, which the actor actively seeks out and exploits
  3. The variance of the policy gradient
  4. The cost of computing ∇aQ\nabla_aQ
Show the answer

B. Overestimated action values, which the actor actively seeks out and exploits

An actor that climbs ∇aQ\nabla_aQ concentrates on actions where the critic errs upward, and bootstrapping spreads the error. Taking the minimum of two independently trained critics biases the target downward, which is safer because the actor does not seek out underestimates.

Question 3

As the temperature α→0\alpha\to0, the soft Bellman optimality equation Q(s,a)=r+γ Es′[αlog⁡∑a′eQ(s′,a′)/α]Q(s,a)=r+\gamma\,\E_{s'}\big[\alpha\log\sum_{a'}e^{Q(s',a')/\alpha}\big] becomes:

  1. The standard Bellman optimality equation, with max⁡a′Q(s′,a′)\max_{a'}Q(s',a')
  2. The Bellman equation of the uniform random policy
  3. Undefined, because the log-sum-exp diverges
  4. The Bellman equation of SARSA's ε-greedy policy
Show the answer

A. The standard Bellman optimality equation, with max⁡a′Q(s′,a′)\max_{a'}Q(s',a')

αlog⁡∑aeq(a)/α\alpha\log\sum_ae^{q(a)/\alpha} lies between max⁡aq(a)\max_aq(a) and max⁡aq(a)+αlog⁡∣A∣\max_aq(a)+\alpha\log\abs{\mathcal A}, so it tends to the max as α→0\alpha\to0, and the Boltzmann policy concentrates on the greedy actions.

Question 4

SAC tunes its temperature by minimizing E[−α(log⁡π(a∣s)+Hˉ)]\E\big[-\alpha\big(\log\pi(a\mid s)+\bar{\mathcal H}\big)\big] for a target entropy Hˉ\bar{\mathcal H}. When does this lower α\alpha?

  1. When the policy's entropy is below the target
  2. When the critic's loss increases
  3. Never: α\alpha only grows during training
  4. When the policy's entropy is above the target
Show the answer

D. When the policy's entropy is above the target

The derivative with respect to α\alpha is −E[log⁡π]−Hˉ=H(π)−Hˉ-\E[\log\pi]-\bar{\mathcal H}=\mathcal H(\pi)-\bar{\mathcal H}. Gradient descent lowers α\alpha when the entropy exceeds the target, so less encouragement to explore is needed, and raises it when the entropy falls below the target.

Further reading

  • V. Mnih, A. P. Badia, M. Mirza, A. Graves, T. Lillicrap, T. Harley, D. Silver & K. Kavukcuoglu, "Asynchronous methods for deep reinforcement learning," ICML (2016).
  • D. Silver, G. Lever, N. Heess, T. Degris, D. Wierstra & M. Riedmiller, "Deterministic policy gradient algorithms," ICML (2014).
  • S. Fujimoto, H. van Hoof & D. Meger, "Addressing function approximation error in actor-critic methods," ICML (2018).
  • T. Haarnoja, A. Zhou, P. Abbeel & S. Levine, "Soft actor-critic: Off-policy maximum entropy deep reinforcement learning with a stochastic actor," ICML (2018).
  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 13 (MIT Press, 2nd ed., 2018).