Simple Algorithm
Reinforcement Learning · Bootstrapping · 24 min

Continuous Control: DDPG, TD3 & SAC

Deterministic policy gradients and maximum-entropy RL for motors and joints.

A robot joint accepts any torque in a range, so "take the action with the highest value" becomes an optimization problem at every step. This lesson builds the three standard answers for continuous actions: Gaussian policies squashed into the action bounds, deterministic policies trained through the gradient of a learned Q-function (DDPG, and TD3, which repairs its overestimation), and maximum-entropy actor–critics that keep the policy random on purpose (SAC).

What you’ll learn

  • Parameterize continuous-action policies as diagonal Gaussians squashed by tanh, and compute the squashed log-likelihood with its Jacobian correction.
  • State the deterministic policy gradient and explain why it lets an actor learn from a replay buffer without importance weights.
  • Describe DDPG and TD3's three fixes, clipped double Q-learning, delayed policy updates and target policy smoothing, and the overestimation they address.
  • Write SAC's entropy-regularized objective and losses, and implement its actor and temperature losses with the reparameterization trick.
  • Choose between PPO, TD3 and SAC according to the cost of samples, the available simulation and the need for stability.

Policies over continuous actions

Value-based control needs max⁡aQ(s,a)\max_aQ(s,a) twice: to act, and to form every bootstrapped target. With a few discrete actions that is a lookup. With a∈[−1,1]da\in[-1,1]^d, say the torques of six joints, it is a nonconvex optimization problem inside every step of every update. Policy methods sidestep it: the policy outputs an action, or a distribution over actions, directly.

The workhorse is the diagonal Gaussian policy: a network outputs the mean mθ(s)∈Rdm_{\boldsymbol\theta}(s)\in\R^d and the log standard deviations, either as a second head that depends on the state (common in off-policy methods) or as a free parameter vector (common in PPO). Real actuators are bounded, and a Gaussian is not. Clipping each sample to the bounds is simple, but then the stored log-probability belongs to an action that was never executed. Squashing is exact: sample u∼N(mθ(s),diag⁡σθ(s)2)\mathbf u\sim\mathcal N\big(m_{\boldsymbol\theta}(s),\operatorname{diag}\sigma_{\boldsymbol\theta}(s)^2\big) and act with a=tanh⁡(u)\mathbf a=\tanh(\mathbf u), applied coordinate by coordinate.

DerivationThe likelihood of a squashed action
  1. πθ(a∣s)=N(u; mθ(s),diag⁡σθ2(s)) ∣det⁡∂a∂u∣−1\pi_{\boldsymbol\theta}(\mathbf a\mid s)=\mathcal N\big(\mathbf u;\,m_{\boldsymbol\theta}(s),\operatorname{diag}\sigma^2_{\boldsymbol\theta}(s)\big)\,\Big|\det\frac{\partial\mathbf a}{\partial\mathbf u}\Big|^{-1}

    The map u↦tanh⁡(u)\mathbf u\mapsto\tanh(\mathbf u) is invertible with a diagonal Jacobian, ∂ai/∂ui=1−tanh⁡2(ui)\partial a_i/\partial u_i=1-\tanh^2(u_i). The change-of-variables formula divides the density by the Jacobian determinant:

  2. log⁡πθ(a∣s)=log⁡N(u; mθ(s),diag⁡σθ2(s))−∑i=1dlog⁡(1−tanh⁡2(ui))\log\pi_{\boldsymbol\theta}(\mathbf a\mid s)=\log\mathcal N\big(\mathbf u;\,m_{\boldsymbol\theta}(s),\operatorname{diag}\sigma^2_{\boldsymbol\theta}(s)\big)-\sum_{i=1}^d\log\big(1-\tanh^2(u_i)\big)

    Take logs. The correction is a sum over action dimensions (Haarnoja et al., 2018, Appendix C):

  3. log⁡(1−tanh⁡2u)=2(log⁡2−u−softplus⁡(−2u)),softplus⁡(x)=log⁡(1+ex)\log\big(1-\tanh^2u\big)=2\big(\log2-u-\operatorname{softplus}(-2u)\big),\qquad\operatorname{softplus}(x)=\log(1+e^x)

    For ∣ui∣\abs{u_i} large, 1−tanh⁡2(ui)1-\tanh^2(u_i) underflows. Since 1−tanh⁡2u=4/(eu+e−u)21-\tanh^2u=4/(e^u+e^{-u})^2, a stable form is

