Simple Algorithm
Reinforcement Learning · Bootstrapping · 24 min

Deep Q-Networks

Experience replay, target networks and learning Atari from pixels.

Forty-nine Atari games, one recipe: in 2015 the same network design and the same settings, trained afresh on each game, learned to play from nothing but the screen's pixels and the score. Its learning rule was Watkins's Q-learning of 1989. What made it work were a few engineering decisions, each answering a specific way that Q-learning with a neural network goes wrong. This lesson builds the agent piece by piece, measures what each piece buys, and follows its overestimation problem to Double DQN and the extensions that became Rainbow.

What you’ll learn

  • Write DQN's loss and training loop, and explain how a replay buffer and a target network turn online Q-learning into a sequence of regression problems.
  • Compute replay statistics from DQN's settings: the replay ratio, how often each transition is reused, and how old the oldest replayed data are.
  • Explain each step of the Atari pipeline (frame preprocessing and stacking, action repeat, reward clipping, the Huber loss) and what it costs.
  • Explain why the max in the target overestimates, how Double DQN fixes it with one changed line, and what the extensions combined in Rainbow change.

Q-learning with a network, done naively

Replace Q-learning's table by a neural network Qθ(s,a)Q_{\boldsymbol\theta}(s,a) and the obvious update after each transition (St,At,Rt+1,St+1)(S_t,A_t,R_{t+1},S_{t+1}) is the semi-gradient step

θ←θ+α δt ∇θQθ(St,At),δt=Rt+1+γmax⁡a′Qθ(St+1,a′)−Qθ(St,At).\boldsymbol\theta\leftarrow\boldsymbol\theta+\alpha\,\delta_t\,\nabla_{\boldsymbol\theta}Q_{\boldsymbol\theta}(S_t,A_t),\qquad\delta_t=R_{t+1}+\gamma\max_{a'}Q_{\boldsymbol\theta}(S_{t+1},a')-Q_{\boldsymbol\theta}(S_t,A_t).

It treats the target as a constant although the target depends on θ\boldsymbol\theta too. With a table this is Q-learning, which converges. With a network it contains all three ingredients of the deadly triad, and in practice it fails in three distinct ways.

  1. Correlated data. Consecutive frames are nearly identical, so a stream of updates drags the network toward whatever happened in the last few seconds. Worse, the data depend on the parameters: while the greedy action is left, the samples come from the left of the screen, and when it switches to right, so does the training distribution. Mnih et al. (2015) name this feedback loop as a cause of poor minima and divergence.
  2. A moving target. Each update changes max⁡a′Qθ(s′,a′)\max_{a'}Q_{\boldsymbol\theta}(s',a') for many states at once, including those that supply the next targets, so the regression chases itself.
  3. An optimistic target. The max over noisy estimates is biased upward, and bootstrapping feeds the bias into later targets.

Earlier successes had sidestepped these problems in special settings: neural fitted Q-iteration (Riedmiller, 2005) retrained a network on a fixed batch of transitions, and TD-Gammon learned backgammon from self-play. The deep Q-network (DQN) of Mnih et al. (2013, 2015) was a recipe that worked across dozens of games with nothing tuned per game.

Think first Why not differentiate through the target as well, and do true gradient descent on the squared TD error E[δ2]\E[\delta^2]?

That is Baird's (1995) residual-gradient algorithm. As true gradient descent on a fixed objective it cannot diverge the way semi-gradient updates can, but the objective is the wrong one when transitions are random: E[δ2]\E[\delta^2] equals the squared Bellman error plus the variance of the target given (s,a)(s,a), and that variance depends on the weights, so the minimizer is biased even when the true values are representable. Removing the bias needs two independent next states from the same state (the double-sampling problem), which a simulator may offer and real experience does not. Residual gradients are also slow in practice. DQN keeps the semi-gradient and stabilizes it in other ways; The Projected Bellman Equation & LSTD compares the objectives.

Two tricks: a replay buffer and a target network

DQN keeps the semi-gradient update but changes what it is applied to. A replay buffer D\data stores the most recent N=106N=10^6 transitions, and each update uses a minibatch of 32 drawn from it uniformly at random (experience replay, an idea of Lin, 1992). A target network with parameters θ−\boldsymbol\theta^-, a copy of θ\boldsymbol\theta refreshed every C=10,000C=10{,}000 updates, computes the targets. Each update descends the loss

L(θ)=E(s,a,r,s′)∼U(D)[ℓ(r+γmax⁡a′Qθ−(s′,a′)−Qθ(s,a))]\loss(\boldsymbol\theta)=\E_{(s,a,r,s')\sim U(\data)}\Big[\ell\Big(r+\gamma\max_{a'}Q_{\boldsymbol\theta^-}(s',a')-Q_{\boldsymbol\theta}(s,a)\Big)\Big]
ℓ\ell is the squared error, or in DQN the Huber loss (below). Between refreshes each transition's target is a fixed number, so minimizing L\loss is ordinary regression, and each refresh starts the next regression: DQN is a stochastic, online version of fitted Q-iteration (Fitted Q-Iteration & Its Guarantees).

