Overview
With a handful of discrete actions you can score each one and pick the best. With continuous actions there are infinitely many, so you cannot compare them all. DDPG trains two networks instead. The critic scores a state and action pair. The actor proposes one action per state, and is nudged in whichever direction the critic says would raise the score. Past experience is stored in a replay buffer and reused, and slow-moving copies of both networks supply the learning targets so that the targets do not chase themselves. The template is a small NumPy version that trains on a two-dimensional point task, not a robotics-scale implementation.
A short history
David Silver and colleagues proved the deterministic policy gradient theorem in 2014. In 2015 Timothy Lillicrap and colleagues at DeepMind combined it with the two tricks that had stabilised DQN, a replay buffer and slowly updated target networks, in the paper Continuous control with deep reinforcement learning. It showed that one off-policy method could learn many simulated control tasks with continuous actions, and it became the base that TD3 and SAC later improved.
How it works
- Act with the actor's output plus exploration noise, and store each transition in the replay buffer.
- Sample a batch of stored transitions. Because they come from older versions of the policy, the method is called off-policy.
- Build the critic's target from the reward plus the discounted value that the target critic gives to the target actor's next action.
- Move the critic toward by reducing the squared error between and .
- Move the actor so that goes up. The gradient flows from the critic's output, through its action input, into the actor.
- Let both target networks drift a small fraction toward the online networks.
Watch out for
- The single critic tends to overestimate values, because the actor is trained to find exactly the actions where the critic's errors are positive. The actor then exploits errors instead of real reward.
- Results are sensitive to the learning rates, and the noise scale. A setting that works on one task often fails on another.
- A deterministic actor explores only through the added noise. If the noise is too small the buffer holds near-identical actions and the critic never learns what other actions are worth.
- The template bounds actions with a tanh. When the actor saturates near the factor is close to zero and the actor's gradient almost vanishes.
Use cases
When to use it
Continuous actions where a deterministic policy is wanted and environment steps are costly enough that reusing old data matters. Treat it as the starting point that TD3 and SAC improve on.
In industry
- Robotics
- Learning joint torques or velocities for arms and legged robots in a physics simulator, where each action is a vector of real numbers.
- Process control
- Tuning continuous setpoints such as valve positions or flow rates in a simulated plant, as a research alternative to hand-tuned controllers.
- Research and teaching
- A baseline in continuous control benchmarks, and the starting point for explaining TD3 and SAC.
Choosing it: what must hold
- Actions are continuous vectors with known bounds.
- A simulator or other cheap source of experience, since it still needs many environment steps.
- Time to tune it: results are sensitive to learning rates, exploration noise and random seed.
When to choose something else
| If | Use instead |
|---|---|
| You want the same idea with fewer failures from overestimated values | TD3 |
| You want stronger exploration and less tuning | SAC |
| Actions are discrete | DQN or Double DQN |
Math foundations
What the actor maximises
The actor is judged by the critic's score of the action it proposes, averaged over states drawn from the replay buffer .
The critic's target
One step of real reward plus the discounted value of what comes next. The next action and its value come from the slow target networks, marked with a prime. The flag removes the bootstrap term when the episode ended.
The critic's loss
Ordinary regression of the critic onto the target, over a batch of replayed transitions. The target is held fixed while the gradient is taken.
The deterministic policy gradient
The chain rule: how the score changes with the action, times how the action changes with the actor's weights. This is the direction the actor steps in.
The soft target update
The targets follow the online networks slowly. With a target moves one percent of the way each update, which keeps from shifting faster than the critic can fit it.
Symbols
- state, action, reward and next state of one stored transition
- done flag: 1 if the episode terminated at this step, else 0
- the actor: a network with weights theta that maps a state to one action
- the critic: a network with weights phi that scores a state and action pair
- weights of the target actor and target critic
- discount factor, between 0 and 1
- soft update rate of the target networks
- the replay buffer of stored transitions
- number of transitions in a batch
- the critic's regression target
Worked by hand
One replayed transition has and . The target critic scores the target actor's next action at , the online critic currently says , and . Then a target weight of follows an online weight of with .
The critic is 0.28 too optimistic for this pair, so its value is pushed down. The target weight moves only from 1.0 to 1.01.
Visual example
Loading the example.
Try this
- Press Run and watch the right panel: once the critic has a slope, the actor's dot climbs toward the brightest part of its map.
- Click a different spot in the left square to probe another state and follow the path the actor takes from it.
- Set τ to 1 and train again: the target copies are no longer slow, and the critic's values run away.
Code sample
from impl import DDPG, PointReach
from config import DDPGConfig
env = PointReach(seed=0)
agent = DDPG(env.obs_dim, env.act_dim, DDPGConfig(total_steps=2000))
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 betterRead the implementation (266 lines)
"""Deep Deterministic Policy Gradient (DDPG) in NumPy, with a tiny continuous-control task to learn on.
An actor network maps an observation to one continuous action; a critic network scores
(observation, action) pairs. The critic is trained by temporal-difference learning on replayed
transitions, and the actor is moved along the critic's gradient with respect to the action, so that
it outputs actions the critic rates higher. Slowly moving target copies of both networks keep the
bootstrap targets stable. The networks are small MLPs with hand-written backpropagation and Adam.
"""
from __future__ import annotations
import numpy as np
try:
from .config import DDPGConfig
except ImportError: # run from the template's own folder
from config import DDPGConfig
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]
class OUNoise:
"""Ornstein-Uhlenbeck process: temporally correlated exploration noise that drifts back to zero.
x <- x - theta * x + sigma * N(0, 1), per action dimension. `reset` sets x back to zero.
"""
def __init__(self, size: int, sigma: float, rng: np.random.Generator, theta: float = 0.15) -> None:
self.sigma, self.theta, self.rng = sigma, theta, rng
self.state = np.zeros(size)
def reset(self) -> None:
self.state = np.zeros_like(self.state)
def sample(self) -> np.ndarray:
self.state = self.state - self.theta * self.state + self.sigma * self.rng.normal(size=self.state.shape)
return self.state.copy()
class DDPG:
"""DDPG agent for actions in [-1, 1]^act_dim.
obs_dim: length of an observation vector. act_dim: length of an action vector.
"""
def __init__(self, obs_dim: int, act_dim: int, config: DDPGConfig | None = None) -> None:
cfg = self.config = config or DDPGConfig()
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.critic = MLP(critic_sizes, self.rng, cfg.critic_lr)
self.actor_target = MLP(actor_sizes, self.rng)
self.critic_target = MLP(critic_sizes, self.rng)
self.actor_target.copy_from(self.actor)
self.critic_target.copy_from(self.critic)
self.buffer = ReplayBuffer(cfg.buffer_size, obs_dim, act_dim)
self.ou = OUNoise(act_dim, cfg.exploration_noise, self.rng)
self.steps = 0
def act(self, obs: np.ndarray, explore: bool = False) -> np.ndarray:
"""Action for one observation, shape (act_dim,). explore=True adds exploration noise."""
action = np.tanh(self.actor.forward(obs))[0]
if explore:
if self.config.noise_type == "ou":
noise = self.ou.sample()
else:
noise = self.config.exploration_noise * self.rng.normal(size=self.act_dim)
action = np.clip(action + noise, -1.0, 1.0)
return action
def q_value(self, obs: np.ndarray, actions: np.ndarray) -> np.ndarray:
"""Critic value Q(s, a). obs: (batch, obs_dim), actions: (batch, act_dim) -> (batch,)."""
return self.critic.forward(np.concatenate([obs, actions], axis=1))[:, 0]
def update(self, batch) -> dict:
"""One critic step, one actor step and a soft target update from a batch
(obs, actions, rewards, next_obs, dones). Returns the critic loss and the mean Q of the actor's actions."""
obs, actions, rewards, next_obs, dones = batch
cfg = self.config
n = len(rewards)
next_actions = np.tanh(self.actor_target.forward(next_obs))
next_q = self.critic_target.forward(np.concatenate([next_obs, next_actions], axis=1))[:, 0]
targets = rewards + cfg.gamma * (1.0 - dones) * next_q
errors = self.q_value(obs, actions) - targets
grads, _ = self.critic.backward((2.0 * errors / n)[:, None])
self.critic.step(grads)
# Actor: ascend Q(s, actor(s)). The critic's input gradient gives dQ/da, tanh gives da/d(pre-activation).
policy_actions = np.tanh(self.actor.forward(obs))
q = self.q_value(obs, policy_actions)
_, grad_in = self.critic.backward(np.full((n, 1), -1.0 / n))
grad_pre = grad_in[:, self.obs_dim:] * (1.0 - policy_actions**2)
grads, _ = self.actor.backward(grad_pre)
self.actor.step(grads)
self.actor_target.copy_from(self.actor, cfg.tau)
self.critic_target.copy_from(self.critic, cfg.tau)
return {"critic_loss": float(np.mean(errors**2)), "actor_q": float(q.mean())}
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, build PointReach(seed=0) and a DDPG agent, call evaluate on PointReach(seed=1) before and after train, and confirm the mean return moves toward 0. Then train a second agent with DDPGConfig(noise_type="ou") and compare. Finally sample a batch from agent.buffer and compare q_value on the stored actions with q_value on the actor's own actions for the same observations.
Check on learning
- The actor is trained to find actions the critic rates highly. Why does that make any error in the critic more dangerous than the same error would be in a supervised regression model?
A way to think about it
Ask who chooses the inputs the critic is evaluated on. In regression the test inputs do not seek out the model's mistakes. Here the actor moves toward wherever the critic's estimate is highest, whether or not it is right.
- What would you expect to see in the critic loss and in the returns if you set , so that the targets equal the online networks at every step?
A way to think about it
Look at the target formula. With the quantity being fitted changes every time the critic changes. Think about what happens when a regression target moves with the prediction.
- PointReach never terminates, it is only cut after a fixed number of steps. Why would it be a mistake to set at the cut?
A way to think about it
Setting tells the critic that no reward follows. Compare that with what really would happen to the point if the episode had continued from that position.
- When might noise that is correlated over time, as in the Ornstein-Uhlenbeck option, explore better than independent Gaussian noise, and when would it make no difference?
A way to think about it
Consider a system with momentum, where one random push is cancelled by the next. Then consider PointReach, where each action moves the point directly.