Predict before you look

A one-dimensional policy samples u=2u=2 and acts with a=tanh⁡(2)≈0.964a=\tanh(2)\approx0.964. By how many nats does log⁡π(a∣s)\log\pi(a\mid s) exceed log⁡N(u;m,σ2)\log\mathcal N(u;m,\sigma^2)?

Show the answer

2.65

The correction is −log⁡(1−tanh⁡22)=−log⁡(1−0.9293)=−log⁡0.0707≈2.65-\log(1-\tanh^22)=-\log(1-0.9293)=-\log0.0707\approx2.65 nats. Near the bounds, tanh squeezes a wide range of uu into a thin sliver of aa, so the density of aa is about e2.65≈14e^{2.65}\approx14 times that of uu. Forget the correction and the entropy of a squashed policy is badly misjudged, which matters for SAC, whose objective rewards entropy.

What a good continuous controller looks like

Before learning anything, look at the answer control theory gives when the model is known. A cart on a frictionless track has position xx and velocity vv; a force uu pushes it, and each step costs x2+v2+Ru2x^2+v^2+Ru^2. With linear dynamics and quadratic costs, the optimal policy is a fixed linear feedback, u=−K1x−K2vu=-K_1x-K_2v, read off the solution of a Riccati equation: the linear–quadratic regulator. It is deterministic, it is a smooth function of the state, and nothing in it is random. Keep that picture in mind: the actor of the next step is a learned version of such a feedback law, found without the model.

LQR is also a testbed for reinforcement learning theory: with linear policies u=−Kxu=-Kx the cost is not convex in KK, yet policy gradient methods converge to the optimal gain (Fazel et al., 2018; Global Convergence of Policy Gradients and The Linear–Quadratic Regulator). Most continuous-control problems are neither linear nor known, which is where the learned methods below come in.

Deterministic policy gradients: DDPG

Following Silver et al. (2014), write a deterministic policy as μθ(s)\mu_{\boldsymbol\theta}(s); in this lesson and its Fixed Point lessons the start distribution is written ν\nu instead of μ\mu. If a critic Q(s,a)Q(s,a) is differentiable in the action, the actor can follow it directly: the gradient of QQ with respect to aa says which way to move the action, and the chain rule turns that into a parameter update. The deterministic policy gradient theorem says this intuitive update is the exact gradient of J(θ)=ES0∼ν[Vμθ(S0)]J(\boldsymbol\theta)=\E_{S_0\sim\nu}\big[V^{\mu_{\boldsymbol\theta}}(S_0)\big]:

∇J(θ)=11−γ ES∼dνμθ[∇θμθ(S)  ∇aQμθ(S,a)∣a=μθ(S)]\nabla J(\boldsymbol\theta)=\frac{1}{1-\gamma}\,\E_{S\sim d^{\mu_{\boldsymbol\theta}}_\nu}\Big[\nabla_{\boldsymbol\theta}\mu_{\boldsymbol\theta}(S)\;\nabla_aQ^{\mu_{\boldsymbol\theta}}(S,a)\big|_{a=\mu_{\boldsymbol\theta}(S)}\Big]
∇θμθ(s)\nabla_{\boldsymbol\theta}\mu_{\boldsymbol\theta}(s) is the Jacobian of the action with respect to the parameters, one column per action dimension. As with stochastic policies, no derivative of the state distribution appears. (Silver et al. use the unnormalized discounted distribution, which absorbs the factor 11−γ\frac{1}{1-\gamma}.)

Two consequences. First, there is no expectation over actions, so no score function and none of its variance; a stochastic policy gradient with a Gaussian of shrinking variance converges to this formula. Second, the states can come from any distribution covering where the policy goes, and the gradient needs no importance weights on actions. Replaying old transitions is therefore natural: averaging the same quantity over the replay buffer's states is the off-policy deterministic policy gradient, an approximation that drops a term, as in off-policy actor–critic for stochastic policies.

