concept / q-learning
Next task →
University/Reinforcement Learning/Value-based methods/Q-Learning and Temporal Difference Control
Reinforcement Learning · Value-based methods · Temporal difference learning

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.

39 sectionsadvanced190 minhand-authored · structural 82/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

Q-learning is an off-policy temporal-difference (TD) control algorithm. It stores estimates Q(s,a)≈Q∗(s,a)Q(s,a)\approx Q^*(s,a) and, after observing a transition (St,At,Rt+1,St+1)(S_t,A_t,R_{t+1},S_{t+1}), performs

Q(St,At)←Q(St,At)+α δt,δt=Rt+1+γmax⁡a′Q(St+1,a′)−Q(St,At).Q(S_t,A_t)\leftarrow Q(S_t,A_t)+\alpha\,\delta_t,\qquad \delta_t=R_{t+1}+\gamma\max_{a'}Q(S_{t+1},a')-Q(S_t,A_t).

Here δt\delta_t is the TD error: a one-step sample of the Bellman optimality residual. The target uses max⁡a′\max_{a'} 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 PP or rr, unlike dynamic programming). Tabular Q-learning converges to Q∗Q^* w.p.1 under mild conditions; with a neural network QθQ_\theta 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 P(s′∣s,a)P(s'|s,a). 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 (O(n3)O(n^3) 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 ε\varepsilon-greedy) from the target policy (greedy w.r.t. QQ). 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 Q∗Q^* from a stream of transitions (St,At,Rt+1,St+1)(S_t,A_t,R_{t+1},S_{t+1}) generated by an unknown MDP while using a behaviour policy that explores. Specifically:

  1. No model: PP and rr are unavailable, so the Bellman optimality backup must be estimated from one sample.
  2. Credit assignment: rewards are delayed; bootstrapping propagates value backward one step at a time.
  3. Exploration vs. exploitation: with a greedy behaviour policy the agent never discovers better actions; with pure random behaviour it never exploits what it learned.
  4. Off-policy correctness: data generated by ε\varepsilon-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,

E[Rt+1+γmax⁡a′Q(St+1,a′)∣St=s,At=a]=r(s,a)+γ∑s′P(s′∣s,a)max⁡a′Q(s′,a′)=(TQ)(s,a).\mathbb{E}\bigl[R_{t+1}+\gamma\max_{a'}Q(S_{t+1},a')\mid S_t=s,A_t=a\bigr] =r(s,a)+\gamma\sum_{s'}P(s'|s,a)\max_{a'}Q(s',a')=(TQ)(s,a).

The behaviour policy's action probabilities cancel because we condition on (s,a)(s,a): 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 Q←Q+α(noisy target−Q)Q\leftarrow Q+\alpha(\text{noisy target}-Q) is a Robbins–Monro root-finding scheme for the equation Q=TQQ=TQ. If the target is unbiased for TQTQ and TT is a γ\gamma-contraction, the iterate tracks the unique fixed point Q∗Q^*.

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 QQ is noisy, since E[max⁡aXa]≥max⁡aE[Xa]\mathbb{E}[\max_a X_a]\ge\max_a\mathbb{E}[X_a] for any non-degenerate noise.

Fact 4 — exploration supplies coverage. Every (s,a)(s,a) must be sampled infinitely often for convergence; ε\varepsilon-greedy with ε>0\varepsilon>0 (or a decaying schedule with ∑tεt=∞\sum_t\varepsilon_t=\infty) 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 (TQ)(s,a)(TQ)(s,a); (b) conditional expectation, so you can see why the behaviour policy cancels when conditioning on (s,a)(s,a); (c) Robbins–Monro stochastic approximation, which explains the ∑tαt=∞\sum_t\alpha_t=\infty, ∑tαt2<∞\sum_t\alpha_t^2<\infty conditions; (d) ε\varepsilon-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.

Qt+1(s,a)=Qt(s,a)+αt(s,a)[Rt+1+γmax⁡a∈AQt(St+1,a)−Qt(s,a)],Q_{t+1}(s,a)=Q_t(s,a)+\alpha_t(s,a)\Bigl[R_{t+1}+\gamma\max_{a\in\mathcal{A}}Q_t(S_{t+1},a)-Q_t(s,a)\Bigr],

with all other entries unchanged.

Target and behaviour policies. Behaviour b(a∣s)b(a|s) generates actions (e.g. ε\varepsilon-greedy: b(a∣s)=ε/m+(1−ε)1[a=arg⁡max⁡Q(s,⋅)]b(a|s)=\varepsilon/m+(1-\varepsilon)\mathbf{1}[a=\arg\max Q(s,\cdot)]); target policy π(s)∈arg⁡max⁡aQ(s,a)\pi(s)\in\arg\max_a Q(s,a) is what we learn about.

Convergence conditions (Watkins & Dayan, 1992). Finite MDP, γ<1\gamma<1, every state-action pair visited infinitely often, rewards bounded, and learning rates satisfying

∑tαt(s,a)=∞,∑tαt(s,a)2<∞w.p.1.\sum_t\alpha_t(s,a)=\infty,\qquad \sum_t\alpha_t(s,a)^2<\infty\quad\text{w.p.1}.

Then Qt→Q∗Q_t\to Q^* w.p.1. Constant α\alpha converges to a noise ball around Q∗Q^*.

Deep Q-networks. With parameters θ\theta and a replay buffer D\mathcal{D},

L(θ)=E(s,a,r,s′,d)∼D[(r+γ(1−d)max⁡a′Q(s′,a′;θ−)−Q(s,a;θ))2],L(\theta)=\mathbb{E}_{(s,a,r,s',d)\sim\mathcal{D}}\Bigl[\bigl(r+\gamma(1-d)\max_{a'}Q(s',a';\theta^-)-Q(s,a;\theta)\bigr)^2\Bigr],

