Deep Q-Networks

Dive into Deep Learning · §15.4

Deep Q-Networks, Replay Buffers, and Double DQN
the deadly triad · Baird’s counterexample · experience replay · target networks · maximization bias · Double DQN

Why Naive Neural Q-Learning Explodes Past 10^8

Motivation

  • Runaway feedback loop: On CartPole (V^\infty = 100 at \gamma = 0.99), regressing Q_w(s, a) directly onto 1 + \gamma \max_{a'} Q_w(s', a') lifts Q_w(s', \cdot) via shared weights, driving predictions past 10^8 while greedy return collapses to \sim 9.
  • The DQN breakthrough (Mnih et al., 2015): Experience replay and a frozen target network Q_{w^-} stabilize off-policy value learning.

Why Semi-Gradient Backups Conflict with Least Squares

Sources of Instability

y = r + \gamma\, \big(1 - \mathbf{1}(s' \textrm{ terminal})\big) \max_{a'} Q_w(s', a')

  • Moving targets: Semi-gradient steps hold y fixed while updating w, so they are not gradient descent on any fixed loss.
  • Norm mismatch: The Bellman backup contracts in the supremum norm \|\cdot\|_\infty, whereas neural regression projects in a visitation-weighted L_2(d) norm that can expand \|\cdot\|_\infty.

The Deadly Triad and Baird’s Counterexample

Fundamental Theory

  • The Deadly Triad (Sutton & Barto, 2018): Instability arises when function approximation, bootstrapping, and off-policy data meet simultaneously.
  • Baird’s 7-State Counterexample (1995): Linear value function v = \Phi \mathbf{w} (8 weights, 7 states), zero rewards everywhere (V^* = \mathbf{0}, exactly representable by \mathbf{w} = \mathbf{0}), and exact expected updates (zero noise).
  • Under uniform off-policy state weighting while evaluating a policy that always jumps to state 7, \|\mathbf{w}\|_\infty diverges exponentially from 10 \to 335.

sup norm of w after 0, 500, 1000 sweeps: 10, 77, 335
the value the weights claim for state 7: 677, true value 0

Where Algorithms Live Inside the Deadly Triad

Algorithmic Taxonomy

  • Any Two Ingredients Can Converge:
    • Bootstrapping + Off-Policy (No Network): Tabular Q-learning converges by \|\cdot\|_\infty contraction.
    • Function Approx + Bootstrapping (On-Policy): Linear TD(0) / Actor-Critic converges under the evaluated policy’s steady-state distribution (Tsitsiklis & Van Roy, 1997).
    • Function Approx + Off-Policy (No Bootstrap): Behavior Cloning is standard supervised learning on fixed targets.
  • Center Intersection: DQN and offline RL combine all three, requiring architectural stabilization.

Two Architectural Devices: Replay and Target Networks

DQN Architecture

  • Device 1 — Experience Replay Buffer: Stores transitions (s, a, r, s', \textrm{term}) in a circular ring and samples uniform minibatches, breaking temporal correlation and reusing each transition dozens of times.
  • Device 2 — Frozen Target Network (Q_{w^-}): Computes the bootstrap \max_{a'} Q_{w^-}(s', a') from a frozen copy of the weights synced only every C = 250 environment steps, holding targets stationary for 125 gradient steps.

Experience Replay: Preallocated Ring Buffer

Replay Mechanics

  • Circular ring buffer (200{,}000 slots): Overwrites oldest transitions at ptr = (ptr + 1) % cap and samples uniform minibatches of 128 uncorrelated 1-step fragments.

Experience Replay: Preallocated Ring Buffer (Code)

Replay Mechanics

class ReplayBuffer:
    """A ring of transitions in preallocated numpy; sample() returns a Batch."""
    def __init__(self, capacity, obs_dim):
        self.obs = np.zeros((capacity, obs_dim), np.float32)
        self.act = np.zeros(capacity, np.int64)
        self.rew = np.zeros(capacity, np.float32)
        self.next_obs = np.zeros((capacity, obs_dim), np.float32)
        self.term = np.zeros(capacity, np.float32)
        self.capacity, self.size, self.ptr = capacity, 0, 0

    def add(self, obs, act, rew, next_obs, term):
        i = self.ptr
        self.obs[i], self.act[i], self.rew[i] = obs, act, rew
        self.next_obs[i], self.term[i] = next_obs, term
        self.ptr, self.size = (i + 1) % self.capacity, min(self.size + 1,
                                                           self.capacity)

    def __len__(self):
        return self.size

    def sample(self, batch_size, rng):
        """batch_size transitions drawn uniformly, each a one-step
        fragment: ep_ends marks every transition as its own episode."""
        i = rng.integers(self.size, size=batch_size)
        return d2l.Batch(self.obs[i], self.act[i], self.rew[i],
                         self.next_obs[i], self.term[i],
                         np.arange(1, batch_size + 1))

Target Network Regression with Clipped Huber Loss

Update Implementation

Between syncs (every C = 250 steps), Q_w solves a stationary Huber regression, gradient norm clipped at 10.0:

def q_values(qnet, obs):
    """The acting forward: numpy in, numpy out, no gradient recorded."""
    with torch.inference_mode():
        return qnet(torch.as_tensor(obs)).numpy()

def fit_q(qnet, opt, batch, y):
    """One clipped Huber regression step of Q_w(s, a) toward the fixed y."""
    pred = qnet(torch.as_tensor(batch.obs)).gather(
        -1, torch.as_tensor(batch.act)[:, None]).squeeze(-1)
    loss = nn.functional.huber_loss(pred, torch.as_tensor(y))
    opt.zero_grad()
    loss.backward()
    nn.utils.clip_grad_norm_(qnet.parameters(), grad_clip)
    opt.step()

def q_step(qnet, target, opt, batch):
    """The DQN update: the critic's own td_target, bootstrapped by the copy."""
    fit_q(qnet, opt, batch, batch.td_target(
        lambda s: q_values(target, s).max(-1), gamma))

The DQN Training Loop on CartPole

Training Loop

After a 1{,}000-step warm-up, train_dqn acts \epsilon-greedily (\epsilon: 1.0 \to 0.05 over 10\text{k} steps), updates every train_freq = 2 steps, and syncs w^- \leftarrow w every sync_every = 250 steps (or every step when use_target=False):

def train_dqn(seed, qnet, use_target=True, step=q_step, copies=1):
    """DQN on CartPole; yields (env step, episode return, max_a Q(s0, a))."""
    rng, env = np.random.default_rng(seed), make_env(copies)
    update, sync = make_learner(qnet, step)
    buffer, s0 = ReplayBuffer(buffer_size, 4), np.zeros(4, np.float32)
    obs, ep_return = env.reset(seed=seed)[0], 0.0

The DQN Training Loop on CartPole (cont.)

Training Loop

Each environment step acts, stores the transition, and then trains and syncs on their schedules:

    for t in range(1, num_env_steps + 1):
        a = d2l.epsilon_greedy(q_values(qnet, obs), epsilon(t), rng)
        next_obs, rew, terminated, truncated, _ = env.step(a)
        buffer.add(obs, a, rew, next_obs, float(terminated))
        obs, ep_return = next_obs, ep_return + rew
        if terminated or truncated:
            yield t, ep_return, q_values(qnet, s0).max()
            obs, ep_return = env.reset()[0], 0.0
        if len(buffer) >= warmup and t % train_freq == 0:
            update(buffer.sample(batch_size, rng))
        if t % (sync_every if use_target else 1) == 0:
            sync()

Always store float(terminated), never terminated or truncated, so that episodes reaching CartPole’s 500-step time limit still bootstrap their continuation value.

Ablation: Behavior Returns With and Without Target Sync

Target Network Ablation

  • With the frozen target network refreshed every 250 steps (DQN), every seed climbs from the random policy’s return (\sim 20) to hundreds of steps (with \epsilon = 0.05 exploration still randomizing 1 in 20 actions).
  • Without a target network (use_target=False, syncing after every step), the policy collapses to \sim 9 steps on every seed and never recovers.

Bounding Value Propagation Across Target Syncs

Why the Target Network Works

  • Without a target network, shared weights lift Q_w(s', \cdot) alongside Q_w(s, a), driving \max_a Q_w(s_0, a) > 10^8.
  • Synchronization Bound: If values start at 0 and fit targets exactly between syncs, after n syncs with r=1 no value can exceed: Q \le \sum_{k=0}^{n-1} \gamma^k = \frac{1 - \gamma^n}{1 - \gamma}
  • Over 50{,}000 steps (n \approx 196 syncs after warm-up), the bound is \approx 86; neural generalization lifts \max_a Q_w(s_0, a) just above this curve toward the true ceiling 100.

continuing-task ceiling: 100; the no-target arm ends at 1e+08, 1e+08, 1e+08

Periodic Greedy Evaluation at Fixed Step Budgets

Policy Evaluation

Training return curves mix exploratory \epsilon-greedy actions with policy improvements. Evaluating the deterministic greedy policy (\operatorname{argmax}_a Q_w(s, a)) for 10 episodes at fixed 5{,}000-step milestones provides an unbiased progress trace:

greedy return (10 episodes) every 5,000 environment steps
              DQN, seed 0: 214 152  57 111 120 136 500 500 500 500
              DQN, seed 1: 232 150 101  93  54 163 101 335 404 103
              DQN, seed 2: 182  92 124 117 117 112 265 500 500 500
no target network, seed 0:   9   9  10   9   9   9   9   9   9  10
no target network, seed 1:  10  10   9   9  10  10   9   9   9  10
no target network, seed 2:   9   9  10  10   9   9   9   9   9   9
  • DQN Progress: Greedy returns sit around 50–250 for the first 30{,}000 steps, then reach the 500-step ceiling on most seeds between 35{,}000 and 45{,}000 steps (though some seeds temporarily drop back).
  • No Target Network: Never exceeds \sim 10 steps at any evaluation checkpoint across the entire 50{,}000-step run.

Auditing Value Estimates Against Realized Returns

Value Calibration

A high greedy return shows that the argmax ranking is good, not that the value predictions are accurate. Following van Hasselt, Guez, & Silver (2016), audit compares \max_a Q_w(s_0, a) against the policy’s actual 500-step discounted return ((1 - 0.99^{500})/0.01 \approx 99.3 ceiling):

              DQN, seed 0: return 500, discounted  99.3, max_a Q(s0)     93.9
              DQN, seed 1: return  93, discounted  61.9, max_a Q(s0)     98.4
              DQN, seed 2: return 500, discounted  99.3, max_a Q(s0)     93.1
no target network, seed 0: return  10, discounted   9.0, max_a Q(s0)  1.4e+08
no target network, seed 1: return   9, discounted   9.1, max_a Q(s0) 1.47e+08
no target network, seed 2: return   9, discounted   8.9, max_a Q(s0) 1.45e+08
  • On solved seeds, Q_w(s_0, a) sits within \sim 8 points of 99.3; on failed seeds (where the policy drops the pole early), the network often overestimates its own discounted return by 20+ points.

Maximization Bias: Why Taking the Max Overestimates

Overestimation Bias

  • By Jensen’s inequality, the maximum of noisy estimates is biased upward: \mathbb{E}[\max_a \hat{Q}(s', a)] \ge \max_a \mathbb{E}[\hat{Q}(s', a)] (Thrun & Schwartz, 1993).
  • For m = 4 actions with true value 0 and independent \mathcal{N}(0, 1) noise, the single estimator \max_a \hat{Q}(a) averages +1.03.
  • The Double Estimator (van Hasselt, 2010): Selecting a^\star = \operatorname{argmax}_a \hat{Q}^{(1)}(a) with one estimate and evaluating \hat{Q}^{(2)}(a^\star) with an independent second estimate has expectation 0.000 for any number of actions m.

Double DQN: Decoupling Selection from Evaluation

Double DQN

y^{\textrm{DDQN}} = r + \gamma\,(1 - \textrm{term})\, Q_{w^-}\Big(s',\ \underset{a'}{\operatorname{argmax}}\, Q_w(s', a')\Big)

  • Decoupled selection & evaluation (van Hasselt et al., 2016): Reuses online network Q_w to select a^\star and target network Q_{w^-} to evaluate it.
def q_step_double(qnet, target, opt, batch):
    """q_step with selection split from evaluation, eq_double_dqn."""
    sel = q_values(qnet, batch.next_obs).argmax(-1)
    fit_q(qnet, opt, batch, batch.td_target(
        lambda s: q_values(target, s)[np.arange(len(s)), sel], gamma))

Exposing Overestimation with 18 Duplicated Actions

18-Action Audit

Offering each of CartPole’s 2 pushes 9 times (copies=9, 18 actions—the size of the Atari action set) leaves Q^* and the ceiling V^\infty = 100 unchanged, but forces \max_{a'} to pick the luckiest of 9 noisy action heads:

             per seed:     greedy return          discounted         max_a Q(s0)
        DQN, 2 actions 500.0  93.4 500.0    99.3  61.9  99.3    93.9  98.4  93.1
 Double DQN, 2 actions 500.0 500.0 500.0    99.3  99.3  99.3    92.7  95.0  91.1
       DQN, 18 actions 181.0 500.0 153.2    83.8  99.3  78.7   117.7 116.2 117.1
Double DQN, 18 actions  94.0 356.2 500.0    61.4  95.8  99.3    95.5 102.0  92.4
  • With 18 actions, standard DQN ends 10 to 30 points above the impossible ceiling of 100 on every seed, whereas Double DQN pulls the estimates down by 10–25 points to stay near 100.

Double DQN Holds 18-Action Estimates Near the Ceiling

Value Trajectory Comparison

  • Tracking \max_a Q_w(s_0, a) across training on the 18-action CartPole task shows standard DQN crossing the theoretical ceiling of 100 before 40{,}000 steps and continuing to climb as maximization bias feeds back through the bootstrap.
  • Double DQN’s decoupled target keeps the value trajectory bounded near the true continuing ceiling of 100.

Concept Check: Triad, Sync Rates, and Token Spaces

Check Your Understanding

Work through these three design questions:

  1. Triad Identification: Which ingredient(s) of the deadly triad are absent in (a) Tabular Q-learning, (b) On-policy REINFORCE with a neural network, and (c) Behavior Cloning?
  2. Slowing the Sync Period: If we increase sync_every from C = 250 to C = 1{,}000 on our 50{,}000-step budget (1{,}000-step warm-up), what is the theoretical upper bound (1 - \gamma^n)/(1 - \gamma) on Q(s_0, a) after n = 49 syncs at \gamma = 0.99?
  3. Q-Learning for LLMs: Why don’t we train a standard DQN over a language model’s vocabulary of m = 10^5 tokens?

Answers:

    1. No function approximation; (b) No bootstrapping and no off-policy data; (c) No bootstrapping.
  1. With n = 49 syncs, (1 - 0.99^{49}) / 0.01 \approx \mathbf{38.9}—a very slow target sync stabilizes regression but starves value propagation.
  2. The expected maximum of m = 10^5 unit-variance noise variables is \approx \sqrt{2 \ln 10^5} \approx \mathbf{4.4\sigma} (and Q_{w^-} remains heavily correlated with Q_w), creating massive maximization bias across 10^5 heads.

Summary: Stabilizing Off-Policy Deep Value Learning

Key Takeaways

Component / Variant Mechanism Failure Mode Prevented Cost / Trade-off
Experience Replay Uniform minibatch sampling from ring buffer Temporal correlation & catastrophic forgetting Requires off-policy target; uses 1-step fragments
Target Network (Q_{w^-}) Frozen copy synced every C = 250 steps Runaway feedback loop (Q(s_0) > 10^8) Propagates reward 1 horizon step per sync
Termination Mask Mask bootstrap on terminated, not truncated Falsely teaching that surviving to step 500 is worth 0 Learns continuing value V^\infty = 1/(1-\gamma) = 100
Double DQN Q_{w^-}(s', \operatorname{argmax}_{a'} Q_w(s', a')) Upward maximization bias across many actions 1 extra online forward pass per update