Deep Q-Networks
Deep Q-networks replace the linear value function with a neural network and confront the fact that a nonlinear approximator, off-policy bootstrapping, and correlated online data — the deadly triad — make naive Q-learning diverge. DQN counters this empirically with two stabilizers: an experience replay buffer that decorrelates and reuses samples, and a periodically-frozen target network that fixes the bootstrap target.
╌╌╌╌
Every method up to now approximated value with a linear map: pick features by hand, and estimate . That works when a person can design good features, and it comes with the projected-Bellman-error geometry that makes stable off-policy methods possible. It fails the moment the state is a raw image. An Atari frame is pixels over three color channels; the number of distinct states is astronomically larger than the number of atoms in the observable universe, and no hand-built feature set can cover it.1 Deep reinforcement learning instead lets a neural network be the feature extractor and the value head at once, learned end to end from reward.
A deep Q-network approximates the action-value function with a neural network whose weights are :
The network takes the state, and outputs one Q-value per action in a single forward pass. That is the whole idea. The rest of this lesson is about the one thing that makes it hard: a nonlinear approximator trained by online Q-learning is unstable, and left alone it diverges. DQN made it converge in practice, and is the algorithm that started modern deep RL.2
From features to a network
A tabular Q-learner keeps a matrix indexed by state and action. Function approximation replaces that lookup with a parametric function, and the gain is generalization: adjusting to fix the value of one state-action pair also shifts the value of every similar pair, so the agent learns from states it has never visited. In a linear model that generalization is limited to what the chosen features can express; a neural network discovers its own features, and can represent the intricate value surfaces that raw perception requires.3
There are two ways to wire a network for , and the choice matters. One feeds in both the state and an action and outputs a single scalar; evaluating all actions then costs one forward pass per action. The efficient alternative — the one DQN uses — feeds in the state alone and outputs a vector of Q-values, one per action. A single forward pass then scores every action at once, handing an -greedy or softmax policy the full vector it consumes.4
Given this network, the greedy action in a state is , computed from one pass, and the whole apparatus of generalized policy iteration carries over: evaluate the current policy by regressing toward a target, improve by acting greedily (with exploration) on the new estimates, repeat. The catch is that with a nonlinear there are no convergence guarantees left.
The ideal objective, and why it is out of reach
Training the network would be ordinary supervised learning if the correct answers were available. They are not, so the target must be manufactured from the network's own estimates, at the cost of a non-stationary target.
If we somehow had access to the optimal action-value function , learning would be ordinary supervised regression: minimize the squared distance to the true values,
This objective is unavailable.5 We have no to regress against — if we did, there would be nothing to learn — and we cannot even sample , because we have neither the optimal policy nor the environment's model. The fix is the same bootstrapping trick as tabular Q-learning: replace the unavailable with a target built from the network's own next-state estimate. For an off-policy Q-learning target,
so the loss over sampled experience tuples becomes
Differentiating, and treating the target as a constant with respect to — the gradient flows only through the predicted value , never through the target — gives the update direction
Detaching the target matters. In supervised learning the labels are fixed
constants; here the label
is manufactured from the very network being optimized,
so letting the gradient propagate through it optimizes a moving definition of
correctness. Backpropagate through the prediction only.6
Why the naive version diverges
Assemble the obvious algorithm — a neural , the Q-learning target above, an -greedy behavior policy, an MSE loss, and a step of RMSprop after each transition — and it will train for a while and then come apart. This is not a bug in the implementation; it is the deadly triad in its most dangerous configuration. All three ingredients are present: function approximation (a neural network), bootstrapping (the TD target), and off-policy training (the learns the greedy policy while behavior explores). Any two are safe; all three can diverge. Two mechanisms cause the instability.7
The target is non-stationary. The regression target is computed from
, so every gradient step that changes also
changes the target for the next step. The network chases a value it is itself
moving. Worse, because the approximator generalizes, updating
drags the value of the next state along with it — and is precisely what
the target for depends on. Improve the prediction and you spoil the target
that defined improvement,
which can spiral into divergence.
The data is not IID. Optimization methods assume samples are independent and identically distributed; online RL supplies the opposite. Consecutive transitions come from the same trajectory, so the sample at time is highly correlated with the one at — the network overfits to whatever local region of the state space the current episode is wandering through. And because the behavior policy keeps changing, the sample distribution drifts too, so the data is neither independent nor identically distributed.8 Both violations push the optimizer toward instability.
DQN's contribution is two mechanisms that repair exactly these two problems, and between them make deep value-based RL behave enough like supervised learning to train reliably.
Stabilizer one: experience replay
The fix for correlated, non-IID data is to stop training on the online stream. As the agent acts, it stores each transition in a large replay buffer ; training then draws a mini-batch uniformly at random from rather than using the most recent transitions.9
Random sampling from a large buffer breaks the temporal correlation: a mini-batch now mixes transitions from many different trajectories and many past policies, so the updates look far more like draws from a fixed distribution — approximately IID, as the optimizer assumes. The second benefit is data efficiency: each transition can be sampled and learned from many times rather than being seen once and thrown away, which matters when interaction with the environment is the expensive part.
The gradient is unchanged in form; only the sampling distribution moves from the online stream to a uniform draw over the buffer, written :
Experience replay predates deep RL — Lin proposed it in 1992 — but pairing it with a neural Q-function is what enabled stable training from raw experience.9
Stabilizer two: the target network
Replay handles the data; it does nothing about the moving target. For that, DQN keeps a second copy of the network whose weights are frozen and used only to compute targets: the target network, with weights .10
The two networks share the same architecture; they differ only in the age of the weights. The online network is the one we optimize on every step. The target network is a snapshot of the online weights from up to steps ago, and it defines the target. The DQN gradient differs from the naive one in exactly one symbol — where the target's parameters used to be :
Because is fixed between refreshes, the target stops moving for steps at a time. Each such window is an ordinary, stationary regression problem: a fixed set of labels the online network can descend toward without the goalposts sliding. Every steps the labels are updated all at once and a new stationary problem is set. Freezing the target does not guarantee convergence to the optimum — that does not exist under nonlinear approximation — but it substantially reduces the risk of divergence, which is the actual failure mode.
How often to refresh depends on the problem. For a small control task like the cart-pole, copying every 10 to 20 steps works; for the convolutional networks used on Atari, the target is frozen for on the order of 10,000 steps. (Steps, not episodes — a common and costly confusion.) A softer variant, Polyak averaging, avoids the abrupt copy entirely: instead of every steps, blend a little of the online weights into the target on every step,
so the target always lags but by a small, smoothly-shrinking gap rather than jumping in discrete leaps.11
The full DQN algorithm
Replay and the target network are the two additions; everything else is standard value-based RL. The complete loop:
- 1input: sync period , discount , exploration
- 2initialize online weights randomly
- 3target weights
- 4empty replay buffer
- 5loop
- 6observe state
- 7with probability choose random action
- 8else
- 9execute , observe reward and next state
- 10store in
- 11sample a minibatch of transitions from
- 12for each sampled do
- 13if is terminal then
- 14
- 15else
- 16
- 17take a gradient step on w.r.t.
- 18every steps:sync target
Two implementation details matter. Terminal states must be grounded to zero: when is terminal there is no future, so the target is just , and forgetting this lets phantom future value leak in and destabilize training.6 And the network outputs a full vector of Q-values, so the prediction for the update is the entry at the action actually taken, gathered from that vector.
The original DQN paper (Mnih et al., 2013) introduced the replay buffer; the 2015 follow-up added the target network, and that two-mechanism version — sometimes called Nature DQN — is the one described above and the baseline every later improvement builds on.2
A minibatch of targets, worked end to end
Take and a minibatch of four transitions sampled from the buffer. For each we need the frozen target network's Q-values at the next state , the online network's prediction at the action actually taken, and a terminal flag. Suppose the target network reports these next-state values, and the online network these predictions:
| terminal? | ||||
|---|---|---|---|---|
| 1 | no | |||
| 2 | no | |||
| 3 | yes | — | ||
| 4 | no |
The target for a non-terminal transition is ; for the terminal transition it is just , with no bootstrap term. Reading down the table:
The minibatch loss is the mean squared TD error, . The gradient for each transition is , so transitions 1 and 2 raise their predicted values (the target sat above the prediction) while 3 and 4 lower theirs. Two details this makes concrete: transition 3 shows the terminal grounding — had we bootstrapped a phantom there, would have carried future value the episode does not have, and that leak is a classic source of divergence. And every gradient flows only through the column; the target column is a constant, computed from and detached.
The Atari architecture and results
The demonstration that made DQN famous is Sutton and Barto's chosen case study: a single agent, with no game-specific features, learning to play dozens of Atari 2600 games directly from pixels.12 The setup is worth stating precisely, because its choices recur throughout deep RL.
Input. Each raw frame is pixels with 128 colors at 60 Hz. DQN preprocesses every frame down to an array of luminance values, then stacks the four most recent frames so the network input has dimension . Stacking matters: a single frame does not reveal velocity or direction — is the ball rising or falling? — and four stacked frames restore enough of that to make the state approximately Markov.
Network. Three convolutional layers extract spatial features, followed by a fully-connected hidden layer and a linear output. Concretely: a first conv layer producing 32 feature maps of , a second producing 64 of , a third producing 64 of , each with a ReLU nonlinearity; the units of the last conv layer feed a fully-connected layer of 512 units, which connects to up to 18 outputs — one Q-value per possible Atari action. This is the state-in, values-out design at scale.
Training choices. The reward is clipped to its sign — when the game score rises, when it falls, otherwise — so one step size works across games whose raw scores span wildly different scales. Behavior is -greedy with decaying linearly over the first million frames and then held low. The optimizer is RMSprop over mini-batches of 32, and the TD error itself is clipped to , a further stabilizer on top of replay and the target network. The semi-gradient Q-learning update the paper uses is precisely the one derived above.
Results. The same architecture, the same hyperparameters, and the same raw pixel input were applied to 49 different games, with only the network weights reset per game.12 Learning ran for 50 million frames per game — roughly 38 days of game experience. Measured against a professional human tester, DQN played at or above human level on 29 of the 46 games evaluated, and beat the best prior (linear, feature-engineered) reinforcement-learning systems on all but 6. What made it a landmark is the uniformity rather than any single score: one learning system, no per-game engineering, reaching human-competitive play across games as different as Breakout, Pong, and Space Invaders. The games it failed — Montezuma's Revenge, where DQN scored about as well as a random player — were the ones demanding long-horizon planning beyond what one-step Q-learning was built for, a gap later chapters take up. This lesson built the core value-based deep agent. The three refinements that make it the standard modern one — Double DQN for the maximization bias, dueling networks, and prioritized experience replay, plus the Rainbow agent that combines them — continue in DQN Improvements: Double, Dueling, and Prioritized Replay.
Footnotes
- Morales, Grokking Deep Reinforcement Learning, Ch. 8 — the kind of feedback deep-RL agents deal with: high-dimensional and continuous state spaces (an Atari frame is , a state count larger than the atoms in the observable universe) that make exhaustive tabular sampling impossible and force function approximation. ↩
- Sutton & Barto, Reinforcement Learning: An Introduction (2nd ed.), §16.5 — Mnih et al.'s deep Q-network combining Q-learning with a deep convolutional network; and Morales, Ch. 9 — DQN as the algorithm that
started a series of research innovations that mark the history of RL,
introduced 2013 (replay) and completed 2015 (target network). ↩ ↩2 - Morales, §8.2 — Introduction to function approximation for RL: replacing tabular lookups with a parametric function so that updating one state-action value generalizes to similar ones, and the efficiency gain of learning underlying relationships from fewer samples. ↩
- Morales, §8.3,
Selecting a neural network architecture
— the state-action-in / value-out design versus the more efficient state-in / values-out design, which returns all action values in one forward pass and suits epsilon-greedy and softmax policies. ↩ - Morales, §8.3,
Selecting what to optimize
— the ideal objective and the argument that we cannot use it because we have neither the optimal action-value function nor an optimal policy to sample it from; we must alternate policy evaluation and improvement as in generalized policy iteration. ↩ - Morales, §8.3, the Q-learning target box and
I Speak Python
on the Q-learning target — the off-policy TD target , the gradient flowing only through the predicted value (the target must be detached / treated as a constant), and grounding terminal states to zero. ↩ ↩2 - Morales, §8.3,
Things that could (and do) go wrong
— the non-stationary-target problem (targets computed from the network being optimized) and the correlated / non-IID online data, the two instabilities that DQN addresses. ↩ - Morales, Ch. 9,
Common problems in value-based deep RL
and the IID boil-it-down — samples from a trajectory are correlated (not independent) and their distribution drifts with the improving policy (not identically distributed), violating the assumptions optimization methods rely on. ↩ - Morales, Ch. 9,
Using experience replay
— the replay buffer of transitions, uniform mini-batch sampling to decorrelate data and reuse experience, buffer sizes of – with oldest-first eviction, and the history note crediting Lin (1992). ↩ ↩2 - Morales, Ch. 9,
Using target networks
and the target-network gradient box — the frozen target weights , the update differing from NFQ only in the age of the weights used for the target, and refresh frequencies (10–20 steps for cart-pole, up to 10,000 for Atari). ↩ - Morales, Ch. 10,
Continuously updating the target network
— Polyak averaging as a smooth alternative to freezing and copying the target network every steps. ↩ - Sutton & Barto, §16.5 — Human-level Video Game Play: preprocessing to luminance and stacking four frames () for Markov-ness; three convolutional layers (32 , 64 , 64 , ReLU), a 512-unit fully-connected layer, and up to 18 action outputs; reward-sign clipping, error clipping to , RMSprop, linearly-decayed epsilon; 49 games at 50M frames each with weights reset per game; human-level play on 29 of 46 games. ↩ ↩2
╌╌ END ╌╌