Sign in

Dueling DQN

Dueling Deep Q-Network

A Q-network split into two streams, one for how good the state is and one for how much each action adds, then recombined into action values.

Overview

In many states it hardly matters which action is taken: the state is simply good or bad. A standard Q-network has to learn that separately for every action. A dueling network separates the two questions. After a shared first stage, one stream outputs a single number, the value of the state. The other outputs one number per action, the advantage, which says how much better or worse that action is than average. The two are added to give the usual action values. Every transition, whatever action it used, now trains the state value, so that part is learned faster. Only the network changes. Training is otherwise the same as DQN. The template is a small NumPy version trained on a 4 by 4 grid.

A short history

Ziyu Wang and colleagues at DeepMind introduced the dueling architecture in a paper that appeared in late 2015 and won a best paper award at ICML 2016. They observed that in many states the choice of action hardly matters, so the network should learn the value of the state separately from the advantage of each action. This was a change to the network only, not to the learning rule, so it combined easily with Double DQN and prioritised replay.

How it works

  1. Pass the observation through the shared trunk to get a feature vector.
  2. Feed the features to the value stream, which outputs one number V(s)V(s).
  3. Feed the same features to the advantage stream, which outputs one number A(s,a)A(s, a) per action.
  4. Subtract the mean advantage from each advantage, then add V(s)V(s) to get Q(s,a)Q(s, a).
  5. Train exactly as in DQN: replay buffer, epsilon-greedy actions, a target network, and a Huber loss on the value of the stored action.
  6. On the backward pass, the gradient at each Q(s,a)Q(s, a) is split between the two streams according to how they were combined.

Watch out for

  • Without subtracting the mean, the split is not unique: a constant could move from one stream to the other with no change in QQ. The streams would then have no stable meaning.
  • With the mean subtracted, the advantage stream's outputs are not true advantages. They are shifted so that they average to zero, not so that the best action has advantage zero.
  • The gain is small when actions differ sharply in every state, since most of the signal is then in the advantages and little is shared.
  • The value stream's output only equals the true state value once training has converged. Early on, reading state_value as a real value estimate is misleading.

Use cases

When to use it

Discrete-action problems where many actions have nearly the same value in most states. It changes only the network, so it combines with Double DQN and prioritised replay.

In industry

Games and simulation
Atari-style agents, especially games where many actions have similar outcomes in most frames.
Autonomous driving research
Discrete manoeuvre selection in a driving simulator, where most moments need no change and the state value carries most of the signal.
Operations
Problems with many similar discrete actions, such as choosing among queues or machines, where learning one state value speeds up training.

Choosing it: what must hold

  • A small, discrete set of actions, as with DQN.
  • Many states in which the actions differ little, which is where the split helps most.
  • An existing DQN-style training loop, since only the network head changes.

When to choose something else

IfUse instead
Actions are continuousDDPG, TD3 or SAC
You want this combined with the other DQN improvementsRainbow
There are only a few statesTabular Q-learning

