With actions such as “left, right, stop,” a network can output 3 Q-values and choose the largest. It resembles regression, except the labels are not fixed ground truth: the target contains the network's own estimates.

For a concrete case where regression loss improves while values drift, start with the two-state fitted Q counterexample. This chapter explains how DQN mitigates related problems.

Turn a transition into a loss

In one lineLabels come from a slower target net and pass no gradient. Replay breaks up correlation and reuses data. Both help; neither guarantees convergence.

A replay buffer stores $(s,a,r,s',d)$. The online network $Q_\theta$ predicts the current action's value; a more slowly updated target network $Q_{\bar\theta}$ constructs its label:

$$ y=r+\gamma(1-d)\max_{a'}Q_{\bar\theta}(s',a'),\qquad L(\theta)=\mathbb E[(Q_\theta(s,a)-\mathrm{stopgrad}(y))^2]. $$

Here $d$ means true termination, not every reset. Replay reduces strong sequential correlations and reuses past transitions. A target network slows target drift. These mitigate problems; they do not guarantee convergence with neural approximation.

This is a semi-gradient update: differentiate the current Q, not the target. It is not a full gradient through every occurrence in a Bellman residual.

Double DQN separates selection from evaluation

In one lineA max favors actions whose noise is high. Double DQN picks with the online net and scores with the target net; a smaller target does not prove accuracy.

A maximum tends to select actions whose noisy estimates are too high. Double DQN selects with the online network and evaluates with the target network:

$$ a^*=\arg\max_a Q_\theta(s',a),\qquad y_{\rm DDQN}=r+\gamma(1-d)Q_{\bar\theta}(s',a^*). $$

Let online Q be $[5,4]$, target Q be $[2,6]$, and $r=1,\gamma=0.9$. DQN uses the target maximum of 6, giving 6.4. Double DQN selects the first action using online Q, then uses its target value of 2, giving 2.8.

Static comparison: DQN target=6.4; Double DQN target=2.8. The interactive changes the online ranking.

We do not know the true $Q^*$ here, so a smaller target is not evidence of greater accuracy. This example illustrates decoupling only. The networks remain correlated and can also underestimate.

Inspect shapes and gradients in code

In one lineTerminal targets equal the reward, so NaN never enters. Rewards must be a flat [batch], or they broadcast against Q into a wrong [batch, batch] table.

The code uses the same Double DQN target but replaces squared error with Smooth L1—equivalent here to Huber loss with threshold 1—to limit the influence of large TD errors on gradients. Action selection and evaluation are unchanged.

import torch

def double_dqn_loss(online, target, states, actions, rewards,
                    next_states, terminated, gamma=0.99):
    if rewards.ndim != 1 or rewards.numel() == 0:
        raise ValueError("rewards must be a nonempty vector")
    if not rewards.is_floating_point():
        raise ValueError("rewards must be floating-point")
    if actions.shape != rewards.shape or terminated.shape != rewards.shape:
        raise ValueError("actions, rewards, and terminated must have shape [batch]")
    if actions.dtype != torch.long or terminated.dtype != torch.bool:
        raise ValueError("actions must be int64 and terminated must be boolean")
    if states.ndim != 2 or states.shape != next_states.shape or states.shape[0] != rewards.numel():
        raise ValueError("states and next_states must have matching [batch, state_dim] shapes")
    if not 0 <= gamma <= 1:
        raise ValueError("gamma must be in [0, 1]")
    prediction = online(states).gather(1, actions[:, None]).squeeze(1)
    with torch.no_grad():
        next_q = torch.zeros_like(rewards)
        continuing = ~terminated
        if gamma > 0 and continuing.any():
            successors = next_states[continuing]
            next_actions = online(successors).argmax(dim=1, keepdim=True)
            next_q[continuing] = target(successors).gather(1, next_actions).squeeze(1)
        expected = rewards + gamma * next_q
    return torch.nn.functional.smooth_l1_loss(prediction, expected)

Here states is [batch, state_dim], actions is int64 [batch], rewards is floating-point [batch], and terminated is boolean [batch]. The example uses a plain MLP with one device and matching floating-point precision. Shape checks reject [batch, 1] rewards rather than silently broadcasting them with [batch] Q values into a [batch, batch] table.

True terminal successors never enter the network: their target is the reward. Computing NaN and then multiplying by zero still produces NaN. External truncation is different and requires the valid final observation before reset. Networks with dropout or BatchNorm need explicit mode handling: no_grad is not eval(), and changing the valid batch affects BatchNorm statistics. This small implementation does not manage those training states for you.

Similar names, different changes

In one lineDouble DQN changes next-action selection, Dueling how Q is built, Prioritized replay the sampling, which then needs importance weights.

Change What it changes What it does not change
Double DQN Decouples next-action selection and evaluation Still Q-learning
Dueling network Combines value and action advantage into Q Not two target networks
Prioritized replay Samples some transitions more frequently Not the target formula; the shifted sampling distribution needs importance-weight correction

Exploration often uses $\epsilon$-greedy. Random training actions collect information; document whether evaluation disables them. Otherwise low scores from exploration and low scores from the policy itself become hard to separate.

Why does max turn zero-mean noise into overestimation?

In one lineTwo actions worth 0 with zero-mean noise still give a max of 0.5 on average: the max keeps the noise that came out high.

Both actions have true value 0, with independent errors of +1 or −1, each equally likely:

Two errors Maximum
−1, −1 −1
−1, +1 +1
+1, −1 +1
+1, +1 +1

Each action’s error has mean zero, but the maximum has expectation 0.5. Selection retains favorable noise. Evaluating the chosen action with independent zero-mean errors returns expectation 0 in this example.

Double DQN networks are not truly independent, so this explains motivation rather than proving unbiasedness. Frequent synchronization can correlate errors; infrequent synchronization can leave targets stale.

Replay and target networks are slow in different ways

In one lineA frozen target net does not freeze every label: in Double DQN a new online ranking changes it. State whether sync counts environment or gradient steps.

Replay stores transitions, not permanent targets. Sample $(s,a,r,s')$, then construct labels using the specified target network. Shuffling reduces consecutive-sample correlation but does not ensure coverage of the new policy’s states.

Freezing the target network does not freeze every label. For the same transition, vanilla DQN's label stays fixed between hard synchronizations, assuming deterministic network outputs. Double DQN still selects actions with the changing online network. With $r=1,\gamma=0.9$, keeping target Q at $[2,6]$ but changing online Q from $[5,4]$ to $[3,4]$ changes its label from 2.8 to 6.4 without synchronizing the target.

Targets may be copied periodically or softly updated as $\bar\theta\leftarrow(1-\tau)\bar\theta+\tau\theta$. Specify whether synchronization counts environment or gradient steps: 1000 steps means different things with ten updates per interaction versus one.

Increase Potential benefit Additional risk
Replay capacity More varied history Staleness and dilution of rare successes
Updates per interaction More reuse of collected data Overfitting replay and amplifying Q errors
Synchronization interval Temporarily steadier targets Stale estimates and slower propagation

Compare environment interactions and gradient updates, not just an hour of training. Otherwise more data and more computation are indistinguishable.

Why off-policy multistep returns need extra care

In one lineAn n-step return's middle actions come from the old policy; a final max cannot undo that. In the example, without correction the target averages 2.35, not 6.4.

One-step Q-learning conditions on the current $(s_t,a_t)$. In the same MDP, the conditional distribution of $r_t,s_{t+1}$ does not change with the behavior-policy version. The target's max chooses the next action, so no probability ratio is needed for the conditioned current action. Concatenating $n$ rewards from replay changes this argument:

$$ y_t^{(n)}=\sum_{k=0}^{n-1}\gamma^k r_{t+k} +\gamma^n\max_aQ_{\bar\theta}(s_{t+n},a). $$

This expression assumes no true termination inside the segment. At a terminal boundary, stop summing and remove the continuation; never cross a reset. For $n>1$, the intermediate $n-1$ actions come from behavior policy $\mu$, not necessarily the greedy policy being evaluated. A max at the end cannot retroactively make the intervening actions greedy. This issue remains even with an accurate Critic.

A two-step counterexample. The initial state has one action: receive 1 and move deterministically to a second state. There, “collect” pays 6 and terminates; “discard” pays 0 and terminates. Set $\gamma=0.9$. Target policy $\pi$ always collects, but the old behavior policy $\mu$ collects only one quarter of the time. Even with exact target Q-values:

Target Values in old replay Conditional expectation
One step, with exact successor Q Always $1+0.9\times6=6.4$ 6.4
Uncorrected two-step return 6.4 with probability 1/4; 1 with probability 3/4 2.35
Importance-corrected two-step return below 22.6 with probability 1/4; 1 with probability 3/4 6.4

For this two-step terminated example, correct only the second action. Set $\rho_1=\pi(a_1\mid s_1)/\mu(a_1\mid s_1)$ and $\tilde y=r_0+\gamma\rho_1r_1$. Collecting gives $\rho_1=4$ and $\tilde y=1+0.9\times4\times6=22.6$; discarding gives $\rho_1=0$ and $\tilde y=1$. The mean returns to $\frac14\times22.6+\frac34\times1=6.4$, but samples fluctuate widely. The initial action is already conditioned on. Longer trajectories need the corresponding products of subsequent action ratios for each reward, with behavior support for target actions.

Multistep learning can reuse data, but it needs a suitable estimator. Munos et al. (2016), §1–3 express such methods through weighted target-policy TD residuals. Retrace uses $c_t=\lambda\min(1,\rho_t)$ to control later traces together with $\delta_t^\pi=r_t+\gamma\sum_a\pi(a\mid s_{t+1})Q(s_{t+1},a)-Q(s_t,a_t)$. This is not arbitrary clipping of raw-return importance weights: simply clipping 4 to 1 in our example restores the biased mean of 2.35. The operator and tabular convergence results do not establish convergence for arbitrary neural DQN.

Before using n-step replay, specify consecutive-trajectory storage and boundaries, the target policy, whether behavior probabilities are available, and the correction or deliberate approximation being used. Double DQN changes selection and evaluation at the bootstrap endpoint; it does not correct the intermediate behavior distribution.

Check these before tuning

In one lineIf loss falls but return does not, check terminal targets, target gradients, replay action–state alignment and sync step units before a bigger network.

First test that terminal targets equal reward. Then verify that targets have no gradients, replay actions align with their states, and target synchronization uses the intended step units. If loss falls while return does not improve, inspect these semantics before enlarging the network.

References: DQN with experience replay and a target network (Mnih et al., 2015) · Double DQN (arXiv v3, 2015). Next: What if continuous actions make enumeration impossible?