Overview
DQN learns from a target that takes the largest of several value estimates for the next state. Each estimate carries some error, and picking the largest tends to pick one whose error is positive. So the target is too high on average, and the inflated value feeds the next target. Double DQN breaks the link between choosing and scoring. The online network, the one being trained, says which next action looks best. The target network, an older copy, says what that action is worth. An action chosen because one network overrates it is unlikely to be overrated by the other by the same amount. The change costs one extra forward pass. The template is a small NumPy version trained on a 4 by 4 grid.
A short history
Hado van Hasselt introduced Double Q-learning in 2010 to remove a bias: taking the maximum over noisy value estimates tends to pick values that are too high. In 2015 van Hasselt, Arthur Guez and David Silver at DeepMind showed that DQN suffers from this on Atari and that the fix needs almost no new code, because DQN's target network can act as the second estimator. Scores and stability improved, and the change became standard in later agents.
How it works
- Act with an epsilon-greedy rule on the online network's values, with falling linearly, and store transitions in a replay buffer.
- Sample a batch of transitions.
- For each next state, find the action with the highest value according to the online network.
- Read the value of that action from the target network and form the target from the reward plus its discounted value.
- Reduce the Huber loss between the online network's value of the stored action and .
- Every
target_update_everysteps, copy the online network into the target network.
Watch out for
- The two networks are not independent: the target is an old copy of the online one. Overestimation is reduced, not removed.
- Just after the target network is synced, both networks are identical and the double target equals the plain DQN target. The benefit grows as the online network moves away.
- It only corrects the bias from the maximum. Other sources of instability, such as too large a learning rate or too rare a target sync, remain.
- Lower value estimates are not proof of a better policy. Compare the returns from
evaluate, not the size of the Q values alone.
Use cases
When to use it
Anywhere DQN is used. It helps most when there are many actions or noisy rewards, since the maximum over estimates overshoots most there.
In industry
- Games and simulation
- Atari-style agents with discrete actions, where it replaces DQN at no extra cost and gives more accurate value estimates.
- Operations
- Choosing among a small set of dispatch, routing or inventory actions in a simulator, where inflated values would lead to overconfident policies.
- Recommendation research
- Selecting one item from a limited slate to optimise long-term engagement, trained from logged or simulated interactions.
Choosing it: what must hold
- A small, discrete set of actions.
- A simulator or a large log of experience, the same as DQN.
- A target network already in place, since it supplies the second value estimate.
When to choose something else
| If | Use instead |
|---|---|
| Actions are continuous | TD3, which applies the same idea with two critics, or SAC |
| You want every well-known DQN improvement together | Rainbow |
| The state space is small enough for a table | Tabular Q-learning |
Math foundations
The DQN target
Reward plus the discounted largest value the target network gives in the next state. One network both chooses the action and scores it.
Why the maximum is biased upward
Even if each estimate is right on average, the largest of several noisy estimates is too high on average. The gap grows with the number of actions and the size of the noise.
The Double DQN target
The online weights select the action and the target weights evaluate it. This is what
td_targetsreturns whendoubleis true.The loss
The Huber loss is quadratic for small errors and linear for large ones, so a single wild target cannot produce a huge gradient. Its slope is the error clipped to .
The target network sync
The target network is a frozen copy that is refreshed at intervals. Between syncs the targets hold still while the online network is fitted to them.
Symbols
- state, action, reward and next state of one stored transition
- done flag: 1 if the episode terminated at this step, else 0
- the online network with weights theta: one value per action
- the target network: a periodically refreshed copy of the online network
- the estimation error in the value of action a
- discount factor
- the regression target
- the Huber loss with threshold 1
- number of transitions in a batch
- steps between target syncs (target_update_every)
Worked by hand
For one next state with three actions the online network gives and the target network gives . The reward is , and . Compute both targets.
DQN's target is 1.682, built on the target network's highest value. Double DQN's is 1.088, because the action the online network prefers is one the target network rates lower. The two networks disagree about which action is best, and the double target does not take the more flattering view.
Visual example
Loading the example.
Try this
- Run the training with reward noise at 1 and watch the DQN line climb above zero while Double DQN stays lower.
- Set the reward noise to 0 and train again: with nothing to overrate, the two rules agree.
- Set the copy interval to 1: the two networks are then the same and the double target equals the DQN target.
Code sample
from impl import DoubleDQN, GridWorld
from config import DoubleDQNConfig
env = GridWorld(size=4)
agent = DoubleDQN(env.obs_dim, env.n_actions, DoubleDQNConfig(double=True))
returns = agent.train(env) # return of every training episode
print(agent.evaluate(env)) # greedy return; 0.5 is the best possible on the 4 x 4 gridRead the implementation (285 lines)
"""Double DQN in NumPy, with a small gridworld to learn on.
DQN's target takes the maximum of noisy value estimates, which is biased upward. Double DQN splits
the two roles: the online network chooses the next action and the target network scores it,
y = r + gamma * Q_target(s', argmax_a Q_online(s', a)). Everything else is DQN: replay buffer,
target copy, epsilon-greedy exploration, a small MLP with hand-written backpropagation and Adam.
"""
from __future__ import annotations
import numpy as np
try:
from .config import DoubleDQNConfig
except ImportError: # run from the template's own folder
from config import DoubleDQNConfig
class GridWorld:
"""Square grid: the agent starts in the top-left cell and must reach the bottom-right cell.
Observation: one-hot vector of the agent's cell, shape (size * size,).
Actions: 0 up, 1 right, 2 down, 3 left. A move into a wall leaves the agent where it is.
Reward: +1.0 for the step that reaches the goal, -0.1 for every other step.
`step` returns (obs, reward, terminated, truncated): terminated at the goal, truncated after
`max_steps` steps. The best return is `optimal_return`, 0.5 for the default 4 x 4 grid.
"""
n_actions = 4
_MOVES = ((-1, 0), (0, 1), (1, 0), (0, -1))
def __init__(self, size: int = 4, max_steps: int = 30) -> None:
if size < 2:
raise ValueError(f"size must be at least 2, got {size!r}")
self.size = size
self.max_steps = max_steps
self.obs_dim = size * size
self.row = self.col = self.t = 0
@property
def optimal_return(self) -> float:
"""Return of a shortest path: 2 * (size - 1) moves, the last one worth +1."""
return 1.0 - 0.1 * (2 * (self.size - 1) - 1)
def _obs(self) -> np.ndarray:
obs = np.zeros(self.obs_dim)
obs[self.row * self.size + self.col] = 1.0
return obs
def reset(self) -> np.ndarray:
"""Put the agent back on the start cell and return the observation, shape (obs_dim,)."""
self.row = self.col = self.t = 0
return self._obs()
def step(self, action: int):
"""Apply one action (0..3). Returns (obs, reward, terminated, truncated)."""
d_row, d_col = self._MOVES[int(action)]
self.row = min(max(self.row + d_row, 0), self.size - 1)
self.col = min(max(self.col + d_col, 0), self.size - 1)
self.t += 1
terminated = self.row == self.size - 1 and self.col == self.size - 1
truncated = not terminated and self.t >= self.max_steps
return self._obs(), (1.0 if terminated else -0.1), terminated, truncated
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 huber(x: np.ndarray) -> np.ndarray:
"""Huber loss with threshold 1: 0.5 * x^2 for |x| <= 1, |x| - 0.5 beyond. Its derivative is clip(x, -1, 1)."""
a = np.abs(x)
return np.where(a <= 1.0, 0.5 * x * x, a - 0.5)
def td_targets(rewards: np.ndarray, dones: np.ndarray, next_q_online: np.ndarray, next_q_target: np.ndarray,
gamma: float, double: bool = True) -> np.ndarray:
"""Bootstrap targets for a batch of transitions.
rewards, dones: (batch,). next_q_online, next_q_target: (batch, n_actions), the two networks'
values of the next observation. With double=True the online values pick the action and the target
values score it; with double=False this is the plain DQN target max_a Q_target. Returns (batch,).
"""
if double:
best = np.argmax(next_q_online, axis=1)
next_value = next_q_target[np.arange(len(best)), best]
else:
next_value = next_q_target.max(axis=1)
return rewards + gamma * (1.0 - dones) * next_value
class EpsilonGreedyAgent:
"""Acting, replay and the training loop shared by the value-based agent in this file.
A subclass provides `q_values(obs) -> (batch, n_actions)`, `update(batch) -> loss` and
`sync_target()`. Epsilon falls linearly from `epsilon_start` to `epsilon_end` over
`epsilon_decay_steps` environment steps.
"""
def __init__(self, obs_dim: int, n_actions: int, config) -> None:
self.obs_dim, self.n_actions, self.config = obs_dim, n_actions, config
self.rng = np.random.default_rng(config.seed)
self.buffer = ReplayBuffer(config.buffer_size, obs_dim)
self.steps = 0
@property
def epsilon(self) -> float:
cfg = self.config
frac = min(self.steps / cfg.epsilon_decay_steps, 1.0)
return cfg.epsilon_start + frac * (cfg.epsilon_end - cfg.epsilon_start)
def act(self, obs: np.ndarray, greedy: bool = False) -> int:
"""Pick an action for one observation, shape (obs_dim,). greedy=True turns exploration off."""
if not greedy and self.rng.random() < self.epsilon:
return int(self.rng.integers(self.n_actions))
return int(np.argmax(self.q_values(obs)[0]))
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):
action = self.act(obs)
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 len(self.buffer) >= max(cfg.learning_starts, cfg.batch_size):
self.update(self.buffer.sample(cfg.batch_size, self.rng))
if self.steps % cfg.target_update_every == 0:
self.sync_target()
return returns
def evaluate(self, env, episodes: int = 1) -> float:
"""Mean return of the greedy policy 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, greedy=True))
total += reward
done = terminated or truncated
return total / episodes
class DoubleDQN(EpsilonGreedyAgent):
"""Double DQN agent. Set `double=False` in the config to get plain DQN for comparison.
obs_dim: length of an observation vector. n_actions: number of discrete actions.
"""
def __init__(self, obs_dim: int, n_actions: int, config: DoubleDQNConfig | None = None) -> None:
config = config or DoubleDQNConfig()
super().__init__(obs_dim, n_actions, config)
sizes = (obs_dim, config.hidden_size, n_actions)
self.online = MLP(sizes, self.rng, config.learning_rate)
self.target = MLP(sizes, self.rng, config.learning_rate)
self.sync_target()
def q_values(self, obs: np.ndarray) -> np.ndarray:
"""Action values of the online network. obs: (batch, obs_dim) or (obs_dim,) -> (batch, n_actions)."""
return self.online.forward(obs)
def sync_target(self) -> None:
"""Copy the online network into the target network."""
self.target.copy_from(self.online)
def update(self, batch) -> float:
"""One gradient step on a batch (obs, actions, rewards, next_obs, dones). Returns the Huber loss."""
obs, actions, rewards, next_obs, dones = batch
cfg = self.config
targets = td_targets(rewards, dones, self.online.forward(next_obs), self.target.forward(next_obs),
cfg.gamma, cfg.double)
q = self.online.forward(obs)
rows = np.arange(len(actions))
errors = q[rows, actions] - targets
grad_q = np.zeros_like(q)
grad_q[rows, actions] = np.clip(errors, -1.0, 1.0) / len(actions)
grads, _ = self.online.backward(grad_q)
self.online.step(grads)
return float(np.mean(huber(errors)))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Using the template, call td_targets with the arrays from the worked example, once with double set to True and once with False, and check both numbers. Then train two DoubleDQN agents on GridWorld(size=4), one with DoubleDQNConfig(double=True) and one with double=False, and compare evaluate and the largest entry of q_values at the start state with the best possible return of 0.5.
Check on learning
- Each value estimate is assumed to be right on average. Why is the maximum of several such estimates still wrong on average?
A way to think about it
Take three actions with the same true value and add independent noise to each. Ask what the largest of the three noisy numbers looks like compared with the true value, over many repetitions.
- Why does the bias grow with the number of actions, and what does that predict about which problems gain most from Double DQN?
A way to think about it
The more draws you take, the more extreme the largest one tends to be. Compare the expected maximum of 2 noisy estimates with that of 20.
- The target network is only an older copy of the online network. Why does splitting selection and evaluation between them still help?
A way to think about it
What matters is whether their errors for a given action agree. Think about how far the online network has moved since the last sync, and what happens to the benefit right after a sync.
- In the worked example the two targets differ a lot. Could the Double DQN target ever be higher than the DQN target for the same transition?
A way to think about it
The DQN target uses the largest value in the target network's row. The double target uses some entry from that same row. Compare an arbitrary entry with the maximum.