DQN: Learning to Play Atari from Pixels with a Convolutional Q-Network and Experience Replay
DQN pairs Q-learning with a convolutional network and experience replay, learning from raw pixels with one architecture and hyperparameter set on seven Atari games. It beat all prior methods on six and a human expert on three. Code checks parameters, normalized scores and a CartPole replay ablation.
On this page
Why this paper matters
Before this paper, applying reinforcement learning to high-dimensional sensory input almost always meant hand-crafted features plus a linear value function, with results depending on the quality of the features. Deep learning had already broken through in vision and speech, but reinforcement learning has its own difficulties: rewards are sparse, delayed and noisy, samples are strongly correlated, and the data distribution shifts with the policy. It was also the common belief that combining Q-learning with nonlinear function approximation diverges.
This paper (Mnih et al., DeepMind, posted in December 2013, NIPS Deep Learning Workshop) gives the first deep reinforcement learning model that learns control policies directly from raw pixels, later known as DQN. It has no new theory. Its contribution is an engineering recipe that makes a deep network and Q-learning work stably together: a convolutional network, experience replay, reward clipping and frame skipping. Later deep RL has reused almost all of these ideas.
Method
The Q-learning target. Define the discounted return . The optimal action value satisfies the Bellman equation:
It is approximated by a network with loss at iteration
where is the behavior distribution. The algorithm is model-free (it does not estimate the environment) and off-policy (it learns about the greedy policy while exploring -greedily).
Experience replay (Algorithm 1). At each step the transition goes into a replay pool , and a random minibatch from is used for one gradient step. The pool keeps only the most recent transitions and is sampled uniformly. The paper admits this does not distinguish important transitions and points to ideas like prioritized sweeping.
Preprocessing and network. A raw frame is a image with a 128-color palette. It is converted to grayscale, downsampled to and cropped to , and stacks the last 4 frames as input. The network takes the state as input and has one output unit per action, so one forward pass gives all Q values. The structure: 16 convolutions of with stride 4 and ReLU; 32 convolutions of with stride 2 and ReLU; a fully connected layer of 256 units; and a linear output layer with one output per valid action (4 to 18 depending on the game).
Training details. RMSProp with minibatch 32; anneals linearly from 1 to 0.1 over the first million frames and stays at 0.1 after; 10 million frames in total with a replay pool of the most recent million frames; frame skipping with ( for Space Invaders, where makes the lasers invisible, the only hyperparameter difference between games); during training positive rewards are clipped to +1 and negative ones to −1 so that one learning rate works for all games, at the cost of not telling large rewards from small ones.
Experiments and findings
Seven games share one architecture, one learning algorithm and one set of hyperparameters. Evaluation runs an policy for a fixed number of steps and averages the score (Table 1, excerpt):
| Game | Random | Sarsa | Contingency | DQN | Human |
|---|---|---|---|---|---|
| Beam Rider | 354 | 996 | 1,743 | 4,092 | 7,456 |
| Breakout | 1.2 | 5.2 | 6 | 168 | 31 |
| Enduro | 0 | 129 | 159 | 470 | 368 |
| Pong | −20.4 | −19 | −17 | 20 | −3 |
| Q*bert | 157 | 614 | 960 | 1,952 | 18,900 |
| Seaquest | 110 | 665 | 723 | 1,705 | 28,010 |
| Space Invaders | 179 | 271 | 268 | 581 | 3,690 |
DQN beats the two learning methods Sarsa and Contingency on all seven games, and beats the evolutionary policy search HNeat on every game except Space Invaders (HNeat’s best single episode is 1,720 against DQN’s 1,075). DQN surpasses the human expert on Breakout, Enduro and Pong, comes close on Beam Rider, and falls far short on Q*bert, Seaquest and Space Invaders. The paper also observes that the average reward is very noisy during training, while the average maximum Q value on a held-out set of states grows much more smoothly and shows no sign of divergence.
Checking it with code
The code has three parts. (1) It counts the network parameters layer by layer following the paper. (2) It converts Table 1 into “position between random and human” (the normalization idea comes from the later Nature paper, and I compute it myself here). (3) It runs a small ablation on CartPole comparing three ways of training: online Q-learning that uses only the newest transition at each step, the experience replay of Algorithm 1 (target from the current network), and replay plus a periodically copied frozen target network (the Nature version’s approach). The network, learning rate, annealing and replay-pool size in part 3 are my own choices scaled down for CartPole, not the paper’s hyperparameters, with 10 seeds and 20,000 steps each.
import math
import random
import statistics as st
import torch
from torch import nn
torch.set_num_threads(1)
# ---- 1) How big is the paper's network: count parameters per layer ----
conv_out = lambda n, k, s: (n - k) // s + 1
h1 = conv_out(84, 8, 4) # 84 -> 20
h2 = conv_out(h1, 4, 2) # 20 -> 9
conv1 = 8 * 8 * 4 * 16 + 16 # 16 filters of 8x8 over 4 stacked frames
conv2 = 4 * 4 * 16 * 32 + 32 # 32 filters of 4x4
fc = h2 * h2 * 32 * 256 + 256 # fully connected, 256 units
for n_act in (4, 18): # the paper: 4 to 18 valid actions
total = conv1 + conv2 + fc + 256 * n_act + n_act
print(f"{n_act:2d} actions: feature map {h1}x{h1}->{h2}x{h2}, "
f"params {total:,}")
# ---- 2) Table 1: average scores, placed between random and human ----
table = {"B. Rider": (354, 4092, 7456), "Breakout": (1.2, 168, 31),
"Enduro": (0, 470, 368), "Pong": (-20.4, 20, -3),
"Q*bert": (157, 1952, 18900), "Seaquest": (110, 1705, 28010),
"S. Invaders": (179, 581, 3690)}
for game, (rand, dqn, human) in table.items():
print(f"{game:11s} (DQN - random) / (human - random) = "
f"{(dqn - rand) / (human - rand):6.1%}")
# ---- 3) How much replay matters: a small ablation on CartPole ----
class CartPole:
"""Dynamics of the classic-control task CartPole (Euler, 0.02 s)."""
def __init__(self, seed):
self.rng = random.Random(seed)
def reset(self):
self.s = [self.rng.uniform(-0.05, 0.05) for _ in range(4)]
self.t = 0
return list(self.s)
def step(self, action):
x, xd, th, thd = self.s
force = 10.0 if action == 1 else -10.0
c, s = math.cos(th), math.sin(th)
temp = (force + 0.05 * thd * thd * s) / 1.1
tha = (9.8 * s - c * temp) / (0.5 * (4 / 3 - 0.1 * c * c / 1.1))
xa = temp - 0.05 * tha * c / 1.1
self.s = [x + 0.02 * xd, xd + 0.02 * xa, th + 0.02 * thd,
thd + 0.02 * tha]
self.t += 1
done = abs(self.s[0]) > 2.4 or abs(self.s[2]) > 0.2095 or self.t >= 500
return list(self.s), 1.0, done
def qnet():
return nn.Sequential(nn.Linear(4, 64), nn.ReLU(), nn.Linear(64, 64),
nn.ReLU(), nn.Linear(64, 2))
def run(variant, seed, steps=20_000, gamma=0.99, mb=32, cap=10_000):
"""variant: online (only the newest transition per step), replay (the
paper's Algorithm 1), replay+target (adds a frozen target network, as in
the later Nature version)."""
torch.manual_seed(seed)
rng = random.Random(seed + 500) # separate random numbers for epsilon
env = CartPole(10_000 + seed)
q, tgt = qnet(), qnet()
tgt.load_state_dict(q.state_dict())
opt = torch.optim.Adam(q.parameters(), lr=1e-3)
buf, obs, ep_ret, rets, curve = [], env.reset(), 0.0, [], []
for t in range(steps):
eps = max(0.05, 1 - 0.95 * t / 5000) # epsilon annealed linearly
if rng.random() < eps:
a = rng.randrange(2)
else:
with torch.no_grad():
a = q(torch.tensor(obs)).argmax().item()
nobs, r, done = env.step(a)
ep_ret += r
buf.append((obs, a, r, nobs, float(done)))
buf = buf[-cap:]
obs = nobs
if done:
rets.append(ep_ret)
ep_ret, obs = 0.0, env.reset()
if variant == "online":
batch = [buf[-1]]
else: # explore 500 steps at random before replay learning
batch = rng.sample(buf, mb) if t >= 500 else None
if batch:
o, a_, r_, n_, d_ = (torch.tensor(x) for x in zip(*batch))
with torch.no_grad(): # target y = r + gamma * max_a' Q(s', a')
net = tgt if variant == "replay+target" else q
y = r_ + gamma * (1 - d_) * net(n_).max(-1).values
pred = q(o).gather(1, a_.long()[:, None]).squeeze(1)
opt.zero_grad()
((pred - y) ** 2).mean().backward()
opt.step()
if variant == "replay+target" and t % 500 == 0:
tgt.load_state_dict(q.state_dict())
if (t + 1) % 5000 == 0: # mean return of the last 10 episodes
curve.append(sum(rets[-10:]) / max(1, len(rets[-10:])))
with torch.no_grad():
maxq = q(torch.tensor([b[0] for b in buf[-2000:]])).max(-1).values
return curve, maxq.mean().item()
print("variant 5k 10k 15k 20k max Q")
for variant in ("online", "replay", "replay+target"):
runs = [run(variant, seed) for seed in range(10)] # 10 seeds
cols = [f"{st.mean(c[i] for c, _ in runs):4.0f}±"
f"{st.stdev(c[i] for c, _ in runs):<4.0f}" for i in range(4)]
maxq = st.mean(m for _, m in runs)
print(f"{variant:14s}", " ".join(cols), f"{maxq:6.1f}")
Output (CPU, single thread, measured 3 to 5 minutes depending on machine load):
4 actions: feature map 20x20->9x9, params 677,172
18 actions: feature map 20x20->9x9, params 680,770
B. Rider (DQN - random) / (human - random) = 52.6%
Breakout (DQN - random) / (human - random) = 559.7%
Enduro (DQN - random) / (human - random) = 127.7%
Pong (DQN - random) / (human - random) = 232.2%
Q*bert (DQN - random) / (human - random) = 9.6%
Seaquest (DQN - random) / (human - random) = 5.7%
S. Invaders (DQN - random) / (human - random) = 11.4%
variant 5k 10k 15k 20k max Q
online 51±13 82±34 107±43 135±54 52.9
replay 183±27 243±49 210±73 246±99 522.2
replay+target 149±14 228±31 208±31 179±23 30.5
How to read these numbers:
- The network is small. With 4 actions it has 677,172 parameters and with 18 actions 680,770, under 700 thousand, and the fully connected layer holds nearly all of them (663,808). Today’s vision models often have hundreds of millions of parameters, and the deep RL network of the time was two orders of magnitude smaller.
- “Beating humans” holds on three games only, and by very different margins. By (DQN − random) / (human − random), Breakout is 560%, Pong 232%, Enduro 128%, Beam Rider 53%, and Q*bert, Seaquest and Space Invaders only 6% to 11%. This normalization is not the paper’s, it just helps to see the gaps.
- Experience replay gives the biggest gain. On CartPole replay reaches 183±27 at 5,000 steps while online Q-learning has only 51±13, and at 20,000 steps the online version has 135±54 and the replay version 246±99 (mean and standard deviation over 10 seeds).
- Without a target network the Q values balloon to impossible numbers. CartPole gives reward 1 per step and the discount is 0.99, so Q is bounded above by . With Algorithm 1’s approach (target from the current network) the mean max Q over the most recent states in the replay pool at the end of training is 522.2, far above the bound, and with a frozen target network it is 30.5, in a sensible range. This matches the motivation for the target network in the Nature version. Note that the paper reports no divergence on Atari, while I see Q inflation on CartPole with my own hyperparameters, which neither contradicts nor proves the other.
- But on this small task the return is not higher with the target network. At 20,000 steps replay has 246±99 and replay plus target 179±23. With 10 seeds that gap is close to two standard errors, and I do not conclude from it. All I can say is that the target network gives a much smaller variance (standard deviation 23 against 99) and a sensible Q scale, while the mean return does not clearly improve.
Limitations and what to keep in mind
- Only seven games. The paper itself says three of them (Q*bert, Seaquest, Space Invaders) are far below human level and need strategies over longer time scales. The later Nature version scaled to 49 games.
- The algorithm and the equations do not fully agree. Equation (2) writes the target with the previous iteration’s parameters , while the pseudocode of Algorithm 1 uses the current . I implemented the pseudocode in the experiment above and compared it with a version that adds a frozen target network.
- Reward clipping has a cost. It lets all games share a learning rate, but the agent cannot tell large rewards from small ones, which the paper admits may affect performance.
- Evaluation is noisy. The paper points out that average score is very sensitive to small weight changes because a policy change can shift the state distribution a lot.
- Uniform replay. The pool keeps only recent data and samples uniformly without telling important transitions apart, which later work such as prioritized experience replay improved.
- The CartPole experiment is teaching scale. With 10 seeds, 20,000 steps and a scaled-down network and hyperparameters, it cannot stand in for conclusions on Atari.
What to take from this paper
- A deep network can learn a value function directly from pixels. Given a recipe that trains stably.
- Experience replay makes RL look more like supervised learning. Reused data, decorrelated samples and a smoothed distribution.
- Off-policy learning is a prerequisite of replay. That is why Q-learning was chosen.
- The target has to be stable. A target that moves with the current network amplifies errors, and a frozen target network became the standard remedy.
- One set of hyperparameters across games is the most convincing part. It shows that the method, not game-specific tuning, does the work.
Further reading
- Paper: Playing Atari with Deep Reinforcement Learning
- Follow-up: Mnih et al., Human-level control through deep reinforcement learning (Nature, 2015, target network and 49 games)
- Related Wiki on this site: Reasoning RL
- Glossary: DQN, Experience replay
FAQ
- What is DQN?
- DQN (Deep Q-Network) is Q-learning with a convolutional neural network approximating the action-value function Q(s, a). The input is the last 4 preprocessed 84×84 frames and the output is one Q value per action. Training stores transitions (state, action, reward, next state) in a replay pool, samples random minibatches and does gradient descent toward the target r + γ·max Q(s', a').
- Why is experience replay useful?
- The paper gives three reasons. Each experience can be used in many weight updates, which is more data efficient. Consecutive samples are strongly correlated and random sampling breaks the correlation and lowers the variance of updates. And in on-policy learning the current parameters determine the next batch of data, which can create feedback loops or even divergence, while replay averages the behavior distribution over many past states. Replay requires off-policy learning, which is why Q-learning was chosen.
- How does this DQN differ from the later Nature version?
- This is the 2013 workshop preprint with seven games, and the regression target in its Algorithm 1 uses the current network parameters. The 2015 Nature version scaled to 49 games and computes the target with a periodically copied frozen network, which makes training more stable. The CartPole experiment here shows the difference in Q-value scale with and without a target network.
- On which games did DQN beat humans?
- By the average scores in Table 1 of the paper, DQN beats the human expert on Breakout (168 vs 31), Enduro (470 vs 368) and Pong (20 vs -3), and comes close on Beam Rider (4,092 vs 7,456, a bit over half). On Q*bert, Seaquest and Space Invaders the gap is large, and the paper says these games need strategies that span longer time scales.