Sign in

Distributional

Distributional reinforcement learning (C51 and QR-DQN)

Value learning that predicts the whole distribution of the return for each action, not just its average: C51 or QR-DQN.

Overview

A Q value is an average. An action that always returns 5 and one that returns 0 or 10 with equal chance have the same average, yet they are different situations. Distributional methods keep the full picture: for each action the network predicts how likely each possible return is. The agent still acts on the average, but the learning signal is richer. The template offers two ways to describe a distribution. C51 fixes a row of evenly spaced return values, called atoms, and learns a probability for each. QR-DQN does the reverse: it fixes equal probabilities and learns where the return values, called quantiles, should sit. The template is a small NumPy version trained on a 4 by 4 grid.

A short history

Marc Bellemare, Will Dabney and Rémi Munos at DeepMind published A Distributional Perspective on Reinforcement Learning in 2017. They argued that an agent should learn the full distribution of the return, not only its mean, and their C51 agent, which uses 51 fixed support points, clearly beat DQN on Atari. Dabney and colleagues followed with QR-DQN, which learns quantiles and removes the need to fix the range of returns in advance. C51 later became one of the components of Rainbow.

How it works

  1. For each action the network outputs n_atoms numbers: logits over the fixed atoms for C51, or quantile values for QR-DQN.
  2. Act epsilon-greedily on the mean of each action's distribution, and store transitions in a replay buffer.
  3. For a sampled transition, take the target network's distribution for the next state's best action, judged by its mean.
  4. Shift and shrink that distribution: every return value zz becomes r+γzr + \gamma z, or just rr if the episode ended.
  5. C51: the shifted values no longer sit on the atoms, so split each one's probability between its two nearest atoms. Then reduce the cross-entropy between this target and the prediction.
  6. QR-DQN: use the shifted values as samples of the target and move each predicted quantile with the quantile Huber loss.
  7. Copy the online network into the target network every target_update_every steps.

Watch out for

  • C51 needs v_min and v_max to cover the real returns. Anything outside is clipped to the end atoms, so the distribution and its mean are wrong there.
  • The agent still acts on the mean. Learning the distribution does not by itself make the policy sensitive to risk.
  • With few atoms or quantiles the distribution is coarse. The projection in C51 then blurs it at every update.
  • QR-DQN's quantiles are not forced to be in increasing order. Early in training they can cross, which makes the output hard to read as a distribution.

Use cases

When to use it

When returns are noisy or have several modes that the mean hides, or as a stronger learning signal than plain DQN. Choose C51 when the range of returns is known in advance and QR-DQN when it is not.

In industry

Games and simulation
Atari-style agents, where predicting the return distribution gives a richer learning signal and higher scores than plain DQN.
Risk-aware decision making
Choosing actions by a low quantile or a tail average of the return, not the mean, in simulated trading or operations problems where rare large losses matter.
Research
Studying uncertainty in returns, and as the value head inside combined agents such as Rainbow.

Choosing it: what must hold

  • A small, discrete set of actions, as with DQN.
  • For C51, a known range that the returns fall within, to set the fixed support.
  • Extra compute and memory for an output per atom or quantile for every action.

When to choose something else

IfUse instead
You do not know the range of returns in advanceQR-DQN, the quantile version in this lesson
You only need the expected return and want the simplest agentDQN or Double DQN
You want the distributional head together with the other DQN improvementsRainbow

