Overview
answers "if I take action now and play well afterward, how much total reward do I get?" DQN learns that score by trial and error. Each step it nudges its guess toward "the reward I just got, plus the best score I expect from where I landed".
A short history
Q-learning dates from Chris Watkins's 1989 thesis, but combining it with neural networks was unstable for years. In 2013 Volodymyr Mnih and colleagues at DeepMind made it work on Atari games by adding experience replay, and their 2015 Nature paper added the target network and reached human-level scores on many games from pixels alone. That result started the modern wave of deep reinforcement learning.
How it works
- Observe state . Pick an action with -greedy: a random action with probability , otherwise the action with the highest .
- Take the action and record in a replay buffer.
- Sample a random minibatch from the buffer. This breaks the correlation between consecutive steps.
- Compute targets with a separate, slowly updated target network, so the goal does not shift every step.
- Minimize the squared gap between and the target. Copy the online weights into the target network every steps.
- Decay over time, moving from exploring to exploiting.
Watch out for
- The max in the target overestimates Q values; Double DQN fixes this.
- It does not handle continuous actions; use DDPG, TD3 or SAC instead.
- Training is sensitive to learning rate, buffer size and reward scale. Clip or normalize rewards.
Use cases
When to use it
Actions are discrete and there are not too many of them: games, routing choices, simple control.
In industry
- Games and simulation
- Agents that learn to play video games or simulated tasks from the screen, the setting DQN was built for.
- Operations
- Choosing among a small set of actions such as routing, dispatch or inventory moves, trained in a simulator.
- Recommendation
- Picking one of a limited slate of items to show when long-term engagement, not the next click, is the goal.
Choosing it: what must hold
- A small, discrete set of actions.
- A simulator or a large log of experience, since it needs many steps to learn.
- Rewards on a known, bounded scale, or the means to clip or normalise them.
When to choose something else
| If | Use instead |
|---|---|
| Actions are continuous | DDPG, TD3 or SAC |
| Overestimated values are hurting learning | Double DQN |
| The state space is small enough for a table | Tabular Q-learning |
Math foundations
What Q means
The Bellman optimality equation. The value of an action is the reward it earns now plus the discounted value of acting as well as possible from the next state.
The target
The right-hand side of the Bellman equation, computed for one stored step with the target network . When the episode ended there is no next state, so only the reward counts.
The loss
The squared gap between the network's current guess and the target, averaged over a minibatch from the replay buffer. Only is updated; is held fixed.
Acting
The -greedy rule. Exploration is the only way the agent ever sees actions its current estimate rates poorly.
Symbols
- state, action, reward, next state
- the online Q-network with weights
- the target network, a periodic copy of the online network
- discount factor, between 0 and 1
- probability of taking a random action
- steps between copies of the weights into the target network
Worked by hand
One stored step has reward , the episode did not end, , the target network rates the next state's actions at and the online network currently says .
The estimate 3.2 is pulled up toward 3.7. Had the episode ended on this step, the target would be just 1 and the estimate would be pulled down.
Visual example
Loading the example.
Try this
- Press Step and click each box of the loop to read what it holds for that step.
- Run the training and watch the right grid: the target network only changes when it is copied.
- Set the copy interval to 1 so the target chases the online network, and compare the loss.
Code sample
from impl import DQN, GridWorld
from config import DQNConfig
env = GridWorld(size=4)
agent = DQN(env.obs_dim, env.n_actions, DQNConfig(total_steps=3000))
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 (275 lines)
"""Deep Q-Network (DQN) in NumPy, with a small gridworld to learn on.
A network maps an observation to one value per action. It is trained on random batches from a replay
buffer toward the target reward + gamma * max_a' Q_target(next_obs, a'), where Q_target is a copy of
the network that is refreshed every `target_update_every` steps. The network is a small MLP with
hand-written backpropagation and Adam.
"""
from __future__ import annotations
import numpy as np
try:
from .config import DQNConfig
except ImportError: # run from the template's own folder
from config import DQNConfig
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_target: np.ndarray, gamma: float) -> np.ndarray:
"""DQN target r + gamma * (1 - done) * max_a Q_target(s', a).
rewards, dones: (batch,). next_q_target: (batch, n_actions). Returns (batch,).
"""
return rewards + gamma * (1.0 - dones) * next_q_target.max(axis=1)
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 DQN(EpsilonGreedyAgent):
"""DQN agent: an online Q-network, a target copy, uniform replay and epsilon-greedy exploration.
obs_dim: length of an observation vector. n_actions: number of discrete actions.
"""
def __init__(self, obs_dim: int, n_actions: int, config: DQNConfig | None = None) -> None:
config = config or DQNConfig()
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
targets = td_targets(rewards, dones, self.target.forward(next_obs), self.config.gamma)
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
Solve Gymnasium's CartPole-v1 with a two-layer MLP Q-network in PyTorch, aiming for a 100-episode average of 475 or more. Then add Double DQN and compare learning curves.
Check on learning
- Why does taking the max over noisy Q estimates produce a target that is too high on average, even if each estimate is right on average?
A way to think about it
Take three actions whose true value is 0 and whose estimates are 0 plus random noise. Work out the expected value of the largest of the three.
- Remove the target network and compute targets with the online network. Describe what goes wrong in terms of what the loss is chasing.
A way to think about it
Every update to now also moves . Think of trying to close a gap whose far end moves each time you step toward it.
- Replay sampling breaks the correlation between consecutive steps. What would a network trained on consecutive steps, in order, tend to forget?
A way to think about it
Consecutive states look alike. A minibatch of near-identical inputs fits the part of the world the agent is in now, at the cost of the parts it visited earlier.
- Your agent's reward plateaus early and has already decayed to 0.01. How would you tell whether the cause is too little exploration or a learning problem?
A way to think about it
Compare what the buffer contains with what a good policy would need to have seen. Hold higher for longer and see whether the plateau moves; if not, look at the loss and the size of the Q values.