Sign in

Rainbow

Rainbow: combined improvements to DQN

One agent that combines six improvements to DQN: double Q-learning, prioritised replay, a dueling network, multi-step returns, C51 and noisy layers.

Overview

After DQN, several separate fixes were proposed, each aimed at a different weakness. Double Q-learning reduces inflated values. Prioritised replay spends more updates on the transitions the network gets most wrong. A dueling network learns the value of a state apart from the ranking of actions. Multi-step returns pass reward back several steps at a time. C51 learns the distribution of the return, not only its mean. Noisy layers put the exploration inside the network's weights. Rainbow shows that these fixes do not conflict and work better together than any one alone. The template is a small NumPy version on a 4 by 4 grid. Each part has a flag, so you can switch parts off and measure what each adds.

A short history

Matteo Hessel and colleagues at DeepMind published Rainbow: Combining Improvements in Deep Reinforcement Learning in 2017. Several separate papers had each improved DQN, and nobody had tested whether the gains added up. Rainbow combined six of them in one agent and set a new best result on the Atari benchmark, and its ablation study showed that prioritised replay and multi-step returns mattered most. The name is not an acronym: it refers to the mix of components.

How it works

  1. Act greedily on the mean of each action's return distribution, with fresh noise drawn in the noisy layers. That noise is the exploration.
  2. Feed each step to the n-step accumulator, which emits a transition holding the discounted sum of the next nn rewards and the discount for the bootstrap.
  3. Store it in the prioritised buffer with the largest priority seen so far, so every new transition is sampled at least once soon.
  4. Sample a batch with probability that grows with priority, together with importance weights that correct for the uneven sampling.
  5. For each next state, the online network picks the best action by mean and the target network supplies that action's distribution.
  6. Shift the distribution by the n-step reward and discount, project it onto the fixed atoms, and reduce the weighted cross-entropy with the prediction.
  7. Set each sampled transition's priority to its new loss, and copy the online network into the target network every target_update_every steps.

Watch out for

  • There are many settings, and they interact. The support range, nn, the priority exponent and the noise scale all need to suit the task, and a poor choice for one can hide the benefit of the others.
  • Multi-step returns use rewards collected by an older policy with no correction. With a large nn the target describes behaviour the current policy would not repeat.
  • Prioritised sampling changes which data the network sees. Without the importance weights the result is biased toward the high-loss transitions.
  • The template samples from a plain probability vector, which costs time proportional to the buffer size. Full-scale versions use a sum tree to make sampling fast.

Use cases

When to use it

When DQN works but learns slowly or unstably and the extra parts are affordable. On a new problem, start from DQN and switch the parts on one at a time to see what each contributes.

In industry

Games and simulation
A strong discrete-action baseline on Atari-style benchmarks, widely used for comparison in research papers.
Sample-limited training
Reduced variants tuned for small data budgets are used when only a limited number of environment steps is available.
Operations research
Discrete decision problems in a simulator where a plain DQN learns too slowly and the extra components are worth the complexity.

Choosing it: what must hold

  • A small, discrete set of actions.
  • Substantial compute and memory: a distributional head, a prioritised buffer and noisy layers all add cost.
  • A known range of returns for the C51 support, and patience for more hyperparameters than DQN.

When to choose something else

IfUse instead
You want a simple agent you can debug quicklyDQN or Double DQN
Actions are continuousSAC or TD3
You need only one of the improvementsDouble DQN, Dueling DQN or distributional RL on its own

