Lesson 9 of 12 · Deep RL
Deep Q-Networks
How deep Q-networks work: function approximation, experience replay, target networks, a tiny DQN in NumPy, a PyTorch CartPole skeleton and Double DQN.
- 13 min read
- Advanced
- Reviewed
- Explain why Q-tables break down for large or continuous state spaces, and what function approximation does instead
- Name the four parts of a DQN: the Q-network, the loss, experience replay and the target network
- Train a tiny DQN written in NumPy and read its results
- Outline a PyTorch DQN for CartPole, and describe Double DQN and other improvements
The idea in plain words
In Q-Learning and Solving a Grid World, the agent kept one number for every state and action: a Q-table. That works for a grid of 48 cells. Now picture CartPole, the classic balancing task, where a cart pushes left or right to keep a pole upright. Its state is four real numbers: the cart's position and speed, and the pole's angle and how fast it is falling. Or picture an Atari game, where the state is the screen. Tables run into two problems:
- Size. A table needs a row for every state. Even if you split each of CartPole's four numbers into just 20 bins, that's 20 × 20 × 20 × 20 = 160,000 rows. A 210 × 160 Atari screen with 128 possible colours per pixel has more possible screens than there are atoms in the universe.
- No generalisation. A table learns about each state separately. Learning that "move left" is good with the ball at position 0.31 teaches it nothing about position 0.32.
The fix is to stop looking values up and start computing them. A function with adjustable parameters θ, usually a neural network, takes the state as input and outputs one Q-value per action. Similar states give similar outputs automatically, and the network needs far fewer numbers than the table would.
A deep Q-network (DQN) is Q-learning with a neural network in place of the table. DeepMind made it famous between 2013 and 2015 by learning to play Atari games from the screen's pixels alone. If neural networks are new to you, Introduction to Deep Learning explains neurons, layers and how a network learns.
The four parts of a DQN
- The Q-network. The state goes in, and one Q-value per action comes out. Choosing the greedy action takes one forward pass and an argmax.
- The loss. The target is the Q-learning target you know. Gradient descent shrinks the squared TD error, but only for the action that was actually taken:
target y = r + γ × (largest Q_target(s', a') over all actions a') just r if the episode ended
loss = average over a batch of (y − Q(s, a; θ))²- Experience replay. Consecutive moves are almost identical, and training on them in order is like revising one page of a book again and again: the network forgets the rest. DQN stores every move (s, a, r, s', done) in a replay memory and trains on random batches drawn from it. That breaks the link between consecutive samples and lets every move be reused many times.
- The target network. If the network that computes the targets is the one being trained, every update also moves the targets, and the network ends up chasing its own tail. DQN computes targets with a frozen copy, the target network, and copies the trained weights into it every few hundred steps.
Around these four parts sits ε-greedy exploration from Exploration vs Exploitation, with ε usually falling from 1 to a small value as training goes on.
A tiny DQN in NumPy
The environment is Catch: a ball falls from a random spot at the top, taking 10 steps to reach the bottom. The paddle starts in the middle and can move 0.1 left, stay, or move 0.1 right at each step. Catching the ball (the paddle is 0.2 wide) earns +1, and missing it −1. The state is three numbers between 0 and 1: the ball's x position, its height and the paddle's x position. Because the ball's position is a real number, no two balls start in exactly the same place, so a table would almost never see the same state twice.
The network has 3 inputs, 32 ReLU units and 3 outputs, and its gradients are written out by hand, with the same backpropagation as in Introduction to Deep Learning. Training runs for 1,000 episodes with γ = 0.9, a learning rate of 0.1, batches of 32 and a target network refreshed every 100 moves, while ε falls from 1 to 0.05 over the first 500 episodes:
import numpy as np
# ---- The environment: catch a falling ball ----
class Catch:
"""A ball falls from a random spot at the top; move the paddle under it.
State: ball x, ball height, paddle x (all between 0 and 1). Actions: 0 left, 1 stay, 2 right."""
def __init__(self, seed=0):
self.rng = np.random.RandomState(seed)
def reset(self):
self.ball_x, self.height, self.paddle = self.rng.rand(), 10, 0.5
return self.state()
def state(self):
return np.array([self.ball_x, self.height / 10, self.paddle])
def step(self, action):
self.paddle = min(max(self.paddle + 0.1 * (action - 1), 0.0), 1.0)
self.height -= 1
if self.height > 0:
return self.state(), 0.0, False
caught = abs(self.ball_x - self.paddle) <= 0.1 # the paddle is 0.2 wide
return self.state(), (1.0 if caught else -1.0), True
# ---- The Q-network: 3 inputs -> 32 ReLU units -> 3 Q-values, one per action ----
def new_network(rng):
return {"W1": rng.randn(3, 32) * np.sqrt(2 / 3), "b1": np.zeros(32),
"W2": rng.randn(32, 3) * np.sqrt(1 / 32), "b2": np.zeros(3)}
def q_values(net, states):
hidden = np.maximum(0, states @ net["W1"] + net["b1"])
return hidden @ net["W2"] + net["b2"], hidden
def train_step(net, states, actions, targets, lr): # one gradient step on the squared TD error
q, hidden = q_values(net, states)
rows = np.arange(len(states))
dq = np.zeros_like(q)
dq[rows, actions] = 2 * (q[rows, actions] - targets) / len(states) # only the actions taken
dhidden = dq @ net["W2"].T * (hidden > 0)
grads = {"W2": hidden.T @ dq, "b2": dq.sum(axis=0), "W1": states.T @ dhidden, "b1": dhidden.sum(axis=0)}
for name in net:
net[name] -= lr * grads[name]
# ---- Training: experience replay + a target network ----
rng, env = np.random.RandomState(0), Catch(seed=1)
net = new_network(rng)
target_net = {name: w.copy() for name, w in net.items()}
size = 5000 # replay memory: the last 5,000 moves
memory = {"s": np.zeros((size, 3)), "a": np.zeros(size, int), "r": np.zeros(size),
"s2": np.zeros((size, 3)), "done": np.zeros(size)}
gamma, lr, batch, stored, caught = 0.9, 0.1, 32, 0, []
for episode in range(1000):
epsilon = max(0.05, 1 - episode / 500) # explore less and less
s, done = env.reset(), False
while not done:
a = rng.randint(3) if rng.rand() < epsilon else int(np.argmax(q_values(net, s[None])[0]))
s2, r, done = env.step(a)
i = stored % size
memory["s"][i], memory["a"][i], memory["r"][i], memory["s2"][i], memory["done"][i] = s, a, r, s2, done
stored, s = stored + 1, s2
if stored >= batch: # learn from a random batch of old moves
idx = rng.randint(min(stored, size), size=batch)
next_q = q_values(target_net, memory["s2"][idx])[0].max(axis=1)
targets = memory["r"][idx] + gamma * next_q * (1 - memory["done"][idx])
train_step(net, memory["s"][idx], memory["a"][idx], targets, lr)
if stored % 100 == 0: # refresh the target network
target_net = {name: w.copy() for name, w in net.items()}
caught.append(r > 0)
if (episode + 1) % 200 == 0:
print(f"episodes {episode - 198:>3}-{episode + 1:<4} caught {np.mean(caught[-200:]):4.0%} (epsilon {epsilon:.2f})")
# ---- Results ----
def test(policy, episodes=500): # 500 new balls, no exploration
game, wins = Catch(seed=2), 0
for _ in range(episodes):
s, done = game.reset(), False
while not done:
s, r, done = game.step(policy(s))
wins += r > 0
return wins / episodes
greedy = test(lambda s: int(np.argmax(q_values(net, s[None])[0])))
random_moves = test(lambda s: rng.randint(3))
print(f"\ntest on 500 new balls: DQN caught {greedy:.1%}, random moves {random_moves:.1%}")
print(f"the network has {sum(w.size for w in net.values())} numbers")
xs = np.linspace(0, 1, 11) # what did it learn? paddle at 0.5,
moves = [np.argmax(q_values(net, np.array([[x, 0.5, 0.5]]))[0]) for x in xs] # ball halfway down
print("\nball x:", " ".join(f"{x:.1f}" for x in xs))
print("move: ", " ".join(f"{'←·→'[m]:>3}" for m in moves))episodes 1-200 caught 26% (epsilon 0.60) episodes 201-400 caught 60% (epsilon 0.20) episodes 401-600 caught 76% (epsilon 0.05) episodes 601-800 caught 85% (epsilon 0.05) episodes 801-1000 caught 90% (epsilon 0.05) test on 500 new balls: DQN caught 98.8%, random moves 19.8% the network has 227 numbers ball x: 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 move: ← ← ← ← ← · → → → → →
- Training. The catch rate climbs from 26%, when most moves are random, to 90% in the last 200 episodes, when ε still forces a random move 5% of the time.
- Testing. Acting greedily, the DQN catches 98.8% of 500 new balls, against 19.8% for random moves. Every one of those balls starts somewhere the network has never seen exactly, and it still knows what to do: that's generalisation.
- What it learned. With the paddle in the middle and the ball halfway down, it moves left for balls on the left, stays for a ball straight above, and moves right for balls on the right. Nobody wrote that rule: it came out of 227 numbers trained on 10,000 moves.
The same idea in PyTorch and Gymnasium
Real projects use a deep learning library, which works out the gradients automatically, and a standard environment. This skeleton trains a DQN on CartPole with PyTorch and Gymnasium. It doesn't run in the browser: it needs a local install with pip install gymnasium torch, and takes a few minutes on a laptop.
import random
from collections import deque
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
env = gym.make("CartPole-v1")
n_inputs, n_actions = env.observation_space.shape[0], env.action_space.n # 4 numbers, 2 actions
def make_network():
return nn.Sequential(nn.Linear(n_inputs, 128), nn.ReLU(),
nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, n_actions))
q_net, target_net = make_network(), make_network()
target_net.load_state_dict(q_net.state_dict()) # start as an exact copy
optimizer = torch.optim.Adam(q_net.parameters(), lr=1e-3)
memory = deque(maxlen=50_000) # experience replay
gamma, batch_size, sync_every, steps = 0.99, 64, 500, 0
for episode in range(400):
state, _ = env.reset(seed=episode)
done, total = False, 0.0
while not done:
epsilon = max(0.05, 1 - steps / 10_000)
if random.random() < epsilon:
action = env.action_space.sample()
else:
with torch.no_grad():
action = int(q_net(torch.as_tensor(state)).argmax())
next_state, reward, terminated, truncated, _ = env.step(action)
memory.append((state, action, reward, next_state, terminated))
state, done = next_state, terminated or truncated
total, steps = total + reward, steps + 1
if len(memory) >= 1_000: # learn from a random batch
s, a, r, s2, term = (torch.as_tensor(np.array(x)) for x in zip(*random.sample(memory, batch_size)))
q = q_net(s).gather(1, a.unsqueeze(1)).squeeze(1) # Q(s, a) for the actions taken
with torch.no_grad(): # no gradient through the target
target = r + gamma * target_net(s2).max(dim=1).values * (1 - term.float())
loss = nn.functional.smooth_l1_loss(q, target.float()) # the Huber loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
if steps % sync_every == 0: # refresh the target network
target_net.load_state_dict(q_net.state_dict())
if episode % 50 == 0:
print(f"episode {episode}: reward {total:.0f}")The parts map one to one onto the NumPy version: q_net and target_net, the replay memory, the target computed inside torch.no_grad() so that no gradient flows into it, and a regular copy into target_net. Two details are new. The Huber loss (smooth_l1_loss) grows only linearly for large errors, which keeps a few wild targets from causing huge updates. And only terminated zeroes the target: CartPole-v1 cuts episodes off at 500 steps (truncated), but the pole hasn't fallen, so the future still counts. The maximum reward is 500, and DQN on CartPole is known to be unstable: scores can climb, collapse and recover, so watch the whole curve and try a few seeds.
Double DQN and other improvements
Taking the largest of several noisy estimates tends to pick one whose noise happens to be positive, so DQN's Q-values drift too high: overestimation. Double DQN splits the job in two. The online network chooses the next action, and the target network says how good it is:
DQN: y = r + γ × Q_target(s', the action with the largest Q_target(s', a'))
Double DQN: y = r + γ × Q_target(s', the action with the largest Q_online(s', a'))It's a one-line change that gives more accurate values and often better policies. Other improvements, all widely used:
- Dueling networks split the network's last layers into the value of the state and the advantage of each action.
- Prioritised experience replay replays surprising moves, those with large TD errors, more often.
- Multi-step returns use several real rewards before bootstrapping, so rewards spread back faster.
- Distributional RL learns the whole spread of possible returns instead of just their average.
- Rainbow (2017) combined Double DQN, these four ideas and noisy networks, which learn how much to explore, into one agent that beat each of them alone on Atari.
Common mistakes
Practice
Compute the DQN and the Double DQN targets for a batch of three moves. Use the target network's values for the DQN target. For Double DQN, let the online network choose each next action and the target network score it.
import numpy as np
gamma = 0.9
rewards = np.array([0.0, 1.0, 0.0])
done = np.array([0, 1, 0]) # the second move ended its episode
target_next = np.array([[0.5, 0.8, 0.2], # the target network's Q-values for the 3 next states
[0.3, 0.1, 0.9],
[0.6, 0.4, 0.7]])
online_next = np.array([[0.9, 0.4, 0.1], # the online network's Q-values for the same states
[0.2, 0.5, 0.3],
[0.1, 0.2, 0.8]])
# 1. DQN: r + gamma x (the target network's largest value), or just r when done
# 2. Double DQN: the online network picks the next action, the target network scores it
dqn = np.zeros(3)
double = np.zeros(3)
print("DQN target: ", " ".join(f"{y:.2f}" for y in dqn))
print("Double DQN target:", " ".join(f"{y:.2f}" for y in double))
What is the main job of the target network in a DQN?
Summary
- Tables need a row for every state and learn nothing about similar states; function approximation, usually a neural network, fixes both.
- A DQN is Q-learning with a Q-network, trained on the squared TD error, plus experience replay and a target network to keep training stable.
- A 227-number NumPy DQN learned Catch, catching 98.8% of new balls against 19.8% for random moves, in states it had never seen exactly.
- Double DQN lets the online network choose and the target network evaluate, which reduces overestimation; Rainbow combines it with other improvements.
Next: Policy Gradients.
Finished reading? Tick it off to track your progress.