Reinforcement Learning/Deep Q-Networks

Lesson 12.32,950 words

Deep Q-Networks

A Deep Q-Network replaces the tabular action-value function with a neural approximator Q(s,a;θ)Q(s,a;\theta) and trains it by regression toward a bootstrapped target. Naive online Q-learning with a network diverges, so DQN adds two stabilizers: an experience-replay buffer that decorrelates samples, and a periodically-frozen target network that holds the regression target still.

╌╌╌╌

Model-free control gave us Q-learning: a table of action values updated toward a one-step bootstrap. The table is the bottleneck. With in the billions, raw Atari frames at being one example, there is no table to fill and no way to generalize across the states never visited. A Deep Q-Network replaces the table with a parametric function , a convolutional network that reads a state and emits one value per action, and trains by regression. The substitution is immediate; making it stable is the entire lesson.

From a table to a network

Tabular Q-learning stores one independent number per and updates it by the rule

Replace the lookup with a network and the update by a gradient step that drives toward the same target . The per-sample objective is the squared temporal-difference error.

The single number per cell is gone; a state never seen still receives a value through the shared weights. That generalization is the benefit, and also the source of every instability that follows.

Why naive online Q-learning diverges

Run Q-learning online, one gradient step per transition as it arrives, with a neural , and training is unstable. Three forces compound.

ProblemCauseEffect on training
Correlated samplesconsecutive transitions in a trajectory are near-identicalgradient steps are not i.i.d.; the net overfits the current locality
Moving target uses the same being updatedthe regression target shifts every step, oscillation and feedback
Distribution shiftthe policy that generates data changes as changesthe data distribution drifts under the optimizer

The combination is an instance of the deadly triad: function approximation, bootstrapping, and off-policy training together can make value estimates diverge, even though any two of the three are safe.

DQN does not remove a leg of the triad; it keeps all three and damps the feedback loop with two engineering devices, experience replay for the correlation and a target network for the moving target.

Experience replay

Rather than learn from each transition once, in order, and discard it, store every transition in a buffer and train on random minibatches drawn from it.

Two benefits follow directly. Random sampling breaks the temporal correlation between successive updates, so the minibatch gradient approximates an expectation over a broad, stationary mixture of past states rather than the current trajectory. And every transition can be reused many times before eviction, so the sample efficiency rises: rare, informative transitions contribute to many updates instead of one.

The replay loop. The agent writes transitions to the buffer while learning reads random minibatches from it, decoupling data collection from the gradient step.

The buffer makes the data look i.i.d. to the optimizer, restoring the assumption stochastic gradient descent needs.

Target network

Replay fixes correlation but not the moving target: if the same that is being updated also defines , the regression chases a label that jumps every step. The fix is a second set of weights , a periodically-frozen copy of , used only to compute the target.

The DQN loss is the expected squared TD error with the target evaluated under the frozen weights.

Differentiating, and treating as a constant because it is frozen, the gradient is

This is a plain supervised regression gradient: target minus prediction, times the prediction's gradient. The only unusual part is that was produced by a stale copy of the same network, which is precisely what makes it stable.

One gradient step, worked

Take a single transition and push it through. Suppose a sampled transition is with reward , discount , and non-terminal. The frozen target network evaluates the three actions at as

so and the bootstrapped label is

Say the online network currently predicts for the action actually taken. The TD error and the per-sample loss are

The gradient of with respect to is ; with a positive the step moves the parameters in the direction that raises , closing the gap. A step size and a local slope that together move the prediction by, say, leave after the step: closer to , but not there, because the same step also perturbs the predictions at every other state that shares those weights. Only is nudged; the labels stay fixed at until the next refresh, which is what keeps this one step a piece of a stationary regression.

One worked gradient step. The frozen target net produces the label ; the online prediction is ; the TD error drives the squared loss and an ascent on .
Online versus target network. Both share architecture; the online net (weights ) is updated each step, the target net (weights ) is a frozen copy refreshed every steps to supply a still target .