DDPG (deep deterministic policy gradient; Lillicrap et al., 2016) combines this actor with the machinery of DQN: a replay buffer of 10610^6 transitions, target networks for both actor and critic that track the learned ones slowly, θ′←τθ+(1−τ)θ′\boldsymbol\theta'\leftarrow\tau\boldsymbol\theta+(1-\tau)\boldsymbol\theta' with τ=0.001\tau=0.001, batch normalization, and exploration by adding temporally correlated Ornstein–Uhlenbeck noise to the actions. With one set of hyperparameters it solved more than 20 simulated physics tasks, from low-dimensional states and, for many, from pixels, nearly all within 2.5 million steps.

text
for each environment step:
    a ← clip(μ_θ(s) + noise);  execute a;  store (s, a, r, s′, done) in D
    sample a minibatch from D
    y ← r + γ·(1 − done)·Q_φ′(s′, μ_θ′(s′))           # target networks
    critic: minimize mean (Q_φ(s, a) − y)²
    actor:  maximize mean Q_φ(s, μ_θ(s))               # gradient: ∇θ μ_θ(s) · ∇a Q_φ(s, a)
    φ′ ← τ·φ + (1 − τ)·φ′;   θ′ ← τ·θ + (1 − τ)·θ′

One DDPG step. The actor's loss differentiates through the critic: automatic differentiation of Qϕ(s,μθ(s))Q_\phi(s,\mu_{\boldsymbol\theta}(s)) with respect to θ\boldsymbol\theta computes exactly the chain rule of the theorem, with the learned QϕQ_\phi in place of QμQ^{\mu}.

TD3: three fixes for overestimation

DDPG is famously brittle, and Fujimoto, van Hoof and Meger (2018) traced much of the trouble to a familiar culprit. Q-learning's maximization bias (Maximization Bias & Double Q-Learning) survives in actor–critic form: an actor that climbs the critic's gradient finds exactly the actions where the critic errs upward, and bootstrapped targets then carry the error back through the values. On Hopper and Walker2d they measured DDPG's value estimates climbing well above the true returns. Double DQN's remedy, evaluating targets with a second network, barely helped: with a slowly changing policy, the current and target networks were too similar to give independent estimates. TD3 (twin delayed DDPG) makes three changes.

FixWhat changesWhy
Clipped double Q-learningTwo critics; every target uses the smaller of the two target-critic valuesAn upward error in one critic cannot enter the target. The resulting tendency to underestimate is the safer error: the actor does not seek out actions whose value is underestimated
Delayed policy updatesThe actor and all target networks are updated once every d=2d=2 critic updatesLet the critic's error shrink before the actor climbs it
Target policy smoothingClipped Gaussian noise on the target actionAverages the target over nearby actions, so a narrow, spurious peak of the critic cannot be exploited
y=r+γ (1−done) min⁡i=1,2Qϕi′(s′,a~),a~=μθ′(s′)+clip⁡(ε,−c,c),ε∼N(0,σ~2)y=r+\gamma\,(1-\text{done})\,\min_{i=1,2}Q_{\phi_i'}(s',\tilde a),\qquad\tilde a=\mu_{\boldsymbol\theta'}(s')+\operatorname{clip}(\varepsilon,-c,c),\quad\varepsilon\sim\mathcal N(0,\tilde\sigma^2)
The TD3 target, with σ~=0.2\tilde\sigma=0.2, c=0.5c=0.5 and the result clipped to the action bounds. The paper also used τ=0.005\tau=0.005, Gaussian exploration noise N(0,0.1)\mathcal N(0,0.1) instead of Ornstein–Uhlenbeck noise (which it found offered no benefit), and purely random actions for the first 1,000 to 10,000 steps.
Check your understanding

Why does TD3's target use the minimum of its two critics rather than their average?

  1. To halve the variance of the target
  2. Because the average of two critics is biased downward
  3. To make the target pessimistic: an upward error in one critic cannot pass into the target, and the resulting underestimation is the safer error because the actor never seeks out underestimated actions
  4. Because the second critic evaluates the exploration policy rather than the actor