Math foundations

  1. The distributional Bellman equation

    Z(s,a)=DR+γ Z(S′,A′)Z(s, a) \overset{D}{=} R + \gamma\, Z(S', A')

    The random return from a state and action has the same distribution as the reward plus the discounted random return from the next state and action. Taking the mean of both sides gives back the ordinary Bellman equation.

  2. The C51 support and the mean

    zj=vmin⁡+j Δz,Δz=vmax⁡−vmin⁡N−1,Q(s,a)=∑j=0N−1zj pj(s,a)z_j = v_{\min} + j\, \Delta z, \quad \Delta z = \frac{v_{\max} - v_{\min}}{N - 1}, \qquad Q(s, a) = \sum_{j=0}^{N-1} z_j\, p_j(s, a)

    The atoms are NN fixed, evenly spaced return values. The network learns the probabilities pjp_j, a softmax over its outputs for that action. The action value is the mean.

  3. The categorical projection

    mi=∑j=0N−1[1−∣[ r+γ(1−d) zj ]vmin⁡vmax⁡−zi∣Δz]01pj(s′,a∗)m_i = \sum_{j=0}^{N-1} \left[ 1 - \frac{ \bigl| [\, r + \gamma (1 - d)\, z_j \,]_{v_{\min}}^{v_{\max}} - z_i \bigr| }{\Delta z} \right]_{0}^{1} p_j(s', a^{*})

    Each shifted atom is clipped to the support and its probability is shared between the two nearest atoms in proportion to closeness. Square brackets with bounds mean clipping. This is project_distribution.

  4. The C51 loss

    L=−∑i=0N−1milog⁡pi(s,a)L = -\sum_{i=0}^{N-1} m_i \log p_i(s, a)

    The cross-entropy between the projected target and the prediction. Minimising it is the same as minimising the KL divergence from target to prediction, since the target is held fixed.

  5. The QR-DQN quantile midpoints

    τi=2i+12N,i=0,…,N−1\tau_i = \frac{2i + 1}{2N}, \qquad i = 0, \dots, N - 1

    The network outputs NN values θi(s,a)\theta_i(s, a), each carrying probability 1/N1/N. Output ii is trained to sit at the τi\tau_i quantile of the return: the value below which a fraction τi\tau_i of returns fall.

  6. The quantile Huber loss

    ρτκ(u)=∣τ−1[u<0]∣ Lκ(u)κ,Lκ(u)={12u2∣u∣≤κκ(∣u∣−12κ)∣u∣>κ\rho_{\tau}^{\kappa}(u) = \bigl| \tau - \mathbf{1}[u < 0] \bigr| \, \frac{L_\kappa(u)}{\kappa}, \qquad L_\kappa(u) = \begin{cases} \tfrac{1}{2} u^2 & |u| \le \kappa \\ \kappa \bigl( |u| - \tfrac{1}{2} \kappa \bigr) & |u| > \kappa \end{cases}

    Here uu is a target sample minus the predicted quantile. Errors on the two sides are weighted τ\tau and 1−τ1 - \tau, and that imbalance is what pulls the output to the right quantile.

  7. The QR-DQN loss for one transition

    L=∑i=0N−11N∑j=0N−1ρτiκ(r+γ(1−d) θj(s′,a∗)−θi(s,a))L = \sum_{i=0}^{N-1} \frac{1}{N} \sum_{j=0}^{N-1} \rho_{\tau_i}^{\kappa}\Bigl( r + \gamma (1 - d)\, \theta_j(s', a^{*}) - \theta_i(s, a) \Bigr)

    Every predicted quantile is compared with every shifted target quantile. No projection is needed, because the values themselves are free to move.

Symbols

Z(s,a)Z(s, a)
the random return after taking action a in state s
r,d,γr, d, \gamma
reward, done flag and discount factor
NN
number of atoms or quantiles per action (n_atoms)
zjz_j
the j-th fixed atom of the C51 support
vmin⁡,vmax⁡v_{\min}, v_{\max}
smallest and largest return on the C51 support
Δz\Delta z
spacing between neighbouring atoms
pj(s,a)p_j(s, a)
predicted probability of atom j for action a
a∗a^{*}
the next action with the highest mean under the target network
mim_i
probability the projected target puts on atom i
θi(s,a)\theta_i(s, a)
the i-th predicted quantile value for action a (QR-DQN)
τi\tau_i
the quantile level that output i is trained to match
uu
a target sample minus a predicted quantile
κ\kappa
threshold of the Huber loss (kappa)
1[⋅]\mathbf{1}[\cdot]
indicator: 1 if the condition holds, else 0

Worked by hand

Use the template's default support: vmin⁡=−3v_{\min} = -3, vmax⁡=1v_{\max} = 1 and N=21N = 21. The next state's distribution puts probability 0.50.5 on the atom zj=0.4z_j = 0.4. The transition has r=−0.1r = -0.1, d=0d = 0 and γ=0.99\gamma = 0.99. Project that atom.

Δz=1−(−3)21−1=0.2\Delta z = \frac{1 - (-3)}{21 - 1} = 0.2
r+γzj=−0.1+0.99×0.4=0.296r + \gamma z_j = -0.1 + 0.99 \times 0.4 = 0.296
0.296−(−3)0.2=16.48  ⇒  between atoms z16=0.2 and z17=0.4\frac{0.296 - (-3)}{0.2} = 16.48 \;\Rightarrow\; \text{between atoms } z_{16} = 0.2 \text{ and } z_{17} = 0.4
weights: 1−0.48=0.52 on z16,0.48 on z17\text{weights: } 1 - 0.48 = 0.52 \text{ on } z_{16}, \quad 0.48 \text{ on } z_{17}
m16+=0.5×0.52=0.26,m17+=0.5×0.48=0.24m_{16} \mathrel{+}= 0.5 \times 0.52 = 0.26, \qquad m_{17} \mathrel{+}= 0.5 \times 0.48 = 0.24

The probability 0.5 is split into 0.26 and 0.24. The split keeps the mean: 0.52×0.2+0.48×0.4=0.2960.52 \times 0.2 + 0.48 \times 0.4 = 0.296, the shifted value.

Visual example

Loading the example.

Try this

  • Run the training, then click cells further from the goal and watch the distribution widen.
  • Set the slip chance to 0 and train again: every return is certain. QR-DQN collapses to one point, while C51 blurs the spike across its fixed atoms.
  • Switch to QR-DQN: the same shape is now described by where 21 equally likely values sit.

Code sample

from impl import Distributional, GridWorld
from config import DistributionalConfig

env = GridWorld(size=4)
agent = Distributional(env.obs_dim, env.n_actions, DistributionalConfig(algorithm="c51"))
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
values, probs = agent.distribution(env.reset())   # each (1, n_actions, n_atoms)
Read the implementation (349 lines)
"""Distributional RL in NumPy: C51 and QR-DQN, with a small gridworld to learn on.

Instead of the expected return Q(s, a), the network predicts the whole distribution of the return.
C51 uses fixed, evenly spaced return values (atoms) and learns their probabilities with a
cross-entropy loss against the projected target distribution. QR-DQN uses fixed probabilities and
learns the return values (quantiles) with the quantile Huber loss. Both act greedily on the mean of
the distribution. The rest is DQN: replay buffer, target copy, epsilon-greedy exploration, a small MLP
with hand-written backpropagation and Adam.
"""
from __future__ import annotations

import numpy as np

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


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 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 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


def quantile_huber_loss(quantiles: np.ndarray, targets: np.ndarray, kappa: float = 1.0):
    """Quantile regression Huber loss of QR-DQN and its gradient.

    quantiles: (batch, n) predicted quantile values theta_i for the midpoints tau_i = (i + 0.5) / n.
    targets:   (batch, m) samples of the target distribution.
    For u = target_j - theta_i the loss is |tau_i - 1[u < 0]| * huber_kappa(u) / kappa, averaged over
    the target samples, summed over the quantiles and averaged over the batch.
    Returns (loss, grad) with grad = d loss / d quantiles, shape (batch, n).
    """
    batch, n = quantiles.shape
    tau = (np.arange(n) + 0.5) / n
    u = targets[:, None, :] - quantiles[:, :, None]  # (batch, n, m)
    abs_u = np.abs(u)
    hub = np.where(abs_u <= kappa, 0.5 * u * u, kappa * (abs_u - 0.5 * kappa))
    weight = np.abs(tau[None, :, None] - (u < 0.0))
    loss = float((weight * hub / kappa).mean(axis=2).sum(axis=1).mean())
    grad = -(weight * np.clip(u, -kappa, kappa) / kappa).mean(axis=2) / batch
    return loss, grad


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 Distributional(EpsilonGreedyAgent):
    """Distributional DQN agent; `algorithm` in the config selects "c51" or "qr".

    obs_dim: length of an observation vector. n_actions: number of discrete actions.
    The network outputs n_actions * n_atoms numbers: logits over the atoms for C51, quantile values
    for QR-DQN.
    """

    def __init__(self, obs_dim: int, n_actions: int, config: DistributionalConfig | None = None) -> None:
        config = config or DistributionalConfig()
        super().__init__(obs_dim, n_actions, config)
        sizes = (obs_dim, config.hidden_size, n_actions * config.n_atoms)
        self.online = MLP(sizes, self.rng, config.learning_rate)
        self.target = MLP(sizes, self.rng, config.learning_rate)
        self.sync_target()
        self.atoms = np.linspace(config.v_min, config.v_max, config.n_atoms)

    def _outputs(self, net: MLP, obs: np.ndarray) -> np.ndarray:
        """Raw network outputs reshaped to (batch, n_actions, n_atoms)."""
        return net.forward(obs).reshape(-1, self.n_actions, self.config.n_atoms)

    def distribution(self, obs: np.ndarray):
        """Return distribution of every action as (values, probs), both (batch, n_actions, n_atoms).

        C51: values are the fixed atoms and probs are learned. QR-DQN: values are the learned quantiles
        and every one has probability 1 / n_atoms.
        """
        out = self._outputs(self.online, obs)
        if self.config.algorithm == "c51":
            return np.broadcast_to(self.atoms, out.shape), softmax(out)
        return out, np.full(out.shape, 1.0 / self.config.n_atoms)

    def q_values(self, obs: np.ndarray) -> np.ndarray:
        """Mean of each action's return distribution. obs: (batch, obs_dim) or (obs_dim,) -> (batch, n_actions)."""
        values, probs = self.distribution(obs)
        return (values * probs).sum(axis=2)

    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 loss."""
        obs, actions, rewards, next_obs, dones = batch
        cfg = self.config
        rows = np.arange(len(actions))
        next_out = self._outputs(self.target, next_obs)
        if cfg.algorithm == "c51":
            next_probs = softmax(next_out)
            best = np.argmax((next_probs * self.atoms).sum(axis=2), axis=1)
            target = project_distribution(rewards, dones, cfg.gamma, next_probs[rows, best], self.atoms)
            probs = softmax(self._outputs(self.online, obs))
            chosen = probs[rows, actions]
            loss = float(-np.mean(np.sum(target * np.log(chosen + 1e-12), axis=1)))
            grad_chosen = (chosen - target) / len(actions)
        else:
            best = np.argmax(next_out.mean(axis=2), axis=1)
            target = rewards[:, None] + cfg.gamma * (1.0 - dones)[:, None] * next_out[rows, best]
            out = self._outputs(self.online, obs)
            loss, grad_chosen = quantile_huber_loss(out[rows, actions], target, cfg.kappa)
        grad_out = np.zeros((len(actions), self.n_actions, cfg.n_atoms))
        grad_out[rows, actions] = grad_chosen
        grads, _ = self.online.backward(grad_out.reshape(len(actions), -1))
        self.online.step(grads)
        return loss
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
10, run with python3 -m unittest -v

Practice

Using the template, call project_distribution with one transition whose next_probs put 0.5 on the atom 0.4 and 0.5 on the atom 0.0, on the default 21 atoms, and check the worked numbers. Then train Distributional on GridWorld(size=4) with algorithm set to c51 and to qr, and for each inspect what distribution returns at the start observation and how q_values relates to it.

Check on learning

  1. The agent picks actions by the mean, exactly as DQN does. Why might learning the whole distribution still produce a better policy?
    A way to think about it

    Compare the two training signals for one transition: a single number to match, or a full set of probabilities. Think about what the shared hidden layer is forced to represent in each case.

  2. C51 must project the shifted distribution back onto the atoms, QR-DQN does not. What property of each representation causes that difference?
    A way to think about it

    Ask what is fixed and what is free in each. If the locations are fixed, a shifted location has nowhere to go. If the locations are the learned outputs, they can simply move.

  3. On the 4 by 4 grid the best return is 0.5 and the default support runs from −3-3 to 11. What would you see if you set v_max to 0?
    A way to think about it

    Follow a return above 0 through the projection. It is clipped to the top atom. Consider what the mean of the learned distribution can then be, at most.

  4. For the quantile loss with τ=0.9\tau = 0.9, which is penalised more: predicting above the target or below it? Use that to explain why the output settles where 90 percent of targets lie below.
    A way to think about it

    Write the weight for u>0u > 0 and for u<0u < 0. The output stops moving when the total pull upward from targets above it balances the total pull downward from targets below.