Sign in

TD3

Twin Delayed Deep Deterministic Policy Gradient

DDPG with three fixes for overestimated values: two critics, smoothed target actions and a delayed actor.

Overview

DDPG's critic makes errors, and its actor is trained to seek out the actions where those errors are flattering. The result is a value estimate that drifts upward and a policy that chases it. TD3 keeps DDPG's design and adds three small guards. It trains two critics and believes the more pessimistic one. It blurs the target action with a little noise, so a narrow spike in the critic cannot dominate the target. It updates the actor less often than the critics, so the actor follows a score that has had time to settle. The template is a small NumPy version that trains on a two-dimensional point task.

A short history

Scott Fujimoto, Herke van Hoof and David Meger introduced TD3 in 2018 in the paper Addressing Function Approximation Error in Actor-Critic Methods. They showed that DDPG, like DQN, overestimates action values and that the actor then exploits those errors. Their three fixes, taking the smaller of two critics, adding noise to target actions and updating the actor less often, made continuous control much more reliable with very little extra code.

How it works

  1. Act with the actor's output plus Gaussian exploration noise, and store each transition in the replay buffer.
  2. Sample a batch. For each next state, take the target actor's action, add noise clipped to [−c,c][-c, c] and clip the result to the action range.
  3. Score that smoothed action with both target critics and keep the smaller of the two values.
  4. Form the target yy from the reward plus the discounted smaller value, and regress both critics onto the same yy.
  5. Once every policy_delay critic updates, move the actor up the slope of the first critic.
  6. At that same delayed moment, let the target actor and both target critics drift a fraction τ\tau toward the online networks.

Watch out for

  • Taking the minimum of two critics trades overestimation for mild underestimation. That is usually the safer error, but it can make the agent slow to try actions that really are good.
  • Target noise that is too large averages the critic over actions that behave very differently, so the target stops describing the action the actor would take.
  • Exploration still depends on a hand-set noise scale. If exploration_noise is too small the buffer never covers the actions needed to correct the critics.
  • A large policy_delay leaves the actor trained on few updates. The critics then describe a policy that barely changes, and learning slows.

Use cases

When to use it

Continuous actions with a deterministic policy. It is a better default than DDPG at almost the same cost. Choose SAC instead when you want a stochastic policy or exploration that tunes itself.

In industry

Robotics
Training continuous joint commands for simulated arms and walkers, often as the first off-policy baseline tried on a new task.
Control engineering research
Learning controllers for simulated vehicles, drones or power systems where actions are bounded real values.
Offline reinforcement learning
Serving as the base learner that offline methods such as TD3+BC modify to train from a fixed log of data.

Choosing it: what must hold

  • Actions are continuous vectors with known bounds.
  • A simulator or a large replay buffer of experience.
  • A deterministic final policy is acceptable, with exploration supplied by added noise.

When to choose something else

IfUse instead
Exploration by added noise is not enough, or you want less tuningSAC
Actions are discreteDQN or Double DQN
You prefer on-policy training across many parallel environmentsPPO

Math foundations

  1. Target policy smoothing

    a~=clip⁡(μθ′(s′)+clip⁡(ϵ,−c,c),  −1,  1),ϵ∼N(0,σ~2)\tilde{a} = \operatorname{clip}\bigl( \mu_{\theta'}(s') + \operatorname{clip}(\epsilon, -c, c),\; -1,\; 1 \bigr), \qquad \epsilon \sim \mathcal{N}(0, \tilde{\sigma}^2)

    The target action is blurred with bounded noise. The target then reflects the value of a small neighbourhood of actions, so a sharp, wrong peak in the critic has less effect.

  2. The clipped double-Q target

    y=r+γ (1−d) min⁡(Qϕ1′(s′,a~),  Qϕ2′(s′,a~))y = r + \gamma\,(1 - d)\, \min\bigl( Q_{\phi'_1}(s', \tilde{a}),\; Q_{\phi'_2}(s', \tilde{a}) \bigr)

    Two critics rarely overestimate the same action by the same amount. Using the smaller value removes most of the upward bias that a single critic has.

  3. The critics' loss

    L(ϕ1,ϕ2)=∑j=121N∑i=1N(Qϕj(si,ai)−yi)2L(\phi_1, \phi_2) = \sum_{j=1}^{2} \frac{1}{N} \sum_{i=1}^{N} \bigl( Q_{\phi_j}(s_i, a_i) - y_i \bigr)^2

    Both critics regress onto the same target. They differ only through their random starting weights, which is enough to make their errors partly independent.

  4. The delayed actor gradient

    ∇θJ≈1N∑i=1N∇aQϕ1(si,a)∣a=μθ(si)  ∇θμθ(si)\nabla_\theta J \approx \frac{1}{N} \sum_{i=1}^{N} \nabla_a Q_{\phi_1}(s_i, a)\Big|_{a = \mu_\theta(s_i)} \; \nabla_\theta \mu_\theta(s_i)

    The same deterministic policy gradient as DDPG, taken through the first critic only, and applied once every policy_delay critic updates.

  5. The soft target update

    ϕj′←τ ϕj+(1−τ) ϕj′,θ′←τ θ+(1−τ) θ′\phi'_j \leftarrow \tau\,\phi_j + (1 - \tau)\,\phi'_j, \qquad \theta' \leftarrow \tau\,\theta + (1 - \tau)\,\theta'

    Applied at the delayed step, together with the actor update. The targets follow the online networks slowly so that yy stays steady.

