Q-learning and DQN¶
Q-learning learns the value of every action in every state from raw experience, without a model of the world and while behaving however it likes. DQN made that work with a deep network by turning an unstable bootstrapping loop into a sequence of supervised regressions: replay old experience, and regress onto a frozen copy of yourself.
10,000 ft
Reinforcement learning has two big families. Value-based methods learn how good each action is and act greedily on that; policy-based methods learn the behaviour directly (policy gradients). Q-learning (Watkins, 1989) is the founding value-based algorithm: model-free, off-policy, provably convergent in the tabular case. DQN (Mnih et al., 2013; Nature 2015) married it to a convolutional network and played 49 Atari games from pixels with one set of hyperparameters — the result that started the deep RL era and led, via the same lab, to AlphaGo and AlphaZero. Its ideas never went away: Q-functions are the critics inside SAC and TD3 (actor-critic), the core of offline RL, and the lens through which RL for language models is increasingly analysed.
2,000 ft
- Learn Q, not V. \(Q(s,a)\) is the return from taking \(a\) in \(s\) and acting well afterwards. With \(Q\) you can act greedily without knowing the environment's dynamics: just take \(\arg\max_a Q(s,a)\).
- Bootstrap from the best next action. After each step, nudge \(Q(s,a)\) toward \(r + \gamma \max_{a'} Q(s',a')\). That target is the sample version of the Bellman optimality equation.
- Behave one way, learn about another. You can explore with ε-greedy while the target uses the greedy max: Q-learning is off-policy.
- Correct the bias of the max. The max of noisy estimates is too high; Double Q-learning selects with one estimate and evaluates with another.
- Scale with a network, and stabilise it. Replace the table by a CNN. Store transitions in a replay buffer and sample them at random; compute targets with a target network that is frozen for thousands of steps.
Ground level¶
Why learn action values¶
The Bellman equations give two ways to describe the optimal solution of a Markov decision process. The state value \(v_*(s)\) says how good it is to be in \(s\); the action value \(q_*(s,a)\) says how good it is to do \(a\) in \(s\) and act optimally afterwards. They are related by
Knowing \(v_*\) is not enough to act. To pick an action from \(v_*\) you must look one step ahead, which needs the transition probabilities \(p(s', r \mid s, a)\): that is dynamic programming, and it needs a model. Knowing \(q_*\) is enough: the optimal policy is \(\pi_*(s) = \arg\max_a q_*(s,a)\), a table lookup. The one-step look-ahead has been cached inside the function. That is the whole reason model-free control learns \(Q\).
Substituting the first identity into the second gives the Bellman optimality equation for \(q_*\), the equation Q-learning solves:
The Q-learning update¶
Temporal-difference learning turns a Bellman expectation into a stochastic update by replacing the expectation with one sample. Do the same to the optimality equation. After taking action \(a\) in \(s\) and observing \(r\) and \(s'\):
The bracket is the TD error \(\delta\). If \(s'\) is terminal, the target is just \(r\).
Worked example: one update by hand
Say \(Q(s,a) = 2.0\), you receive \(r = 1\), and the next state's action values are \(Q(s',\cdot) = (5.0,\ 3.0,\ -1.0)\). With \(\gamma = 0.9\) and \(\alpha = 0.1\): target \(= 1 + 0.9 \times 5.0 = 5.5\); TD error \(\delta = 5.5 - 2.0 = 3.5\); new \(Q(s,a) = 2.0 + 0.1 \times 3.5 = 2.35\). Note what did not matter: which action you will actually take in \(s'\). If your ε-greedy behaviour goes on to pick the \(-1.0\) action, the target still used \(5.0\).
That last point is the defining property. SARSA, the on-policy cousin from the previous page, uses \(Q(s', a')\) for the action \(a'\) the agent really takes next; Q-learning uses the greedy \(\max_{a'}\). SARSA therefore learns the value of the policy it follows, exploration included. Q-learning learns the value of the greedy policy (the target policy) while following any behaviour policy that keeps trying every action. That is what off-policy means, and it is what lets Q-learning learn from old data, from demonstrations, from another agent, or from a replay buffer.
The tabular algorithm, in full:
- Initialise \(Q(s,a)\) arbitrarily (zero is fine) and \(Q(\text{terminal},\cdot) = 0\).
- For each episode, start in \(s\). Until \(s\) is terminal: choose \(a\) from \(s\) by ε-greedy on \(Q\); take it, observe \(r, s'\); apply the update above; set \(s \leftarrow s'\).
Cliff walking: what off-policy buys and costs¶
Sutton and Barto's cliff-walking grid (Example 6.6) makes the difference visible. A 4 × 12 grid; every step costs \(-1\); stepping into the cliff along the bottom edge costs \(-100\) and sends you back to the start. Running both algorithms with ε = 0.1 and α = 0.5 for 500 episodes (the code is in Build it):
q : online return, last 100 episodes = -40.0 | greedy path: 13 steps through rows [2, 3]
max_a Q along row 2 (just above the cliff): [-12. -11. -10. -9. -8. -7. -6. -5. -4. -3. -2. -1.]
sarsa: online return, last 100 episodes = -23.5 | greedy path: 17 steps through rows [0, 1, 2, 3]
Q-learning has learned the exactly optimal values — the row above the cliff reads \(-12, -11, \dots, -1\), the true number of steps to go — and its greedy path hugs the cliff edge in 13 steps. SARSA's greedy path detours along the top row in 17 steps. Yet while training, SARSA earns more (\(-23.5\) against \(-40\) per episode), because Q-learning's ε-greedy behaviour walks along the edge and occasionally stumbles off it. Q-learning optimises the policy you will deploy once exploration is switched off; SARSA optimises the policy you are actually running. Neither is wrong; they answer different questions.
Exploration is the price of admission¶
Q-learning only converges if every state–action pair keeps being tried. The usual behaviour policy is ε-greedy: with probability ε pick a uniformly random action, otherwise the greedy one, with ε decayed over training. Alternatives carried over from bandits: optimistic initialisation (start \(Q\) high so untried actions look attractive), Boltzmann exploration (sample from \(\operatorname{softmax}(Q/\tau)\)), and count- or uncertainty-based bonuses. ε-greedy is crude: it explores uniformly, not where uncertainty is, and it needs on the order of \(|\mathcal A|^{k}\) tries to stumble on a specific \(k\)-step sequence. The hard-exploration Atari games (Montezuma's Revenge, Pitfall) stayed near zero for DQN for exactly this reason; Agent57's headline in 2020 was beating the human baseline on all 57 games, including those, by adding learned intrinsic-novelty rewards (Badia et al., 2020).
Maximisation bias and Double Q-learning¶
The \(\max\) in the target has a subtle side effect. Suppose every action's true value is \(-0.1\) but your estimates are noisy. The maximum of noisy estimates is systematically higher than the maximum of the true values. Sutton and Barto's Example 6.7 builds a trap from this. From state A, right ends the episode with reward 0. Left leads (reward 0) to state B, which has ten actions, each ending the episode with reward drawn from \(\mathcal N(-0.1, 1)\). Going left is worse in expectation, so the optimal policy always goes right; with ε = 0.1 exploration you would still go left 5% of the time.
Q-learning initially goes left far more often, because \(\max_b Q(B,b)\) over ten noisy averages is positive long before each average has settled near \(-0.1\). The fix, Double Q-learning (van Hasselt, 2010), keeps two independent tables. On each step, flip a coin to choose which one to update; select the best next action with that table and evaluate it with the other:
Because \(Q_2\)'s noise is independent of the noise that made \(Q_1\) pick that action, the evaluation is no longer biased upwards. Measured over 2,000 runs:
The last two lines of the experiment's output isolate the cause with ten samples of \(\mathcal N(-0.1, 1)\): the expected maximum is \(+1.443\), although every mean is \(-0.1\); evaluating the arg-max of one sample set on an independent set gives \(-0.104\), unbiased.
From tables to networks, and why the naive version breaks¶
A table needs one entry per state–action pair. An Atari screen is \(210 \times 160\) pixels with 128 colours: no table will do, and states never repeat exactly. So replace the table with a parameterised function \(Q(s,a;\theta)\) and do gradient descent on the squared TD error:
This is a semi-gradient method: the target also depends on \(\theta\), but we do not differentiate through it (see The maths). People tried this with neural networks throughout the 1990s, with one famous success — TD-Gammon (Tesauro, 1992–95), which learned a state-value network for backgammon by self-play — and many quiet failures. Three things go wrong at once:
- Correlated samples. Consecutive frames are nearly identical. SGD assumes roughly independent samples; feeding it a long run of near-duplicates overfits to the current part of the game and forgets the rest.
- A moving target. Every update changes \(\theta\), which changes the targets for every other state, including the one you just updated. You are chasing your own tail.
- The deadly triad. Sutton and Barto name three ingredients — function approximation, bootstrapping and off-policy training — any two of which are safe, but all three together can make the weights diverge to infinity even on a two-state problem (First principles works one through with numbers). Q-learning with a network has all three by construction.
Riedmiller's Neural Fitted Q Iteration (2005) showed the way out on small control problems: collect a batch of transitions, then repeatedly fit a network to targets computed from the previous fit, as a supervised regression. DQN is the online, scaled-up version of that idea.
DQN: two tricks and a recipe¶
Mnih et al.'s DQN (workshop paper 2013, Nature 2015) changed two things.
Experience replay (from Lin, 1992). Every transition \((s,a,r,s')\) goes into a buffer holding the last million. Each update samples a random minibatch of 32 from it. This breaks the temporal correlation, reuses each transition many times (data efficiency), and averages the training distribution over many past behaviours so it does not lurch when the policy changes. Replay is only legitimate because Q-learning is off-policy: the stored actions came from older policies, and the update does not care.
A target network. Targets are computed with a separate copy of the weights, \(\theta^-\), that is overwritten with \(\theta\) only every \(C\) = 10,000 updates:
Between copies, this is ordinary supervised regression onto fixed labels \(y\). Training becomes a sequence of regression problems, each one an approximate step of value iteration — exactly fitted Q iteration, but interleaved with data collection.
The rest is a recipe, and every item in it was there for a reason:
| Ingredient | Value in the Nature paper | Why |
|---|---|---|
| Input | last 4 frames, grey, \(84 \times 84\) | one frame hides velocity; stacking restores (near) Markov state |
| Network | conv 32@8×8/4 → conv 64@4×4/2 → conv 64@3×3/1 → FC 512 → one output per action | one forward pass gives \(Q(s,\cdot)\) for all actions, so the max is cheap |
| Action repeat | 4 frames per decision | 4× less compute per second of play |
| Reward clipping | rewards clipped to \([-1, 1]\) | one learning rate works across games with very different score scales |
| Loss | squared error with the error clipped to \([-1, 1]\) — i.e. the Huber loss | caps the gradient from rare huge TD errors |
| Optimiser | RMSProp, learning rate \(2.5\times10^{-4}\), minibatch 32, one update per 4 steps | |
| Replay | 1,000,000 transitions; 50,000 random steps before learning starts | |
| Target update | every \(C\) = 10,000 updates | |
| Exploration | ε annealed from 1.0 to 0.1 over the first million steps | |
| Discount | \(\gamma = 0.99\) | horizon of roughly \(1/(1-\gamma) = 100\) decisions |
(Values from the paper's Extended Data Table 1, as reproduced in the Dopamine and Rainbow papers.) The network has 1.69 million parameters for 18 actions, 95% of them in the single \(3136 \times 512\) fully connected layer. The 2013 workshop version, on seven games, beat all previous methods on six and a human expert on three; the 2015 version played 49 games with the same architecture and hyperparameters, reaching a level comparable to a professional human games tester across the set. It failed badly on games that need long-horizon exploration.
Reward clipping changes the problem
Clipping rewards to \([-1,1]\) means DQN optimises the number of reward events, not their size: in a game where one action earns 10 points and another 1,000, both count as \(+1\). That was an acceptable trade for one-hyperparameter-set-fits-all, and later agents removed it (R2D2 and MuZero use an invertible value rescaling instead). When you read an Atari result, check what was clipped.
The improvements, each aimed at one failure¶
The years 2015–2017 produced a set of fixes, each targeting one weakness of DQN. Hessel et al.'s Rainbow (2017) combined six of them and measured each one's contribution by ablation.
- Double DQN (van Hasselt, Guez and Silver, 2015). DQN already has two networks, so use them: select with the online net, evaluate with the target net, \(y = r + \gamma\, Q\big(s', \arg\max_{a'} Q(s',a';\theta);\ \theta^-\big)\). One line of code; large reductions in overestimation on Atari.
- Dueling architecture (Wang et al., 2015). Split the head into a state value \(V(s)\) and advantages \(A(s,a)\), recombined as \(Q = V + A - \tfrac{1}{|\mathcal A|}\sum_{a'} A(s,a')\). In many states the action barely matters; the \(V\) stream learns that from every sample, whatever action was taken.
- Prioritised experience replay (Schaul et al., 2015). Sample transition \(i\) with probability \(P(i) \propto p_i^{\alpha}\), where \(p_i = |\delta_i| + \epsilon\) is its last TD error, and correct the resulting bias with importance weights \(w_i \propto (N\,P(i))^{-\beta}\). Surprising transitions get replayed more. The paper's proportional variant used \(\alpha = 0.6\) and \(\beta\) annealed from 0.4 to 1.
- Multi-step targets. Replace the one-step target by \(\sum_{k=0}^{n-1}\gamma^k r_{t+k} + \gamma^n \max_{a'} Q(s_{t+n},a')\). Reward propagates \(n\) steps per update instead of one; Rainbow found \(n = 3\) best. (Strictly, this is no longer off-policy-correct — the intermediate actions came from the behaviour policy — and it works anyway for small \(n\).)
- Distributional RL / C51 (Bellemare, Dabney and Munos, 2017). Learn the whole distribution of the return, as a categorical over 51 fixed atoms spanning \([-10, 10]\), not just its mean. The distributional Bellman update is a projection onto those atoms followed by a cross-entropy loss — RL turned into classification. It helps more than theory predicted, probably through richer auxiliary learning signal.
- Noisy nets (Fortunato et al., 2017). Replace ε-greedy by learned, state-dependent noise in the weights of the linear layers.
Rainbow reached a median human-normalised score of 223% on 57 games (no-op starts), against 79% for DQN, and matched DQN's final performance after only 7 million frames instead of 200 million (Hessel et al., Table 2). In the ablations, removing prioritised replay or multi-step returns caused the largest drops in median score. Later landmarks: R2D2 (recurrent networks, distributed replay), Agent57 (2020, above the human baseline on all 57 games) and BBF (Schwarzer et al., 2023), which reached human-level interquartile-mean score on the Atari 100K benchmark — two hours of game play per game — by scaling the network and resetting parts of it periodically.
Where Q-learning hands over¶
The \(\max_{a'}\) is a lookup over 18 outputs on Atari. With a continuous action (a torque, a steering angle) it is an optimisation problem inside every update. The fix is to learn the maximiser: a second network \(\mu(s)\) trained to output \(\arg\max_a Q(s,a)\). That network is an actor, \(Q\) is its critic, and the result — DDPG, TD3, SAC — is on the actor-critic page. Q-learning's other descendant is offline RL, where the off-policy property is pushed to its limit: learn only from a fixed dataset, never acting at all — and where the maximisation bias returns with a vengeance.
History¶
Chris Watkins introduced Q-learning in his 1989 Cambridge PhD thesis, Learning from Delayed Rewards; the convergence proof appeared with Peter Dayan in Machine Learning in 1992. The same year, Long-Ji Lin's paper in the same journal introduced experience replay, and Gerald Tesauro's TD-Gammon showed a neural network trained by TD learning could reach expert backgammon. Then a decade of negative results: Baird's 1995 counterexample and Tsitsiklis and Van Roy's 1997 analysis showed that off-policy TD with function approximation can diverge, and "Q-learning with neural networks is unstable" became received wisdom. Riedmiller's NFQ (2005) and the DeepMind Atari work (2013–2015) showed it was unstable as usually done. The Nature paper and its Breakout video — the agent learning to tunnel behind the wall — made deep RL a field.
First principles¶
Why the max must be there. The optimal action value is defined by a recursion: acting optimally from \(s'\) means taking the best action there, so the value of the future is \(\max_{a'} q_*(s',a')\). Any other operator in the target — an average, the action actually taken — computes the value of some other policy. The max is what makes Q-learning a control algorithm rather than an evaluation algorithm.
Why it converges in a table. Define the Bellman optimality operator on action-value tables, \((\mathcal T Q)(s,a) = \mathbb E[r + \gamma \max_{a'} Q(s',a')]\). It is a \(\gamma\)-contraction in the max norm (The maths proves it), so repeatedly applying it — value iteration — converges to its unique fixed point \(q_*\) from any start. Q-learning applies \(\mathcal T\) noisily: its target is an unbiased sample of \((\mathcal T Q)(s,a)\) for the current table. Stochastic approximation theory (Robbins and Monro, 1951) says that averaging noisy evaluations of a contraction with suitably decaying step sizes converges to the same fixed point, provided every component is updated infinitely often. Those are exactly Watkins and Dayan's conditions.
Why off-policy needs no importance weights here. A one-step Q-learning target is about the transition \((s,a) \to (r,s')\), and the environment, not the policy, decides \(r\) and \(s'\). The action \(a\) is an argument of \(Q\), not a random draw to be reweighted, and the next action is replaced by the max. No step in the target depends on the behaviour policy, so no correction is needed. That breaks for \(n\)-step targets (the intermediate actions were drawn by the behaviour policy) and for Monte Carlo returns, which is why off-policy versions of those need importance sampling or truncated variants such as Retrace.
Why the triad diverges: a two-state example with numbers. Take one weight \(w\) and two states whose features are 1 and 2, so the approximate values are \(w\) and \(2w\). The first state transitions to the second with reward 0; the second transitions to a terminal state with reward 0. All true values are 0. Semi-gradient TD on the first transition changes \(w\) by \(\alpha(0 + \gamma \cdot 2w - w)\cdot 1\), multiplying it by \(1 + \alpha(2\gamma - 1)\). With \(\gamma = 0.9\) and \(\alpha = 0.1\) that is \(1.08\) per update. If an off-policy data distribution only ever shows you that transition, \(w\) grows without bound: \(w = 2{,}200\) after 100 updates, from a start of 1. Under the on-policy distribution you would also update the second state, which multiplies \(w\) by \(1 - 4\alpha = 0.6\), and the product \(0.648 < 1\) converges. Generalisation (raising \(w\) raises both values) plus bootstrapping (the target moves with \(w\)) plus an off-policy distribution (the correcting update never comes) is the whole story. DQN's target network and large replay buffer do not remove the triad; they slow the feedback loop enough that it rarely bites (van Hasselt et al., 2018, measured how rarely).
Why the target network works. With \(\theta^-\) frozen, \(L(\theta)\) is a fixed regression problem whose minimiser is the projection of \(\mathcal T Q_{\theta^-}\) onto the network class. Each phase therefore performs one step of approximate value iteration. If those projected steps are accurate enough, the sequence approaches \(q_*\): the classical bound for approximate value iteration (Bertsekas and Tsitsiklis, Neuro-Dynamic Programming, 1996) says that if every step has max-norm error at most \(\epsilon\), the greedy policies eventually lose at most \(2\gamma\epsilon/(1-\gamma)^2\) in value. With \(\gamma = 0.99\) that amplification factor is about 20,000 — one reason long horizons are hard.
The maths¶
Notation. States \(s \in \mathcal S\), actions \(a \in \mathcal A\), rewards \(r\), discount \(\gamma \in [0,1)\), transition kernel \(p(s',r \mid s,a)\). A Q-table is a vector in \(\mathbb R^{|\mathcal S||\mathcal A|}\); a Q-network maps a state to a vector in \(\mathbb R^{|\mathcal A|}\).
Bellman optimality operator.
Derivation: \(\mathcal T\) is a \(\gamma\)-contraction in the max norm
For any two tables \(Q_1, Q_2\) and any \((s,a)\),
Use \(|\max_x f(x) - \max_x g(x)| \le \max_x |f(x) - g(x)|\) (if \(f\) peaks at \(x_1\), \(\max f - \max g \le f(x_1) - g(x_1)\), and symmetrically). Then
Taking the max over \((s,a)\) on the left: \(\|\mathcal T Q_1 - \mathcal T Q_2\|_\infty \le \gamma \|Q_1 - Q_2\|_\infty\). By the Banach fixed-point theorem, \(\mathcal T\) has a unique fixed point — which the optimality equation says is \(q_*\) — and iterating \(\mathcal T\) converges to it geometrically: after \(k\) iterations the error is at most \(\gamma^k\) times the initial error.
Q-learning as stochastic approximation. Write the update as
where \(\mathbb E[\varepsilon_t \mid \text{past}] = 0\). Theorem (Watkins and Dayan, 1992): with bounded rewards, if every pair \((s,a)\) is updated infinitely often and the step sizes for each pair satisfy \(\sum_t \alpha_t = \infty\) and \(\sum_t \alpha_t^2 < \infty\), then \(Q_t \to q_*\) with probability 1. (A constant \(\alpha\), as everyone uses in practice, gives convergence to a neighbourhood instead.)
The semi-gradient. For a network, the per-sample loss is \(\ell(\theta) = \tfrac12\big(y - Q(s,a;\theta)\big)^2\) with \(y\) treated as a constant, so
If you also differentiated through \(y\) (the "residual gradient" of Baird, 1995) you would be
minimising the mean squared Bellman residual, which converges more reliably but to a worse solution
and, with stochastic transitions, to a biased one: \(\mathbb E[(y - Q)^2]\) includes the variance of
\(y\), which the residual gradient also tries to shrink. In code, the semi-gradient is
torch.no_grad() around the target.
The DQN loss, with shapes. For a minibatch of \(B\) transitions: states \(S \in \mathbb R^{B\times 4\times 84\times 84}\); \(Q(S;\theta) \in \mathbb R^{B\times|\mathcal A|}\); actions \(\mathbf a \in \{1..|\mathcal A|\}^B\); rewards and done flags \(\mathbf r, \mathbf d \in \mathbb R^B\).
with \(\operatorname{Huber}(x) = \tfrac12 x^2\) for \(|x| \le 1\) and \(|x| - \tfrac12\) otherwise, whose derivative is the error clipped to \([-1,1]\).
Double DQN target. \(y_i = r_i + \gamma(1-d_i)\,Q\big(s'_i,\ \arg\max_{a'}Q(s'_i,a';\theta);\ \theta^-\big)\).
Maximisation bias. For random estimates \(\hat Q(a)\) with \(\mathbb E[\hat Q(a)] = q(a)\), since \(\max\) is convex, Jensen's inequality gives \(\mathbb E[\max_a \hat Q(a)] \ge \max_a \mathbb E[\hat Q(a)] = \max_a q(a)\), with equality only when there is no noise. For \(n\) independent \(\mathcal N(\mu, \sigma^2)\) estimates, the bias is \(\sigma\,\mathbb E[\max_i Z_i]\) with \(Z_i\) standard normal: \(1.54\sigma\) for \(n = 10\) — matching the \(+1.443 = -0.1 + 1.54\) measured above. The double estimator \(\hat Q_2(\arg\max_a \hat Q_1(a))\) satisfies \(\mathbb E \le \max_a q(a)\): it can underestimate, but never systematically overestimates (van Hasselt, 2010).
Dueling identifiability. \(Q = V + A\) is not identifiable: adding \(c\) to \(V\) and subtracting it from every \(A\) leaves \(Q\) unchanged. Subtracting the mean advantage forces \(\sum_a A(s,a) = 0\), which pins down \(V(s) = \tfrac1{|\mathcal A|}\sum_a Q(s,a)\).
Build it¶
NumPy. Part 1 is tabular Q-learning and SARSA on cliff walking — note that the two algorithms differ in one line. Part 2 reproduces the maximisation-bias experiment. Part 3 is the two-state divergence.
import numpy as np
rng = np.random.default_rng(0)
# Cliff walking (Sutton & Barto, Example 6.6): 4 x 12 grid, start (3,0), goal (3,11).
# Every step costs -1; stepping into the cliff (3,1..10) costs -100 and resets to start.
H, W = 4, 12
MOVES = np.array([(-1, 0), (0, 1), (1, 0), (0, -1)]) # up, right, down, left
def step(s, a):
r, c = np.clip(np.array(s) + MOVES[a], (0, 0), (H - 1, W - 1))
if r == 3 and 1 <= c <= 10:
return (3, 0), -100.0, False
return (r, c), -1.0, (r, c) == (3, 11)
def run(method, episodes=500, alpha=0.5, eps=0.1, gamma=1.0):
Q = np.zeros((H, W, 4)); returns = []
pick = lambda s: rng.integers(4) if rng.random() < eps else int(np.argmax(Q[s]))
for _ in range(episodes):
s, a, G, done = (3, 0), None, 0.0, False
a = pick(s)
while not done:
s2, r, done = step(s, a); G += r
a2 = pick(s2)
# The ONLY difference: Q-learning bootstraps from the greedy action, SARSA from the one taken.
nxt = Q[s2].max() if method == "q" else Q[s2][a2]
Q[s][a] += alpha * (r + gamma * (0.0 if done else nxt) - Q[s][a])
s, a = s2, a2
returns.append(G)
return Q, np.array(returns)
def greedy_path(Q):
s, path = (3, 0), [(3, 0)]
while s != (3, 11) and len(path) < 50:
s, _, _ = step(s, int(np.argmax(Q[s]))); path.append(s)
return path
for m in ("q", "sarsa"):
Q, R = run(m)
p = greedy_path(Q)
rows = sorted({int(r) for r, _ in p})
print(f"{m:5s}: online return, last 100 episodes = {R[-100:].mean():6.1f} | "
f"greedy path: {len(p) - 1} steps through rows {rows}")
if m == "q":
print(" max_a Q along row 2 (just above the cliff):", Q[2].max(1).round(1))
q : online return, last 100 episodes = -40.0 | greedy path: 13 steps through rows [2, 3]
max_a Q along row 2 (just above the cliff): [-12. -11. -10. -9. -8. -7. -6. -5. -4. -3. -2. -1.]
sarsa: online return, last 100 episodes = -23.5 | greedy path: 17 steps through rows [0, 1, 2, 3]
import numpy as np
rng = np.random.default_rng(1)
# Maximisation bias (Sutton & Barto, Example 6.7). From A: "right" ends the episode (reward 0);
# "left" goes to B (reward 0). B has 10 actions, each ends with reward ~ N(-0.1, 1).
# Left is worse in expectation (-0.1), so the optimal policy always goes right.
N_B, RUNS, EPISODES, ALPHA, EPS = 10, 2000, 300, 0.1, 0.1
def egreedy(q):
return rng.integers(len(q)) if rng.random() < EPS else int(rng.choice(np.flatnonzero(q == q.max())))
def experiment(double):
left = np.zeros(EPISODES)
for _ in range(RUNS):
QA, QB = np.zeros((2, 2)), np.zeros((2, N_B)) # [table 1, table 2] for states A and B
for ep in range(EPISODES):
a = egreedy(QA.sum(0)) # act on Q1 + Q2 (one table if not double)
left[ep] += a == 0
if a == 1: # right: terminal, reward 0
i = rng.integers(2) if double else 0
QA[i, 1] += ALPHA * (0 - QA[i, 1]); continue
i = rng.integers(2) if double else 0 # which table to update this step
j = 1 - i if double else 0 # which table evaluates
best = int(np.argmax(QB[i])) # select with one table...
QA[i, 0] += ALPHA * (0 + QB[j, best] - QA[i, 0]) # ...evaluate with the other
b = egreedy(QB.sum(0))
QB[i, b] += ALPHA * (rng.normal(-0.1, 1) - QB[i, b])
return 100 * left / RUNS
q, dq = experiment(False), experiment(True)
for ep in (1, 10, 25, 50, 100, 300):
print(f"episode {ep:3d}: % left Q-learning {q[ep-1]:5.1f} Double Q {dq[ep-1]:5.1f} (optimal 5.0)")
# Why: the max of noisy estimates is biased upwards, even when every estimate is unbiased.
samples = rng.normal(-0.1, 1, size=(100_000, N_B, 2))
print("E[max_a Qhat(a)] =", samples[..., 0].max(1).mean().round(3), " (true max = -0.1)")
idx = samples[..., 0].argmax(1)
print("E[Qhat2(argmax Qhat1)] =", samples[np.arange(len(idx)), idx, 1].mean().round(3))
episode 1: % left Q-learning 49.6 Double Q 50.0 (optimal 5.0)
episode 10: % left Q-learning 87.3 Double Q 45.2 (optimal 5.0)
episode 25: % left Q-learning 94.0 Double Q 26.4 (optimal 5.0)
episode 50: % left Q-learning 82.8 Double Q 13.8 (optimal 5.0)
episode 100: % left Q-learning 45.9 Double Q 8.1 (optimal 5.0)
episode 300: % left Q-learning 11.9 Double Q 6.2 (optimal 5.0)
E[max_a Qhat(a)] = 1.443 (true max = -0.1)
E[Qhat2(argmax Qhat1)] = -0.104
import numpy as np
# The smallest divergence (Sutton & Barto, section 11.2): one weight w, two states with
# features 1 and 2, so v(s1) = w and v(s2) = 2w. Transition s1 -> s2 with reward 0.
# s2 -> terminal with reward 0. True values are 0, so w* = 0.
gamma, alpha, w0 = 0.9, 0.1, 1.0
def td_update(w, x, x_next, r): # semi-gradient TD(0) for v(s) = w * x(s)
return w + alpha * (r + gamma * w * x_next - w * x) * x
w_off, w_on = w0, w0
for k in range(100):
w_off = td_update(w_off, 1, 2, 0) # off-policy: only ever update the s1 -> s2 transition
w_on = td_update(td_update(w_on, 1, 2, 0), 2, 0, 0) # on-policy: s1 -> s2 then s2 -> end
if k + 1 in (1, 10, 50, 100):
print(f"after {k+1:3d} rounds: off-policy w = {w_off:12.4g} on-policy w = {w_on:.4g}")
print("off-policy growth factor per update: 1 + alpha(2 gamma - 1) =", 1 + alpha * (2 * gamma - 1))
print("on-policy factor per round: (1 + alpha(2 gamma - 1)) * (1 - 4 alpha) =",
round((1 + alpha * (2 * gamma - 1)) * (1 - 4 * alpha), 3))
after 1 rounds: off-policy w = 1.08 on-policy w = 0.648
after 10 rounds: off-policy w = 2.159 on-policy w = 0.01305
after 50 rounds: off-policy w = 46.9 on-policy w = 3.791e-10
after 100 rounds: off-policy w = 2200 on-policy w = 1.437e-19
off-policy growth factor per update: 1 + alpha(2 gamma - 1) = 1.08
on-policy factor per round: (1 + alpha(2 gamma - 1)) * (1 - 4 alpha) = 0.648
The deep version, in PyTorch (standard code, not run here): the Nature network and the Double DQN
loss. A full agent adds a replay buffer, an ε schedule and the environment loop; CleanRL's
single-file dqn_atari.py is the cleanest complete reference.
import torch, torch.nn as nn, torch.nn.functional as F
class QNet(nn.Module): # the Nature DQN torso
def __init__(self, n_actions):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(4, 32, 8, stride=4), nn.ReLU(), # 84 -> 20
nn.Conv2d(32, 64, 4, stride=2), nn.ReLU(), # 20 -> 9
nn.Conv2d(64, 64, 3, stride=1), nn.ReLU(), # 9 -> 7
nn.Flatten(), nn.Linear(64 * 7 * 7, 512), nn.ReLU(),
nn.Linear(512, n_actions))
def forward(self, x): # x: (B, 4, 84, 84) uint8 frames
return self.net(x.float() / 255.0) # (B, n_actions)
def double_dqn_loss(q, q_target, s, a, r, s2, done, gamma=0.99):
q_sa = q(s).gather(1, a[:, None]).squeeze(1) # Q(s, a; θ), shape (B,)
with torch.no_grad(): # semi-gradient: y is a constant
a2 = q(s2).argmax(1, keepdim=True) # select with the online net
y = r + gamma * (1 - done) * q_target(s2).gather(1, a2).squeeze(1) # evaluate with θ⁻
return F.smooth_l1_loss(q_sa, y) # Huber loss
# every C steps: q_target.load_state_dict(q.state_dict())
Things to try
- In Part 1, decay ε to 0 over training. Show that SARSA's greedy path then converges to the cliff-edge path as well — on-policy and off-policy agree once behaviour is greedy.
- In Part 2, replace the ten actions at B by 100 actions. Predict the size of Q-learning's initial bias from \(\sigma\,\mathbb E[\max_{i\le 100} Z_i] \approx 2.5\sigma\), then measure it.
- In Part 3, find the largest \(\gamma\) for which the off-policy update does not diverge (hint: \(2\gamma - 1 \le 0\)). Then add a target "network": hold \(w^-\) fixed for 20 updates before copying. Does it still diverge? Why does slowing the loop not cure the triad here?
- Implement Q-learning with a linear function approximator on the cliff grid (one-hot features reproduce the table exactly; then try coarser tile features) and watch where generalisation starts to hurt.
- Train
QNetonCartPole-v1from Gymnasium with an MLP instead of the conv torso. Plot the loss: notice it does not go down like a supervised loss, because the targets move.
Check yourself¶
Why can you act greedily with Q but not with V, without a model?
\(\arg\max_a Q(s,a)\) is a lookup. Acting greedily on \(V\) needs \(\arg\max_a \sum_{s',r} p(s',r\mid s,a)[r + \gamma V(s')]\), which needs the transition model. \(Q\) caches that one-step look-ahead.
What makes Q-learning off-policy, in one sentence — and why does that make experience replay legitimate?
Its target uses \(\max_{a'}Q(s',a')\), the greedy policy's next action, regardless of what the behaviour policy did next; so transitions generated by any earlier policy are valid training data, which is what a replay buffer contains.
In cliff walking, Q-learning's online return is worse than SARSA's although it learns the optimal policy. Explain.
Q-learning learns values of the greedy policy, which walks along the cliff edge. But it behaves ε-greedily, and a random step from the edge falls off (\(-100\)). SARSA learns the value of the ε-greedy policy it is running and so prefers a safer path that random steps cannot ruin.
Why is \(\mathbb E[\max_a \hat Q(a)] \ge \max_a q(a)\), and how does Double Q-learning avoid it?
The max is convex, so by Jensen the expectation of the max exceeds the max of expectations; intuitively, the max preferentially selects actions whose noise happened to be positive. Double Q-learning selects the arg-max with one estimator and evaluates it with an independent one, whose noise is not correlated with the selection.
Name the three ingredients of the deadly triad and say which DQN component addresses which symptom.
Function approximation, bootstrapping, off-policy learning. DQN keeps all three; the target network slows the bootstrapping feedback loop (targets don't move every step), and the large replay buffer makes the training distribution change slowly and covers many behaviours. Neither removes the possibility of divergence.
How many parameters does the Nature DQN have for 18 actions, and where are they?
Conv layers: \(8{,}224 + 32{,}832 + 36{,}928\); FC: \(3136 \times 512 + 512 = 1{,}606{,}144\); output: \(512 \times 18 + 18 = 9{,}234\). Total \(1{,}693{,}362\), about 95% in the first fully connected layer.
Hard: why is the \(n\)-step Q-learning target not off-policy-correct, and why might it help anyway?
\(\sum_{k<n}\gamma^k r_{t+k} + \gamma^n\max Q(s_{t+n},\cdot)\) assumes the actions at \(t+1..t+n-1\) were greedy, but they came from the (older, exploratory) behaviour policy, so the target estimates a mixture of the two policies' values. The bias is small for small \(n\) and near-greedy behaviour, while propagating reward \(n\) steps per update speeds learning a lot — Rainbow's ablations show it as one of the two most important components.
Hard: why does DQN use the Huber loss, and what would change if it used plain squared error?
The Huber gradient is the TD error clipped to \([-1,1]\): rare transitions with huge TD errors (new reward discovered, target network just updated) cannot produce huge parameter jumps. With plain squared error, a single such minibatch can wreck the network, which, through bootstrapping, corrupts every target that depends on it.
Go deeper¶
Papers
- Q-learning — Watkins and Dayan, Machine Learning, 1992. The convergence proof; short and readable.
- Playing Atari with Deep Reinforcement Learning — Mnih et al., 2013. The seven-game workshop paper; Algorithm 1 is DQN on half a page.
- Human-level control through deep reinforcement learning — Mnih et al., Nature, 2015. Adds the target network; read Methods and Extended Data Table 1.
- Self-improving reactive agents based on reinforcement learning, planning and teaching — Lin, Machine Learning, 1992. Where experience replay comes from.
- Neural Fitted Q Iteration — Riedmiller, ECML 2005. Batch Q-learning with a network as repeated regression — DQN's conceptual parent.
- An analysis of temporal-difference learning with function approximation — Tsitsiklis and Van Roy, 1997. Why on-policy linear TD converges and off-policy can diverge.
- Double Q-learning — van Hasselt, NeurIPS 2010, and Deep RL with Double Q-learning — van Hasselt, Guez and Silver, 2015.
- Dueling Network Architectures — Wang et al., 2015 · Prioritized Experience Replay — Schaul et al., 2015.
- A Distributional Perspective on Reinforcement Learning — Bellemare, Dabney and Munos, 2017. C51; the projection step in Algorithm 1 is worth working through.
- Rainbow — Hessel et al., 2017. The ablation figure is a map of what mattered.
- Deep Reinforcement Learning and the Deadly Triad — van Hasselt et al., 2018. Empirical: how often divergence really happens in DQN variants.
- Agent57 — Badia et al., 2020 · Bigger, Better, Faster — Schwarzer et al., 2023. The two ends of Atari: all 57 games, and human-level sample efficiency.
Videos and lectures
- RL Course by David Silver, Lecture 6: Value Function Approximation — DeepMind/UCL. Semi-gradient TD, the convergence table, and DQN from its authors' lab.
- CS 285: Deep Reinforcement Learning — Sergey Levine, UC Berkeley. The Q-learning lectures derive fitted Q iteration and DQN as approximate value iteration.
Articles and courses
- Hugging Face Deep RL Course — Units 2–3 build tabular Q-learning and DQN step by step.
- Reinforcement Learning: An Introduction — Sutton and Barto, 2nd ed., 2018 (free). Section 6.5 (Q-learning), 6.7 (maximisation bias), chapter 11 (the deadly triad).
Code
- CleanRL — Single-file dqn.py and Atari variants with benchmarked results.
- Stable-Baselines3 — Production-quality DQN with documented defaults.
Where this leads¶
- Policy gradients and REINFORCE — the other family: optimise the policy directly, which handles continuous and stochastic policies naturally.
- Actor-critic and PPO — Q-functions return as critics; DDPG, TD3 and SAC are Q-learning with a learned maximiser.
- Model-based RL and planning — instead of caching look-ahead in \(Q\), learn a model and search.
- Offline RL and RL for language models — off-policy learning from a fixed dataset, where overestimation of unseen actions is the central problem.