where θ−\theta^- is a slowly updated target network. Gradient: ∇θL=E[−2δ∇θQ(s,a;θ)]\nabla_\theta L=\mathbb{E}[-2\delta\nabla_\theta Q(s,a;\theta)]; the target is treated as a constant (no gradient through θ−\theta^-).

8. Notation dictionary

| Symbol | Meaning | Type / shape | |---|---|---| | Q(s,a)Q(s,a) | estimate of optimal action value | table R∣S∣×∣A∣\mathbb{R}^{|S|\times|A|} or network output | | Q∗Q^* | true optimal action value | R∣S∣×∣A∣\mathbb{R}^{|S|\times|A|} | | Rt+1R_{t+1} | sampled reward | scalar | | St+1S_{t+1} | sampled successor state | state | | δt\delta_t | TD error | scalar | | αt\alpha_t | learning rate | scalar in (0,1](0,1] | | γ\gamma | discount factor | scalar in [0,1)[0,1) | | max⁡a′Q(St+1,a′)\max_{a'}Q(S_{t+1},a') | bootstrapped target value | scalar | | b(a∣s)b(a|s) | behaviour policy | distribution over actions | | ε\varepsilon | exploration probability | scalar | | TT | Bellman optimality operator | R∣S∣∣A∣→R∣S∣∣A∣\mathbb{R}^{|S||A|}\to\mathbb{R}^{|S||A|} | | θ,θ−\theta,\theta^- | online and target network parameters | vectors in Rd\mathbb{R}^d | | D\mathcal{D} | replay buffer | store of transitions | | d∈{0,1}d\in\{0,1\} | terminal flag | scalar | | CC | 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

Q∗(s,a)=Es′∼P(⋅∣s,a)[r(s,a)+γmax⁡a′Q∗(s′,a′)].Q^*(s,a)=\mathbb{E}_{s'\sim P(\cdot|s,a)}\bigl[r(s,a)+\gamma\max_{a'}Q^*(s',a')\bigr].

Sampling one successor s′s' gives a noisy target y=r(s,a)+γmax⁡a′Qt(s′,a′)y=r(s,a)+\gamma\max_{a'}Q_t(s',a').

Step 2 — stochastic approximation. Move the current estimate a fraction αt\alpha_t toward the target:

Qt+1(s,a)=Qt(s,a)+αt(y−Qt(s,a)).Q_{t+1}(s,a)=Q_t(s,a)+\alpha_t(y-Q_t(s,a)).

This is a Robbins–Monro iteration for the root of Q−(TQ)=0Q-(TQ)=0.