The two devices are complementary. Replay makes the inputs look i.i.d.; the target network makes the labels hold still. Without either, the network tracks a fast-moving feedback loop and diverges.

DeviceWhat it stabilizesMechanismHyperparameter
Experience replayinput correlation, data efficiencyrandom minibatch from a FIFO buffercapacity , batch size
Target networkthe bootstrapped labelfrozen copy refreshed every refresh period

The DQN algorithm

Putting the pieces together gives the algorithm of the 2015 Nature paper: -greedy action selection, a replay write each step, a minibatch gradient step against the target network, and a periodic refresh.

Algorithm:DQN\textsc{DQN} — deep Q-learning with replay and a target network
  1. 1
    initialize replay buffer D\mathcal{D} to capacity MM
  2. 2
    initialize online weights θ\theta at random; set θθ\theta^{-} \gets \theta
  3. 3
    for each episode do
  4. 4
    observe initial state ss
  5. 5
    repeat
  6. 6
    with probability ϵ\epsilon pick random aa, else aargmaxaQ(s,a;θ)a \gets \arg\max_{a'} Q(s,a';\theta)
    explore vs exploit
  7. 7
    execute aa, observe reward rr and next state ss'
  8. 8
    store (s,a,r,s)(s,a,r,s') in D\mathcal{D}
    write experience
  9. 9
    sample minibatch (sj,aj,rj,sj)D(s_j,a_j,r_j,s'_j) \sim \mathcal{D}
    decorrelate
  10. 10
    yjrj+γmaxaQ(sj,a;θ)y_j \gets r_j + \gamma \max_{a'} Q(s'_j,a';\theta^{-}) if sjs'_j non-terminal, else rjr_j
    frozen target
  11. 11
    take a gradient step on j(yjQ(sj,aj;θ))2\sum_j \parens{y_j - Q(s_j,a_j;\theta)}^2
    regress
  12. 12
    every CC steps set θθ\theta^{-} \gets \theta
    refresh target
  13. 13
    sss \gets s'
  14. 14
    until ss terminal
  15. 15
    return θ\theta

The whole thing is one cycle: the agent acts, stores what it saw, samples an unrelated batch of old experience, builds targets from the frozen copy, takes one SGD step, and every steps copies its weights into that frozen copy.

The DQN training cycle. Acting writes transitions to the buffer; learning reads a random batch, forms targets from , and steps by SGD; every steps closes the loop.

Hyperparameter defaults

The Nature agent fixed one set of hyperparameters across all games. The defaults are not arbitrary; each trades off a specific failure mode.

HyperparameterDefaultWhy this value
Replay capacity large enough to hold minutes of play, so batches mix many episodes and old policies; too small and the buffer re-correlates with the current trajectory
Target refresh stepslong enough that the label is effectively stationary between refreshes, short enough that it does not lag the online net into staleness
Minibatch sizea gradient estimate with usable variance at low compute per step; larger batches waste samples the buffer could reuse across more updates
Discount weights a horizon of roughly steps, matching Atari's reward delays without letting the bootstrap sum diverge
Exploration over stepsanneal from all-random to mostly-greedy so early play covers the state space and later play exploits the learned values, then hold a small floor for continued exploration
Learning ratesmall enough that the moving-target feedback does not blow up, given the frozen-target damping

The Atari setup

The benchmark that made DQN famous is the Arcade Learning Environment: one network, one set of hyperparameters, learning games from raw pixels and the score alone. The input pipeline turns the screen into a Markov state and the CNN turns that state into action values.

StageOperationOutput
Grayscale + downsampleRGB to luminance, resize
Frame stackconcatenate the last frames
Frame skiprepeat each action for frames fewer decisions
Reward clipclip reward to one scale across games

A single frame is not Markov: it shows position but not velocity or direction. The frame stack of four restores enough state for the dynamics to be (approximately) Markov, so the CNN can read motion from the channel axis.

The Atari Q-network. Four stacked frames pass through three convolutions and two dense layers to a head of one Q-value per action.

Trace the convolutional stack of the Nature architecture dimension by dimension. The input tensor is the frame stack (height, width, channels). Three convolutions, each followed by a ReLU, shrink the spatial extent while growing the channel count; a valid convolution with kernel , stride , and no padding maps a spatial size to .

LayerKernel / strideFiltersOutput tensorParameters
Input0
Conv 1, stride
Conv 2, stride
Conv 3, stride
Flatten0
FCdense
Outputdense

Working the spatial arithmetic: , then , then . The final feature map flattens to units, which the dense layer compresses to and the output head expands to one value per action. For a -action game the output is a length- vector and the whole network holds roughly million weights, dominated by the first dense layer.

The Q-head is the key design choice: the network outputs all action values at once, so and are both a single forward pass, not one pass per action.

Overestimation and Double DQN

The operator in the target has a bias. The target uses the same network both to select the best next action and to evaluate its value, and a single noisy estimate that happens to be too high is preferentially selected by the . The result is a systematic overestimation of action values.

Overestimation. A single noisy estimator (blue) used for both selection and evaluation yields a max above the true value (black line); decoupling the two removes the upward bias.

Double DQN breaks the coupling. The online network selects the action; the target network evaluates it. Selecting with one estimator and evaluating with another removes the systematic bias of selecting and evaluating with the same noise.

The change is one symbol: the now uses the online weights , while the value lookup still uses . No new network is added; DQN already carries both and , so the fix is free.

Double DQN splits selection from evaluation. The online net's argmax picks ; the frozen target net evaluates that chosen action, , so no single noisy estimate both selects and scores itself.
TargetSelectionEvaluationBias
DQNoverestimates (same net)
Double DQNdecoupled, near-unbiased

The dueling architecture

Many states have similar value under every action: when no action matters, the detail of which action is slightly better is noise. The dueling network factors the Q-value into a state-value and an action-advantage , estimated by two streams off a shared convolutional trunk and recombined.

The naive recombination is unidentifiable: adding a constant to and subtracting it from every leaves unchanged, so the two streams cannot be recovered uniquely. Subtracting the mean advantage pins them down.

The dueling split. A shared trunk feeds two streams, a scalar value and a per-action advantage , recombined by adding to the mean-centered advantage.

The gain is data efficiency: the value stream learns from every transition in a state regardless of the action taken, so states are evaluated accurately even for actions rarely tried.

Prioritized experience replay

Uniform replay samples every transition equally, but transitions are not equally informative: one with a large TD error carries more to learn from than one the network already predicts well. Prioritized experience replay samples in proportion to TD-error magnitude.

Biasing the sampling distribution biases the expected gradient: the network now trains on a distribution that is not the buffer's empirical one, so high-error transitions are over-represented. Importance sampling corrects the estimate by down-weighting each sampled transition by the inverse of how much it was over-sampled.

normalized by for stability. The exponent is annealed from a small value toward over training, so the correction is full only near convergence, when the unbiased gradient matters most.

SchemeSampling CorrectionEffect
Uniform replaynoneunbiased, slow on rare events
Greedy prioritizedneededfast but over-focuses, can overfit
Proportional () with tunable, asymptotically unbiased

Rainbow and beyond

Each improvement targets a distinct defect, and they are largely orthogonal. Rainbow combines six of them into one agent and shows the gains compound rather than cancel.

VariantProblem it fixes
Experience replaycorrelated, single-use samples
Target networka moving bootstrap target
Double DQNoverestimation from coupled
Duelingwasted value learning across actions
Prioritized replayuniform sampling ignores TD error
Multi-step returnsslow one-step credit assignment
Distributional (C51)a point estimate discards return spread
Noisy netshand-tuned -greedy exploration

Two of the Rainbow ingredients change what the network predicts. Distributional RL (C51) replaces the scalar with a full distribution over returns, modeled as a categorical over a fixed set of atoms, and minimizes a cross-entropy to the distributional Bellman target; the mean of that distribution recovers the usual , but the spread carries extra signal. Noisy nets make exploration learnable by adding parametric noise to the weights, with random and trained, so the policy explores through its own learned uncertainty and the -greedy schedule disappears.

What came after Rainbow

Goodfellow's text predates DQN's Rainbow line, so the citations here are the canonical papers themselves: the 2015 Nature DQN,1 Double DQN,2 the dueling architecture,3 prioritized replay,4 and the Rainbow combination.5 Two later directions follow, both continued in the full reinforcement-learning subject's deep-RL module.

Sample efficiency became the frontier. Rainbow needed hundreds of millions of frames per game. The successors — data-efficient variants and model-based agents that learn a world model and plan inside it — reach comparable scores from a small fraction of the data. Learning a model recovers the planning power the foundations lesson had with a known model, without being handed one, and it is the value-based counterpart to the policy-based methods of the next lesson.

The scaling story split by action space. DQN's one-value-per-action head needs a discrete, small action set: the and enumerate actions, which is impossible for continuous control (a robot's torques). That limitation motivates the actor-critic and policy-gradient methods of the following lesson, which parameterize the policy directly and so handle continuous actions the cannot. Value-based deep RL owns the discrete-action, high-sample-budget regime; policy-based methods own continuous control.

In short, DQN solved value-based deep RL for discrete actions, and everything after either made it cheaper (sample efficiency, model-based planning) or worked around its discrete-action ceiling (policy gradients). The two stabilizers this lesson built — replay and a frozen target — survive into nearly every value-based deep-RL agent since.

Takeaways

  • A Q-network replaces the tabular action-value with a CNN that emits one value per action in a single forward pass, generalizing across states no table could hold.
  • Naive online Q-learning with a network diverges: correlated samples, a moving bootstrapped target, and off-policy updates form the deadly triad.
  • Experience replay stores transitions and samples random minibatches, decorrelating updates and reusing each transition many times.
  • A target network , refreshed every steps, freezes the regression label so each interval is a stationary least-squares problem; the DQN loss is .
  • The Atari pipeline grayscales and stacks four frames for an approximate Markov state, feeding a three-conv CNN with a one-value-per-action head.
  • The operator overestimates action values; Double DQN decouples selection (online ) from evaluation (target ) to remove the bias.
  • The dueling architecture splits into value and mean-centered advantage streams, made identifiable by the mean subtraction.
  • Prioritized replay samples by TD-error magnitude and corrects the induced bias with importance weights annealed to full strength.
  • Rainbow combines replay, target nets, Double DQN, dueling, prioritized replay, multi-step returns, distributional (C51) values, and noisy-net exploration into one agent whose gains compound.
  • After DQN: DQN solved value-based deep RL for discrete actions; its successors made it cheaper (sample-efficient and model-based agents), while the discrete-action ceiling of the head is what motivates the policy-gradient and actor-critic methods for continuous control in the next lesson.

Footnotes

  1. Mnih et al., Human-level Control through Deep Reinforcement Learning, Nature 2015 — the DQN agent: a convolutional Q-network trained with experience replay and a periodically-frozen target network, learning 49 Atari games from pixels.
  2. van Hasselt, Guez & Silver, Deep Reinforcement Learning with Double Q-learning, AAAI 2016 — decouples action selection (online net) from evaluation (target net) to remove the max-operator overestimation bias.
  3. Wang et al., Dueling Network Architectures for Deep Reinforcement Learning, ICML 2016 — splits the Q-network into a state-value and a mean-centered advantage stream for more data-efficient value learning.
  4. Schaul et al., Prioritized Experience Replay, ICLR 2016 — samples transitions in proportion to TD-error magnitude with importance-sampling correction, focusing learning on surprising experience.
  5. Hessel et al., Rainbow: Combining Improvements in Deep Reinforcement Learning, AAAI 2018 — integrates six DQN extensions (double, dueling, prioritized replay, multi-step, distributional C51, noisy nets) into one agent whose gains compound.

╌╌ END ╌╌