Math foundations

  1. The n-step return

    Rt(n)=∑k=0n−1γk rt+kR_t^{(n)} = \sum_{k=0}^{n-1} \gamma^{k}\, r_{t+k}

    The discounted sum of the next nn real rewards. The bootstrap from the state nn steps ahead is then discounted by γn\gamma^{n}. Reward travels back nn steps in one update.

  2. Double action selection on distributions

    a∗=arg⁡max⁡a∑jzj pj(st+n,a;θ)a^{*} = \arg\max_{a} \sum_{j} z_j\, p_j(s_{t+n}, a; \theta)

    The online weights θ\theta choose the next action by its mean return. The target weights θ−\theta^{-} then supply that action's distribution, as in Double DQN.

  3. The shifted atoms

    z^j=Rt(n)+γn(1−d) zj\hat{z}_j = R_t^{(n)} + \gamma^{n} (1 - d)\, z_j

    Each atom of the next distribution is moved by the n-step reward and shrunk by the n-step discount. The result is projected back onto the fixed atoms to give target probabilities mim_i, as in C51.

  4. The loss for one transition

    L=−∑imilog⁡pi(st,at;θ)L = -\sum_{i} m_i \log p_i(s_t, a_t; \theta)

    The cross-entropy between the projected target and the predicted distribution. In the template this per-sample loss also becomes the transition's new priority.

  5. Prioritised sampling and its correction

    P(i)=uiω∑kukω,wi=(M P(i))−βmax⁡k(M P(k))−βP(i) = \frac{u_i^{\omega}}{\sum_{k} u_k^{\omega}}, \qquad w_i = \frac{\bigl( M\, P(i) \bigr)^{-\beta}}{\max_{k} \bigl( M\, P(k) \bigr)^{-\beta}}

    Transition ii is drawn with probability that grows with its priority uiu_i. The weight wiw_i scales its gradient down by how over-sampled it was. β\beta is raised to 1 during training, where the correction is complete.

  6. A noisy linear layer

    y=(μw+σw⊙εw) x+μb+σb⊙εby = \bigl( \mu^{w} + \sigma^{w} \odot \varepsilon^{w} \bigr)\, x + \mu^{b} + \sigma^{b} \odot \varepsilon^{b}

    Each weight is a learned mean plus a learned scale times random noise. The network can shrink σ\sigma where it is confident, so exploration fades per weight instead of by a global schedule.

Symbols

rt,γr_t, \gamma
reward at step t and the discount factor
nn
number of rewards summed before bootstrapping (n_step)
Rt(n)R_t^{(n)}
the n-step return from step t
dd
done flag: 1 if the episode terminated within the n steps
zjz_j
the j-th fixed atom of the return support
pj(s,a;θ)p_j(s, a; \theta)
predicted probability of atom j for action a
θ,θ−\theta, \theta^{-}
weights of the online and the target network
mim_i
probability the projected target puts on atom i
uiu_i
priority of stored transition i: its last loss
ω\omega
priority exponent (priority_alpha): 0 gives uniform sampling
β\beta
importance-sampling exponent, annealed from priority_beta to 1
MM
number of transitions currently in the buffer
μw,σw,μb,σb\mu^{w}, \sigma^{w}, \mu^{b}, \sigma^{b}
learned means and noise scales of a noisy layer's weights and biases
εw,εb\varepsilon^{w}, \varepsilon^{b}
random noise for the weights and biases, redrawn by reset_noise

Worked by hand

First a 3-step return with rewards −0.1-0.1, −0.1-0.1, 1.01.0 and γ=0.99\gamma = 0.99. Then prioritised sampling from a buffer of three transitions with priorities 44, 11, 11, exponent ω=0.5\omega = 0.5 and β=1\beta = 1.

R(3)=−0.1+0.99×(−0.1)+0.992×1.0=−0.1−0.099+0.9801=0.7811R^{(3)} = -0.1 + 0.99 \times (-0.1) + 0.99^2 \times 1.0 = -0.1 - 0.099 + 0.9801 = 0.7811
u0.5=(2,  1,  1),P=(24,  14,  14)=(0.5,  0.25,  0.25)u^{0.5} = (2,\; 1,\; 1), \qquad P = \bigl( \tfrac{2}{4},\; \tfrac{1}{4},\; \tfrac{1}{4} \bigr) = (0.5,\; 0.25,\; 0.25)
(3P)−1=(11.5,  10.75,  10.75)=(0.667,  1.333,  1.333)(3 P)^{-1} = \bigl( \tfrac{1}{1.5},\; \tfrac{1}{0.75},\; \tfrac{1}{0.75} \bigr) = (0.667,\; 1.333,\; 1.333)
w=(0.667,  1.333,  1.333)/1.333=(0.5,  1,  1)w = (0.667,\; 1.333,\; 1.333) / 1.333 = (0.5,\; 1,\; 1)