Step 3 — verify unbiasedness. Conditioning on (s,a)(s,a), E[y]=r(s,a)+γEs′[max⁡a′Qt(s′,a′)]=(TQt)(s,a)\mathbb{E}[y]=r(s,a)+\gamma\mathbb{E}_{s'}[\max_{a'}Q_t(s',a')]=(TQ_t)(s,a). Note the expectation is over the MDP transition, not over the behaviour policy's choice of At+1A_{t+1}; this is the mathematical source of off-policy learning.

Step 4 — convergence intuition. Write Qt+1−Q∗=(1−αt)(Qt−Q∗)+αt(TQt−TQ∗)+αtηtQ_{t+1}-Q^*=(1-\alpha_t)(Q_t-Q^*)+\alpha_t(TQ_t-TQ^*)+\alpha_t\eta_t with martingale noise ηt\eta_t. Taking norms and using ∥TQt−TQ∗∥≤γ∥Qt−Q∗∥\lVert TQ_t-TQ^*\rVert\le\gamma\lVert Q_t-Q^*\rVert gives a recursion whose deterministic part is a contraction; Robbins–Monro conditions on αt\alpha_t kill the noise.

Step 5 — policy extraction. The greedy policy π(s)=arg⁡max⁡aQ(s,a)\pi(s)=\arg\max_a Q(s,a) is optimal once Q=Q∗Q=Q^*. If ∥Q−Q∗∥∞≤ε\lVert Q-Q^*\rVert_\infty\le\varepsilon, then π\pi is 2ε/(1−γ)2\varepsilon/(1-\gamma)-optimal, since action-value gaps are distorted by at most 2ε2\varepsilon and errors compound by 1/(1−γ)1/(1-\gamma).

Step 6 — deep version. Replace the table by QθQ_\theta, sample mini-batches from replay, and use a frozen θ−\theta^- 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). E[Rt+1+γmax⁡aQ(St+1,a)∣St=s,At=a]=(TQ)(s,a)\mathbb{E}[R_{t+1}+\gamma\max_a Q(S_{t+1},a)\mid S_t=s,A_t=a]=(TQ)(s,a) for any behaviour policy with b(a∣s)>0b(a|s)>0 where needed. Proof. Given (s,a)(s,a), the pair (St+1,Rt+1)(S_{t+1},R_{t+1}) is distributed according to the MDP kernel P(⋅∣s,a)P(\cdot|s,a), independent of the action chosen at time t+1t+1. The max is over all actions, so no bb appears. □\square

Theorem (tabular convergence, Watkins & Dayan 1992). Under the conditions in section 7, Qt→Q∗Q_t\to Q^* w.p.1. Proof sketch. Decompose the error as in Step 4. Let Δt=∥Qt−Q∗∥∞\Delta_t=\lVert Q_t-Q^*\rVert_\infty. Since (1−αt)+αtγ<1(1-\alpha_t)+\alpha_t\gamma<1 for αt>0\alpha_t>0, the deterministic part is a strict contraction; the noise term αtηt\alpha_t\eta_t has bounded variance and ∑αt2<∞\sum\alpha_t^2<\infty, so it sums to a finite martingale limit (Robbins–Siegmund theorem). Infinite visitation ensures every coordinate is updated often enough, giving Δt→0\Delta_t\to0. □\square

