Course contents 06 / 27

06 / 27 · Reinforcement Learning

Deep Q-networks

Q-learning with a neural network in place of the table: semi-gradient updates, the deadly triad and why it can diverge, experience replay and target networks, the Atari agent, overestimation and Double DQN, and what dueling networks, prioritized replay and Rainbow fix.

On this page 8

The previous note learned action values from experience, one entry of a table per state and action, with guarantees that hold as long as every entry is visited infinitely often. Interesting tasks never visit the same state twice. A video game shows a new screen at every step, a robot’s joints take continuous angles, and a language model’s context is practically never repeated. The values must be computed by a function with far fewer parameters than there are states, a function that also carries what was learned in one state over to similar ones. This note puts a neural network in place of the table, shows why the combination can diverge where the table could not, and builds the deep Q-network (DQN), whose two stabilizing devices made it the first agent to learn many Atari games from pixels with one set of hyperparameters. It ends with the fixes that followed: Double DQN, dueling networks, prioritized replay and their combination, Rainbow.

Notation. As in the previous notes, with these additions. Qθ(s,a)Q_\theta(s, a) is an action-value function with parameters θ\theta, a neural network or a linear function θ⊤ϕ(s,a)\theta^\top \phi(s, a) of features ϕ\phi. θ−\theta^- are the parameters of a second copy, the target network. D\mathcal D is the replay buffer, a store of past transitions (s,a,r,s′)(s, a, r, s'), with d∈{0,1}d \in \{0, 1\} marking whether s′s' is terminal. yy is a regression target and L(θ)L(\theta) a loss. NN, BB and CC are the buffer size, the minibatch size and the number of steps between copies of θ\theta into θ−\theta^-.

Baseline: a table with one entry per state#

A grey-scale Atari screen downsampled to 84×8484 \times 84 pixels with 256 levels, four consecutive frames stacked, can take 2564⋅84⋅84=25628 224256^{4 \cdot 84 \cdot 84} = 256^{28\,224} values. No table has that many rows, and even if it had, almost every row would be visited at most once, so its entry would be an average of one sample. The cart-pole of the Code section, a pole balanced on a cart, has a state of four real numbers: position, velocity, angle and angular velocity; it has no finite table at all. Splitting the continuous state into bins brings the table back, but its size grows exponentially with the number of state variables, and two neighbouring bins are still learned independently.

What is missing is generalization: a pole tilted by 3.1 degrees should be treated almost like one tilted by 3.0. The ML course gets generalization from parametric models fitted by gradient descent, and the same tool applies here once Q-learning is written as regression.

Q-learning as regression#

Suppose an oracle gave the true value y=Q⋆(s,a)y = Q^\star(s, a) for the sampled state and action. Fitting QθQ_\theta to it would be ordinary regression with the squared error 12(y−Qθ(s,a))2\frac12 (y - Q_\theta(s, a))^2, and one step of stochastic gradient descent with step size α\alpha would be

θ←θ−α ∇θ12(y−Qθ(s,a))2=θ+α(y−Qθ(s,a))∇θQθ(s,a).\theta \leftarrow \theta - \alpha\, \nabla_\theta \tfrac12 \big( y - Q_\theta(s, a) \big)^2 = \theta + \alpha \big( y - Q_\theta(s, a) \big) \nabla_\theta Q_\theta(s, a).

There is no oracle. Q-learning’s answer is to use its own target, y=r+γmax⁡a′Qθ(s′,a′)y = r + \gamma \max_{a'} Q_\theta(s', a') (with y=ry = r when s′s' is terminal), and to treat it as a constant when taking the gradient:

  θ←θ+α[r+γmax⁡a′Qθ(s′,a′)−Qθ(s,a)]∇θQθ(s,a)  \boxed{\; \theta \leftarrow \theta + \alpha \Big[ r + \gamma \max_{a'} Q_\theta(s', a') - Q_\theta(s, a) \Big] \nabla_\theta Q_\theta(s, a) \;}

This is semi-gradient Q-learning. With a table, Qθ(s,a)=θs,aQ_\theta(s, a) = \theta_{s,a} and the gradient is 1 at entry (s,a)(s, a) and 0 elsewhere, so the update is exactly tabular Q-learning. With linear features, ∇θQθ(s,a)=ϕ(s,a)\nabla_\theta Q_\theta(s, a) = \phi(s, a), and the update moves every state that shares features with ss. With a network, the gradient comes from backpropagation, as in the PyTorch note.

Why “semi”? The target depends on θ\theta too. The full gradient of the squared TD error 12δ2\frac12 \delta^2 would contain a second term, −γ∇θmax⁡a′Qθ(s′,a′)-\gamma \nabla_\theta \max_{a'} Q_\theta(s', a'), that also moves the target. Following the full gradient gives residual-gradient methods (Baird, 1995), which are true gradient descent and do converge, but slowly, and in a stochastic environment they need two independent samples of s′s' to be unbiased. The semi-gradient is not the gradient of any fixed objective. It learns faster in practice, and it is what every method of this note uses, but it gives up the guarantee that comes with descending a loss.

The deadly triad#

Three ingredients are each useful and each benign alone, and together they can make the estimates diverge (Sutton and Barto, 2018, section 11.3):

  1. Function approximation: one set of parameters for many states, so an update to one state changes others.
  2. Bootstrapping: targets built from the current estimates, as in TD and Q-learning, rather than from complete returns.
  3. Off-policy training: updates distributed differently from the states the target policy visits, as when Q-learning learns the greedy policy from ε-greedy data, or from old data.

Any two are safe. Linear TD with on-policy updates converges (Tsitsiklis and Van Roy, 1997). Monte Carlo targets with function approximation are plain regression. Tabular Q-learning is off-policy and bootstraps, and converges, as the previous note stated. Q-learning with a neural network has all three.

Worked example. Two states have features 11 and 22, and a linear estimate with one weight ww gives them the values ww and 2w2w. From state 1 the agent moves to state 2 with reward 0; from state 2 the episode ends with reward 0. All true values are 0, which w=0w = 0 represents exactly. Now suppose the data contain only the first transition, as can happen off-policy when a behaviour policy visits state 1 but its continuation is never sampled. The TD error is 0+γ⋅2w−w=(2γ−1)w0 + \gamma \cdot 2w - w = (2\gamma - 1) w and the semi-gradient update is

w←w+α(2γ−1) w⋅1=(1+α(2γ−1)) w.w \leftarrow w + \alpha (2\gamma - 1)\, w \cdot 1 = \big( 1 + \alpha (2\gamma - 1) \big)\, w .

For γ>1/2\gamma > 1/2 the factor exceeds 1: with γ=0.9\gamma = 0.9 and α=0.1\alpha = 0.1 it is 1.081.08, and after 60 updates ww has grown from 1 to 101. Each update raises the value of state 1 towards γ\gamma times the value of state 2, and because the two share the weight, raising one raises the other twice as much. Remove any one leg of the triad and the same example converges:

Figure

The deadly triad on two states

The deadly triad on two statesThe estimate of the first state over 60 updates, on a log scale. Semi-gradient TD with features 1 and 2 that updates only the transition out of the first state grows by a factor 1.08 per update and reaches 101. Updating both states as the episodes visit them sends the estimate to zero. With the Monte Carlo target it falls like 0.9 to the power of the number of updates. With a separate value for each state it levels off at 1.8.0.0010.010.111010010000204060updatesestimate of state 1 (log scale)all three: divergesno approximation: a tableno bootstrapping: Monte Carlonot off-policy: updates follow episodesThe deadly triad on two statesThe estimate of the first state over 60 updates, on a log scale. Semi-gradient TD with features 1 and 2 that updates only the transition out of the first state grows by a factor 1.08 per update and reaches 101. Updating both states as the episodes visit them sends the estimate to zero. With the Monte Carlo target it falls like 0.9 to the power of the number of updates. With a separate value for each state it levels off at 1.8.0.0010.010.111010010000204060updatesestimate of state 1 (log scale)all three: divergesno approximation: a tableno bootstrapping: Monte Carlonot off-policy: updates follow episodes
State 1 has feature 1 and state 2 feature 2, so a linear estimate with one weight w gives v(1) = w and v(2) = 2w; the transition 1 → 2 has reward 0 and then the episode ends, so every true value is 0; γ = 0.9, α = 0.1, w = 1 at the start. The red curve combines all three legs of the triad and is multiplied by 1 + α(2γ − 1) = 1.08 per update. Each of the other three removes one leg and converges: updates that follow the episodes (clipped at 0.001 in the plot), a Monte Carlo target without bootstrapping, and a table without shared features (it converges to γ · 2 = 1.8 because state 2 is never updated).

The divergence is not caused by noise or a large step size: there is no randomness in this example, and a smaller α\alpha only slows it. Better-known counterexamples, such as Baird’s seven-state star, show the same effect with features that are linearly independent and a perfect solution available (Baird, 1995; Sutton and Barto, 2018, section 11.2). In deep networks, values usually stay bounded in practice, but inflated, oscillating estimates are common (van Hasselt et al., 2018). DQN cannot leave the triad, because a network that bootstraps off-policy is what it is. What it can do is make each step look as much as possible like the supervised regression that SGD handles well.

DQN: experience replay and a target network#

Mnih et al. (2015), following Mnih et al. (2013), minimize, at every step, the loss

  L(θ)=E(s,a,r,s′,d)∼U(D)[ℓ(r+γ(1−d)max⁡a′Qθ−(s′,a′)−Qθ(s,a))]  \boxed{\; L(\theta) = \mathbb E_{(s, a, r, s', d) \sim \mathcal U(\mathcal D)} \Big[ \ell\Big( r + \gamma (1 - d) \max_{a'} Q_{\theta^-}(s', a') - Q_\theta(s, a) \Big) \Big] \;}

where U(D)\mathcal U(\mathcal D) is the uniform distribution over the transitions in the buffer, ℓ\ell is the Huber loss (quadratic for errors below 1 and linear above, which clips the gradient of large errors), and the gradient is taken with respect to θ\theta only:

Figure

The DQN training loop

The DQN training loopOn the left, the environment and the ε-greedy choice of action. Transitions (s, a, r, s′) go into the replay buffer, from which a random minibatch is drawn. On the right, from top to bottom: the target network with frozen weights θ⁻ evaluates s′ and gives the target y; a Huber loss compares it with the online network's Q_θ(s, a); the gradient changes only θ; every C steps θ is copied into θ⁻. Bottom left, the settings of the Atari agent.environmentCartPole, an Atari gameact ε-greedilygreedy in Q, or random1(s, a, r, s′)replay buffer Dlast N = 10⁶ transitions2minibatchB = 32, drawn uniformly3s′target network Qθ⁻a frozen copy of θy = r + γ max Qθ⁻(s′, ·)0 after a terminal state4s, aHuber loss of Qθ(s, a) − ygradient step on θ onlyonline network Qθgives Q(s, a) and chooses actions∇θ5θ⁻ ← θ6Atari (Mnih et al., 2015):input: 4 frames of 84 × 84 pixels3 conv layers + 512 units → up to 18 Q-valuesC = 10 000 updates; ε: 1 → 0.1The DQN training loopOn the left, the environment and the ε-greedy choice of action. Transitions (s, a, r, s′) go into the replay buffer, from which a random minibatch is drawn. On the right, from top to bottom: the target network with frozen weights θ⁻ evaluates s′ and gives the target y; a Huber loss compares it with the online network's Q_θ(s, a); the gradient changes only θ; every C steps θ is copied into θ⁻. Bottom left, the settings of the Atari agent.environmentCartPole, Atariact ε-greedilygreedy in Q1(s, a, r, s′)replay buffer Dlast N = 10⁶ transitions2minibatchB = 32, drawn uniformly3s′target network Qθ⁻a frozen copy of θtarget yr + γ max over a′ of Q⁻(s′, a′)4Huber lossQ(s, a) − y, step on θonline network Qθgives Q(s, a)s, a5θ⁻ ← θ6
The two devices of DQN are coloured: the replay buffer (green) breaks the correlation between consecutive transitions and lets each transition be used many times; the target network (amber) holds the target y still between synchronizations, so that each stretch of training is an ordinary regression. Without them, Q-learning with a network chases a target that moves with every step.
  1. Act. The agent picks aa ε-greedily from Qθ(s,⋅)Q_\theta(s, \cdot); the environment returns rr and s′s'.
  2. Store. The transition goes into the buffer D\mathcal D, which keeps the last NN of them.
  3. Sample. A minibatch of BB transitions is drawn uniformly from the buffer.
  4. Target. The target network evaluates each s′s': y=r+γ(1−d)max⁡a′Qθ−(s′,a′)y = r + \gamma (1 - d) \max_{a'} Q_{\theta^-}(s', a').
  5. Step. One gradient step on L(θ)L(\theta) moves the online network’s Qθ(s,a)Q_\theta(s, a) towards yy.
  6. Sync. Every CC steps, θ−←θ\theta^- \leftarrow \theta.

Why replay helps. Consecutive transitions are strongly correlated: the frames of one second of play look alike, and a minibatch of them is one example repeated, not BB independent ones. Sampling from the last million transitions mixes thousands of episodes. Replay also reuses data: in the Atari agent, a gradient step of 32 transitions every 4 steps means 8 samples drawn per step, so a transition that stays in the buffer for a million steps is drawn about 8 times on average. And it averages the training distribution over many past policies, which damps a feedback loop in which the current greedy action decides the next data, which decide the next greedy action. Replay is possible only because Q-learning is off-policy: the stored transitions come from older policies. The idea goes back to Lin (1992).

Why the target network helps. With θ−\theta^- fixed, the targets yy do not move while θ\theta is fitted to them, so between two copies the problem is a regression with fixed labels. Each copy then starts a new regression, one step of value iteration done by a network: the method is a version of fitted Q-iteration (Ernst, Geurts and Wehenkel, 2005; Riedmiller, 2005). In the two-state example the target network does not save the day: if each regression is solved exactly, ww becomes 2γw−2\gamma w^-, and 1.81.8 per copy still diverges. A target network slows the feedback between the estimates and their targets; it does not remove the triad.

Both devices on CartPole. The Code section trains the same network four ways: with neither device, with replay only, with the target network only, and with both, plus Double DQN, two seeds each.

Figure

Replay and the target network on CartPole

Replay and the target network on CartPoleFive curves of the mean episode return over 20,000 steps. Without a target network, with or without replay, the return falls to 10: the Q-values diverge to millions. With the target network alone it wanders between 10 and 30. DQN and Double DQN climb to 150–200 by 5000 steps and stay there, averaging 154 and 162 over the last 10,000 steps.05010015020025005101520environment steps, thousandsmean episode returnDQN: bothDouble DQNtarget network onlyreplay onlyneitherReplay and the target network on CartPoleFive curves of the mean episode return over 20,000 steps. Without a target network, with or without replay, the return falls to 10: the Q-values diverge to millions. With the target network alone it wanders between 10 and 30. DQN and Double DQN climb to 150–200 by 5000 steps and stay there, averaging 154 and 162 over the last 10,000 steps.05010015020025005101520environment steps, thousandsmean episode returnDQN: bothDouble DQNtarget network onlyreplay onlyneither
The Code section of the note: CartPole, a 4–64–64–2 network, ε-greedy behaviour with ε going from 1 to 0.05 over the first 5000 steps, two runs per variant. Each point is the mean return of the episodes that ended in a block of 1000 steps. Episodes last at most 500 steps, and ε = 0.05 at the end of training drops the pole sooner than the greedy policy would. Without a target network the largest |Q| seen in training is 5.7e+6 and 3.8e+7, although the true values cannot exceed 1/(1 − γ) = 100. Two runs per variant are too few to tell DQN and Double DQN apart.
variantmean episode length in traininggreedy return after traininglargest ∣Q∣\lvert Q \rvert in training
neither10.49.55.7⋅1065.7 \cdot 10^6
replay only10.39.33.8⋅1073.8 \cdot 10^7
target network only14.184.277
DQN: both94.0281.877
Double DQN106.7151.157

With rewards of 1 per step and γ=0.99\gamma = 0.99, no true value can exceed 1/(1−γ)=1001/(1 - \gamma) = 100. Without a target network the estimates reached millions, and the agent drops the pole within about 10 steps, no better than at the start. The target network alone keeps the values bounded but learns slowly, from one transition per update. Both together learn to balance for hundreds of steps. The greedy returns vary a lot between seeds; two runs are not enough to rank DQN against Double DQN.

The Atari setup#

The Arcade Learning Environment (Bellemare et al., 2013) exposes Atari 2600 games as environments: the observation is the screen, the actions are joystick positions (up to 18), and the reward is the change in the game score. Mnih et al. (2015) used one architecture and one set of hyperparameters for all 49 games they tested:

  • Input. Each frame converted to grey and downsampled to 84×8484 \times 84; the last four frames stacked, so that velocities are visible and the state is closer to Markov. Each action is repeated for four frames.
  • Network. Three convolutional layers (32 filters of 8×88 \times 8 with stride 4, 64 of 4×44 \times 4 with stride 2, 64 of 3×33 \times 3 with stride 1), a fully connected layer of 512 units, and one linear output per action. One forward pass gives the values of all actions, so the max in the target costs one evaluation, not 18.
  • Training. RMSProp, minibatches of 32, a buffer of 10610^6 transitions, a gradient step every 4 actions, the target network copied every 10410^4 updates, ε annealed from 1 to 0.1 over the first million frames, γ=0.99\gamma = 0.99, and rewards clipped to [−1,1][-1, 1] so that one learning rate fits games whose scores differ by orders of magnitude.

Trained for 50 million frames per game, which the paper puts at about 38 days of game experience, the agent outperformed the best previous machine-learning methods on 43 of the 49 games and reached more than 75% of a professional human tester’s score on more than half of them (Mnih et al., 2015; Google Research, 2015). The paper’s ablation on five games shows that both devices matter, replay the most (scores from its Extended Data Table 3, rounded):

gameneithertarget network onlyreplay onlyboth
Breakout310241317
Enduro291428311006
River Raid1453286841037447
Seaquest27610038232894
Space Invaders3023738261089

Reward clipping changes the objective: the agent maximizes the number of times the score increases, not the score. Clipped rewards, frame stacking and action repeat are domain-specific choices, and later work removed some of them, for example by normalizing targets adaptively instead of clipping rewards (van Hasselt et al., 2016b).

Overestimation and Double DQN#

The target takes a maximum over estimates, and a maximum of noisy estimates is biased upwards. If the estimates Q(s′,a)Q(s', a) are unbiased, E[Q(s′,a)]=q(a)\mathbb E[Q(s', a)] = q(a), then, because the maximum of a sum is at most the sum of the maxima, or by Jensen’s inequality for the convex function max⁡\max,

E[max⁡aQ(s′,a)]≥max⁡aE[Q(s′,a)]=max⁡aq(a),\mathbb E\Big[ \max_a Q(s', a) \Big] \ge \max_a \mathbb E\big[ Q(s', a) \big] = \max_a q(a),

with equality only when the noise never changes which action is largest. Worked example. Ten actions have the same true value, and their estimates carry independent noise with standard deviation σ\sigma. The maximum of ten standard normal variables has mean 1.5391.539, so the target is too high by 1.539σ1.539\sigma on average, although every single estimate is unbiased. With two actions the bias is 0.564σ0.564\sigma. The error is fed back through bootstrapping, so states whose actions are uncertain look systematically better than they are (Thrun and Schwartz, 1993).

The tabular version is the maximization-bias example of Sutton and Barto (2018), example 6.7: from A, going right ends the episode with 0; going left leads to B, whose ten actions end the episode with a reward of mean −0.1-0.1 and standard deviation 1. Left is worse, and still Q-learning prefers it for a long time:

Figure

Maximization bias: Q-learning against Double Q-learning

Maximization bias: Q-learning against Double Q-learningTwo curves of the fraction of episodes in which the agent went left from A, over 300 episodes. Q-learning climbs to almost 0.95 by episode 22 and only slowly comes down to 0.11. Double Q-learning starts at 0.5 and drops quickly towards 0.08. The dashed line is 0.05, the fraction of left actions of the optimal ε-greedy policy.0.000.250.500.751.000100200300episodesfraction of episodes that go left from Aoptimal with ε = 0.1: 0.05Q-learningDouble Q-learningMaximization bias: Q-learning against Double Q-learningTwo curves of the fraction of episodes in which the agent went left from A, over 300 episodes. Q-learning climbs to almost 0.95 by episode 22 and only slowly comes down to 0.11. Double Q-learning starts at 0.5 and drops quickly towards 0.08. The dashed line is 0.05, the fraction of left actions of the optimal ε-greedy policy.0.000.250.500.751.000100200300episodesfraction of episodes that go left from Aoptimal with ε = 0.1: 0.05Q-learningDouble Q-learning
From A, "right" ends the episode with reward 0 and "left" leads to B with reward 0; B has ten actions, each ending the episode with a reward drawn from N(−0.1, 1), so left is worse by 0.1. ε = 0.1, α = 0.1, γ = 1, averaged over 2000 runs and smoothed over windows of 5 episodes. Q-learning values A–left through the maximum of ten noisy estimates in B, which at first is almost always positive; over the first 100 episodes it goes left in 75% of them. Double Q-learning chooses the action in B with one table and evaluates it with the other, and goes left in 19%.

Double Q-learning (van Hasselt, 2010) separates choosing the action from evaluating it. With two independent estimates Q1Q^1 and Q2Q^2, take a⋆=arg⁡max⁡aQ1(s′,a)a^\star = \arg\max_a Q^1(s', a) and use Q2(s′,a⋆)Q^2(s', a^\star) as the value. Since the noise of Q2Q^2 is independent of the choice, E[Q2(s′,a⋆)]=E[q(a⋆)]≤max⁡aq(a)\mathbb E[Q^2(s', a^\star)] = \mathbb E[q(a^\star)] \le \max_a q(a): the estimate is never biased upwards, and in the example above it is unbiased. A simulation of the ten-action example gives 1.5391.539 for the single estimator and −0.004-0.004 for the double one. The price is a possible underestimate when the chosen action is not the best.

Double DQN (van Hasselt, Guez and Silver, 2016) gets the second estimate for free from the two networks DQN already has: the online network chooses, the target network evaluates,

  y=r+γ(1−d) Qθ−(s′,arg⁡max⁡a′Qθ(s′,a′))  \boxed{\; y = r + \gamma (1 - d)\, Q_{\theta^-}\Big( s', \arg\max_{a'} Q_\theta(s', a') \Big) \;}

a change of one line in the code. The two networks are not independent, so the bias is reduced rather than removed. Over 57 Atari games, the median human-normalized score (0% for random play, 100% for a human tester) rose from 79% for DQN to 117% for Double DQN, in the no-op starts evaluation; both figures are as collected by Hessel et al. (2018), table 2, from the original publications and their own runs.

Dueling networks, prioritized replay and Rainbow#

Each later improvement fixes one identified weakness of DQN.

Dueling networks (Wang et al., 2016) split the head of the network into a state value V(s)V(s) and advantages A(s,a)A(s, a) and combine them as

Q(s,a)=V(s)+A(s,a)−1∣A∣∑a′A(s,a′).Q(s, a) = V(s) + A(s, a) - \frac{1}{|\mathcal A|} \sum_{a'} A(s, a').

In many states the action barely matters, a car on an empty road, and a plain Q-network must still learn each action’s value separately. The dueling head learns V(s)V(s) from every update, whatever action was taken. The subtracted mean makes the split unique: V=5V = 5 with A=(2,0,1)A = (2, 0, 1) gives Q=(6,4,5)Q = (6, 4, 5), and adding a constant to all advantages would give the same QQ, so without the mean VV and AA could drift in opposite directions.

Prioritized experience replay (Schaul et al., 2016) samples transitions with probability proportional to a power of their last TD error, P(i)=piω/∑kpkωP(i) = p_i^\omega / \sum_k p_k^\omega with pi=∣δi∣p_i = |\delta_i| plus a small constant. Uniform replay spends most updates on transitions the network already predicts well. Non-uniform sampling changes the distribution the loss is averaged over, so each sample is reweighted by wi=(N⋅P(i))−βw_i = (N \cdot P(i))^{-\beta}, normalized by the largest weight, with β\beta increased to 1 during training. Worked example. Three transitions with TD errors 22, 11 and 0.50.5 and ω=0.6\omega = 0.6 are drawn with probabilities 0.4770.477, 0.3150.315 and 0.2080.208; with β=1\beta = 1 their weights are 0.4350.435, 0.6600.660 and 11.

Multi-step targets use the n-step returns of the previous note, so rewards propagate nn steps per update. Distributional RL (Bellemare, Dabney and Munos, 2017) learns the whole distribution of the return on 51 fixed atoms rather than its mean, which gives the network a richer training signal. Noisy networks (Fortunato et al., 2018) add learned noise to the weights of the linear layers and so replace ε-greedy by exploration that depends on the state.

Rainbow (Hessel et al., 2018) combined all six: Double DQN, prioritized replay, dueling heads, 3-step targets, distributional learning and noisy networks.

componentwhat it fixes
Double Q-learningthe upward bias of the max in the target
prioritized replayupdates wasted on transitions already learned
dueling headlearning a value for every action where only the state matters
multi-step targetsslow propagation of reward, one step per update
distributional learninga single mean as the only training signal
noisy networksundirected ε-greedy exploration

On 57 Atari games with 200 million frames each, Rainbow reached a median human-normalized score of 223% in the no-op starts evaluation, against 79% for DQN, and matched DQN’s final performance after 7 million frames. Its ablations found prioritized replay and multi-step targets the most important components; removing Double Q-learning or the dueling head changed the median little (Hessel et al., 2018). A later agent, Agent57, was the first to exceed the human benchmark on all 57 games, by adding learned exploration bonuses and a meta-controller over exploration rates (Badia et al., 2020).

What changed#

tabular Q-learningDQN
representationone entry per state–action paira network Qθ(s,⋅)Q_\theta(s, \cdot) that outputs all actions
updateone entrya gradient step that moves every state
dataeach transition used once, in ordera replay buffer, random minibatches, reuse
targetthe current estimatesa frozen target network, refreshed every CC steps
guaranteeconvergence with probability 1none: the deadly triad
scalesmall discrete state spacesraw pixels, 49 Atari games with one set of hyperparameters

Limitations#

  • No convergence guarantee. DQN sits inside the deadly triad. Its devices make divergence rare in practice, not impossible, and results vary strongly with seeds and hyperparameters, as the CartPole runs show.
  • Discrete actions only. The target needs max⁡a′Q(s′,a′)\max_{a'} Q(s', a'), which is one pass of the network for 18 joystick positions but an optimization problem for a continuous action such as a torque. The next note’s policy-gradient methods handle continuous actions directly.
  • Sample inefficiency. Fifty million frames per game is far more experience than a person needs. Replay helped; learning a model of the environment, two notes ahead, helps more.
  • Exploration is still ε-greedy. Games that need a long precise sequence before the first reward, such as Montezuma’s Revenge, defeated DQN; noisy networks and count-based bonuses help only partly.
  • Overestimation is reduced, not removed, and clipped rewards change the objective the agent optimizes.

What you should remember#

  • Function approximation turns Q-learning into regression on its own targets: θ←θ+α[r+γmax⁡a′Qθ(s′,a′)−Qθ(s,a)]∇θQθ(s,a)\theta \leftarrow \theta + \alpha[r + \gamma \max_{a'} Q_\theta(s', a') - Q_\theta(s, a)] \nabla_\theta Q_\theta(s, a), a semi-gradient, not the gradient of a fixed loss.
  • The deadly triad, function approximation plus bootstrapping plus off-policy data, can diverge even without noise; in the two-state example the weight grows by 1+α(2γ−1)1 + \alpha(2\gamma - 1) per update.
  • DQN stabilizes Q-learning with a replay buffer (independent-looking, reused data) and a target network (fixed regression targets between copies), and it learned 49 Atari games from pixels with one set of hyperparameters.
  • The max over noisy estimates overestimates: 1.539σ1.539\sigma for ten equal actions. Double DQN chooses with the online network and evaluates with the target network.
  • Dueling heads, prioritized replay, multi-step targets, distributional learning and noisy networks each fix one weakness; Rainbow combined them, and prioritized replay and multi-step targets mattered most.

Code#

CartPole written as equations, a DQN with switches for experience replay, the target network and the Double DQN target, the ablation of the figure and the table, and two small checks: the bias of the max of noisy estimates against the double estimator, and the probabilities and weights of prioritized replay. PyTorch on the CPU, one thread; seeds are fixed, and exact numbers vary across platforms and library versions. The script runs in about 35 seconds.

import math
import numpy as np
import torch
import torch.nn as nn

torch.set_num_threads(1)

# 1. the environment: the cart-pole equations of Barto, Sutton and Anderson (1983), as in Gym's CartPole-v1
class CartPole:
    g, m_cart, m_pole, half_len, force, dt = 9.8, 1.0, 0.1, 0.5, 10.0, 0.02
    def __init__(self, rng):
        self.rng = rng
    def reset(self):
        self.s, self.t = self.rng.uniform(-0.05, 0.05, 4), 0     # position, velocity, angle, angular velocity
        return self.s.astype(np.float32)
    def step(self, a):
        x, v, th, w = self.s
        f, c, s, m = (self.force if a == 1 else -self.force), math.cos(th), math.sin(th), self.m_cart + self.m_pole
        tmp = (f + self.m_pole * self.half_len * w * w * s) / m
        acc_th = (self.g * s - c * tmp) / (self.half_len * (4 / 3 - self.m_pole * c * c / m))
        acc_x = tmp - self.m_pole * self.half_len * acc_th * c / m
        self.s = np.array([x + self.dt * v, v + self.dt * acc_x, th + self.dt * w, w + self.dt * acc_th])
        self.t += 1
        fell = abs(self.s[0]) > 2.4 or abs(self.s[2]) > 12 * math.pi / 180
        return self.s.astype(np.float32), 1.0, fell, self.t >= 500  # reward 1 per step; episodes stop at 500

def q_net():
    return nn.Sequential(nn.Linear(4, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 2))

# 2. DQN, with switches for experience replay, the target network and the Double DQN target
def train(replay=True, target=True, double=False, steps=20_000, seed=0, gamma=0.99,
          buffer=10_000, batch=64, sync=250, every=2, lr=1e-3):
    torch.manual_seed(seed); rng = np.random.default_rng(seed)
    env, q, q_tgt = CartPole(rng), q_net(), q_net()
    q_tgt.load_state_dict(q.state_dict())
    opt = torch.optim.Adam(q.parameters(), lr=lr)
    N = buffer if replay else 1                                   # without replay: only the latest transition
    S, A, R = np.zeros((N, 4), np.float32), np.zeros(N, np.int64), np.zeros(N, np.float32)
    S2, D = np.zeros((N, 4), np.float32), np.zeros(N, np.float32)
    n, s, ret, episodes, q_max = 0, env.reset(), 0.0, [], 0.0
    for t in range(1, steps + 1):
        eps = max(0.05, 1 - t / 5000)                               # epsilon from 1 to 0.05 over 5000 steps
        with torch.no_grad():
            a = int(rng.integers(2)) if rng.random() < eps else int(q(torch.from_numpy(s)).argmax())
        s2, r, fell, cut = env.step(a)
        i = n % N; S[i], A[i], R[i], S2[i], D[i] = s, a, r, s2, float(fell); n += 1
        s, ret = s2, ret + r
        if fell or cut:                                             # a cut at 500 steps is not a terminal state
            episodes.append((t, ret)); s, ret = env.reset(), 0.0
        if t % every == 0 and n >= (500 if replay else 1):
            idx = rng.integers(min(n, N), size=batch) if replay else np.array([i])
            sb, ab, rb, s2b, db = (torch.from_numpy(x[idx]) for x in (S, A, R, S2, D))
            with torch.no_grad():
                net = q_tgt if target else q                        # who computes the target
                if double:                                          # choose with the online net, evaluate with the target
                    nxt = net(s2b).gather(1, q(s2b).argmax(1, keepdim=True)).squeeze(1)
                else:
                    nxt = net(s2b).max(1).values
                y = rb + gamma * (1 - db) * nxt                     # r + gamma max_a' Q(s', a'), 0 after a fall
            pred = q(sb).gather(1, ab[:, None]).squeeze(1)
            loss = nn.functional.smooth_l1_loss(pred, y)            # Huber loss, as in DQN
            opt.zero_grad(); loss.backward(); opt.step()
            q_max = max(q_max, pred.abs().max().item())
        if target and t % sync == 0:
            q_tgt.load_state_dict(q.state_dict())                   # copy theta into the target network
    return q, episodes, q_max

def greedy_return(q, episodes=10, seed=100):
    env, total = CartPole(np.random.default_rng(seed)), 0.0
    for _ in range(episodes):
        s, done = env.reset(), False
        while not done:
            with torch.no_grad():
                s, r, fell, cut = env.step(int(q(torch.from_numpy(s)).argmax()))
            total, done = total + r, fell or cut
    return total / episodes

# 3. the ablation: which of the two devices matters? two seeds each, 20,000 steps per run
variants = [('neither', dict(replay=False, target=False)), ('replay only', dict(target=False)),
            ('target only', dict(replay=False)), ('DQN', {}), ('Double DQN', dict(double=True))]
curves = {}
for name, kw in variants:
    rows = []
    for seed in (0, 1):
        q, eps_, q_max = train(seed=seed, **kw)
        rows.append((len(eps_), 20_000 / len(eps_), greedy_return(q), q_max))
        curves[(name, seed)] = eps_                                 # (step, return) of every episode
    m = np.array(rows).mean(0)
    print(f'{name:11s} episodes {m[0]:6.0f}  mean length {m[1]:6.1f}  greedy return {m[2]:6.1f}  largest |Q| {m[3]:9.3g}')
# neither     episodes   1924  mean length   10.4  greedy return    9.5  largest |Q|  5.69e+06
# replay only episodes   1934  mean length   10.3  greedy return    9.3  largest |Q|  3.81e+07
# target only episodes   1423  mean length   14.1  greedy return   84.2  largest |Q|        77
# DQN         episodes    217  mean length   94.0  greedy return  281.8  largest |Q|      77.4
# Double DQN  episodes    188  mean length  106.7  greedy return  151.1  largest |Q|      56.5

# 4. overestimation: ten actions with true value 0 and unit-variance noise; single against double estimator
rng = np.random.default_rng(0)
Q1, Q2 = rng.normal(size=(200_000, 10)), rng.normal(size=(200_000, 10))
rows = np.arange(len(Q1))
print(round(Q1.max(1).mean(), 3), round(Q2[rows, Q1.argmax(1)].mean(), 3))   # 1.539 -0.004

# 5. prioritized replay: probabilities from TD errors, then importance weights normalized by the largest
delta = np.array([2.0, 1.0, 0.5])
P = np.abs(delta) ** 0.6 / (np.abs(delta) ** 0.6).sum()
w = (len(P) * P) ** -1.0
print(P.round(3), (w / w.max()).round(3))                     # [0.477 0.315 0.208] [0.435 0.66  1.   ]

With an Atari game in place of CartPole, the same loop needs the convolutional network, frame stacking and many millions of steps on a GPU; the mechanism does not change.

Next#

DQN chooses actions by maximizing over its outputs, which ties it to small discrete action sets, and its policy is always the deterministic argmax of its values, so it cannot represent a policy that should be random. A robot arm has continuous torques, and a language model chooses among tens of thousands of tokens at every step with a probability distribution that is itself the object to train. The next note drops the value table altogether and adjusts the parameters of a stochastic policy directly, by the gradient of the expected return.

References#