Symbols

s,a,r,s′s, a, r, s'
state, action, reward and next state of one stored transition
dd
done flag: 1 if the episode terminated at this step, else 0
μθ,μθ′\mu_\theta, \mu_{\theta'}
the actor and its target copy
Qϕ1,Qϕ2Q_{\phi_1}, Q_{\phi_2}
the two critics, with target copies marked by a prime
a~\tilde{a}
the smoothed target action
ϵ\epsilon
Gaussian noise added to the target action
σ~\tilde{\sigma}
standard deviation of the target noise (target_noise)
cc
bound on the target noise (noise_clip)
γ\gamma
discount factor
τ\tau
soft update rate of the target networks
NN
number of transitions in a batch
yy
the regression target shared by both critics

Worked by hand

The target actor proposes 0.90.9 for one action dimension and the drawn noise is 0.80.8, with c=0.5c = 0.5. The two target critics then score the smoothed action at −2.0-2.0 and −2.4-2.4. The reward is −0.3-0.3, d=0d = 0 and γ=0.99\gamma = 0.99.

clip⁡(0.8,−0.5,0.5)=0.5\operatorname{clip}(0.8, -0.5, 0.5) = 0.5
a~=clip⁡(0.9+0.5,−1,1)=1.0\tilde{a} = \operatorname{clip}(0.9 + 0.5, -1, 1) = 1.0
min⁡(−2.0,−2.4)=−2.4\min(-2.0, -2.4) = -2.4
y=−0.3+0.99×(−2.4)=−2.676y = -0.3 + 0.99 \times (-2.4) = -2.676

The target is −2.676-2.676. A single critic that happened to be the optimistic one would have given −0.3+0.99×(−2.0)=−2.28-0.3 + 0.99 \times (-2.0) = -2.28.

Visual example

Loading the example.

Try this

  • Run the training with all three guards on and compare the two lines: plain DDPG rates its own actions above what they really earn.
  • Switch the guards off one at a time and train again to see which of them does the most here.
  • Move the probe state and compare the critics' curves with the dashed true curve at the actor's action.

Code sample

from impl import TD3, PointReach
from config import TD3Config

env = PointReach(seed=0)
agent = TD3(env.obs_dim, env.act_dim, TD3Config(policy_delay=2))
before = agent.evaluate(PointReach(seed=1), episodes=20)
agent.train(env)
after = agent.evaluate(PointReach(seed=1), episodes=20)
print(before, after)              # mean return per episode, closer to 0 is better
Read the implementation (269 lines)
"""Twin Delayed DDPG (TD3) in NumPy, with a tiny continuous-control task to learn on.

TD3 is DDPG with three fixes for the critic's overestimation: two critics whose smaller value forms
the bootstrap target, clipped noise added to the target action so the target is smoothed over nearby
actions, and actor and target-network updates only every `policy_delay` critic updates. The networks
are small MLPs with hand-written backpropagation and Adam.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import TD3Config
except ImportError:  # run from the template's own folder
    from config import TD3Config


class PointReach:
    """Tiny continuous-control task: drive a point on the square [-1, 1]^2 to the origin.

    Observation: the position, shape (2,). Action: shape (2,), each entry in [-1, 1]; the point moves
    by 0.2 * action and is clipped to the square. Reward: minus the squared distance to the origin
    after the move. An episode starts at a uniformly random position and is truncated after `horizon`
    steps (there is no terminal state). `step` returns (obs, reward, terminated, truncated).
    A policy that does not move scores about -13 per episode on average; the best possible one about -0.55.
    """

    obs_dim = 2
    act_dim = 2

    def __init__(self, horizon: int = 20, seed: int = 0) -> None:
        self.horizon = horizon
        self.rng = np.random.default_rng(seed)
        self.pos = np.zeros(2)
        self.t = 0

    def reset(self) -> np.ndarray:
        self.pos = self.rng.uniform(-1.0, 1.0, size=2)
        self.t = 0
        return self.pos.copy()

    def step(self, action: np.ndarray):
        """Apply one action, shape (2,). Returns (obs, reward, terminated, truncated)."""
        action = np.clip(np.asarray(action, dtype=float), -1.0, 1.0)
        self.pos = np.clip(self.pos + 0.2 * action, -1.0, 1.0)
        self.t += 1
        return self.pos.copy(), -float(self.pos @ self.pos), False, self.t >= self.horizon


class MLP:
    """Fully connected network with tanh hidden layers and a linear output, trained by manual backprop.

    sizes: layer widths, for example (16, 32, 4) is 16 inputs, one hidden layer of 32 units, 4 outputs.
    rng:   NumPy generator used for the initial weights.
    lr:    Adam step size used by `step`.
    """

    def __init__(self, sizes, rng: np.random.Generator, lr: float = 1e-3) -> None:
        self.sizes = tuple(int(s) for s in sizes)
        self.weights = [rng.normal(0.0, np.sqrt(1.0 / m), size=(m, n)) for m, n in zip(self.sizes[:-1], self.sizes[1:])]
        self.biases = [np.zeros(n) for n in self.sizes[1:]]
        self.lr = lr
        self._m = [np.zeros_like(p) for p in self.params()]
        self._v = [np.zeros_like(p) for p in self.params()]
        self._t = 0
        self._acts: list[np.ndarray] = []

    def params(self) -> list[np.ndarray]:
        """All parameter arrays: the weight matrices, then the bias vectors."""
        return self.weights + self.biases

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (batch, n_in) or (n_in,) -> (batch, n_out). Keeps the activations for `backward`."""
        h = np.atleast_2d(np.asarray(x, dtype=float))
        self._acts = [h]
        last = len(self.weights) - 1
        for i, (w, b) in enumerate(zip(self.weights, self.biases)):
            h = h @ w + b
            if i < last:
                h = np.tanh(h)
            self._acts.append(h)
        return h

    def backward(self, grad_out: np.ndarray):
        """Backpropagate through the most recent `forward` call.

        grad_out: d loss / d output, shape (batch, n_out).
        Returns (grads, grad_in): grads in the order of `params()`, grad_in = d loss / d input (batch, n_in).
        """
        g = np.asarray(grad_out, dtype=float)
        n_layers = len(self.weights)
        grad_w: list = [None] * n_layers
        grad_b: list = [None] * n_layers
        for i in reversed(range(n_layers)):
            if i < n_layers - 1:
                g = g * (1.0 - self._acts[i + 1] ** 2)
            grad_w[i] = self._acts[i].T @ g
            grad_b[i] = g.sum(axis=0)
            g = g @ self.weights[i].T
        return grad_w + grad_b, g

    def step(self, grads) -> None:
        """One Adam step that moves the parameters against `grads` (same order as `params()`)."""
        self._t += 1
        for p, g, m, v in zip(self.params(), grads, self._m, self._v):
            m *= 0.9
            m += 0.1 * g
            v *= 0.999
            v += 0.001 * g * g
            p -= self.lr * (m / (1.0 - 0.9**self._t)) / (np.sqrt(v / (1.0 - 0.999**self._t)) + 1e-8)

    def copy_from(self, other: "MLP", tau: float = 1.0) -> None:
        """Polyak update: params <- tau * other + (1 - tau) * params. tau = 1 is a plain copy."""
        for p, q in zip(self.params(), other.params()):
            p *= 1.0 - tau
            p += tau * q


class ReplayBuffer:
    """Fixed-size ring buffer of transitions (obs, action, reward, next_obs, done).

    capacity: number of transitions kept; the oldest is overwritten when the buffer is full.
    obs_dim:  length of an observation vector.
    act_dim:  0 for integer (discrete) actions, otherwise the length of a continuous action vector.
    """

    def __init__(self, capacity: int, obs_dim: int, act_dim: int = 0) -> None:
        self.capacity = capacity
        self.obs = np.zeros((capacity, obs_dim))
        self.next_obs = np.zeros((capacity, obs_dim))
        self.actions = np.zeros(capacity, dtype=int) if act_dim == 0 else np.zeros((capacity, act_dim))
        self.rewards = np.zeros(capacity)
        self.dones = np.zeros(capacity)
        self.size = 0
        self._next = 0

    def __len__(self) -> int:
        return self.size

    def add(self, obs, action, reward: float, next_obs, done: bool) -> None:
        """Store one transition. `done` must be True only for a real terminal state, not a time limit."""
        i = self._next
        self.obs[i], self.actions[i], self.rewards[i] = obs, action, reward
        self.next_obs[i], self.dones[i] = next_obs, float(done)
        self._next = (i + 1) % self.capacity
        self.size = min(self.size + 1, self.capacity)

    def sample(self, batch_size: int, rng: np.random.Generator):
        """Uniform random batch: (obs, actions, rewards, next_obs, dones), each with leading size batch_size."""
        idx = rng.integers(0, self.size, size=batch_size)
        return self.obs[idx], self.actions[idx], self.rewards[idx], self.next_obs[idx], self.dones[idx]


def smoothed_target_actions(target_actions: np.ndarray, noise: np.ndarray, noise_clip: float) -> np.ndarray:
    """Target policy smoothing: add noise clipped to [-noise_clip, noise_clip], keep the result in [-1, 1].

    target_actions, noise: (batch, act_dim). Returns (batch, act_dim).
    """
    return np.clip(target_actions + np.clip(noise, -noise_clip, noise_clip), -1.0, 1.0)


def clipped_double_q_targets(rewards, dones, next_q1, next_q2, gamma: float) -> np.ndarray:
    """TD3 target r + gamma * (1 - done) * min(Q1', Q2'). All inputs (batch,). Returns (batch,)."""
    return rewards + gamma * (1.0 - dones) * np.minimum(next_q1, next_q2)


class TD3:
    """TD3 agent for actions in [-1, 1]^act_dim.

    obs_dim: length of an observation vector. act_dim: length of an action vector.
    `critic_updates` and `actor_updates` count the gradient steps taken so far.
    """

    def __init__(self, obs_dim: int, act_dim: int, config: TD3Config | None = None) -> None:
        cfg = self.config = config or TD3Config()
        self.obs_dim, self.act_dim = obs_dim, act_dim
        self.rng = np.random.default_rng(cfg.seed)
        actor_sizes = (obs_dim, cfg.hidden_size, cfg.hidden_size, act_dim)
        critic_sizes = (obs_dim + act_dim, cfg.hidden_size, cfg.hidden_size, 1)
        self.actor = MLP(actor_sizes, self.rng, cfg.actor_lr)
        self.actor_target = MLP(actor_sizes, self.rng)
        self.actor_target.copy_from(self.actor)
        self.critics = [MLP(critic_sizes, self.rng, cfg.critic_lr) for _ in range(2)]
        self.critic_targets = [MLP(critic_sizes, self.rng) for _ in range(2)]
        for target, critic in zip(self.critic_targets, self.critics):
            target.copy_from(critic)
        self.buffer = ReplayBuffer(cfg.buffer_size, obs_dim, act_dim)
        self.steps = 0
        self.critic_updates = 0
        self.actor_updates = 0

    def act(self, obs: np.ndarray, explore: bool = False) -> np.ndarray:
        """Action for one observation, shape (act_dim,). explore=True adds Gaussian exploration noise."""
        action = np.tanh(self.actor.forward(obs))[0]
        if explore:
            action = np.clip(action + self.config.exploration_noise * self.rng.normal(size=self.act_dim), -1.0, 1.0)
        return action

    def q_values(self, obs: np.ndarray, actions: np.ndarray):
        """Both critics' values of (s, a). obs: (batch, obs_dim), actions: (batch, act_dim) -> two (batch,) arrays."""
        x = np.concatenate([obs, actions], axis=1)
        return self.critics[0].forward(x)[:, 0], self.critics[1].forward(x)[:, 0]

    def update(self, batch) -> dict:
        """One step for both critics and, every `policy_delay` calls, one actor step and a soft target update.

        batch: (obs, actions, rewards, next_obs, dones). Returns the mean critic loss.
        """
        obs, actions, rewards, next_obs, dones = batch
        cfg = self.config
        n = len(rewards)
        noise = cfg.target_noise * self.rng.normal(size=(n, self.act_dim))
        next_actions = smoothed_target_actions(np.tanh(self.actor_target.forward(next_obs)), noise, cfg.noise_clip)
        next_x = np.concatenate([next_obs, next_actions], axis=1)
        targets = clipped_double_q_targets(rewards, dones, self.critic_targets[0].forward(next_x)[:, 0],
                                           self.critic_targets[1].forward(next_x)[:, 0], cfg.gamma)
        x = np.concatenate([obs, actions], axis=1)
        loss = 0.0
        for critic in self.critics:
            errors = critic.forward(x)[:, 0] - targets
            grads, _ = critic.backward((2.0 * errors / n)[:, None])
            critic.step(grads)
            loss += 0.5 * float(np.mean(errors**2))
        self.critic_updates += 1

        if self.critic_updates % cfg.policy_delay == 0:
            policy_actions = np.tanh(self.actor.forward(obs))
            self.critics[0].forward(np.concatenate([obs, policy_actions], axis=1))
            _, grad_in = self.critics[0].backward(np.full((n, 1), -1.0 / n))
            grads, _ = self.actor.backward(grad_in[:, self.obs_dim:] * (1.0 - policy_actions**2))
            self.actor.step(grads)
            self.actor_updates += 1
            self.actor_target.copy_from(self.actor, cfg.tau)
            for target, critic in zip(self.critic_targets, self.critics):
                target.copy_from(critic, cfg.tau)
        return {"critic_loss": loss}

    def train(self, env, total_steps: int | None = None) -> list[float]:
        """Interact with `env` for total_steps steps, learning from replay. Returns the episode returns."""
        cfg = self.config
        returns: list[float] = []
        obs, episode_return = env.reset(), 0.0
        for _ in range(cfg.total_steps if total_steps is None else total_steps):
            if self.steps < cfg.learning_starts:
                action = self.rng.uniform(-1.0, 1.0, size=self.act_dim)
            else:
                action = self.act(obs, explore=True)
            next_obs, reward, terminated, truncated = env.step(action)
            self.buffer.add(obs, action, reward, next_obs, terminated)
            self.steps += 1
            episode_return += reward
            obs = next_obs
            if terminated or truncated:
                returns.append(episode_return)
                obs, episode_return = env.reset(), 0.0
            if self.steps >= cfg.learning_starts and len(self.buffer) >= cfg.batch_size:
                self.update(self.buffer.sample(cfg.batch_size, self.rng))
        return returns

    def evaluate(self, env, episodes: int = 10) -> float:
        """Mean return of the deterministic policy (no exploration noise) over `episodes` episodes."""
        total = 0.0
        for _ in range(episodes):
            obs, done = env.reset(), False
            while not done:
                obs, reward, terminated, truncated = env.step(self.act(obs, explore=False))
                total += reward
                done = terminated or truncated
        return total / episodes
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
10, run with python3 -m unittest -v

Practice

Using the template, call clipped_double_q_targets and smoothed_target_actions on small arrays you can check by hand. Then train TD3 on PointReach(seed=0) with policy_delay set to 1, 2 and 4, and for each compare evaluate on PointReach(seed=1) and the counters agent.critic_updates and agent.actor_updates.

Check on learning

  1. Both critics see the same data and the same targets. Why do they still disagree, and why is that disagreement useful?
    A way to think about it

    Think about what differs between them at the start and how a network's error at one input depends on its initial weights. Then ask what the minimum does when only one of them is too high.

  2. The minimum of two noisy estimates is biased low. Why is a low bias less harmful than a high one in this setting?
    A way to think about it

    Follow each bias through the loop. An overvalued action attracts the actor and its inflated value feeds the next target. An undervalued action is avoided, so its error is not amplified in the same way.

  3. The actor uses only the first critic for its gradient, not the minimum. What would change if it used the minimum, and is the simpler choice a problem?
    A way to think about it

    Compare the two directions at a point where the critics agree and at a point where they disagree. The pessimism that matters most is in the target the critics learn from.

  4. If the true value function has a sharp cliff, where a slightly different action gives a much worse outcome, what does target smoothing do to the learned values near the edge?
    A way to think about it

    Smoothing averages the target over nearby actions. Near a cliff, some of those neighbours are much worse. Decide whether that makes the agent bolder or more cautious there.