Lemma (max overestimation). If Q^(s,a)=Q∗(s,a)+ϵa\hat Q(s,a)=Q^*(s,a)+\epsilon_a with i.i.d. zero-mean noise, then E[max⁡aQ^(s,a)]≥max⁡aQ∗(s,a)\mathbb{E}[\max_a\hat Q(s,a)]\ge\max_aQ^*(s,a), with strict inequality unless all ϵa\epsilon_a are identical constants. Proof. max⁡aQ∗(s,a)=max⁡aE[Q^(s,a)]≤E[max⁡aQ^(s,a)]\max_a Q^*(s,a)=\max_a\mathbb{E}[\hat Q(s,a)]\le\mathbb{E}[\max_a\hat Q(s,a)] by Jensen's inequality applied to the convex function max⁡\max. □\square 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 QQ is a point in R∣S∣∣A∣\mathbb{R}^{|S||A|}. Each update moves one coordinate toward the surface defined by (TQ)(s,a)(TQ)(s,a). The Bellman optimality operator TT is a γ\gamma-contraction in sup norm, so repeated exact backups spiral into the unique point Q∗Q^*; 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 QbQ^b (the value of the behaviour policy), while Q-learning's is Q∗Q^*. Geometrically, SARSA moves toward the value of the policy actually executed; Q-learning moves toward the upper envelope max⁡aQ(s′,a)\max_a Q(s',a), 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 QθQ_\theta, the table becomes a dd-dimensional manifold in R∣S∣∣A∣\mathbb{R}^{|S||A|}; 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 = Q(s,a)Q(s,a). 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 max⁡aQ(s,a)\max_a Q(s,a) versus training steps for the two-state example, with dashed lines at the true Q∗(A,walk)=8/3Q^*(A,\text{walk})=8/3 and Q∗(B,walk)=10/3Q^*(B,\text{walk})=10/3; the estimates climb monotonically on average with noise from exploration.

Cliff-walking comparison (Sutton & Barto, Example 6.6): draw a 4×124\times12 grid with a cliff along the bottom row. Plot episode returns for SARSA and Q-learning: SARSA converges near −50-50 per episode by taking a safe upper route, Q-learning converges near −13-13 along the cliff edge while ε\varepsilon-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: γ=0.5\gamma=0.5; from AA, "walk" gives reward 1 and goes to BB, "stay" gives 0 and remains in AA; from BB, "walk" gives 2 and goes to AA, "stay" gives 0 and remains in BB. True Q∗(A,walk)=8/3≈2.667Q^*(A,\text{walk})=8/3\approx2.667, Q∗(A,stay)=4/3Q^*(A,\text{stay})=4/3, Q∗(B,walk)=10/3≈3.333Q^*(B,\text{walk})=10/3\approx3.333, Q∗(B,stay)=5/3Q^*(B,\text{stay})=5/3.

Initialize Q=0Q=0, α=0.1\alpha=0.1, and alternate the transitions A→walkBA\xrightarrow{\text{walk}} B (reward 1) and B→walkAB\xrightarrow{\text{walk}} A (reward 2):

  • t=1t=1: δ=1+0.5⋅max⁡(0,0)−0=1\delta=1+0.5\cdot\max(0,0)-0=1, so Q(A,walk)=0.1Q(A,\text{walk})=0.1.
  • t=2t=2: δ=2+0.5⋅max⁡(0.1,0)−0=2.05\delta=2+0.5\cdot\max(0.1,0)-0=2.05, so Q(B,walk)=0.205Q(B,\text{walk})=0.205.
  • t=3t=3: δ=1+0.5(0.205)=1.1025\delta=1+0.5(0.205)=1.1025, so Q(A,walk)=0.1+0.1(1.1025)=0.20025Q(A,\text{walk})=0.1+0.1(1.1025)=0.20025.
  • t=4t=4: δ=2+0.5(0.20025)=2.100125\delta=2+0.5(0.20025)=2.100125, so Q(B,walk)=0.205+0.1(2.100125)=0.4150125Q(B,\text{walk})=0.205+0.1(2.100125)=0.4150125 if the updated AA value were used; reading the table before the update (as in the code below) gives 0.205+0.1(2+0.5⋅0.1)=0.3945120.205+0.1(2+0.5\cdot0.1)=0.394512.

Continuing with the code's update order, Q(A,walk)Q(A,\text{walk}) takes values 0.1, 0.20025, 0.299951, 0.398459,…0.1,\ 0.20025,\ 0.299951,\ 0.398459,\dots and Q(B,walk)Q(B,\text{walk}) takes 0.205, 0.394512, 0.570059, 0.732976,…0.205,\ 0.394512,\ 0.570059,\ 0.732976,\dots, approaching 8/38/3 and 10/310/3 geometrically (the contraction factor γ=0.5\gamma=0.5 is modulated by (1−α)(1-\alpha)). Note that Q(A,stay)Q(A,\text{stay}) and Q(B,stay)Q(B,\text{stay}) stay near zero: their targets are 0.5max⁡aQ(⋅,a)0.5\max_aQ(\cdot,a) 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 ε\varepsilon-greedy expected value would turn this into SARSA / Expected SARSA. The assertion checks convergence to the known Q∗Q^*.

DQN walkthrough. QNet maps a 4-dimensional observation to 2 action values; with hidden layers 128/128 it has (4+1)128+(128+1)128+(128+1)2=17,410(4+1)128+(128+1)128+(128+1)2=17{,}410 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 L(θ)L(\theta). The target network is refreshed every C=500C=500 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: Q∈R∣S∣×∣A∣Q\in\mathbb{R}^{|S|\times|A|} needs 4mn4mn bytes in fp32; for 10001000 states and 44 actions that is only 16 KB. No model or gradient buffers are required.

Deep case with a 4→128→128→2 MLP: 17,41017{,}410 parameters = 69.6 KB fp32; add the same for target (69.6 KB) and Adam moments (2×69.62\times69.6 KB) — under 0.3 MB total.

Replay buffer with capacity BB: each transition stores (s,a,r,s′,d)(s,a,r,s',d). For CartPole, ss has 4 fp32 values: 4+1+1+4+1=114+1+1+4+1=11 floats = 44 bytes per transition, so B=106B=10^6 is 44 MB. For Atari with a (4,84,84)(4,84,84) uint8 frame stack, one transition contains two frames = 56,448 bytes; B=106B=10^6 would need 56 GB, which is why DQN implementations store compressed frames or indices into a frame ring buffer.

Training batch b=64b=64: sb, s2b are (64,4)(64,4) fp32 (1 KB each); q(sb) is (64,2)(64,2); activations for the MLP are 64×12864\times128 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: O(∣A∣)O(|\mathcal{A}|) to evaluate max⁡a′Q(s′,a′)\max_{a'}Q(s',a') (or O(1)O(1) with an incrementally maintained max), plus O(1)O(1) for the write. TT updates cost O(T∣A∣)O(T|\mathcal{A}|). With a linear address and constant average branching, this is independent of ∣S∣|\mathcal{S}| — the algorithm's main appeal.

Sample complexity: tabular Q-learning needs enough visits to every (s,a)(s,a); high-probability PAC bounds scale roughly like O(∣S∣∣A∣/(ε2(1−γ)4))O\bigl(|\mathcal{S}||\mathcal{A}|/(\varepsilon^2(1-\gamma)^4)\bigr) up to logarithmic factors, and worse when mixing is slow. Constant α\alpha gives O(1/α)O(1/\alpha) convergence to a noise ball rather than exact convergence.

Deep Q-learning: each gradient step costs O(b⋅cost(Qθ))O(b\cdot\mathrm{cost}(Q_\theta)) forward and backward; the target-network max adds O(b⋅∣A∣⋅cost)O(b\cdot|\mathcal{A}|\cdot\mathrm{cost}) 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: O(∣S∣∣A∣)O(|\mathcal{S}||\mathcal{A}|) for QQ plus O(1)O(1) working memory per update; no model needed. This is the minimal memory for a value-based controller without generalization.

Deep: O(d)O(d) for online network, O(d)O(d) for target, O(2d)O(2d) for Adam moments, O(B⋅transition size)O(B\cdot\text{transition size}) for replay, and O(b⋅activation size)O(b\cdot\text{activation size}) for backpropagation. For the CartPole network above: ≈0.3\approx0.3 MB of parameters/optimizer state plus 44 MB of replay at B=106B=10^6. Checkpointing can trade activation memory for recomputation in very deep Q networks.

22. Experimental demonstration

  1. Run the scratch Q-learning loop and record max⁡s,a∣Q−Q∗∣\max_{s,a}|Q-Q^*| every 1000 updates: expect geometric decay toward the α=0.1\alpha=0.1 noise floor (about 0.02–0.05). Re-run with α∈{0.01,0.1,0.5}\alpha\in\{0.01,0.1,0.5\}; large α\alpha is faster but noisier.
  2. 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 −13-13; SARSA's avoids the edge near −50-50; with ε=0.1\varepsilon=0.1, Q-learning shows occasional large negative returns from exploratory falls. This directly demonstrates off-policy vs. on-policy targets.
  3. Run the DQN CartPole code and log episode lengths: expect a rise from ∼20\sim20 steps to 150–200+ steps within a few thousand steps, with variance due to exploration decay.
  4. 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×104^4 environment steps (run-dependent). Tabular Q-learning on FrozenLake-4×4 with γ=0.99\gamma=0.99 and ε\varepsilon-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 ε\varepsilon-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 (α\alpha, ε\varepsilon schedule, replay size, target period) are sensitive and interact.

25. Failure scenarios

  1. Divergence with a neural QQ: the target moves as θ\theta changes and bootstrapping amplifies errors. Fix with target network, replay, gradient clipping, smaller lr.
  2. Overestimation / catastrophic overoptimism: noisy max picks lucky high estimates; use Double Q-learning / Double DQN or clipped double Q (TD3).
  3. No exploration: with ε=0\varepsilon=0 and QQ initialized uniformly, the agent never tries alternatives; use optimistic initialization or ε>0\varepsilon>0.
  4. Catastrophic forgetting: sequential on-policy batches are correlated; without replay the network overwrites old state values.
  5. Wrong terminal handling: omitting (1−d)(1-d) in the DQN target bootstraps from terminal states, inflating values; conversely treating time-limit truncations as true terminals can bias finite-horizon tasks.
  6. Reward scale explosion: large rewards make TD errors huge; use reward clipping/normalization (DQN clips to [−1,1][-1,1]).
  7. Persisting stale target: if C is too large, learning stalls; if C=1, instability returns. Monitor the gap ∥θ−θ−∥\lVert\theta-\theta^-\rVert.

26. Common misconceptions

  • "Q-learning is on-policy because it uses the action it took." The update targets max⁡a′\max_{a'}, 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 Q∗Q^*." 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 GtG_t; TD replaces it with r+γV(s′)r+\gamma V(s'), trading bias for variance.
  • "More exploration always improves final performance." Persistent high ε\varepsilon 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 θ\theta changes.
  • "DQN can trivially handle continuous actions." Taking max⁡\max over a continuum requires a separate actor or explicit optimization.

27. Alternative approaches

  • SARSA (on-policy TD): target r+γQ(s′,a′)r+\gamma Q(s',a') with a′∼ba'\sim b; safer policies, no replay required.
  • Expected SARSA: target r+γ∑a′π(a′∣s′)Q(s′,a′)r+\gamma\sum_{a'}\pi(a'|s')Q(s',a'); 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 P,rP,r 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

  1. Implement tabular Q-learning from memory; verify convergence to Q∗=[[8/3,4/3],[10/3,5/3]]Q^*=[[8/3,4/3],[10/3,5/3]] in the two-state MDP.
  2. Implement SARSA on the same MDP with ε\varepsilon-greedy behaviour and compare the learned values to QbQ^b.
  3. Derive Expected SARSA's target and show it equals Q-learning's when π\pi is greedy.
  4. Implement the cliff-walking task and reproduce the SARSA vs. Q-learning return curves with error bars over 10 seeds.
  5. Modify the DQN code to Double DQN (select with q, evaluate with target) and compare Overestimation: measure max⁡aQ(s,a)\max_a Q(s,a) on held-out states vs. true values.
  6. Sweep the target update period C∈{1,10,100,1000}C\in\{1,10,100,1000\} 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 (s,a)(s,a) are never explored; raise ε\varepsilon or use optimistic initialization.
  • Tabular Q-learning oscillates forever: constant α\alpha with noisy transitions; decay αt∝1/t\alpha_t\propto1/t.
  • 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.
  • gather produces shape (b,1) while y is (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,done when unpacking.

34. Advanced exercises

  1. Prove the Watkins–Dayan convergence theorem in detail using the Robbins–Siegmund lemma; identify exactly where infinite visitation is used.
  2. Derive the Expected SARSA update and show its variance is no larger than SARSA's under the same policy.
  3. Implement Double Q-learning with two tables and verify empirically that it removes the max bias on a randomly generated MDP.
  4. Implement n-step Q-learning and show the target interpolates between one-step TD and Monte Carlo returns.
  5. Implement a prioritized replay buffer with proportional priorities and importance-sampling weights; verify the bias correction mathematically.
  6. 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 (TQ)(s,a)(TQ)(s,a) 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 ε\varepsilon-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 Q o[[8/3,4/3],[10/3,5/3]]Q\ o[[8/3,4/3],[10/3,5/3]] 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 ≥80%\ge80\%; 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.`

Research papers linked to this concept

watkins1989 · citation recorded, library entry pending
watkins1992 · citation recorded, library entry pending
mnih2013 · citation recorded, library entry pending
mnih2015 · citation recorded, library entry pending
vanhasselt2010 · citation recorded, library entry pending