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 twice: to act, and to form every bootstrapped target. With a few discrete actions that is a lookup. With , 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 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 and act with , applied coordinate by coordinate.
The map is invertible with a diagonal Jacobian, . The change-of-variables formula divides the density by the Jacobian determinant:
Take logs. The correction is a sum over action dimensions (Haarnoja et al., 2018, Appendix C):
For large, underflows. Since , a stable form is
A one-dimensional policy samples and acts with . By how many nats does exceed ?
Show the answer
2.65
The correction is nats. Near the bounds, tanh squeezes a wide range of into a thin sliver of , so the density of is about times that of . 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 and velocity ; a force pushes it, and each step costs . With linear dynamics and quadratic costs, the optimal policy is a fixed linear feedback, , 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 the cost is not convex in , 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 ; in this lesson and its Fixed Point lessons the start distribution is written instead of . If a critic is differentiable in the action, the actor can follow it directly: the gradient of with respect to 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 :
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 transitions, target networks for both actor and critic that track the learned ones slowly, with , 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.
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 with respect to computes exactly the chain rule of the theorem, with the learned in place of .
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.
| Fix | What changes | Why |
|---|---|---|
| Clipped double Q-learning | Two critics; every target uses the smaller of the two target-critic values | An 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 updates | The actor and all target networks are updated once every critic updates | Let the critic's error shrink before the actor climbs it |
| Target policy smoothing | Clipped Gaussian noise on the target action | Averages the target over nearby actions, so a narrow, spurious peak of the critic cannot be exploited |
Why does TD3's target use the minimum of its two critics rather than their average?
- To halve the variance of the target
- Because the average of two critics is biased downward
- 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
- 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 :
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 with drawn fresh from the current policy, and an actor that minimizes over replayed states.
The actor's gradient is pathwise: write the action as with 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 automatically: it treats "average entropy at least " as a constraint, with target , and takes gradient steps on the dual variable.
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_lossIf the policy's entropy falls below the target, is positive on average and the temperature loss pushes up, strengthening the entropy bonus; if the entropy is above target, shrinks. Only the actor's parameters should be stepped with actor_loss; the critics are trained by their own loss.
Which algorithm when?
| Feature | PPO | DDPG | TD3 | SAC |
|---|---|---|---|---|
| Data | On-policy batches, discarded after a few epochs | Replay buffer | Replay buffer | Replay buffer |
| Policy | Stochastic Gaussian | Deterministic, plus exploration noise | Deterministic, plus exploration noise | Stochastic, tanh-squashed Gaussian |
| Critic | State values | One | Two , minimum in the target | Two soft , minimum |
| Exploration | The policy's own randomness | Ornstein–Uhlenbeck noise | Gaussian noise | Entropy bonus with a tuned temperature |
| Character | Stable and simple; needs many samples | Sample-efficient but brittle | Repairs DDPG's overestimation | Sample-efficient; similar results across seeds |
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 in the log-likelihood.
- The deterministic policy gradient, , 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 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 .
- 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.
Why is Q-learning awkward for a robot arm whose action is a vector of six continuous torques?
- Because Q-values cannot be learned for continuous actions
- Because acting greedily and forming every target require , a nonconvex optimization over a six-dimensional box at every step
- Because continuous actions make the environment non-Markov
- Because the Bellman equation does not hold for continuous actions
Show the answer
B. Because acting greedily and forming every target require , 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 amortizes that maximization, and the deterministic policy gradient trains it.
Stochastic off-policy actor–critics weight each action by . Why does DDPG's actor update need no such weight?
- Because the replay buffer only stores actions from the current policy
- Because the noise added for exploration is small
- Because the target networks remove the bias
- Because the deterministic policy gradient has no expectation over actions: it evaluates at the policy's own action in each sampled state
Show the answer
D. Because the deterministic policy gradient has no expectation over actions: it evaluates at the policy's own action 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.
TD3 adds clipped Gaussian noise to the target action . Which failure does this address?
- 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
- The replay buffer lacks exploratory actions
- The critic's learning rate is too high
- 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 . A deterministic policy that maximizes 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.
SAC tunes its temperature so that the policy's entropy stays near a target . What does the temperature update do when the entropy falls below the target?
- It lowers , so that the policy can become deterministic faster
- It leaves unchanged and lowers the learning rate instead
- It raises , strengthening the entropy bonus until the policy is random enough again
- It resets the policy to the uniform distribution
Show the answer
C. It raises , strengthening the entropy bonus until the policy is random enough again
The temperature is the dual variable of the constraint "entropy at least ". When the constraint is violated, , so the loss falls as grows and gradient descent raises ; when the entropy exceeds the target, decays toward zero.
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?
- PPO, run on many parallel copies of the robot
- An off-policy actor–critic with a replay buffer, such as SAC or TD3, which reuses every transition many times
- REINFORCE without a baseline, for its unbiased gradients
- 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
- Deterministic Policy Gradients: DDPG & TD3 · The DPG theorem, its deep version, and three fixes for overestimation.
- Maximum-Entropy RL & Soft Actor–Critic · Soft Bellman equations, soft policy iteration and automatic temperature tuning.
- Control as Inference · RL as probabilistic inference: optimality variables, the evidence lower bound and MPO.
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).