The first transition is drawn twice as often as each of the others, and its gradient is halved to compensate. Under uniform sampling every PP would be 1/31/3 and every weight 1.

Visual example

Loading the example.

Try this

  • Run the training with all six parts on and compare the curve with plain DQN.
  • Switch on one part at a time, starting from none, to see what each adds on this small grid.
  • Click a box in the diagram to read what that part is doing at this moment of training.

Code sample

from impl import Rainbow, GridWorld
from config import RainbowConfig

env = GridWorld(size=4)
agent = Rainbow(env.obs_dim, env.n_actions, RainbowConfig(n_step=3, noisy=True))
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
Read the implementation (447 lines)
"""Rainbow in NumPy: the six DQN improvements combined, with a small gridworld to learn on.

The agent joins double Q-learning, prioritised replay, a dueling network, multi-step returns, a
categorical (C51) return distribution and noisy linear layers for exploration. Each part can be
switched off in the config. The network and its backpropagation are written by hand and sized for
toy problems.
"""
from __future__ import annotations

from collections import deque

import numpy as np

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


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


def softmax(logits: np.ndarray) -> np.ndarray:
    """Softmax over the last axis."""
    z = logits - logits.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)


def project_distribution(rewards, dones, discounts, next_probs, atoms) -> np.ndarray:
    """Categorical projection of the C51 target distribution onto the fixed support.

    Each atom z_j of the next-state distribution moves to r + discount * (1 - done) * z_j, is clipped to
    [atoms[0], atoms[-1]], and its probability is split between the two neighbouring atoms in proportion
    to how close it lands to each.

    rewards, dones: (batch,). discounts: scalar or (batch,). next_probs: (batch, n_atoms), rows sum to 1.
    atoms: (n_atoms,) evenly spaced support. Returns (batch, n_atoms), rows sum to 1.
    """
    rewards, dones = np.asarray(rewards, dtype=float), np.asarray(dones, dtype=float)
    batch, n_atoms = next_probs.shape
    v_min, v_max = atoms[0], atoms[-1]
    delta = (v_max - v_min) / (n_atoms - 1)
    scale = np.broadcast_to(np.asarray(discounts, dtype=float), rewards.shape) * (1.0 - dones)
    moved = np.clip(rewards[:, None] + scale[:, None] * atoms[None, :], v_min, v_max)
    pos = (moved - v_min) / delta
    lower = np.clip(np.floor(pos + 1e-9).astype(int), 0, n_atoms - 1)
    upper = np.clip(lower + 1, 0, n_atoms - 1)
    w_upper = np.clip(pos - lower, 0.0, 1.0)
    w_upper[upper == lower] = 0.0
    rows = np.repeat(np.arange(batch), n_atoms)
    target = np.zeros((batch, n_atoms))
    np.add.at(target, (rows, lower.ravel()), (next_probs * (1.0 - w_upper)).ravel())
    np.add.at(target, (rows, upper.ravel()), (next_probs * w_upper).ravel())
    return target