Math foundations

  1. Value plus advantage

    Qπ(s,a)=Vπ(s)+Aπ(s,a)Q^{\pi}(s, a) = V^{\pi}(s) + A^{\pi}(s, a)

    The value of an action is the value of the state plus how much better or worse that action is than the policy's usual behaviour there. This is the definition of the advantage.

  2. Why a plain sum is ambiguous

    V(s)+A(s,a)=(V(s)+c)+(A(s,a)−c)for any cV(s) + A(s, a) = \bigl( V(s) + c \bigr) + \bigl( A(s, a) - c \bigr) \quad \text{for any } c

    Shifting a constant between the streams leaves QQ unchanged, so the loss cannot tell the two apart. Something must pin the split down.

  3. The dueling aggregation

    Q(s,a)=V(s)+A(s,a)−1∣A∣∑bA(s,b)Q(s, a) = V(s) + A(s, a) - \frac{1}{|\mathcal{A}|} \sum_{b} A(s, b)

    Subtracting the mean advantage removes the ambiguity. The centred advantages sum to zero, so V(s)V(s) is forced to equal the mean of the action values.

  4. What the value stream represents

    1∣A∣∑aQ(s,a)=V(s)\frac{1}{|\mathcal{A}|} \sum_{a} Q(s, a) = V(s)

    This follows directly from the aggregation. It also shows that the greedy action is unchanged, since the ranking of actions depends only on the advantages.

  5. How the gradient is split

    ∂L∂V(s)=∑a∂L∂Q(s,a),∂L∂A(s,a)=∂L∂Q(s,a)−1∣A∣∑b∂L∂Q(s,b)\frac{\partial L}{\partial V(s)} = \sum_{a} \frac{\partial L}{\partial Q(s, a)}, \qquad \frac{\partial L}{\partial A(s, a)} = \frac{\partial L}{\partial Q(s, a)} - \frac{1}{|\mathcal{A}|} \sum_{b} \frac{\partial L}{\partial Q(s, b)}

    The value stream receives the gradient from every action's output. So one transition, which has a gradient at a single action, still updates the shared estimate of the state.

  6. The training target

    y=r+γ (1−d) max⁡a′Qθ−(s′,a′)y = r + \gamma\,(1 - d)\, \max_{a'} Q_{\theta^{-}}(s', a')

    The ordinary DQN target, computed with a target copy of the dueling network. The online network is fitted to it with the Huber loss.

Symbols

s,as, a
state and action
V(s)V(s)
output of the value stream: one number per state
A(s,a)A(s, a)
output of the advantage stream: one number per action
Q(s,a)Q(s, a)
the combined action value
∣A∣|\mathcal{A}|
number of actions
cc
an arbitrary constant
LL
the training loss
r,s′,dr, s', d
reward, next state and done flag of a stored transition
γ\gamma
discount factor
Qθ−Q_{\theta^{-}}
the target copy of the dueling network

Worked by hand

For one state the value stream outputs V=2.0V = 2.0 and the advantage stream outputs (1.0,−1.0,0.0,2.0)(1.0, -1.0, 0.0, 2.0) for the four actions. Combine them.

14(1.0−1.0+0.0+2.0)=0.5\tfrac{1}{4}(1.0 - 1.0 + 0.0 + 2.0) = 0.5
A−0.5=(0.5,  −1.5,  −0.5,  1.5)A - 0.5 = (0.5,\; -1.5,\; -0.5,\; 1.5)
Q=2.0+(0.5,  −1.5,  −0.5,  1.5)=(2.5,  0.5,  1.5,  3.5)Q = 2.0 + (0.5,\; -1.5,\; -0.5,\; 1.5) = (2.5,\; 0.5,\; 1.5,\; 3.5)
14(2.5+0.5+1.5+3.5)=2.0\tfrac{1}{4}(2.5 + 0.5 + 1.5 + 3.5) = 2.0

The action values are (2.5,0.5,1.5,3.5)(2.5, 0.5, 1.5, 3.5) and their mean is 2.02.0, the value stream's output. The fourth action is best, as it was in the raw advantages.

Visual example

Loading the example.

Try this

  • Run the training, then click the boxes from left to right to follow one cell through the two streams.
  • Pick different cells: V changes a lot from cell to cell while the advantages stay small.
  • Switch the aggregation to the plain sum and train again: V no longer equals the mean of the four Q values.

Code sample

from impl import DuelingDQN, GridWorld
from config import DuelingDQNConfig

env = GridWorld(size=4)
agent = DuelingDQN(env.obs_dim, env.n_actions, DuelingDQNConfig(hidden_size=32))
returns = agent.train(env)        # return of every training episode
print(agent.evaluate(env))        # greedy return; 0.5 is the best possible on the 4 x 4 grid
print(agent.state_value(env.reset()))   # V(start) from the value stream
Read the implementation (319 lines)
"""Dueling DQN in NumPy, with a small gridworld to learn on.

The Q-network has a shared trunk and two streams: a state value V(s) and one advantage A(s, a) per
action, joined as Q(s, a) = V(s) + A(s, a) - mean_a A(s, a). The value stream learns from every
transition whatever action was taken, which helps when many actions have similar values. Training is
DQN: replay buffer, target copy, epsilon-greedy exploration. Backpropagation is written by hand.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import DuelingDQNConfig
except ImportError:  # run from the template's own folder
    from config import DuelingDQNConfig


class GridWorld:
    """Square grid: the agent starts in the top-left cell and must reach the bottom-right cell.

    Observation: one-hot vector of the agent's cell, shape (size * size,).
    Actions: 0 up, 1 right, 2 down, 3 left. A move into a wall leaves the agent where it is.
    Reward: +1.0 for the step that reaches the goal, -0.1 for every other step.
    `step` returns (obs, reward, terminated, truncated): terminated at the goal, truncated after
    `max_steps` steps. The best return is `optimal_return`, 0.5 for the default 4 x 4 grid.
    """

    n_actions = 4
    _MOVES = ((-1, 0), (0, 1), (1, 0), (0, -1))

    def __init__(self, size: int = 4, max_steps: int = 30) -> None:
        if size < 2:
            raise ValueError(f"size must be at least 2, got {size!r}")
        self.size = size
        self.max_steps = max_steps
        self.obs_dim = size * size
        self.row = self.col = self.t = 0

    @property
    def optimal_return(self) -> float:
        """Return of a shortest path: 2 * (size - 1) moves, the last one worth +1."""
        return 1.0 - 0.1 * (2 * (self.size - 1) - 1)

    def _obs(self) -> np.ndarray:
        obs = np.zeros(self.obs_dim)
        obs[self.row * self.size + self.col] = 1.0
        return obs

    def reset(self) -> np.ndarray:
        """Put the agent back on the start cell and return the observation, shape (obs_dim,)."""
        self.row = self.col = self.t = 0
        return self._obs()

    def step(self, action: int):
        """Apply one action (0..3). Returns (obs, reward, terminated, truncated)."""
        d_row, d_col = self._MOVES[int(action)]
        self.row = min(max(self.row + d_row, 0), self.size - 1)
        self.col = min(max(self.col + d_col, 0), self.size - 1)
        self.t += 1
        terminated = self.row == self.size - 1 and self.col == self.size - 1
        truncated = not terminated and self.t >= self.max_steps
        return self._obs(), (1.0 if terminated else -0.1), terminated, truncated


class MLP:
    """Fully connected network with tanh hidden layers and a linear output, trained by manual backprop.

    sizes: layer widths, for example (16, 32, 4) is 16 inputs, one hidden layer of 32 units, 4 outputs.
    rng:   NumPy generator used for the initial weights.
    lr:    Adam step size used by `step`.
    """

    def __init__(self, sizes, rng: np.random.Generator, lr: float = 1e-3) -> None:
        self.sizes = tuple(int(s) for s in sizes)
        self.weights = [rng.normal(0.0, np.sqrt(1.0 / m), size=(m, n)) for m, n in zip(self.sizes[:-1], self.sizes[1:])]
        self.biases = [np.zeros(n) for n in self.sizes[1:]]
        self.lr = lr
        self._m = [np.zeros_like(p) for p in self.params()]
        self._v = [np.zeros_like(p) for p in self.params()]
        self._t = 0
        self._acts: list[np.ndarray] = []

    def params(self) -> list[np.ndarray]:
        """All parameter arrays: the weight matrices, then the bias vectors."""
        return self.weights + self.biases

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (batch, n_in) or (n_in,) -> (batch, n_out). Keeps the activations for `backward`."""
        h = np.atleast_2d(np.asarray(x, dtype=float))
        self._acts = [h]
        last = len(self.weights) - 1
        for i, (w, b) in enumerate(zip(self.weights, self.biases)):
            h = h @ w + b
            if i < last:
                h = np.tanh(h)
            self._acts.append(h)
        return h

    def backward(self, grad_out: np.ndarray):
        """Backpropagate through the most recent `forward` call.

        grad_out: d loss / d output, shape (batch, n_out).
        Returns (grads, grad_in): grads in the order of `params()`, grad_in = d loss / d input (batch, n_in).
        """
        g = np.asarray(grad_out, dtype=float)
        n_layers = len(self.weights)
        grad_w: list = [None] * n_layers
        grad_b: list = [None] * n_layers
        for i in reversed(range(n_layers)):
            if i < n_layers - 1:
                g = g * (1.0 - self._acts[i + 1] ** 2)
            grad_w[i] = self._acts[i].T @ g
            grad_b[i] = g.sum(axis=0)
            g = g @ self.weights[i].T
        return grad_w + grad_b, g

    def step(self, grads) -> None:
        """One Adam step that moves the parameters against `grads` (same order as `params()`)."""
        self._t += 1
        for p, g, m, v in zip(self.params(), grads, self._m, self._v):
            m *= 0.9
            m += 0.1 * g
            v *= 0.999
            v += 0.001 * g * g
            p -= self.lr * (m / (1.0 - 0.9**self._t)) / (np.sqrt(v / (1.0 - 0.999**self._t)) + 1e-8)

    def copy_from(self, other: "MLP", tau: float = 1.0) -> None:
        """Polyak update: params <- tau * other + (1 - tau) * params. tau = 1 is a plain copy."""
        for p, q in zip(self.params(), other.params()):
            p *= 1.0 - tau
            p += tau * q


class DuelingNetwork:
    """Q-network with a shared trunk, a value stream and an advantage stream.

    obs_dim -> hidden (tanh) is the trunk; each stream is hidden -> hidden (tanh) -> output, with
    1 output for the value and n_actions outputs for the advantages.
    """

    def __init__(self, obs_dim: int, hidden: int, n_actions: int, rng: np.random.Generator, lr: float = 1e-3) -> None:
        self.trunk = MLP((obs_dim, hidden), rng, lr)
        self.value = MLP((hidden, hidden, 1), rng, lr)
        self.advantage = MLP((hidden, hidden, n_actions), rng, lr)
        self._features = np.zeros((1, hidden))

    def streams(self, x: np.ndarray):
        """x: (batch, obs_dim) -> (V of shape (batch, 1), A of shape (batch, n_actions))."""
        self._features = np.tanh(self.trunk.forward(x))
        return self.value.forward(self._features), self.advantage.forward(self._features)

    def forward(self, x: np.ndarray) -> np.ndarray:
        """Q(s, a) = V(s) + A(s, a) - mean_a A(s, a). x: (batch, obs_dim) -> (batch, n_actions)."""
        value, advantage = self.streams(x)
        return value + advantage - advantage.mean(axis=1, keepdims=True)

    def backward(self, grad_q: np.ndarray):
        """grad_q: d loss / d Q, (batch, n_actions), for the most recent forward call.

        Returns (grads, grad_in) where grads = (trunk grads, value grads, advantage grads).
        """
        grad_value = grad_q.sum(axis=1, keepdims=True)
        grad_adv = grad_q - grad_q.mean(axis=1, keepdims=True)
        value_grads, g_from_value = self.value.backward(grad_value)
        adv_grads, g_from_adv = self.advantage.backward(grad_adv)
        grad_features = (g_from_value + g_from_adv) * (1.0 - self._features**2)
        trunk_grads, grad_in = self.trunk.backward(grad_features)
        return (trunk_grads, value_grads, adv_grads), grad_in

    def step(self, grads) -> None:
        """One Adam step on all three parts; `grads` is the first value returned by `backward`."""
        for part, g in zip((self.trunk, self.value, self.advantage), grads):
            part.step(g)

    def params(self) -> list[np.ndarray]:
        return self.trunk.params() + self.value.params() + self.advantage.params()

    def copy_from(self, other: "DuelingNetwork") -> None:
        for mine, theirs in zip((self.trunk, self.value, self.advantage), (other.trunk, other.value, other.advantage)):
            mine.copy_from(theirs)


class ReplayBuffer:
    """Fixed-size ring buffer of transitions (obs, action, reward, next_obs, done).

    capacity: number of transitions kept; the oldest is overwritten when the buffer is full.
    obs_dim:  length of an observation vector.
    act_dim:  0 for integer (discrete) actions, otherwise the length of a continuous action vector.
    """

    def __init__(self, capacity: int, obs_dim: int, act_dim: int = 0) -> None:
        self.capacity = capacity
        self.obs = np.zeros((capacity, obs_dim))
        self.next_obs = np.zeros((capacity, obs_dim))
        self.actions = np.zeros(capacity, dtype=int) if act_dim == 0 else np.zeros((capacity, act_dim))
        self.rewards = np.zeros(capacity)
        self.dones = np.zeros(capacity)
        self.size = 0
        self._next = 0

    def __len__(self) -> int:
        return self.size

    def add(self, obs, action, reward: float, next_obs, done: bool) -> None:
        """Store one transition. `done` must be True only for a real terminal state, not a time limit."""
        i = self._next
        self.obs[i], self.actions[i], self.rewards[i] = obs, action, reward
        self.next_obs[i], self.dones[i] = next_obs, float(done)
        self._next = (i + 1) % self.capacity
        self.size = min(self.size + 1, self.capacity)

    def sample(self, batch_size: int, rng: np.random.Generator):
        """Uniform random batch: (obs, actions, rewards, next_obs, dones), each with leading size batch_size."""
        idx = rng.integers(0, self.size, size=batch_size)
        return self.obs[idx], self.actions[idx], self.rewards[idx], self.next_obs[idx], self.dones[idx]


def huber(x: np.ndarray) -> np.ndarray:
    """Huber loss with threshold 1: 0.5 * x^2 for |x| <= 1, |x| - 0.5 beyond. Its derivative is clip(x, -1, 1)."""
    a = np.abs(x)
    return np.where(a <= 1.0, 0.5 * x * x, a - 0.5)


class EpsilonGreedyAgent:
    """Acting, replay and the training loop shared by the value-based agent in this file.

    A subclass provides `q_values(obs) -> (batch, n_actions)`, `update(batch) -> loss` and
    `sync_target()`. Epsilon falls linearly from `epsilon_start` to `epsilon_end` over
    `epsilon_decay_steps` environment steps.
    """

    def __init__(self, obs_dim: int, n_actions: int, config) -> None:
        self.obs_dim, self.n_actions, self.config = obs_dim, n_actions, config
        self.rng = np.random.default_rng(config.seed)
        self.buffer = ReplayBuffer(config.buffer_size, obs_dim)
        self.steps = 0

    @property
    def epsilon(self) -> float:
        cfg = self.config
        frac = min(self.steps / cfg.epsilon_decay_steps, 1.0)
        return cfg.epsilon_start + frac * (cfg.epsilon_end - cfg.epsilon_start)

    def act(self, obs: np.ndarray, greedy: bool = False) -> int:
        """Pick an action for one observation, shape (obs_dim,). greedy=True turns exploration off."""
        if not greedy and self.rng.random() < self.epsilon:
            return int(self.rng.integers(self.n_actions))
        return int(np.argmax(self.q_values(obs)[0]))

    def train(self, env, total_steps: int | None = None) -> list[float]:
        """Interact with `env` for total_steps steps, learning from replay. Returns the episode returns."""
        cfg = self.config
        returns: list[float] = []
        obs, episode_return = env.reset(), 0.0
        for _ in range(cfg.total_steps if total_steps is None else total_steps):
            action = self.act(obs)
            next_obs, reward, terminated, truncated = env.step(action)
            self.buffer.add(obs, action, reward, next_obs, terminated)
            self.steps += 1
            episode_return += reward
            obs = next_obs
            if terminated or truncated:
                returns.append(episode_return)
                obs, episode_return = env.reset(), 0.0
            if len(self.buffer) >= max(cfg.learning_starts, cfg.batch_size):
                self.update(self.buffer.sample(cfg.batch_size, self.rng))
            if self.steps % cfg.target_update_every == 0:
                self.sync_target()
        return returns

    def evaluate(self, env, episodes: int = 1) -> float:
        """Mean return of the greedy policy over `episodes` episodes."""
        total = 0.0
        for _ in range(episodes):
            obs, done = env.reset(), False
            while not done:
                obs, reward, terminated, truncated = env.step(self.act(obs, greedy=True))
                total += reward
                done = terminated or truncated
        return total / episodes


class DuelingDQN(EpsilonGreedyAgent):
    """DQN agent whose Q-network is a `DuelingNetwork`.

    obs_dim: length of an observation vector. n_actions: number of discrete actions.
    """

    def __init__(self, obs_dim: int, n_actions: int, config: DuelingDQNConfig | None = None) -> None:
        config = config or DuelingDQNConfig()
        super().__init__(obs_dim, n_actions, config)
        self.online = DuelingNetwork(obs_dim, config.hidden_size, n_actions, self.rng, config.learning_rate)
        self.target = DuelingNetwork(obs_dim, config.hidden_size, n_actions, self.rng, config.learning_rate)
        self.sync_target()

    def q_values(self, obs: np.ndarray) -> np.ndarray:
        """Action values of the online network. obs: (batch, obs_dim) or (obs_dim,) -> (batch, n_actions)."""
        return self.online.forward(obs)

    def state_value(self, obs: np.ndarray) -> np.ndarray:
        """Output of the value stream, V(s). obs: (batch, obs_dim) or (obs_dim,) -> (batch,)."""
        return self.online.streams(obs)[0][:, 0]

    def sync_target(self) -> None:
        """Copy the online network into the target network."""
        self.target.copy_from(self.online)

    def update(self, batch) -> float:
        """One gradient step on a batch (obs, actions, rewards, next_obs, dones). Returns the Huber loss."""
        obs, actions, rewards, next_obs, dones = batch
        targets = rewards + self.config.gamma * (1.0 - dones) * self.target.forward(next_obs).max(axis=1)
        q = self.online.forward(obs)
        rows = np.arange(len(actions))
        errors = q[rows, actions] - targets
        grad_q = np.zeros_like(q)
        grad_q[rows, actions] = np.clip(errors, -1.0, 1.0) / len(actions)
        grads, _ = self.online.backward(grad_q)
        self.online.step(grads)
        return float(np.mean(huber(errors)))
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Using the template, build a DuelingDQN on GridWorld(size=4), call agent.online.streams on one observation and combine the two outputs by hand, then check the result against q_values. After train, print state_value for the start observation and compare it with the mean and the maximum of q_values there.

Check on learning

  1. A transition updates only one action's value in a standard Q-network. Why does the same transition teach a dueling network something about the other actions in that state?
    A way to think about it

    Trace the gradient from the one Q output that has an error. It reaches the value stream, whose single output is added to every action's value.

  2. The aggregation subtracts the mean advantage. An alternative subtracts the maximum. What would V(s)V(s) then represent, and why might the mean be easier to train?
    A way to think about it

    With the maximum subtracted, the best action gets a centred advantage of zero, so VV equals the best action value. Consider how each choice reacts when the identity of the best action changes during training.

  3. On the 4 by 4 grid, in which cells would you expect the advantages to be nearly equal across actions, and in which would they differ most?
    A way to think about it

    Think about cells where two different moves both lie on a shortest path, and about cells next to a wall where a move leaves the agent where it is.

  4. The dueling network has more parameters than a plain Q-network with the same hidden size. How would you check that any improvement comes from the structure and not from the extra capacity?
    A way to think about it

    Design a comparison where the plain network is given a similar number of weights. If the gain remains, capacity alone does not explain it.