Replay addresses the first failure: a minibatch from a million stored transitions mixes many moments of many episodes, and each transition is reused several times. The target network addresses the second: within a refresh period, an update cannot move its own targets. Neither touches the third, the optimistic max, which returns at the end of this lesson. The loop, with the settings of the 2015 paper:

text
initialize Q_θ at random;  θ⁻ ← θ;  replay buffer D ← empty (capacity 1,000,000)
act uniformly at random for the first 50,000 steps, storing every transition in D
for each step t:
    ε ← falls linearly from 1.0 to 0.1 over the first million steps, then stays at 0.1
    a ← a random action with probability ε, else argmax_a Q_θ(s, a)
    repeat a for 4 frames; observe the clipped reward r, the next state s', terminated
    store (s, a, r, s', terminated) in D, evicting the oldest transition when full
    every 4 steps:  sample 32 transitions uniformly from D;  one RMSProp step on L(θ)
    every C = 10,000 updates:  θ⁻ ← θ

Mnih et al.'s table states the ε schedule, the random start and the memory in "frames" and the target-network period in parameter updates, but DeepMind's released code counts all four in agent steps of 4 frames, so its target network is copied every 10,000 steps, that is every 2,500 updates. Later reimplementations follow the code (Hessel et al., 2018, describe DQN's ε schedule as 4 million frames).

python
import torch
import torch.nn.functional as F

def dqn_loss(q_net, target_net, batch, gamma=0.99, double=False):
    """batch: s, s2 of shape (B, 4, 84, 84); a (B,) int64; r, d (B,) float (d = terminated)."""
    s, a, r, s2, d = batch
    q = q_net(s).gather(1, a.unsqueeze(1)).squeeze(1)   # Q_theta(s, a)
    with torch.no_grad():                                 # the target is a constant
        q2 = target_net(s2)                               # Q_theta-(s', .)
        if double:                                        # Double DQN: the online net chooses a'
            a2 = q_net(s2).argmax(dim=1, keepdim=True)
            v2 = q2.gather(1, a2).squeeze(1)
        else:                                             # DQN: max of the target net
            v2 = q2.max(dim=1).values
        y = r + gamma * (1.0 - d) * v2                    # no bootstrap after termination
    return F.smooth_l1_loss(q, y)                         # Huber loss with threshold 1

One update is opt.zero_grad(); dqn_loss(q_net, target_net, batch).backward(); opt.step(). The flag d must mark true terminations only: when a time limit cuts an episode off (Gymnasium's truncated), the last state still has a value, and the target should bootstrap from it.

What the two tricks buy

Predict before you look

DQN does one update on 32 transitions after every 4 environment steps, and its buffer holds the most recent 1,000,000 transitions. On average, how many times is a transition drawn for an update before it is evicted?

Show the answer

8

Each step adds one transition and draws, on average, 32/4=832/4=8 samples from the buffer. A transition stays for 10610^6 steps, during which 8×1068\times10^6 samples are drawn uniformly from 10610^6 transitions: 8 draws each. The buffer size cancels. It decides how old the replayed data are, not how often each transition is reused.

Fedus et al. (2020) name the quantities this count separates. The replay ratio is the number of gradient updates per environment step: 1/41/4 for DQN, and times the minibatch size it gives the reuse count. The age of the oldest policy in the buffer, in gradient updates, is the capacity times the replay ratio: 106×14=250,00010^6\times\tfrac14=250{,}000 updates for DQN. A bigger buffer at the same replay ratio holds older, more off-policy data; whether that helps depends on the rest of the agent (Experience Replay in Depth).

Mnih et al. also measured what each trick is worth, training for 10 million frames with each switched on or off (each entry the best over three step sizes and over the evaluations made during training):

GameReplay and target networkReplay onlyTarget network onlyNeither
Breakout316.8240.710.23.2
Enduro1006.3831.4141.929.1
River Raid7446.64102.82867.71453.0
Seaquest2894.4822.61003.0275.8
Space Invaders1088.9826.3373.2302.0
Game scores from Extended Data Table 3 of Mnih et al. (2015).
Check your understanding

What does this table support?

  1. The target network does most of the work; replay is a minor refinement
  2. Replay alone matches the full agent
  3. Each trick helps on its own, and together they are best on every game
  4. Without replay, adding a target network makes things worse
Show the answer

C. Each trick helps on its own, and together they are best on every game

In every row the agent with both tricks scores highest and the agent with neither lowest, and each trick alone beats neither. Removing replay costs more than removing the target network on four of the five games (Breakout falls to 10.2 without replay, to 240.7 without the target network); Seaquest is the exception. Five games, with no repeated runs reported, are a small sample, but the pattern is consistent.

From pixels to Q-values: the Atari pipeline

The Arcade Learning Environment (Bellemare et al., 2013) serves Atari 2600 games as 210 × 160 color frames at 60 Hz, with up to 18 joystick actions and the change in score as reward. DQN's network has three convolutional layers (32 filters of 8 × 8 with stride 4, then 64 of 4 × 4 with stride 2, then 64 of 3 × 3 with stride 1), a fully connected layer of 512 rectifier units, and one linear output per action (4 to 18, depending on the game). A single forward pass scores every action, which is what the max in the target needs. The rest of the pipeline is a set of trades:

ChoiceWhyWhat it costs
Pixelwise max of each frame and the one before; luminance only; 84 × 84Some sprites are drawn only on even frames, others only on odd ones; a smaller inputColor and fine detail
Act every 4th frame, repeating the action in betweenAbout 4 times more play per unit of computationCoarser control: no reaction inside 4 frames
Input = the last 4 processed frames (frame stacking)One frame cannot show which way the ball is movingAnything older than 4 decisions is forgotten (Memory in Deep RL)
Rewards clipped to −1-1, 00, +1+1One step size suits games whose scores differ by orders of magnitudeA 10-point and a 1,000-point event look the same
Error clipping: the Huber loss with threshold 1A single large TD error cannot cause a huge stepLarge errors shrink at a bounded rate
Losing a life ends the episode during trainingEarlier, denser signal that dying is badThe training task differs from the evaluated one
All from Mnih et al. (2015). The hyperparameters were tuned informally on five games (Pong, Breakout, Seaquest, Space Invaders, Beam Rider), then used unchanged on all 49; each game was trained for 50 million agent steps, 200 million frames or about 38 days of play (the paper says "50 million frames", but 38 days at 60 Hz is 200 million).
Think first The convolutional layers turn the 84×84×484\times84\times4 input into a 7×7×647\times7\times64 block. Where do most of the network's roughly 1.7 million parameters live?

In the fully connected layer: 7⋅7⋅64=31367\cdot7\cdot64=3136 inputs times 512 units is about 1.61 million weights, about 95% of the total. The three convolutional layers have about 78,000 parameters together (8⋅8⋅4⋅32+4⋅4⋅32⋅64+3⋅3⋅64⋅64=77,8248\cdot8\cdot4\cdot32+4\cdot4\cdot32\cdot64+3\cdot3\cdot64\cdot64=77{,}824 weights plus 160 biases), and the output layer about 9,200 for 18 actions. The networks that later scaled deep RL up replaced this small encoder (Plasticity Loss & Scaling Deep RL).

With these settings fixed, DQN beat the best earlier reinforcement-learning methods on 43 of the 49 games and reached at least 75% of a professional games tester's score on 29. Scores are human-normalized, 100×(agent−random)/(human−random)100\times(\text{agent}-\text{random})/(\text{human}-\text{random}): 1,327% on Breakout and 2,539% on Video Pinball, but 0% on Montezuma's Revenge (DQN scored 0), 2.5% on Private Eye and 5.3% on Gravitar. Those are games where reward is sparse and long sequences of correct actions come before any (Exploration Bonuses at Scale).

Read these numbers with their protocol. The human baseline is one tester after about two hours of practice per game; evaluation episodes began after up to 30 random no-op actions and used ε=0.05\varepsilon=0.05. Because the emulator is deterministic, an agent can score by memorizing action sequences; later protocols add sticky actions, repeating the previous action with probability 0.25 (Machado et al., 2018), and report robust aggregates over many runs (Benchmarks & Honest Evaluation).

Think first A game awards 10 points for small targets and 1,000 for a boss. What does DQN, trained on clipped rewards, actually learn to maximize?

The discounted count of rewarding events (minus penalized ones), whatever their sizes: after clipping, a small target and the boss both give +1+1. If shooting three small targets is quicker than reaching the boss, the clipped objective prefers the targets, though the score prefers the boss. Mnih et al. name this cost: the agent cannot tell rewards of different magnitudes apart. Later agents keep the magnitudes and tame the scale in other ways, for example by normalizing the value targets adaptively.

Overestimation and Double DQN

The third failure is statistical. Suppose all mm actions in s′s' are equally good and their estimates are right on average but noisy. The max picks whichever estimate happens to be highest, so it is biased upward, E[max⁡aQ^(s′,a)]≥max⁡aE[Q^(s′,a)]\E\big[\max_a\hat Q(s',a)\big]\ge\max_a\E\big[\hat Q(s',a)\big]: this is maximization bias. Thrun and Schwartz (1993) computed its size for errors spread uniformly over an interval. Bootstrapping then spreads it: every target is built from maxima that were themselves too high (Maximization Bias & Double Q-Learning proves both effects).

Predict before you look

All 18 actions of a full Atari joystick are equally good, and each estimate carries an independent error uniform on [−1,1][-1,1]. What is the expected value of the largest error?

Show the answer

0.89

The largest of mm independent uniforms on [0,1][0,1] has mean m/(m+1)m/(m+1); rescaling to [−1,1][-1,1] gives 2m/(m+1)−1=(m−1)/(m+1)=17/19≈0.892m/(m+1)-1=(m-1)/(m+1)=17/19\approx0.89, almost the whole error range. With 2 actions it is only 1/31/3. This is Thrun and Schwartz's estimate: with errors in [−ϵ,ϵ][-\epsilon,\epsilon] each target is overestimated by up to γϵ (m−1)/(m+1)\gamma\epsilon\,(m-1)/(m+1).

Double Q-learning (van Hasselt, 2010) lets one estimate choose the maximizing action and another evaluate it. DQN already has two networks, so Double DQN (van Hasselt, Guez & Silver, 2016) lets the online network choose and the target network evaluate:

yDouble=r+γ Qθ−(s′, arg max⁡a′Qθ(s′,a′))y^{\text{Double}}=r+\gamma\,Q_{\boldsymbol\theta^-}\Big(s',\ \argmax_{a'}Q_{\boldsymbol\theta}(s',a')\Big)
One line differs from DQN (double=True in the loss above). An action picked because its online estimate happens to be too high is scored by the target network, whose error for that action is not systematically high. The two networks share history, so the correction is partial.

On Atari, DQN's value estimates were too high in all 49 games, by varying amounts; on Asterix and Wizard of Wor they rose far above the true values of the learned policies (the paper plots them on a log scale) just as the scores fell. With DQN's hyperparameters unchanged, Double DQN raised the median human-normalized score from 93.5% to 114.7%. A tuned version, with the period between target-network copies tripled from 10,000 to 30,000 (the paper counts it in frames), ε=0.01\varepsilon=0.01 while learning and one shared bias for all action values, reached a median of 116.7% under the harder human-starts evaluation, where DQN scored 47.5%.

From DQN to Rainbow

Double DQN was one of the first of many targeted repairs, each changing one part of the pipeline:

ExtensionPart it changesThe change
Double DQN (van Hasselt et al., 2016)TargetThe online network chooses a′a', the target network evaluates it
Prioritized replay (Schaul et al., 2016)Which transitions are replayedSample by a power of the last TD error; correct with importance weights
Dueling network (Wang et al., 2016)Network headQ(s,a)=V(s)+A(s,a)−1∣A∣∑a′A(s,a′)Q(s,a)=V(s)+A(s,a)-\frac{1}{\abs{\mathcal A}}\sum_{a'}A(s,a')
Multi-step targetsTargetnn real rewards before bootstrapping (n=3n=3 in Rainbow)
Distributional RL: C51 (Bellemare et al., 2017)Target and lossPredict 51 probabilities of the return; cross-entropy loss
Noisy networks (Fortunato et al., 2018)ExplorationLearned noise on the weights replaces ε\varepsilon-greedy
Rainbow (Hessel et al., 2018) combined all six. After 200 million frames its median human-normalized score over 57 games was 223%, against 79% for DQN in the same comparison, and it matched DQN's final performance after only 7 million frames.

Other lines of work changed the setting rather than the agent: hundreds of actors filling one shared prioritized buffer (Ape-X; Horgan et al., 2018), recurrent networks trained on replayed sequences (Memory in Deep RL), exploration bonuses for games like Montezuma's Revenge (Exploration Bonuses at Scale), and learning from a fixed dataset with no interaction (Offline RL). The Atari 100k benchmark (Kaiser et al., 2020) caps interaction at 100,000 agent steps, about two hours of play per game; by the mid-2020s value-based agents reach human-level aggregate scores within it, with far larger networks and far more updates per step than DQN used.

Key takeaways

  • DQN runs Q-learning on a convolutional network with two stabilizers: minibatches drawn uniformly from the last million transitions, and targets from a frozen copy refreshed every 10,000 updates. Between refreshes it solves a regression, which makes it a stochastic, online form of fitted Q-iteration.
  • Reuse per transition is the replay ratio times the minibatch size (8 for DQN), whatever the buffer size; the buffer size sets the age of the replayed data (250,000 updates for DQN).
  • In Mnih et al.'s ablation each trick helped on its own and both together were best on all five games, with replay the more important on four of them.
  • The Atari pipeline (frame max and stacking, action repeat, reward and error clipping) trades information for one setting that works across games; DQN beat earlier methods on 43 of 49 games yet scored 0 on Montezuma's Revenge.
  • The max over noisy estimates overestimates, more so with more actions; Double DQN lets the online network choose and the target network evaluate, at the price of a tendency to underestimate. Rainbow combined it with five other repairs.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You double DQN's buffer to 2,000,000 transitions and keep one update on 32 transitions every 4 steps. What changes?

  1. Each transition is replayed about twice as often
  2. The replay ratio halves
  3. Neither the reuse nor the age of the replayed data changes
  4. Each transition is still replayed about 8 times, but the oldest data are now twice as old, 500,000 updates
Show the answer

D. Each transition is still replayed about 8 times, but the oldest data are now twice as old, 500,000 updates

Reuse per transition is the replay ratio times the minibatch size, 14×32=8\tfrac14\times32=8, whatever the capacity. The oldest transition was generated 2×1062\times10^6 steps ago, which at 14\tfrac14 update per step is 500,000 updates: the data are older and more off-policy.

Question 2

Within one target-network period, what problem is DQN solving?

  1. A regression of Qθ(s,a)Q_{\boldsymbol\theta}(s,a) onto fixed labels r+γmax⁡a′Qθ−(s′,a′)r+\gamma\max_{a'}Q_{\boldsymbol\theta^-}(s',a') for transitions drawn from the buffer
  2. Minimizing the squared Bellman error of QθQ_{\boldsymbol\theta}
  3. Evaluating the ε\varepsilon-greedy policy that collected the data
  4. Maximizing the game score by gradient ascent
Show the answer

A. A regression of Qθ(s,a)Q_{\boldsymbol\theta}(s,a) onto fixed labels r+γmax⁡a′Qθ−(s′,a′)r+\gamma\max_{a'}Q_{\boldsymbol\theta^-}(s',a') for transitions drawn from the buffer

With θ−\boldsymbol\theta^- frozen, each replayed transition has a fixed label, and the loss is a supervised regression toward an approximate Bellman backup of Qθ−Q_{\boldsymbol\theta^-}, one step of approximate value iteration. Refreshing θ−\boldsymbol\theta^- moves on to the next step.

Question 3

DQN clips the TD error's contribution to the gradient: the per-sample gradient is δ\delta when ∣δ∣≤1\abs\delta\le1 and ±1\pm1 beyond. What does this change?

  1. It makes the update an unbiased estimate of the Bellman error's gradient
  2. A transition with a huge TD error moves the weights no further than one with ∣δ∣=1\abs\delta=1, so rare large errors cannot cause huge steps
  3. Transitions with ∣δ∣>1\abs\delta>1 are ignored
  4. It is the same as clipping the rewards
Show the answer

B. A transition with a huge TD error moves the weights no further than one with ∣δ∣=1\abs\delta=1, so rare large errors cannot cause huge steps

Clipping the error's derivative is exactly the Huber loss with threshold 1: quadratic near zero, linear beyond, so the gradient's size is capped at 1. Large errors are still corrected, at a bounded rate. Mnih et al. report that it improved stability.

Question 4

Why does the overestimation caused by the max grow with the number of actions?

  1. The discount is applied once per action, so more actions compound it
  2. Each extra output unit adds parameters that overfit
  3. The max has more chances to land on an estimate whose error happens to be large
  4. It does not: the bias depends only on how noisy each estimate is
Show the answer

C. The max has more chances to land on an estimate whose error happens to be large

For equally good actions with independent errors uniform on [−ϵ,ϵ][-\epsilon,\epsilon], the expected largest error is ϵ(m−1)/(m+1)\epsilon(m-1)/(m+1): zero for one action, ϵ/3\epsilon/3 for two, 0.89ϵ0.89\epsilon for eighteen. In the widget, Q-learning's peak share of left moves rises from 51% with one action in B to 96% with twenty.

Question 5

With B's mean reward at +0.1+0.1, left is the better action, yet Double Q-learning goes left only 14% of the time over episodes 251–300. Why?

  1. It explores less than Q-learning does
  2. Scoring the chosen action with an independent estimate removes the upward bias, but the result tends to fall below the true maximum, so left is undervalued
  3. Each of its two tables sees only half the data, so it has learned nothing yet
  4. Double Q-learning prefers actions that end the episode
Show the answer

B. Scoring the chosen action with an independent estimate removes the upward bias, but the result tends to fall below the true maximum, so left is undervalued

If QAQ_A picks a^\hat a and QBQ_B is unbiased and independent of QAQ_A, then E[QB(a^)]=E[q(a^)]≤max⁡aq(a)\E[Q_B(\hat a)]=\E[q(\hat a)]\le\max_aq(a), with strict inequality whenever QAQ_A sometimes picks a worse action. In the widget's engine, Double Q-learning's average estimate of left's value after 300 episodes is −0.023-0.023, where the truth is 0.10.1: often enough below right's exact 0 to keep the agent away.

Go deeper

Further reading

  • V. Mnih et al., "Human-level control through deep reinforcement learning", Nature 518, 529–533 (2015).
  • V. Mnih et al., "Playing Atari with deep reinforcement learning", NIPS Deep Learning Workshop, arXiv:1312.5602 (2013).
  • H. van Hasselt, A. Guez & D. Silver, "Deep reinforcement learning with double Q-learning", AAAI (2016).
  • L.-J. Lin, "Self-improving reactive agents based on reinforcement learning, planning and teaching", Machine Learning 8(3–4), 293–321 (1992).