Show the answer

C. To make the target pessimistic: an upward error in one critic cannot pass into the target, and the resulting underestimation is the safer error because the actor never seeks out underestimated actions

Averaging two estimates that share a replay buffer and are both climbed by the actor would still overestimate. The minimum caps the target at the less optimistic estimate. It can underestimate, but an underestimated action is simply avoided by the actor, so the error does not feed on itself the way overestimation does.

SAC: random on purpose

Soft actor–critic (SAC; Haarnoja, Zhou, Abbeel & Levine, 2018) changes the objective instead of the critic. Maximum-entropy RL adds the entropy of the policy to every reward, weighted by a temperature α>0\alpha>0:

J(π)=Eπ[∑t≥0γt(Rt+1+α H(π(⋅∣St)))],H(π(⋅∣s))=−Ea∼π(⋅∣s)log⁡π(a∣s)J(\pi)=\E_\pi\Big[\sum_{t\ge0}\gamma^t\Big(R_{t+1}+\alpha\,\mathcal H\big(\pi(\cdot\mid S_t)\big)\Big)\Big],\qquad\mathcal H\big(\pi(\cdot\mid s)\big)=-\E_{a\sim\pi(\cdot\mid s)}\log\pi(a\mid s)
As α→0\alpha\to0 the standard objective returns. The values become soft: Q(s,a)=r(s,a)+γEs′[V(s′)]Q(s,a)=r(s,a)+\gamma\E_{s'}[V(s')] with V(s)=Ea∼π[Q(s,a)−αlog⁡π(a∣s)]V(s)=\E_{a\sim\pi}\big[Q(s,a)-\alpha\log\pi(a\mid s)\big], the soft Bellman equation.

The bonus keeps exploration alive without hand-tuned noise, keeps several good actions in play instead of committing early, and tends to produce policies that tolerate perturbations. SAC trains two soft critics on targets y=r+γ(1−done)(min⁡jQϕˉj(s′,a′)−αlog⁡π(a′∣s′))y=r+\gamma(1-\text{done})\big(\min_jQ_{\bar\phi_j}(s',a')-\alpha\log\pi(a'\mid s')\big) with a′a' drawn fresh from the current policy, and an actor that minimizes E[αlog⁡π(a∣s)−min⁡jQϕj(s,a)]\E\big[\alpha\log\pi(a\mid s)-\min_jQ_{\phi_j}(s,a)\big] over replayed states.

The actor's gradient is pathwise: write the action as a=tanh⁡(mθ(s)+σθ(s)⊙ε)a=\tanh\big(m_{\boldsymbol\theta}(s)+\sigma_{\boldsymbol\theta}(s)\odot\boldsymbol\varepsilon\big) with ε∼N(0,I)\boldsymbol\varepsilon\sim\mathcal N(0,I) and backpropagate through the critic, as DDPG does, instead of through a score function (The Policy Gradient Theorem in Depth compares the two estimators). The second version of SAC (Haarnoja et al., 2018b) also tunes α\alpha automatically: it treats "average entropy at least Hˉ\bar{\mathcal H}" as a constraint, with target Hˉ=−dim⁡A\bar{\mathcal H}=-\dim\mathcal A, and takes gradient steps on the dual variable.

python
import math
import torch
import torch.nn.functional as F
from torch.distributions import Normal

def sac_actor_losses(policy, q1, q2, obs, log_alpha, target_entropy):
    """policy(obs) -> (mean, log_std), each (B, d); target_entropy is usually -d."""
    mean, log_std = policy(obs)
    dist = Normal(mean, log_std.clamp(-20, 2).exp())
    u = dist.rsample()                                     # mean + std * eps: gradients flow
    a = torch.tanh(u)
    log_det = 2 * (math.log(2.0) - u - F.softplus(-2 * u))  # log(1 - tanh(u)^2), stable
    log_pi = (dist.log_prob(u) - log_det).sum(-1)
    q = torch.min(q1(obs, a), q2(obs, a)).squeeze(-1)       # twin critics, pessimistic
    alpha = log_alpha.exp()
    actor_loss = (alpha.detach() * log_pi - q).mean()
    alpha_loss = -(log_alpha * (log_pi.detach() + target_entropy)).mean()
    return actor_loss, alpha_loss

