Q-Learning and Temporal Difference Control
Q-learning learns the optimal action-value function directly from sampled transitions using a bootstrapped, off-policy temporal-difference target: r + γ max_a' Q(s',a'). Because the expected update is the Bellman optimality operator, a contraction, the tabular algorithm converges to Q* under standard stochastic-approximation conditions; its deep counterpart is the DQN family.
1. Concept overview
Q-learning is an off-policy temporal-difference (TD) control algorithm. It stores estimates and, after observing a transition , performs
Here is the TD error: a one-step sample of the Bellman optimality residual. The target uses rather than the action actually taken next, so the algorithm learns the optimal policy regardless of the exploratory behaviour policy generating data — hence off-policy.
Two ingredients make it powerful: bootstrapping (update a guess from another guess, no need to wait for an episode to end, unlike Monte Carlo) and sampling (no need to know or , unlike dynamic programming). Tabular Q-learning converges to w.p.1 under mild conditions; with a neural network the same target, plus experience replay and a target network, yields Deep Q-Networks (DQN).
2. Why this concept exists
Dynamic programming solves the Bellman optimality equation but requires the full model . Monte Carlo control estimates returns from complete episodes but has high variance and only updates at episode end. TD learning sits between them: it updates after every step using a bootstrapped target, giving lower variance than Monte Carlo and no model requirement.
Earlier control methods:
- Policy iteration needs a model and repeated exact evaluations ( solves).
- Monte Carlo exploring starts needs episodes that terminate and an "exploring starts" assumption.
- SARSA learns the value of the policy being followed, so exploration changes what is learned (it finds a safe policy, not the optimal one).
Q-learning removes the model and the exploring-starts assumption while still targeting the optimal policy. The key trick is decoupling the behaviour policy (how actions are chosen, typically -greedy) from the target policy (greedy w.r.t. ). This separation is the foundation of off-policy deep RL and replay buffers that reuse old data from many different policies.
3. Historical background
Christopher Watkins introduced Q-learning in his 1989 PhD thesis and proved convergence with Peter Dayan in their 1992 Machine Learning paper "Q-learning" — the canonical Robbins–Monro-style proof. The name "Q" came from the action-value notation used in dynamic programming.
Sutton (1988) had already formalized temporal-difference learning for prediction; Q-learning extended TD to control by inserting the max. Lin (1992) studied the interplay of exploration and function approximation. Van Hasselt (2010) identified the overestimation bias of the max operator and proposed Double Q-learning.
Mnih et al. (2013, 2015) combined Q-learning with a convolutional network, experience replay, and a periodically frozen target network (DQN), achieving human-level control on Atari from pixels. Follow-ups include Double DQN (van Hasselt et al. 2016), Prioritized Experience Replay (Schaul et al. 2015), Dueling networks (Wang et al. 2016), and Rainbow (Hessel et al. 2018).
4. Fundamental problem
Learn from a stream of transitions generated by an unknown MDP while using a behaviour policy that explores. Specifically:
- No model: and are unavailable, so the Bellman optimality backup must be estimated from one sample.
- Credit assignment: rewards are delayed; bootstrapping propagates value backward one step at a time.
- Exploration vs. exploitation: with a greedy behaviour policy the agent never discovers better actions; with pure random behaviour it never exploits what it learned.
- Off-policy correctness: data generated by -greedy behaviour must still yield the greedy (optimal) policy, not the behaviour policy's value.
5. First-principles explanation
Fact 1 — the expected TD target is the Bellman backup. For a transition drawn under any behaviour policy with sufficient support,
The behaviour policy's action probabilities cancel because we condition on : the transition is drawn from the MDP, not from the policy. This is why the update is off-policy.
Fact 2 — stochastic approximation. The update is a Robbins–Monro root-finding scheme for the equation . If the target is unbiased for and is a -contraction, the iterate tracks the unique fixed point .
Fact 3 — the max encodes optimality. Choosing the largest next-state value in the target implements Bellman's principle of optimality: the tail of an optimal trajectory must be optimal. The same max later causes overestimation when is noisy, since for any non-degenerate noise.
Fact 4 — exploration supplies coverage. Every must be sampled infinitely often for convergence; -greedy with (or a decaying schedule with ) supplies this.
6. Prerequisite concepts
You need: (a) the MDP formalism and both Bellman equations — the TD target is a single-sample estimate of the optimality backup ; (b) conditional expectation, so you can see why the behaviour policy cancels when conditioning on ; (c) Robbins–Monro stochastic approximation, which explains the , conditions; (d) -greedy exploration and the exploration–exploitation tradeoff; (e) basic concentration inequalities for the convergence intuition; (f) NumPy for the tabular implementation and PyTorch nn.Module, autograd, and tensor indexing for the DQN version. Familiarity with Monte Carlo control and SARSA makes the off-policy distinction much easier to see.
7. Complete mathematical formulation
Tabular update.
with all other entries unchanged.
Target and behaviour policies. Behaviour generates actions (e.g. -greedy: ); target policy is what we learn about.
Convergence conditions (Watkins & Dayan, 1992). Finite MDP, , every state-action pair visited infinitely often, rewards bounded, and learning rates satisfying
Then w.p.1. Constant converges to a noise ball around .
Deep Q-networks. With parameters and a replay buffer ,
where is a slowly updated target network. Gradient: ; the target is treated as a constant (no gradient through ).
8. Notation dictionary
| Symbol | Meaning | Type / shape | |---|---|---| | | estimate of optimal action value | table or network output | | | true optimal action value | | | | sampled reward | scalar | | | sampled successor state | state | | | TD error | scalar | | | learning rate | scalar in | | | discount factor | scalar in | | | bootstrapped target value | scalar | | | behaviour policy | distribution over actions | | | exploration probability | scalar | | | Bellman optimality operator | | | | online and target network parameters | vectors in | | | replay buffer | store of transitions | | | terminal flag | scalar | | | target-network update period | integer |
9. Step-by-step derivation
Step 1 — replace the expectation by a sample. The Bellman optimality equation for action values is
Sampling one successor gives a noisy target .
Step 2 — stochastic approximation. Move the current estimate a fraction toward the target:
This is a Robbins–Monro iteration for the root of .
Step 3 — verify unbiasedness. Conditioning on , . Note the expectation is over the MDP transition, not over the behaviour policy's choice of ; this is the mathematical source of off-policy learning.
Step 4 — convergence intuition. Write with martingale noise . Taking norms and using gives a recursion whose deterministic part is a contraction; Robbins–Monro conditions on kill the noise.
Step 5 — policy extraction. The greedy policy is optimal once . If , then is -optimal, since action-value gaps are distorted by at most and errors compound by .
Step 6 — deep version. Replace the table by , sample mini-batches from replay, and use a frozen in the target. The expected gradient of the squared TD error is the same root-finding direction in parameter space; the target network stabilizes the moving regression target.
10. Proofs and proof intuition
Lemma (off-policy unbiasedness). for any behaviour policy with where needed. Proof. Given , the pair is distributed according to the MDP kernel , independent of the action chosen at time . The max is over all actions, so no appears.
Theorem (tabular convergence, Watkins & Dayan 1992). Under the conditions in section 7, w.p.1. Proof sketch. Decompose the error as in Step 4. Let . Since for , the deterministic part is a strict contraction; the noise term has bounded variance and , so it sums to a finite martingale limit (Robbins–Siegmund theorem). Infinite visitation ensures every coordinate is updated often enough, giving .
Lemma (max overestimation). If with i.i.d. zero-mean noise, then , with strict inequality unless all are identical constants. Proof. by Jensen's inequality applied to the convex function . This motivates Double Q-learning and Double DQN.
Proof intuition. Q-learning is gradient-free stochastic approximation: every sample nudges one cell of a table toward a (noisy) Bellman target. The contraction guarantees the nudges point inward; the learning-rate conditions guarantee the noise averages out.
11. Geometric interpretation
The table is a point in . Each update moves one coordinate toward the surface defined by . The Bellman optimality operator is a -contraction in sup norm, so repeated exact backups spiral into the unique point ; Q-learning follows a stochastic version of that spiral with one coordinate touched per step.
SARSA and Q-learning target different points in the same space: SARSA's fixed point is (the value of the behaviour policy), while Q-learning's is . Geometrically, SARSA moves toward the value of the policy actually executed; Q-learning moves toward the upper envelope , so its updates can point "above" the current policy's values. On the cliff-walking task this visibly produces two different policies: Q-learning hugs the cliff edge (optimal return), SARSA detours away (safer but lower return).
With function approximation , the table becomes a -dimensional manifold in ; the update is a projection onto that manifold, and the contraction argument no longer strictly applies — the source of the "deadly triad" instability.
12. Visual explanation
Use a Q-value heat map for a grid world: rows = states, columns = actions, colour = . After each episode, watch the high-value cells propagate one step backward from the goal (the TD wavefront). Overlay the greedy policy arrows; they should point toward increasing value and stabilize.
A second visual: plot versus training steps for the two-state example, with dashed lines at the true and ; the estimates climb monotonically on average with noise from exploration.
Cliff-walking comparison (Sutton & Barto, Example 6.6): draw a grid with a cliff along the bottom row. Plot episode returns for SARSA and Q-learning: SARSA converges near per episode by taking a safe upper route, Q-learning converges near along the cliff edge while -greedy exploration occasionally falls (large negative spikes). The Interactive Q-Learning Lab in Practical Labs reproduces both curves.
13. Numerical worked example
Use the two-state MDP from the Bellman section: ; from , "walk" gives reward 1 and goes to , "stay" gives 0 and remains in ; from , "walk" gives 2 and goes to , "stay" gives 0 and remains in . True , , , .
Initialize , , and alternate the transitions (reward 1) and (reward 2):
- : , so .
- : , so .
- : , so .
- : , so if the updated value were used; reading the table before the update (as in the code below) gives .
Continuing with the code's update order, takes values and takes , approaching and geometrically (the contraction factor is modulated by ). Note that and stay near zero: their targets are and they are never selected greedily.
14. Real-world analogy
Imagine learning which restaurants are worth revisiting in a new city. You explore randomly 20% of the time, otherwise go to your current favourite. After each visit you update its rating using the enjoyment you got plus the discounted value of the best-rated restaurant you could go to next. Crucially, your rating update asks "what would be best next?" rather than "what did I actually do next?" — so even after a random exploratory visit you still learn about the optimal strategy. That is off-policy learning. SARSA would instead update using the restaurant you actually choose next, eventually learning the value of your exploratory habits — safer, but not optimal.
15. Algorithm pseudocode
algorithm TabularQLearning(alpha, gamma, epsilon, episodes):
Q[s,a] <- 0 for all s,a # arbitrary initialisation
for each episode:
s <- initial state
while s is not terminal:
a <- epsilon_greedy(s, Q, epsilon) # behaviour policy
r, s' <- environment.step(a) # sample transition
target <- r + gamma * max_a' Q[s',a'] # bootstrapped, off-policy
Q[s,a] <- Q[s,a] + alpha*(target - Q[s,a]) # TD update
s <- s'
return Q, pi(s)=argmax_a Q[s,a]
algorithm DQN(theta, theta_minus, replay D, batch b, target period C):
for each environment step:
a <- epsilon_greedy(Q_theta) ; observe (s,a,r,s',done)
D.push(s,a,r,s',done)
if len(D) >= b:
sample mini-batch (s_j,a_j,r_j,s'_j,d_j) from D
y_j <- r_j + gamma*(1-d_j)*max_a' Q(s'_j,a'; theta_minus)
gradient step on sum_j (y_j - Q(s_j,a_j; theta))^2
every C steps: theta_minus <- theta
16. Implementation from scratch
import numpy as np
gamma, alpha, epsilon = 0.5, 0.1, 0.2
P = np.zeros((2, 2, 2)) # [a, s, s']
r = np.zeros((2, 2, 2))
P[0,0,1] = 1.0; r[0,0,1] = 1.0 # A: walk -> B (+1)
P[1,0,0] = 1.0 # A: stay -> A (0)
P[0,1,0] = 1.0; r[0,1,0] = 2.0 # B: walk -> A (+2)
P[1,1,1] = 1.0 # B: stay -> B (0)
def transition(s, a):
s2 = np.random.choice(2, p=P[a, s])
return s2, r[a, s, s2]
def act(s, Q):
if np.random.rand() < epsilon:
return np.random.randint(2) # explore
return int(np.argmax(Q[s])) # exploit (ties broken by argmax)
def q_learning(n_updates=20000):
Q = np.zeros((2, 2)) # rows = states, columns = actions
for t in range(n_updates):
s = np.random.randint(2)
a = act(s, Q)
s2, reward = transition(s, a)
td_error = reward + gamma*np.max(Q[s2]) - Q[s, a] # off-policy target
Q[s, a] += alpha*td_error
return Q
Q = q_learning()
Q_star = np.array([[8/3, 4/3], [10/3, 5/3]])
print(np.round(Q, 3))
assert np.allclose(Q, Q_star, atol=0.05)
assert np.argmax(Q, axis=1).tolist() == [0, 0] # walk in both states
17. Professional library implementation
import random
from collections import deque
import gymnasium as gym
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class QNet(nn.Module):
"""Mapping (batch, 4) -> (batch, 2) for CartPole-v1."""
def __init__(self, n_actions=2):
super().__init__()
self.net = nn.Sequential(
nn.Linear(4, 128), nn.ReLU(),
nn.Linear(128, 128), nn.ReLU(),
nn.Linear(128, n_actions))
def forward(self, x):
return self.net(x) # Q(s, .) for every action
class ReplayBuffer:
def __init__(self, capacity=10_000):
self.buf = deque(maxlen=capacity)
def push(self, s, a, r, s2, done):
self.buf.append((s, a, r, s2, done))
def sample(self, b):
batch = random.sample(self.buf, b)
s, a, r, s2, d = zip(*batch)
return (torch.as_tensor(np.stack(s), dtype=torch.float32),
torch.as_tensor(a, dtype=torch.int64),
torch.as_tensor(r, dtype=torch.float32),
torch.as_tensor(np.stack(s2), dtype=torch.float32),
torch.as_tensor(d, dtype=torch.float32))
env = gym.make("CartPole-v1")
q, target = QNet(), QNet()
target.load_state_dict(q.state_dict())
opt = optim.Adam(q.parameters(), lr=1e-3)
buf = ReplayBuffer()
gamma, batch_size, C = 0.99, 64, 500
epsilon, eps_min, eps_decay = 1.0, 0.05, 0.995
s, _ = env.reset()
updates = 0
for step in range(20_000):
if random.random() < epsilon:
a = env.action_space.sample()
else:
with torch.no_grad():
a = int(q(torch.as_tensor(s, dtype=torch.float32)).argmax())
epsilon = max(eps_min, epsilon*eps_decay)
s2, r, terminated, truncated, _ = env.step(a)
done = terminated or truncated
buf.push(s, a, r, s2, done)
s = env.reset()[0] if done else s2
if len(buf) < 1000:
continue
sb, ab, rb, s2b, db = buf.sample(batch_size)
q_sa = q(sb).gather(1, ab[:, None]).squeeze(1) # (b,)
with torch.no_grad():
y = rb + gamma*(1 - db)*target(s2b).max(dim=1).values
loss = F.mse_loss(q_sa, y) # Bellman residual
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
updates += 1
if updates % C == 0:
target.load_state_dict(q.state_dict())
env.close()
Production variants add Double DQN (use q to select the action, target to evaluate it), prioritized sampling, n-step returns, and dueling heads.
18. Code walkthrough
Scratch version. P[a,s,s2] and r[a,s,s2] encode the MDP; np.random.choice(2, p=P[a,s]) samples the successor, so the algorithm never reads the model directly in the update — the model is only the simulator. np.max(Q[s2]) is the off-policy bootstrap; replacing it with Q[s2, act(s2)] or an -greedy expected value would turn this into SARSA / Expected SARSA. The assertion checks convergence to the known .
DQN walkthrough. QNet maps a 4-dimensional observation to 2 action values; with hidden layers 128/128 it has parameters. gather(1, ab[:,None]) selects the Q value of the taken action for each batch element — without this, the gradient would update all actions toward the same target. The target y = r + gamma*(1-d)*max Q(s',a';theta^-) is computed under no_grad(), freezing it as a regression label; this breaks the moving-target feedback loop. F.mse_loss is the sample estimate of . The target network is refreshed every updates; too-frequent refresh reintroduces instability, too-slow refresh slows value propagation.
Common shape check: q_sa, rb, db and the max over target(s2b) must all have shape (batch_size,); broadcasting a (b,1) against (b,) silently creates (b,b).
19. Tensor and memory analysis
Tabular case: needs bytes in fp32; for states and actions that is only 16 KB. No model or gradient buffers are required.
Deep case with a 4→128→128→2 MLP: parameters = 69.6 KB fp32; add the same for target (69.6 KB) and Adam moments ( KB) — under 0.3 MB total.
Replay buffer with capacity : each transition stores . For CartPole, has 4 fp32 values: floats = 44 bytes per transition, so is 44 MB. For Atari with a uint8 frame stack, one transition contains two frames = 56,448 bytes; would need 56 GB, which is why DQN implementations store compressed frames or indices into a frame ring buffer.
Training batch : sb, s2b are fp32 (1 KB each); q(sb) is ; activations for the MLP are per layer (32 KB each). GPU training is dominated by replay sampling and memory traffic, not compute for such small networks; for Atari CNNs the activations dominate.
20. Time complexity
Tabular update: to evaluate (or with an incrementally maintained max), plus for the write. updates cost . With a linear address and constant average branching, this is independent of — the algorithm's main appeal.
Sample complexity: tabular Q-learning needs enough visits to every ; high-probability PAC bounds scale roughly like up to logarithmic factors, and worse when mixing is slow. Constant gives convergence to a noise ball rather than exact convergence.
Deep Q-learning: each gradient step costs forward and backward; the target-network max adds in the no-grad pass. Experience replay amortizes samples but each sample is used multiple times, so environment interaction and gradient computation scale independently.
21. Space complexity
Tabular: for plus working memory per update; no model needed. This is the minimal memory for a value-based controller without generalization.
Deep: for online network, for target, for Adam moments, for replay, and for backpropagation. For the CartPole network above: MB of parameters/optimizer state plus 44 MB of replay at . Checkpointing can trade activation memory for recomputation in very deep Q networks.
22. Experimental demonstration
- Run the scratch Q-learning loop and record every 1000 updates: expect geometric decay toward the noise floor (about 0.02–0.05). Re-run with ; large is faster but noisier.
- Compare Q-learning with SARSA on the cliff-walking task (Sutton & Barto Fig. 6.10): Q-learning's greedy route follows the cliff edge with per-episode return near ; SARSA's avoids the edge near ; with , Q-learning shows occasional large negative returns from exploratory falls. This directly demonstrates off-policy vs. on-policy targets.
- Run the DQN CartPole code and log episode lengths: expect a rise from steps to 150–200+ steps within a few thousand steps, with variance due to exploration decay.
- Ablate the target network (set
C=1): learning curves become unstable or collapse, illustrating the moving-target problem. Ablate replay (on-policy sequential batches): samples are correlated and the network forgets early transitions.
23. Benchmark results
Mnih et al. (2015, Nature) reported DQN from raw pixels achieving a mean score of ~5881 on Seaquest and ~6934 on Breakout, and performing at or above a human expert on 29 of 49 Atari games, using a single architecture and fixed hyperparameters. These are landmark numbers but come with heavy preprocessing (frame skipping 4, grayscale 84×84, 4-frame stack), a 1M-frame replay buffer, and 200M training frames (~8 days on a GPU at the time).
On CartPole-v1, the small DQN above typically reaches the 195-step "solved" criterion within roughly 2–5×10 environment steps (run-dependent). Tabular Q-learning on FrozenLake-4×4 with and -greedy exploration converges to near-optimal success rates within a few thousand episodes.
Do not compare these numbers directly: metric (return vs. success rate), exploration schedule, frame-skip, and evaluation protocol (greedy vs. training policy) change results dramatically. Always report all of them, plus error bars over seeds.
24. Limitations
- Tabular convergence guarantees vanish with nonlinear function approximation, bootstrapping, and off-policy data — the "deadly triad" (Sutton & Barto, 2018).
- The max operator overestimates action values under noise; can produce systematically optimistic policies and instability.
- Requires sufficient exploration; in sparse-reward environments -greedy may take exponentially long to find the first reward.
- Sample-inefficient: every improvement comes from many single-step samples; on-policy alternatives are even less efficient but more stable in practice.
- DQN is virtually always off-policy value-based: it cannot naturally represent stochastic policies or continuous actions (continuous control needs DDPG/TD3/SAC).
- Replay buffers assume relatively stationary dynamics; highly non-stationary environments break the i.i.d.-sampling rationale.
- Hyperparameters (, schedule, replay size, target period) are sensitive and interact.
25. Failure scenarios
- Divergence with a neural : the target moves as changes and bootstrapping amplifies errors. Fix with target network, replay, gradient clipping, smaller lr.
- Overestimation / catastrophic overoptimism: noisy max picks lucky high estimates; use Double Q-learning / Double DQN or clipped double Q (TD3).
- No exploration: with and initialized uniformly, the agent never tries alternatives; use optimistic initialization or .
- Catastrophic forgetting: sequential on-policy batches are correlated; without replay the network overwrites old state values.
- Wrong terminal handling: omitting in the DQN target bootstraps from terminal states, inflating values; conversely treating time-limit truncations as true terminals can bias finite-horizon tasks.
- Reward scale explosion: large rewards make TD errors huge; use reward clipping/normalization (DQN clips to ).
- Persisting stale
target: ifCis too large, learning stalls; ifC=1, instability returns. Monitor the gap .
26. Common misconceptions
- "Q-learning is on-policy because it uses the action it took." The update targets , not the behaviour's next action; it is off-policy. SARSA uses the sampled next action.
- "Q-learning converges with a constant learning rate to ." It converges to a noise ball; Robbins–Monro decay is needed for exact convergence.
- "The TD error is the same as the Monte Carlo error." MC uses the full return ; TD replaces it with , trading bias for variance.
- "More exploration always improves final performance." Persistent high prevents exploiting the learned policy; evaluation must use the greedy policy.
- "The max in the target is harmless." It creates systematic overestimation under value noise (Jensen's inequality).
- "Replay makes data i.i.d., so any optimizer works." Replay reduces correlation but the targets are still non-stationary because changes.
- "DQN can trivially handle continuous actions." Taking over a continuum requires a separate actor or explicit optimization.
27. Alternative approaches
- SARSA (on-policy TD): target with ; safer policies, no replay required.
- Expected SARSA: target ; removes sampling noise from the next action.
- Double Q-learning / Double DQN: decouple action selection from evaluation to debias the max.
- Dueling / Prioritized / Rainbow DQN: architectural and sampling improvements.
- Monte Carlo control: unbiased full returns, no bootstrapping, only for episodic tasks.
- Actor–critic / PPO: directly optimize a parameterized policy; handles stochastic and continuous actions.
- Model-based RL (Dyna-Q): learn and interleave model-based backups with real updates for sample efficiency.
29. Research applications
- Game AI: Atari, board games, and fighting-game agents via DQN variants; combination with MCTS for discrete planning.
- Robotics: value-based control with discretized actions; sample-efficient hybrids with model-based rollouts.
- Recommender systems / ads: off-policy evaluation and reward modeling from logged behaviour policies.
- Healthcare: off-policy treatment recommendation from observational data, where safety demands conservative value estimates.
- Language-model alignment: preference-based reward models trained with TD-style regression; RLHF pipelines inspired by value-based bootstrapping.
- Theory: sample-complexity lower bounds, safe exploration, and value-function approximation error propagation.
30. Important research papers
- Watkins C. J. C. H. (1989), Learning from Delayed Rewards, PhD thesis, University of Cambridge — original Q-learning.
- Watkins C. J. C. H., Dayan P. (1992), Q-learning, Machine Learning 8:279–292 — convergence proof.
- Sutton R. S. (1988), Learning to Predict by the Methods of Temporal Differences, Machine Learning 3:9–44.
- Van Hasselt H. (2010), Double Q-learning, NIPS — overestimation bias and its correction.
- Mnih V. et al. (2013), Playing Atari with Deep Reinforcement Learning, arXiv:1312.5602.
- Mnih V. et al. (2015), Human-level control through deep reinforcement learning, Nature 518:529–533.
- Schaul T. et al. (2015), Prioritized Experience Replay, ICLR.
- Hessel M. et al. (2018), Rainbow: Combining Improvements in Deep Reinforcement Learning, AAAI.
31. Further reading
- Sutton & Barto (2018), chapters 5–6 (TD prediction/control) and 9–10 (function approximation, DQN).
- Watkins & Dayan (1992) for the full convergence proof; Szepesvári (2010), chapter 5, for a modern treatment.
- Mnih et al. (2015) Nature paper plus the arXiv appendix for preprocessing and training details.
- OpenAI Spinning Up "Q-Learning" and "DQN" algorithm pages.
- DeepMind's "Rainbow" paper for an ablation study of DQN components.
- David Silver's UCL RL lecture videos, lectures 4–5 (model-free prediction and control).
32. Practical exercises
- Implement tabular Q-learning from memory; verify convergence to in the two-state MDP.
- Implement SARSA on the same MDP with -greedy behaviour and compare the learned values to .
- Derive Expected SARSA's target and show it equals Q-learning's when is greedy.
- Implement the cliff-walking task and reproduce the SARSA vs. Q-learning return curves with error bars over 10 seeds.
- Modify the DQN code to Double DQN (select with
q, evaluate withtarget) and compare Overestimation: measure on held-out states vs. true values. - Sweep the target update period and plot stability vs. convergence speed.
33. Debugging challenges
- Q values explode to 1e10: check reward scale, missing
(1-d)multiplier, and learning rate; add gradient clipping. - Q values never move for some states: those are never explored; raise or use optimistic initialization.
- Tabular Q-learning oscillates forever: constant with noisy transitions; decay .
- DQN loss is NaN: likely catastrophic bootstrap divergence; freeze target longer, clip rewards, reduce lr, check terminal flags.
- The learned greedy policy is worse than the behaviour policy: you may be evaluating with exploration still on; evaluate greedily.
gatherproduces shape(b,1)whileyis(b,): broadcasting to(b,b)wastes memory and corrupts loss; squeeze correctly.- Replay buffer returns tuples in wrong order: assert the field order
s,a,r,s2,donewhen unpacking.
34. Advanced exercises
- Prove the Watkins–Dayan convergence theorem in detail using the Robbins–Siegmund lemma; identify exactly where infinite visitation is used.
- Derive the Expected SARSA update and show its variance is no larger than SARSA's under the same policy.
- Implement Double Q-learning with two tables and verify empirically that it removes the max bias on a randomly generated MDP.
- Implement n-step Q-learning and show the target interpolates between one-step TD and Monte Carlo returns.
- Implement a prioritized replay buffer with proportional priorities and importance-sampling weights; verify the bias correction mathematically.
- Analyze the deadly triad: construct a small MDP where off-policy linear function approximation with bootstrapping diverges, and reproduce it.
35. Interview questions
- Write the Q-learning update and explain why it is off-policy.
- Prove that the expected TD target equals regardless of the behaviour policy.
- State the Robbins–Monro conditions and explain why a constant learning rate does not give exact convergence.
- Contrast Q-learning and SARSA on cliff walking; why do they find different policies?
- Why does the max operator cause overestimation? Give the Jensen inequality argument and a fix.
- What do experience replay and target networks each stabilize in DQN?
- How should terminal states and time-limit truncations be treated in the DQN target?
- When would you prefer an actor–critic method over Q-learning?
36. Research questions
- Can we prove convergence for off-policy value-based learning with general nonlinear function approximation under realistic exploration assumptions?
- How should exploration be designed in sparse-reward, continuous-state tasks where -greedy fails?
- What is the exact bias–variance tradeoff of Double/Clipped Double Q-learning under heavy-tailed rewards?
- Can replay prioritization be made theoretically sound with non-stationary targets and importance weights?
- How do value-based methods interact with reward models learned from human preferences, where labels are itself noisy and non-stationary?
37. Mastery assessment
To pass: (1) write and derive the Q-learning update from the Bellman optimality equation without notes; (2) prove the TD target's unbiasedness and outline the convergence proof with its conditions; (3) explain off-policy vs. on-policy via cliff walking; (4) reproduce the two-state numerical example; (5) implement both tabular Q-learning and a minimal DQN that passes shape/convergence checks; (6) diagnose the deadly triad and max bias; (7) answer the interview questions. Complete the linked assessment; reading alone is not mastery.
38. Implementation submission
Push a repository containing q_learning.py (tabular Q-learning and SARSA), dqn.py (network, replay buffer, target network, Double DQN option), experiments.ipynb (two-state convergence, cliff-walking curves, CartPole learning curves with 3 seeds, target-period ablation), a README.md with derivations and observed rates, and tests asserting and correct batch shapes. Submit the repository URL and exact reproduction command.
39. Completion criteria
All of: every section read; update derived on paper; tabular and deep implementations passing tests; at least three experiments with plots and recorded numbers; assessment score ; one failure mode (overestimation or bootstrap divergence) reproduced and explained; one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`