class NoisyLinear:
    """Linear layer y = x W + b whose weights carry learned, factorised Gaussian noise.

    W = w_mu + w_sigma * eps_w and b = b_mu + b_sigma * eps_b, with eps_w = outer(f(e_in), f(e_out)),
    eps_b = f(e_out), f(e) = sign(e) * sqrt(|e|) and e_in, e_out standard normal. `reset_noise` draws
    new noise, `remove_noise` sets it to zero (the mean weights). With noisy=False the layer has no
    sigma parameters and is an ordinary linear layer.
    """

    def __init__(self, n_in: int, n_out: int, rng: np.random.Generator, noisy: bool = True, sigma0: float = 0.5) -> None:
        bound = 1.0 / np.sqrt(n_in)
        self.noisy = noisy
        self.rng = rng
        self.w_mu = rng.uniform(-bound, bound, size=(n_in, n_out))
        self.b_mu = rng.uniform(-bound, bound, size=n_out)
        self.w_sigma = np.full((n_in, n_out), sigma0 * bound)
        self.b_sigma = np.full(n_out, sigma0 * bound)
        self.eps_w = np.zeros((n_in, n_out))
        self.eps_b = np.zeros(n_out)
        self._x = np.zeros((1, n_in))

    def params(self) -> list[np.ndarray]:
        return [self.w_mu, self.b_mu, self.w_sigma, self.b_sigma] if self.noisy else [self.w_mu, self.b_mu]

    def reset_noise(self) -> None:
        """Draw fresh factorised noise (does nothing when the layer is not noisy)."""
        if not self.noisy:
            return
        e_in = self.rng.normal(size=self.w_mu.shape[0])
        e_out = self.rng.normal(size=self.w_mu.shape[1])
        f_in = np.sign(e_in) * np.sqrt(np.abs(e_in))
        f_out = np.sign(e_out) * np.sqrt(np.abs(e_out))
        self.eps_w = np.outer(f_in, f_out)
        self.eps_b = f_out

    def remove_noise(self) -> None:
        """Set the noise to zero so the layer uses its mean weights."""
        self.eps_w = np.zeros_like(self.eps_w)
        self.eps_b = np.zeros_like(self.eps_b)

    def _weight(self) -> np.ndarray:
        return self.w_mu + self.w_sigma * self.eps_w if self.noisy else self.w_mu

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (batch, n_in) -> (batch, n_out)."""
        self._x = x
        bias = self.b_mu + self.b_sigma * self.eps_b if self.noisy else self.b_mu
        return x @ self._weight() + bias

    def backward(self, grad_out: np.ndarray):
        """grad_out: (batch, n_out). Returns (grads in the order of `params()`, grad_in (batch, n_in))."""
        grad_w = self._x.T @ grad_out
        grad_b = grad_out.sum(axis=0)
        grads = [grad_w, grad_b, grad_w * self.eps_w, grad_b * self.eps_b] if self.noisy else [grad_w, grad_b]
        return grads, grad_out @ self._weight().T


class RainbowNetwork:
    """Maps observations to a categorical return distribution per action.

    Trunk: obs_dim -> hidden (ReLU). Advantage stream: hidden -> hidden (ReLU) -> n_actions * n_atoms.
    Value stream (when dueling): hidden -> hidden (ReLU) -> n_atoms. The stream layers are noisy when
    noisy=True. Logits are value + advantage - mean over actions of advantage, then a softmax over atoms.
    """

    def __init__(self, obs_dim: int, hidden: int, n_actions: int, n_atoms: int, rng: np.random.Generator,
                 dueling: bool = True, noisy: bool = True, sigma0: float = 0.5, lr: float = 1e-3) -> None:
        self.n_actions, self.n_atoms, self.dueling, self.lr = n_actions, n_atoms, dueling, lr
        self.trunk = NoisyLinear(obs_dim, hidden, rng, noisy=False)
        self.adv1 = NoisyLinear(hidden, hidden, rng, noisy, sigma0)
        self.adv2 = NoisyLinear(hidden, n_actions * n_atoms, rng, noisy, sigma0)
        self.layers = [self.trunk, self.adv1, self.adv2]
        if dueling:
            self.val1 = NoisyLinear(hidden, hidden, rng, noisy, sigma0)
            self.val2 = NoisyLinear(hidden, n_atoms, rng, noisy, sigma0)
            self.layers += [self.val1, self.val2]
        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._cache: tuple = ()

    def params(self) -> list[np.ndarray]:
        return [p for layer in self.layers for p in layer.params()]

    def reset_noise(self) -> None:
        for layer in self.layers:
            layer.reset_noise()

    def remove_noise(self) -> None:
        for layer in self.layers:
            layer.remove_noise()

    def logits(self, x: np.ndarray) -> np.ndarray:
        """x: (batch, obs_dim) or (obs_dim,) -> logits over atoms, (batch, n_actions, n_atoms)."""
        x = np.atleast_2d(np.asarray(x, dtype=float))
        h = np.maximum(self.trunk.forward(x), 0.0)
        h_adv = np.maximum(self.adv1.forward(h), 0.0)
        out = self.adv2.forward(h_adv).reshape(len(x), self.n_actions, self.n_atoms)
        h_val = None
        if self.dueling:
            h_val = np.maximum(self.val1.forward(h), 0.0)
            value = self.val2.forward(h_val)[:, None, :]
            out = value + out - out.mean(axis=1, keepdims=True)
        self._cache = (h, h_adv, h_val)
        return out

    def forward(self, x: np.ndarray) -> np.ndarray:
        """Probabilities over atoms, (batch, n_actions, n_atoms); each [b, a] row sums to 1."""
        return softmax(self.logits(x))

    def backward(self, grad_logits: np.ndarray) -> list[np.ndarray]:
        """grad_logits: d loss / d logits, (batch, n_actions, n_atoms). Returns grads in the order of `params()`."""
        h, h_adv, h_val = self._cache
        batch = len(grad_logits)
        grad_adv = grad_logits
        if self.dueling:
            grad_adv = grad_logits - grad_logits.mean(axis=1, keepdims=True)
        g_adv2, g = self.adv2.backward(grad_adv.reshape(batch, -1))
        g_adv1, grad_h = self.adv1.backward(g * (h_adv > 0.0))
        grads = g_adv1 + g_adv2
        if self.dueling:
            g_val2, g = self.val2.backward(grad_logits.sum(axis=1))
            g_val1, g = self.val1.backward(g * (h_val > 0.0))
            grad_h = grad_h + g
            grads = grads + g_val1 + g_val2
        g_trunk, _ = self.trunk.backward(grad_h * (h > 0.0))
        return g_trunk + grads

    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: "RainbowNetwork") -> None:
        for p, q in zip(self.params(), other.params()):
            p[...] = q


class PrioritizedReplay:
    """Replay buffer that samples transition i with probability p_i^alpha / sum_k p_k^alpha.

    A stored transition is (obs, action, reward, next_obs, done, discount), where `discount` is the
    factor applied to the bootstrap value (gamma^n for an n-step transition). New transitions get the
    largest priority seen so far. alpha = 0 gives uniform sampling.
    """

    def __init__(self, capacity: int, obs_dim: int, alpha: float = 0.5) -> None:
        self.capacity, self.alpha = capacity, alpha
        self.obs = np.zeros((capacity, obs_dim))
        self.next_obs = np.zeros((capacity, obs_dim))
        self.actions = np.zeros(capacity, dtype=int)
        self.rewards = np.zeros(capacity)
        self.dones = np.zeros(capacity)
        self.discounts = np.zeros(capacity)
        self.priorities = np.zeros(capacity)
        self.max_priority = 1.0
        self.size = 0
        self._next = 0

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

    def add(self, obs, action, reward, next_obs, done, discount) -> None:
        i = self._next
        self.obs[i], self.actions[i], self.rewards[i] = obs, action, reward
        self.next_obs[i], self.dones[i], self.discounts[i] = next_obs, float(done), discount
        self.priorities[i] = self.max_priority
        self._next = (i + 1) % self.capacity
        self.size = min(self.size + 1, self.capacity)

    def probabilities(self) -> np.ndarray:
        """Sampling probability of every stored transition, shape (size,)."""
        scaled = self.priorities[: self.size] ** self.alpha
        return scaled / scaled.sum()

    def sample(self, batch_size: int, rng: np.random.Generator, beta: float = 1.0):
        """Returns (batch, indices, weights).

        batch = (obs, actions, rewards, next_obs, dones, discounts). weights are the importance-sampling
        corrections (size * P(i))^-beta, divided by their maximum so the largest is 1.
        """
        probs = self.probabilities()
        idx = rng.choice(self.size, size=batch_size, p=probs)
        weights = (self.size * probs[idx]) ** (-beta)
        batch = (self.obs[idx], self.actions[idx], self.rewards[idx], self.next_obs[idx], self.dones[idx],
                 self.discounts[idx])
        return batch, idx, weights / weights.max()

    def update_priorities(self, idx: np.ndarray, priorities: np.ndarray) -> None:
        """Set new priorities (for example the per-sample loss) for the transitions at `idx`."""
        priorities = np.abs(priorities) + 1e-6
        self.priorities[idx] = priorities
        self.max_priority = max(self.max_priority, float(priorities.max()))


class NStepAccumulator:
    """Turns one-step transitions into n-step transitions.

    `push` returns the transitions that became complete: (obs, action, n_step_reward, next_obs, done,
    discount) where n_step_reward = sum_k gamma^k r_k and discount = gamma^(number of rewards summed).
    """

    def __init__(self, n: int, gamma: float) -> None:
        self.n, self.gamma = n, gamma
        self.queue: deque = deque()

    def _pop(self, next_obs, done: bool):
        reward = sum(self.gamma**k * item[2] for k, item in enumerate(self.queue))
        discount = self.gamma ** len(self.queue)
        obs, action, _ = self.queue.popleft()
        return obs, action, reward, next_obs, done, discount

    def push(self, obs, action, reward: float, next_obs, terminated: bool) -> list:
        """Add one step. At a terminal state every pending transition is completed."""
        self.queue.append((obs, action, reward))
        out = []
        if len(self.queue) == self.n:
            out.append(self._pop(next_obs, terminated))
        while terminated and self.queue:
            out.append(self._pop(next_obs, True))
        return out

    def flush(self, next_obs) -> list:
        """Complete the pending transitions when an episode is cut by a time limit (they still bootstrap)."""
        out = []
        while self.queue:
            out.append(self._pop(next_obs, False))
        return out


class Rainbow:
    """Rainbow agent for discrete actions.

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

    def __init__(self, obs_dim: int, n_actions: int, config: RainbowConfig | None = None) -> None:
        cfg = self.config = config or RainbowConfig()
        self.obs_dim, self.n_actions = obs_dim, n_actions
        self.rng = np.random.default_rng(cfg.seed)
        self.atoms = np.linspace(cfg.v_min, cfg.v_max, cfg.n_atoms)
        args = (obs_dim, cfg.hidden_size, n_actions, cfg.n_atoms, self.rng, cfg.dueling, cfg.noisy, cfg.sigma0,
                cfg.learning_rate)
        self.online = RainbowNetwork(*args)
        self.target = RainbowNetwork(*args)
        self.target.copy_from(self.online)
        self.buffer = PrioritizedReplay(cfg.buffer_size, obs_dim, cfg.priority_alpha if cfg.prioritized else 0.0)
        self.n_step = NStepAccumulator(cfg.n_step, cfg.gamma)
        self.steps = 0

    @property
    def epsilon(self) -> float:
        """Exploration rate. Zero with noisy layers, which explore through their weight noise."""
        cfg = self.config
        if cfg.noisy:
            return 0.0
        frac = min(self.steps / cfg.epsilon_decay_steps, 1.0)
        return cfg.epsilon_start + frac * (cfg.epsilon_end - cfg.epsilon_start)

    @property
    def beta(self) -> float:
        """Importance-sampling exponent, annealed linearly from priority_beta to 1 over total_steps."""
        cfg = self.config
        return cfg.priority_beta + min(self.steps / cfg.total_steps, 1.0) * (1.0 - cfg.priority_beta)

    def q_values(self, obs: np.ndarray) -> np.ndarray:
        """Mean of each action's return distribution under the current weights, (batch, n_actions)."""
        return (self.online.forward(obs) * self.atoms).sum(axis=2)

    def act(self, obs: np.ndarray, greedy: bool = False) -> int:
        """Action for one observation. greedy=True uses the mean weights and no epsilon."""
        if greedy:
            self.online.remove_noise()
        else:
            self.online.reset_noise()
            if self.rng.random() < self.epsilon:
                return int(self.rng.integers(self.n_actions))
        return int(np.argmax(self.q_values(obs)[0]))

    def update(self, batch, weights: np.ndarray | None = None) -> np.ndarray:
        """One gradient step on a batch (obs, actions, rewards, next_obs, dones, discounts).

        weights: optional per-sample importance weights, (batch,). Returns the per-sample
        cross-entropy losses, (batch,), which serve as the new priorities.
        """
        obs, actions, rewards, next_obs, dones, discounts = batch
        cfg = self.config
        rows = np.arange(len(actions))
        weights = np.ones(len(actions)) if weights is None else weights
        self.online.reset_noise()
        self.target.reset_noise()
        next_probs = self.target.forward(next_obs)
        chooser = self.online.forward(next_obs) if cfg.double else next_probs
        best = np.argmax((chooser * self.atoms).sum(axis=2), axis=1)
        target = project_distribution(rewards, dones, discounts, next_probs[rows, best], self.atoms)
        probs = self.online.forward(obs)
        chosen = probs[rows, actions]
        losses = -np.sum(target * np.log(chosen + 1e-12), axis=1)
        grad_logits = np.zeros_like(probs)
        grad_logits[rows, actions] = weights[:, None] * (chosen - target) / len(actions)
        self.online.step(self.online.backward(grad_logits))
        return losses

    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)
            ready = self.n_step.push(obs, action, reward, next_obs, terminated)
            if truncated:
                ready += self.n_step.flush(next_obs)
            for transition in ready:
                self.buffer.add(*transition)
            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):
                batch, idx, weights = self.buffer.sample(cfg.batch_size, self.rng, self.beta)
                losses = self.update(batch, weights)
                if cfg.prioritized:
                    self.buffer.update_priorities(idx, losses)
            if self.steps % cfg.target_update_every == 0:
                self.target.copy_from(self.online)
        return returns

    def evaluate(self, env, episodes: int = 1) -> float:
        """Mean return of the greedy policy (mean weights, no exploration) 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
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
10, run with python3 -m unittest -v

Practice

Using the template, add three transitions to a PrioritizedReplay with alpha 0.5, call update_priorities to set priorities 4, 1, 1, and check probabilities against the worked example. Push three steps through NStepAccumulator(3, 0.99) and read the reward and discount it emits. Then train Rainbow on GridWorld(size=4) with all flags on, and again with one of double, dueling, noisy or prioritized set to False, and compare evaluate.

Check on learning

  1. Prioritised replay deliberately samples some transitions more often. Why does that bias the learning, and how do the importance weights undo it?
    A way to think about it

    The loss you want is an average over the buffer as it is. Sampling unevenly changes that average. Multiply each sample by something inversely related to how often it is drawn and see what the expected update becomes.

  2. Why is β\beta started below 1 and raised to 1 over training, instead of being fixed at 1 from the start?
    A way to think about it

    Early on, estimates change quickly and some bias does little harm, while small weights slow learning on exactly the transitions chosen for attention. Near convergence an unbiased update matters more.

  3. With noisy layers the template sets ε\varepsilon for epsilon-greedy to zero. In what way is exploration through weight noise different from picking a random action now and then?
    A way to think about it

    A random action is unrelated to the state and to the step before. A perturbed network acts consistently for as long as its noise is held, and the size of the perturbation is itself learned.

  4. You switch off one component at a time and find that removing multi-step returns hurts most on the grid. What about this task could explain that?
    A way to think about it

    The only positive reward comes at the goal, six moves from the start. Count how many updates it takes for that reward to influence the start state's value with one-step targets and with three-step targets.

  5. The n-step target uses rewards from actions an older policy chose, without correction. When is that a small error and when a large one?
    A way to think about it

    The target treats the stored actions as if the current policy would take them. Compare a policy that has barely changed since the data was stored with one that has changed a lot, and a small nn with a large one.