If the policy's entropy −E[log⁡π]-\E[\log\pi] falls below the target, log⁡π+Hˉ\log\pi+\bar{\mathcal H} is positive on average and the temperature loss pushes α\alpha up, strengthening the entropy bonus; if the entropy is above target, α\alpha shrinks. Only the actor's parameters should be stepped with actor_loss; the critics are trained by their own loss.

Which algorithm when?

FeaturePPODDPGTD3SAC
DataOn-policy batches, discarded after a few epochsReplay bufferReplay bufferReplay buffer
PolicyStochastic GaussianDeterministic, plus exploration noiseDeterministic, plus exploration noiseStochastic, tanh-squashed Gaussian
CriticState values VVOne QQTwo QQ, minimum in the targetTwo soft QQ, minimum
ExplorationThe policy's own randomnessOrnstein–Uhlenbeck noiseGaussian noiseEntropy bonus with a tuned temperature
CharacterStable and simple; needs many samplesSample-efficient but brittleRepairs DDPG's overestimationSample-efficient; similar results across seeds
Benchmarks such as the MuJoCo locomotion tasks (HalfCheetah, Hopper, Walker2d, Ant, Humanoid) are where these methods were compared; rankings there depend on implementation details and seeds, so read single published curves with care.

The main dial is the cost of a sample. When simulation is cheap and runs thousands of copies in parallel, on-policy PPO is a common choice: it is simple, stable, and its data are easy to replace. When every sample is expensive, as on a physical robot, off-policy methods that replay each transition many times win. With SAC, Haarnoja et al. (2018b) taught a Minitaur quadruped to walk from about 160,000 steps, roughly 2 hours of real-world experience, and the gait carried over to slopes, obstacles and stairs it had never seen; a three-fingered hand learned to turn a valve from camera images in about 20 hours. All of these methods remain sensitive to implementation details and random seeds; compare them over many seeds (Benchmarks & Honest Evaluation).

Key takeaways

  • Continuous-action policies are usually diagonal Gaussians; squashing samples through tanh enforces action bounds exactly, at the price of a Jacobian term −∑ilog⁡(1−tanh⁡2ui)-\sum_i\log(1-\tanh^2u_i) in the log-likelihood.
  • The deterministic policy gradient, ∇J=11−γEdμ[∇θμθ ∇aQμ]\nabla J=\frac{1}{1-\gamma}\E_{d^{\mu}}\big[\nabla_{\boldsymbol\theta}\mu_{\boldsymbol\theta}\,\nabla_aQ^{\mu}\big], differentiates through the critic, has no expectation over actions and so learns from replayed states without importance weights; DDPG adds DQN's replay and target networks.
  • Actor–critics overestimate because the actor climbs the critic's errors; TD3 answers with clipped double Q-learning, delayed policy updates and target policy smoothing.
  • SAC maximizes reward plus α\alpha times entropy using two soft critics, an actor that samples a tanh-squashed Gaussian through the reparameterization trick, and a temperature adjusted to hold the entropy near a target, usually −dim⁡A-\dim\mathcal A.
  • Cheap parallel simulation favors on-policy PPO; expensive samples favor off-policy TD3 and SAC, which is how SAC learned to walk on a real quadruped from about two hours of experience.

Check yourself

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

Question 1

Why is Q-learning awkward for a robot arm whose action is a vector of six continuous torques?

  1. Because Q-values cannot be learned for continuous actions
  2. Because acting greedily and forming every target require max⁡aQ(s,a)\max_aQ(s,a), a nonconvex optimization over a six-dimensional box at every step
  3. Because continuous actions make the environment non-Markov
  4. Because the Bellman equation does not hold for continuous actions
Show the answer

B. Because acting greedily and forming every target require max⁡aQ(s,a)\max_aQ(s,a), a nonconvex optimization over a six-dimensional box at every step

A Q-function over continuous actions can be learned perfectly well (DDPG's critic is one); the trouble is maximizing it. An actor network that outputs μθ(s)≈arg max⁡aQ(s,a)\mu_{\boldsymbol\theta}(s)\approx\argmax_aQ(s,a) amortizes that maximization, and the deterministic policy gradient trains it.

Question 2

Stochastic off-policy actor–critics weight each action by π(a∣s)/b(a∣s)\pi(a\mid s)/b(a\mid s). Why does DDPG's actor update need no such weight?

  1. Because the replay buffer only stores actions from the current policy
  2. Because the noise added for exploration is small
  3. Because the target networks remove the bias
  4. Because the deterministic policy gradient has no expectation over actions: it evaluates ∇aQ\nabla_aQ at the policy's own action μθ(s)\mu_{\boldsymbol\theta}(s) in each sampled state
Show the answer

D. Because the deterministic policy gradient has no expectation over actions: it evaluates ∇aQ\nabla_aQ at the policy's own action μθ(s)\mu_{\boldsymbol\theta}(s) in each sampled state

The stochastic gradient averages over actions drawn from the policy, so data from another policy must be reweighted. The deterministic gradient only needs states; the action at which the critic is differentiated is computed, not sampled. The states still come from the wrong distribution, which the off-policy version simply accepts as an approximation.

Question 3

TD3 adds clipped Gaussian noise to the target action μθ′(s′)\mu_{\boldsymbol\theta'}(s'). Which failure does this address?

  1. A deterministic target policy can sit exactly on a narrow, spurious peak of the critic; averaging the target over nearby actions removes the incentive to exploit such peaks
  2. The replay buffer lacks exploratory actions
  3. The critic's learning rate is too high
  4. The actor's output can leave the action bounds
Show the answer

A. A deterministic target policy can sit exactly on a narrow, spurious peak of the critic; averaging the target over nearby actions removes the incentive to exploit such peaks

Function approximation produces sharp errors in QQ. A deterministic policy that maximizes QQ lands on them, and bootstrapping copies the error into the targets. Smoothing assumes similar actions have similar values and fits the critic to a local average.

Question 4

SAC tunes its temperature so that the policy's entropy stays near a target Hˉ=−dim⁡A\bar{\mathcal H}=-\dim\mathcal A. What does the temperature update do when the entropy falls below the target?

  1. It lowers α\alpha, so that the policy can become deterministic faster
  2. It leaves α\alpha unchanged and lowers the learning rate instead
  3. It raises α\alpha, strengthening the entropy bonus until the policy is random enough again
  4. It resets the policy to the uniform distribution
Show the answer

C. It raises α\alpha, strengthening the entropy bonus until the policy is random enough again

The temperature is the dual variable of the constraint "entropy at least Hˉ\bar{\mathcal H}". When the constraint is violated, E[log⁡π]+Hˉ>0\E[\log\pi]+\bar{\mathcal H}>0, so the loss −α E[log⁡π+Hˉ]-\alpha\,\E[\log\pi+\bar{\mathcal H}] falls as α\alpha grows and gradient descent raises α\alpha; when the entropy exceeds the target, α\alpha decays toward zero.

Question 5

A team must learn a controller on a single physical robot, where every hour of experience costs money and wears the hardware. Which approach fits best?

  1. PPO, run on many parallel copies of the robot
  2. An off-policy actor–critic with a replay buffer, such as SAC or TD3, which reuses every transition many times
  3. REINFORCE without a baseline, for its unbiased gradients
  4. DDPG exactly as published, since it was the first deep continuous-control method
Show the answer

B. An off-policy actor–critic with a replay buffer, such as SAC or TD3, which reuses every transition many times

Off-policy methods replay each transition for many gradient steps, which is what makes learning in a few hours of real experience possible; SAC learned quadruped walking from about 2 hours of data. PPO shines when parallel simulation makes samples cheap.

Go deeper

Further reading

  • D. Silver, G. Lever, N. Heess, T. Degris, D. Wierstra & M. Riedmiller, "Deterministic policy gradient algorithms," ICML (2014).
  • T. P. Lillicrap, J. J. Hunt, A. Pritzel, N. Heess, T. Erez, Y. Tassa, D. Silver & D. Wierstra, "Continuous control with deep reinforcement learning," ICLR (2016).
  • 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).