Reinforcement learning · Atari

C51: A Distributional Perspective on Reinforcement Learning

Learn the whole probability distribution of future reward, not only its average.

C51 keeps DQN's network, replay memory and target network, but for every action it outputs 51 probabilities over fixed return values from −10 to 10. Each update shrinks the next state's distribution by the discount, shifts it by the reward, splits it back onto the 51 values, and minimizes a cross-entropy.

Explaining the paperA Distributional Perspective on Reinforcement LearningBellemare, Dabney, Munos · ICML 2017 · arXiv:1707.06887 ↗

A 2017 DeepMind paper that proves the distributional Bellman update converges for a fixed policy, shows that the greedy version need not, and raises DQN's median Atari score from 79% to 178% of the human baseline.

A DQN agent predicts, for each action, one number: the discounted reward it expects to collect from here on. Marc Bellemare, Will Dabney and Rémi Munos asked what happens if the network predicts the whole probability distribution of that future reward instead. Their agent, C51 (categorical, 51 atoms), changes DQN's output layer, its loss and its optimizer, and on the 57-game Atari benchmark it beat on median score every DQN variant the paper compared against.

The page covers the paper in six parts:

  1. the return is a random variable, and the Bellman equation has a version for its distribution;
  2. for a fixed policy, repeated Bellman updates converge in the Wasserstein distance, and not in KL or total variation;
  3. with greedy action selection, a two-state example shows the distributions need not converge;
  4. the practical algorithm: 51 fixed return values, a projection onto them, and a cross-entropy loss;
  5. why the loss is a cross-entropy when the theory is stated in Wasserstein distance;
  6. the Atari results, and the paper's hypotheses for why a distribution helps an agent that still acts on the mean.

The return is a random variable; DQN learns its mean

An agent in state xx takes action aa, receives a reward, lands in a new state, and repeats. The return is the discounted sum of the rewards it collects, ∑tγtRt\sum_t \gamma^t R_t, with discount γ=0.99\gamma = 0.99 in DQN and C51: a reward 100 steps ahead counts 0.99100≈0.370.99^{100} \approx 0.37 as much as one received now. The paper writes Zπ(x,a)Z^\pi(x, a) for this return when the agent starts with aa in xx and follows policy π\pi afterwards, and QπQ^\pi for its expectation:

Qπ(x,a):=E Zπ(x,a)=E[∑t=0∞γtR(xt,at)]Q^\pi(x,a) := \mathbb{E}\, Z^\pi(x,a) = \mathbb{E}\Big[\sum_{t=0}^{\infty} \gamma^t R(x_t, a_t)\Big]Qπ(x,a):=E Zπ(x,a)=E[∑t=0∞γtR(xt,at)]\begin{aligned} Q^\pi(x,a) &:= \mathbb{E}\, Z^\pi(x,a) \\ &= \mathbb{E}\Big[\sum_{t=0}^{\infty} \gamma^t R(x_t, a_t)\Big] \end{aligned}
(1)

The return is random for three reasons: the reward can be random, the next state can be random, and the policy can choose randomly. QπQ^\pi averages all three away. Standard reinforcement learning works with QQ because it satisfies Bellman's equation, which ties the value here to the value one step later:

Qπ(x,a)=E R(x,a)+γ EP,π Qπ(x′,a′)Q^\pi(x,a) = \mathbb{E}\,R(x,a) + \gamma\, \mathbb{E}_{P,\pi}\, Q^\pi(x',a')

DQN learns the optimal version of this, with a max over next actions, by regressing Q(x,a)Q(x,a) toward r+γmax⁡a′Q(x′,a′)r + \gamma \max_{a'} Q(x', a') on transitions sampled from a replay memory, under a squared loss.

The mean of a return with two outcomes can be a value that never occurs. The paper's Figure 4 shows C51's predictions in Space Invaders at a moment when three of the six actions (those that fire the laser) release it too early and lead to losing the game: their distributions put substantial probability on a return of 0, next to a second mode of higher returns for surviving. As a concrete version, suppose an action ends the game with probability 0.3 (return 0) and otherwise leads to a return of about 8. Its value is 0.3⋅0+0.7⋅8=5.60.3 \cdot 0 + 0.7 \cdot 8 = 5.6, a return the agent never receives. DQN's network is trained toward 5.6; C51's is trained toward the two separate outcomes and their probabilities.

The distribution describes randomness in the return itself, not the agent's uncertainty about its estimate. Section 3.3 of the paper says ZπZ^\pi describes "the intrinsic randomness of the agent's interactions with its environment, rather than some measure of uncertainty about the environment itself."

The distributional Bellman equation

Remove the expectations from Bellman's equation and the same recursion holds for the random return:

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

The symbol =D\overset{D}{=} means equality in distribution: the left side and the right side are random variables with the same probability law, not the same value on every run. The right side combines three independent sources of randomness: the reward RR, the random next state and action (X′,A′)(X', A'), and the return Z(X′,A′)Z(X', A') from there on. Taking the expectation of both sides gives back the ordinary equation for QQ.

A worked case: the reward is always 1, there is one possible next state, and its return is 0 with probability 0.3 and 8 with probability 0.7. With γ=0.9\gamma = 0.9 the return here is 1+0.9⋅0=11 + 0.9 \cdot 0 = 1 with probability 0.3 and 1+0.9⋅8=8.21 + 0.9 \cdot 8 = 8.2 with probability 0.7. Its mean, 6.04, equals 1+0.9×5.61 + 0.9 \times 5.6, as the ordinary Bellman equation requires, but the distribution keeps both outcomes.

The paper writes the update as two operators. The transition operator PπP^\pi replaces the return at (x,a)(x, a) with the return at a random next state-action pair, and the distributional Bellman operator Tπ\mathcal{T}^\pi discounts that and adds the reward:

PπZ(x,a):=DZ(X′,A′),X′∼P(⋅∣x,a),  A′∼π(⋅∣X′)P^\pi Z(x,a) \overset{D}{:=} Z(X', A'), \quad X' \sim P(\cdot \mid x, a),\; A' \sim \pi(\cdot \mid X')PπZ(x,a):=DZ(X′,A′),X′∼P(⋅∣x,a),  A′∼π(⋅∣X′)\begin{gathered} P^\pi Z(x,a) \overset{D}{:=} Z(X', A'), \\ X' \sim P(\cdot \mid x, a),\; A' \sim \pi(\cdot \mid X') \end{gathered}
(4)
TπZ(x,a):=DR(x,a)+γ PπZ(x,a)\mathcal{T}^\pi Z(x,a) \overset{D}{:=} R(x,a) + \gamma\, P^\pi Z(x,a)
(5)

Read as an operation on a histogram, (5) does three things in order: mix the return distributions of the possible next states (weighted by how likely each is), multiply every return by γ\gamma (which squeezes the distribution toward 0), and add the reward (which shifts it, or blurs it if the reward is random). The paper's Figure 1 draws these stages, and Figure 3 below lets you step through them. Section 3 of the paper asks whether applying Tπ\mathcal{T}^\pi over and over, starting from any guess, ends at the true return distribution ZπZ^\pi.

Why distributional policy evaluation converges

The ordinary Bellman operator converges because it is a contraction: for any two value functions, one application shrinks the largest gap between them by a factor γ\gamma. Banach's fixed-point theorem then gives a unique fixed point, and the gap to it falls like γk\gamma^k after kk applications. To say the same of distributions, the paper needs a distance between distributions under which Tπ\mathcal{T}^\pi shrinks things, and the choice of distance decides whether the statement is true.

The distance it uses is the Wasserstein metric. For two distributions on the real line with cumulative distribution functions (CDFs) FF and GG, line up their quantiles and average the gaps:

dp(F,G)=(∫01∣F−1(u)−G−1(u)∣p du)1/pd_p(F, G) = \Big( \int_0^1 \big| F^{-1}(u) - G^{-1}(u) \big|^p \, du \Big)^{1/p}dp(F,G)=(∫01∣F−1(u)−G−1(u)∣p du)1/p\begin{aligned} d_p(F, G) &= \Big( \int_0^1 \big| F^{-1}(u) \\ &\qquad - G^{-1}(u) \big|^p \, du \Big)^{1/p} \end{aligned}

In this formula F−1(u)F^{-1}(u) is the uu-quantile, the return below which a fraction uu of the probability lies. For p=1p = 1 this equals the area between the two CDFs. Think of each distribution as a pile of sand along the return axis: d1d_1 is the least average distance the sand has to travel to turn one pile into the other (hence its other name, earth mover's distance). The picture stops working for p>1p > 1, where long moves are penalized more than in proportion to their length. Two point masses at 0 and 0.01 are 0.01 apart in d1d_1. In total variation (the largest difference in probability the two assign to any event) they are 1 apart, the maximum, and the KL divergence (the expected log-ratio of the two probabilities) is infinite, because each puts all its mass where the other puts none.

A value distribution has one return distribution per state-action pair, so the paper takes the worst case over pairs, the maximal Wasserstein metric:

dˉp(Z1,Z2):=sup⁡x,a dp(Z1(x,a), Z2(x,a))\bar d_p(Z_1, Z_2) := \sup_{x,a}\, d_p\big(Z_1(x,a),\, Z_2(x,a)\big)

Lemma 3 states that the policy-evaluation operator contracts it by γ\gamma:

dˉp(TπZ1,TπZ2)≤γ dˉp(Z1,Z2)\bar d_p(\mathcal{T}^\pi Z_1, \mathcal{T}^\pi Z_2) \le \gamma\, \bar d_p(Z_1, Z_2)

The proof uses two properties of dpd_p. Multiplying both distributions by a constant multiplies the distance by at most that constant's size (property P1), because every quantile gap scales by the same amount. Adding the same independent random variable to both cannot increase the distance (property P2), because shifting both piles of sand by the same random amount does not make them harder to match. Apply P2 to the reward and P1 to γ\gamma, and the distance at (x,a)(x, a) is at most γ\gamma times the distance between the two next-step distributions PπZ1(x,a)P^\pi Z_1(x,a) and PπZ2(x,a)P^\pi Z_2(x,a). Each of those is a mixture of the same next state-action pairs with the same weights, so their distance is at most the worst case over all pairs, dˉp(Z1,Z2)\bar d_p(Z_1, Z_2). Banach's theorem then gives a unique fixed point, ZπZ^\pi, reached from any starting guess with bounded moments.

Figure 1 runs this on the smallest possible process: one state, a reward of 0 or 1 by a fair coin, and discount γ\gamma. One guess starts as a point mass at 0, the other as a point mass near the largest possible return. Each application doubles the number of atoms. Watch the shaded area between the CDFs, which is d1d_1, and the readouts for total variation and KL.

Figure 1 · two guesses under repeated Bellman updates
0
0.70
Press Play or drag k to apply the operator again; drag γ to change the discount. The second guess is always the first shifted by γk\gamma^k times the starting gap, so d1d_1 falls by exactly γ\gamma per step. At γ=0.5\gamma = 0.5 both converge to the uniform distribution on [0, 2]; at γ=0\gamma = 0 they coincide after one step.

The two guesses approach each other in Wasserstein distance at rate γ\gamma, while total variation stays at 1 and KL stays infinite for every kk: their atoms never coincide, so by those measures they are as far apart as two distributions can be. The paper's remark that Tπ\mathcal{T}^\pi is not a contraction in total variation (shown by Chung and Sobel in 1987), KL divergence, or Kolmogorov distance (the largest vertical gap between two CDFs) refers to this behaviour.

The paper also tracks the moments. The mean contracts by γ\gamma (it is the ordinary Bellman operator), and the variance contracts by γ2\gamma^2, a result of Sobel (1982): with the reward independent of the next return, the variance of R+γZ′R + \gamma Z' is VR+γ2 VZ′\mathbb{V}R + \gamma^2\, \mathbb{V}Z'. Higher centered moments are not contracted at each step, but the paper shows they still converge exponentially fast.

Why greedy (control) updates can fail to converge

Policy evaluation fixes π\pi. Control looks for the best policy, and Q-learning does it with a max over next actions. The paper calls any operator that picks a greedy policy with respect to the mean, and then applies that policy's Tπ\mathcal{T}^\pi, a distributional Bellman optimality operator:

TZ=TπZfor some π∈GZ\mathcal{T} Z = \mathcal{T}^\pi Z \quad \text{for some } \pi \in \mathcal{G}_Z

where GZ\mathcal{G}_Z is the set of policies that, in every state, choose an action with the largest E Z(x,a)\mathbb{E}\, Z(x, a). Lemma 4 shows the means still behave: the largest gap between the means of two iterates shrinks by γ\gamma per application, so EZk→Q∗\mathbb{E} Z_k \to Q^* exponentially fast, as in Q-learning.

The distributions need not converge with them. Proposition 1 shows T\mathcal{T} is not a contraction with a two-state example (the paper's Figure 2). State x1x_1 always moves to x2x_2 with no reward. At x2x_2, action a1a_1 ends the episode with reward 0, and action a2a_2 ends it with reward ϵ+1\epsilon + 1 or ϵ−1\epsilon - 1, each with probability 1/2. For small ϵ>0\epsilon > 0, a2a_2 has the higher mean and is optimal, so the optimal distributions Z∗(x1)Z^*(x_1) and Z∗(x2,a2)Z^*(x_2, a_2) are both ϵ±1\epsilon \pm 1. Now take a guess ZZ that equals Z∗Z^* everywhere except Z(x2,a2)=−ϵ±1Z(x_2, a_2) = -\epsilon \pm 1. Its distance to Z∗Z^* is the cost of sliding both atoms by 2ϵ2\epsilon:

dˉ1(Z,Z∗)=d1(Z(x2,a2), Z∗(x2,a2))=2ϵ\bar d_1(Z, Z^*) = d_1\big(Z(x_2,a_2),\, Z^*(x_2,a_2)\big) = 2\epsilondˉ1(Z,Z∗)=d1(Z(x2,a2), Z∗(x2,a2))=2ϵ\begin{aligned} \bar d_1(Z, Z^*) &= d_1\big(Z(x_2,a_2),\, Z^*(x_2,a_2)\big) \\ &= 2\epsilon \end{aligned}

When T\mathcal{T} is applied to ZZ, the greedy choice at x2x_2 uses the means under ZZ: action a2a_2 has mean −ϵ-\epsilon, below a1a_1's 0, so it picks a1a_1 and the new TZ(x1)\mathcal{T}Z(x_1) becomes the point mass at 0. Its distance to Z∗(x1)=ϵ±1Z^*(x_1) = \epsilon \pm 1 is the cost of moving half the mass to ϵ+1\epsilon + 1 and half to ϵ−1\epsilon - 1:

d1(TZ(x1), Z∗(x1))=12∣1−ϵ∣+12∣1+ϵ∣=1d_1\big(\mathcal{T}Z(x_1),\, Z^*(x_1)\big) = \tfrac12 |1 - \epsilon| + \tfrac12 |1 + \epsilon| = 1d1(TZ(x1), Z∗(x1))=12∣1−ϵ∣+12∣1+ϵ∣=1\begin{aligned} d_1\big(\mathcal{T}Z(x_1),\, Z^*(x_1)\big) &= \tfrac12 |1 - \epsilon| + \tfrac12 |1 + \epsilon| \\ &= 1 \end{aligned}

For ϵ<1/2\epsilon < 1/2 that is larger than 2ϵ2\epsilon, so one application moved ZZ further from Z∗Z^*. With ϵ=0.1\epsilon = 0.1 the distance goes from 0.2 to 1. The example is undiscounted; with γ<1\gamma < 1 the same construction shows the operator is not a contraction. The mean gap meanwhile goes from 0.2 to 0.1, as Lemma 4 requires.

Figure 2 · the paper's two-state counterexample
0.10
1
Teal bars are the iterate ZkZ_k at each of the three state-action entries, dashed amber outlines are Z∗Z^*. Drag ε and k, or click a pair of bars. The teal bar is the distance between full distributions, the amber bar the distance between means. At ε = 0 the two actions tie and the tie-break rule of Proposition 2 alternates forever.

In the figure the distribution distance jumps to 1 at k=1k = 1 and then drops to 0, because the second application uses a2a_2's updated distribution (mean +ϵ+\epsilon), so the greedy choice switches back to a2a_2. Set ϵ=0\epsilon = 0 and both actions have mean 0. Proposition 2 uses a tie-break that picks a2a_2 if Z(x1)Z(x_1) is the point mass at 0 and a1a_1 otherwise; the iterates at x1x_1 then alternate between the two distributions forever, so that operator has no fixed point, while every mean stays at 0.

Theorem 1 gives what does hold: with finitely many actions, the iterates approach, state by state, the set of nonstationary optimal value distributions, the return distributions of following a sequence of optimal policies that may change from step to step. Such a sequence can produce a distribution no single policy produces. The appendix's example has one state and two optimal actions with γ=1/2\gamma = 1/2: a1a_1 pays 1/2, a2a_2 pays 0 or 1 by a fair coin. Taking a1a_1 forever returns 12(1+12+14+⋯ )=1\tfrac12 (1 + \tfrac12 + \tfrac14 + \cdots) = 1. Taking a2a_2 forever returns R0+R1/2+R2/4+⋯R_0 + R_1/2 + R_2/4 + \cdots, a binary expansion with random digits, which is uniform on [0, 2]. Taking a1a_1 once and then a2a_2 returns 12+12U\tfrac12 + \tfrac12 U with UU uniform on [0, 2], uniform on [1/2, 3/2], which no fixed mix of the two actions produces. The paper reads this as a symptom of the instability of greedy updates generally, and leaves open whether it matters in practice.

How C51 works: 51 atoms and a projection

A neural network cannot output an arbitrary distribution, so the paper fixes a grid of returns and learns probabilities on it. With NN atoms between VMINV_{\text{MIN}} and VMAXV_{\text{MAX}}:

zi=VMIN+i Δz,Δz=VMAX−VMINN−1,0≤i<Nz_i = V_{\text{MIN}} + i\,\Delta z, \qquad \Delta z = \frac{V_{\text{MAX}} - V_{\text{MIN}}}{N - 1}, \qquad 0 \le i < Nzi=VMIN+i Δz,Δz=VMAX−VMINN−1,0≤i<N\begin{gathered} z_i = V_{\text{MIN}} + i\,\Delta z, \\ \Delta z = \frac{V_{\text{MAX}} - V_{\text{MIN}}}{N - 1}, \qquad 0 \le i < N \end{gathered}
Zθ(x,a)=zi   with probability   pi(x,a)=eθi(x,a)∑jeθj(x,a)Z_\theta(x,a) = z_i \;\text{ with probability }\; p_i(x,a) = \frac{e^{\theta_i(x,a)}}{\sum_j e^{\theta_j(x,a)}}Zθ(x,a)=zi   with probability pi(x,a)=eθi(x,a)∑jeθj(x,a)\begin{gathered} Z_\theta(x,a) = z_i \;\text{ with probability } \\ p_i(x,a) = \frac{e^{\theta_i(x,a)}}{\sum_j e^{\theta_j(x,a)}} \end{gathered}

C51 uses N=51N = 51, VMAX=−VMIN=10V_{\text{MAX}} = -V_{\text{MIN}} = 10, so Δz=0.4\Delta z = 0.4 and the atoms are −10, −9.6, …, 9.6, 10. A discrete distribution on a fixed grid is a softmax classifier over 51 classes, which is easy to train and can represent several modes; earlier work had modeled the return as a Gaussian, which has one. The network is DQN's: three convolutional layers and a 512-unit fully connected layer on a stack of four 84×84 frames. Only the output layer changes, from one number per action to 51 logits (unnormalized scores) per action, followed by a softmax over each action's 51, which turns them into probabilities that sum to 1. For a batch of 32 states and the full 18-action set the output has shape (32, 18, 51), and the final layer grows from 9,234 to 470,934 parameters (2.16 million in the whole network against DQN's 1.69 million). The agent still acts ε-greedily (it takes the action with the highest mean, except with probability ε, when it acts at random), with the mean computed from each action's distribution:

Q(x,a)=∑i=0N−1zi pi(x,a)Q(x,a) = \sum_{i=0}^{N-1} z_i\, p_i(x,a)

The grid creates a problem for the Bellman update. Moving atom zjz_j to r+γzjr + \gamma z_j almost never lands on another grid point, so the target and the model have disjoint supports and cannot be compared atom by atom. C51 projects the moved atoms back onto the grid. Each moved atom, clipped to [VMIN,VMAX][V_{\text{MIN}}, V_{\text{MAX}}], gives its probability to the two grid atoms on either side of it, in proportion to how close it is to each. The paper writes this as its Eq. (7), for a sampled transition (x,a,r,x′)(x, a, r, x') and the greedy next action π(x′)\pi(x'):

(ΦT^Zθ(x,a))i=∑j=0N−1[1−∣[T^zj]VMINVMAX−zi∣Δz]01 pj(x′,π(x′))\big(\Phi \hat{\mathcal{T}} Z_\theta(x,a)\big)_i = \sum_{j=0}^{N-1} \Big[ 1 - \frac{\big| [\hat{\mathcal{T}} z_j]_{V_{\text{MIN}}}^{V_{\text{MAX}}} - z_i \big|}{\Delta z} \Big]_0^1 \, p_j\big(x', \pi(x')\big)(ΦT^Zθ(x,a))i=∑j=0N−1[1−∣[T^zj]VMINVMAX−zi∣Δz]01pj(x′,π(x′))\begin{aligned} \big(\Phi \hat{\mathcal{T}} Z_\theta(x,a)\big)_i &= \sum_{j=0}^{N-1} \Big[ 1 - \frac{\big| [\hat{\mathcal{T}} z_j]_{V_{\text{MIN}}}^{V_{\text{MAX}}} - z_i \big|}{\Delta z} \Big]_0^1 \\ &\qquad p_j\big(x', \pi(x')\big) \end{aligned}
(7)

In (7), T^zj=r+γzj\hat{\mathcal{T}} z_j = r + \gamma z_j is the moved atom and [⋅]ab[\cdot]_a^b clips to [a,b][a, b]. The bracketed weight is a triangle centered on grid atom ziz_i: 1 when the moved atom sits exactly on ziz_i, falling linearly to 0 one grid step away. Only the two grid atoms within Δz\Delta z of a moved atom get any of its probability, and their two weights add to 1. The split is the expectation of stochastic rounding: round the value to one of its two neighbours at random, with each neighbour's chance proportional to closeness, and record the average outcome rather than one draw. The analogy is exact for the mean, which stochastic rounding preserves, and stops there; the projection is deterministic.

With r=1r = 1, γ=0.99\gamma = 0.99, take the atom zj=4.0z_j = 4.0. It moves to 1+0.99×4.0=4.961 + 0.99 \times 4.0 = 4.96, which is 37.4 grid steps above −10, between z37=4.8z_{37} = 4.8 and z38=5.2z_{38} = 5.2. Atom 37 gets 60% of its probability and atom 38 gets 40%, and 0.6×4.8+0.4×5.2=4.960.6 \times 4.8 + 0.4 \times 5.2 = 4.96: the split keeps the moved atom's position as its mean. The top atoms behave differently. z=9.2z = 9.2 moves to 10.108 and is clipped to 10, as are 9.6 and 10.0, so all three put their full probability on the +10 atom and the target's mean drops below the true r+γEZr + \gamma \mathbb{E}Z. Clipping is the only place the projection changes the mean.

Rowland et al. (2018) later showed that this heuristic split is exactly the orthogonal projection onto the grid distributions under the Cramér distance, the L2L_2 distance between CDFs, and that the projected operator is a γ\sqrt{\gamma}-contraction in that distance. The projection breaks Lemma 3's Wasserstein contraction (for p>1p > 1), so the Cramér result covers the algorithm actually run, in the policy-evaluation case.

Figure 3 runs the four stages of the update on a two-mode next-state distribution. Step through the tabs, then try the edges: γ=0\gamma = 0 (a terminal transition, where every atom collapses onto rr), N=2N = 2 (the paper's one-parameter "Bernoulli" variant), and large rr with γ\gamma near 1, where mass piles up on the +10 atom.

Figure 3 · discount, shift, project
0.90
1.0
11
The tabs step through the paper's Figure 1: amber spikes are atoms of the next-state distribution as they move, teal bars are the projected target on the grid (ticks). Sliders set the discount, the reward and the number of atoms. Algorithm 1 as printed recomputes the projection with the paper's floor/ceiling loop; red dashed outlines mark probability it drops.

The default view (11 atoms, γ=0.9\gamma = 0.9, r=1r = 1) already shows the floor/ceiling problem when the toggle is on. Algorithm 1 in the paper computes the split with bj=(T^zj−VMIN)/Δzb_j = (\hat{\mathcal{T}} z_j - V_{\text{MIN}})/\Delta z, l=⌊bj⌋l = \lfloor b_j \rfloor, u=⌈bj⌉u = \lceil b_j \rceil, and adds pj(u−bj)p_j (u - b_j) to atom ll and pj(bj−l)p_j (b_j - l) to atom uu. When the moved atom lands exactly on a grid point, bjb_j is a whole number, l=ul = u, and both shares are 0. Here the top atom moves to 1+0.9×10=101 + 0.9 \times 10 = 10 exactly and its probability vanishes. With the paper's 51 atoms the same happens to every atom clipped to ±10, and on a terminal transition with reward 0 every atom moves to 0 (index 25), the whole target is zero, and that transition contributes no gradient. Eq. (7) has no such case, and Dopamine's C51 computes it directly.

Why the loss is cross-entropy, not the Wasserstein distance

With the target projected onto the grid, C51 minimizes the cross-entropy between the projected target m=ΦT^Zθ~(x,a)m = \Phi \hat{\mathcal{T}} Z_{\tilde\theta}(x, a), computed with a frozen copy θ~\tilde\theta of the parameters (DQN's target network), and the model's prediction:

Lx,a(θ)=−∑i=0N−1milog⁡pi(x,a)\mathcal{L}_{x,a}(\theta) = -\sum_{i=0}^{N-1} m_i \log p_i(x, a)

This is DKL(m ∥ p)D_{\text{KL}}(m \,\|\, p) minus the entropy of mm, which does not depend on θ\theta, so the two have the same gradient. With respect to the logits that gradient is p−mp - m, the same as for any softmax classifier. Section 3 measured everything in Wasserstein distance, which also handles distributions on different supports, so minimizing dpd_p directly looks like the natural loss. The paper rules it out because training sees one sampled transition at a time.

A sampled transition gives one reward and one next state, so its target r+γZ(x′)r + \gamma Z(x') is one component of the mixture over all possible next states that the true target TZ\mathcal{T}Z is. The projection is linear in the distribution it projects, and cross-entropy is linear in its target, so averaging the per-sample loss over transitions gives the loss against the projected mixture, and stochastic gradients point the right way on average. The Wasserstein distance is not linear in its arguments. Lemma 7 shows the expected per-sample distance is an upper bound on the true distance, strict in general, with a different gradient. Its example: the target returns 0 or 1 with probability 1/2 each, and the model returns 0 with probability pp and 1 otherwise. The true distance is ∣p−1/2∣|p - 1/2|, minimized at p=1/2p = 1/2. A sample of 0 gives distance 1−p1 - p, a sample of 1 gives pp, and their average is 1/2 for every pp, so the expected sampled loss is the same at every pp.

Figure 4 · sampled Wasserstein loss against cross-entropy
1500
Left (top on phones): the true d1d_1 (dashed) and the expected sampled loss (flat amber line) as functions of pp; dots mark where each learner currently sits. Right: four runs of each learner on the same stream of samples, starting at p=0.2p = 0.2. Press Play or drag the step slider.

The cross-entropy runs settle around p=0.5p = 0.5 within a few hundred steps and then fluctuate within about 0.1 of it. The Wasserstein runs take a step up for every 0 and a step down for every 1, a random walk with no drift, and end wherever the walk leaves them: at step 1,500 the four sit at 0.74, 0.66, 0.32 and 0.07, against 0.48 to 0.54 for the cross-entropy runs. Appendix D of the paper reports the same in a gridworld (CliffWalk): minimizing the sampled Wasserstein loss by stochastic gradient descent converged to distributions that missed the Monte Carlo ground truth, while the categorical algorithm tracked its variance. The follow-up work went two ways. Bellemare and coauthors proposed the Cramér distance, which has unbiased sample gradients. QR-DQN (Dabney et al., 2017) fixed the probabilities and learned the atom positions with quantile regression (a loss whose minimizer is a chosen quantile of the target), whose sample gradients are unbiased and whose minimizer is the 1-Wasserstein projection.

One training step in code

Below is NumPy-style pseudocode for one minibatch update, following Eq. (7) rather than Algorithm 1's floor/ceiling loop; the comments carry the shapes.

# One C51 update. B = 32 transitions (x, a, r, x_next, done), A actions, N = 51.
z  = np.linspace(-10.0, 10.0, 51)                  # the support, dz = 0.4
dz = z[1] - z[0]

# --- target: target network (parameters theta~), no gradient ---
p_next = softmax(target_net(x_next), axis=-1)      # (B, A, N)
q_next = (p_next * z).sum(-1)                      # (B, A) expected returns
a_star = q_next.argmax(-1)                         # (B,)  greedy on the mean
p_star = p_next[np.arange(B), a_star]              # (B, N)

g  = gamma * (1.0 - done)                          # (B,)  0 on terminal steps
tz = np.clip(r[:, None] + g[:, None] * z, -10.0, 10.0)   # (B, N) moved atoms
# Eq. (7): moved atom j gives grid atom i the weight max(0, 1 - |tz_j - z_i|/dz)
w  = np.clip(1 - np.abs(tz[:, None, :] - z[None, :, None]) / dz, 0, 1)  # (B,N,N)
m  = (w * p_star[:, None, :]).sum(-1)              # (B, N), each row sums to 1

# --- loss: gradient reaches theta only through log p(x, a) ---
logits = online_net(x)[np.arange(B), a]            # (B, N)
loss = -(m * log_softmax(logits, axis=-1)).sum(-1).mean()

The target uses the target network both to pick the next action by its mean and to supply that action's distribution, as in DQN (not the separate selection of Double DQN). The (B,N,N)(B, N, N) weight tensor is the simplest way to write Eq. (7); Algorithm 1 does the same work in O(N)O(N) per transition by touching only two atoms for each moved atom. The rest of the training setup is DQN's, with one change: Adam replaces RMSProp, with step size 0.00025 (DQN's) and Adam's epsilon set to 0.01/32≈3.1×10−40.01/32 \approx 3.1 \times 10^{-4}. That epsilon and VMAXV_{\text{MAX}} were the two hyperparameters tuned, on five training games: VMAX∈{3,10,100}V_{\text{MAX}} \in \{3, 10, 100\} and five epsilons from 1/321/32 down to 0.0001/320.0001/32.

With N=2N = 2 the grid is just −10 and +10, and the projected target is a single probability on +10 equal to (E[[T^Z]−1010]+10)/20(\mathbb{E}\big[[\hat{\mathcal{T}} Z]_{-10}^{10}\big] + 10)/20, the mean of the moved atoms after each is clipped to [−10, 10] as in Eq. 7. The paper calls this the Bernoulli algorithm. A two-atom distribution is fixed by its mean, so it models nothing beyond the value; the change from DQN is the loss (cross-entropy on a bounded scale instead of squared error).

Results on 57 Atari games

The paper first varied the number of atoms on five training games (Asterix, Breakout, Pong, Q*Bert and Seaquest), with exploration ϵ=0.05\epsilon = 0.05. Performance rose with the atom count, 5 to 11 to 21 to 51, and the 51-atom agent beat DQN on all five; the Bernoulli variant beat DQN on 3 of the 5. On Seaquest the 51-atom agent set a new state of the art.

For the full evaluation the paper used ϵ=0.01\epsilon = 0.01 in training, evaluated with ϵ=0.001\epsilon = 0.001 every million frames, and reported each agent's best evaluation score during training over 200 million frames, on 57 games. Scores are normalized so that 0% is a random agent and 100% is the human baseline:

score=100×agent−randomhuman−random %\text{score} = 100 \times \frac{\text{agent} - \text{random}}{\text{human} - \text{random}}\,\%

The median over games is the more stable summary, because a few games normalize to thousands of percent and dominate the mean.

Figure 5 · Atari results
Summary: the paper's Figure 6, by metric. Per game: human-normalized scores of DQN and C51 from the appendix table, games sorted by C51's score, log scale; click a column or drag the slider to read one game.

C51's median is 178%, against 79% for DQN and 172% for the best earlier combination (prioritized replay with a dueling network). It scores above the human baseline on 40 of 57 games (DQN: 24) and above DQN on 50. The mean is 701%; the camera-ready version printed 1010% because Atlantis episodes had been allowed to run past the standard 30-minute cap, and an erratum corrected it. The per-game view shows where the gains are large. On Seaquest C51 scores 266,434 against DQN's 5,860.6, about 45 times as much and six times the human baseline. On Private Eye and Venture, games with sparse rewards, DQN reaches 0% and 14% of the human baseline and C51 reaches 22% and 128%. The paper suggests value distributions propagate rarely occurring events better.

The paper reports two more results. Averaged over 3 seeds, C51 beat a fully trained DQN (200 million frames) on 45 of 57 games within its first 50 million frames; the paper calls this comparison more representative of an agent's average performance. A best score over many evaluations is biased upward for any agent whose score fluctuates during training. On a version of the Atari emulator with "sticky actions", which ignores the agent's chosen action with probability 0.25 on each frame, C51 improved on DQN by 126% in mean and 21.5% in median, on a scale where 0% is random and 100% is DQN.

In Pong the exact frame on which a point is scored depends on internal state the agent cannot see, and C51's distribution kept two modes over five consecutive frames: the agent cannot tell whether the reward has arrived, and because its input does not include past rewards it keeps part of the prediction even after receiving it. The paper also found many distributions close to Gaussian despite the emulator being deterministic, which it attributes to discretizing "the diffusion process induced by γ\gamma".

Why a distribution helps an agent that still maximizes the mean

C51 picks actions the way DQN does, by the mean, so the distribution can only matter through learning. The paper states its position as "learning distributions matters in the presence of approximation" and offers five possible reasons, as hypotheses:

Lyle, Castro and Bellemare (2019) asked when distributional RL can behave differently from expected RL at all. In many tabular and linear settings they proved that the two produce the same behaviour, and that where they differ in those settings the distributional version can perform worse; they then compared the two with neural networks to locate where the gains come from. Both findings fit the paper's claim that the distribution matters through approximation. The distributional loss went on to become one of the six components of Rainbow, which uses this paper's 51 atoms on [−10, 10] and its projection.

Provenance Verified against primary literatureHow we verify
Bellemare, Dabney & Munos (2017), Sec. 3Lemma 3: the policy-evaluation operator is a gamma-contraction in the maximal Wasserstein metric, proved from properties P1 (scaling) and P2 (adding an independent variable). Not a contraction in total variation (Chung & Sobel 1987), KL or Kolmogorov distance. Lemma 4: means contract under the greedy operator; Proposition 1: distributions need not (two-state example, distance 2 eps becomes 1).
Same paper, Sec. 4, Algorithm 1, App. CN = 51 atoms on [-10, 10], so dz = 0.4; probabilities by softmax; projection Eq. (7); loss is the cross-entropy term of KL(projected target || model). Adam with step size 0.00025 and epsilon 0.01/L, L = 32; V_MAX chosen from {3, 10, 100} and the Adam epsilon from five values on the five training games. Terminal transitions use gamma_t = 0.
Same paper, App. B, Lemma 7 and Prop. 5The expected sample Wasserstein loss upper-bounds the true Wasserstein loss, in general strictly, and the gradients differ. Worked example: a fair 0/1 target gives |p - 1/2| for the true loss and 1/2 for the expected sample loss at every p.
Same paper, Fig. 6, Fig. 14 and erratumFig. 6: C51 mean 701% (the camera-ready said 1010% before Atlantis was capped at 30 minutes), median 178%, 40 games above the human baseline, 50 above DQN. Normalising the Fig. 14 raw scores with its random and human columns reproduces every median and both counts exactly (DQN 79%, C51 178%; 24 and 40 above human; 50 above DQN). The means do not reproduce (Video Pinball alone normalises to 66,148% for C51).
Rowland et al. (2018)The categorical projection is the orthogonal projection in the Cramer distance (an L2 distance between CDFs). The projected policy-evaluation operator is a sqrt(gamma)-contraction in that distance, and is in general not a contraction in d_p for p > 1. Proves convergence of sample-based categorical policy evaluation.
Dopamine (google/dopamine), JAX Rainbow agentNo official code accompanied the paper. dopamine/jax/agents/rainbow/rainbow_agent.py lines 493-533 (project_distribution) implement Eq. (7) directly, with no floor or ceiling; lines 104-145 (target_distribution) build r + gamma(1 - terminal) z and take the next-state distribution of the action with the highest mean; dopamine/jax/networks.py lines 299-334 (RainbowNetwork) output num_actions x num_atoms logits after the Nature DQN torso. Its c51.gin uses Rainbow-matched settings (sticky actions, target update every 8,000 steps), not the paper's.
Lyle, Castro & Bellemare (2019)Proves that in many tabular and linear settings distributional RL behaves exactly like expected RL, and that where the two differ there it can hurt; then compares them empirically with non-linear approximators. Supports reading the paper's Sec. 6.1 reasons as hypotheses.
Numbering in the paperThe main text's Proposition 3 appears as Proposition 4 in the appendix, and the appendix reuses "Proposition 1" for Sobel's variance result.
correctionAlgorithm 1 does not compute Eq. (7) in every case. It sets l = floor(b_j), u = ceil(b_j) and adds p_j(u - b_j) to atom l and p_j(b_j - l) to atom u. When b_j is a whole number, l = u and both shares are 0, so atom j's probability disappears from the target. With 51 atoms on [-10, 10] this happens to every atom clipped to -10 or +10 (b = 0 or 50 exactly in floating point) and, on a terminal transition with reward 0, to every atom at once (all move to 0, b = 25), leaving an all-zero target and no gradient from that transition. Eq. (7) itself has no such case. This page teaches Eq. (7); Dopamine implements it directly, and the Kaixhin Rainbow code patches the loop by moving l down or u up when they coincide. Separately, the erratum reports Atlantis at 5,199% of the human baseline; its own 841,075 points with the appendix table's random (12,850) and human (29,028.1) scores give 5,119%.

Questions you might still have

?

Does C51 use the distribution to choose actions, for example to avoid risky ones?
No. It picks actions epsilon-greedily on the mean of each action's distribution, exactly as DQN picks on Q. The paper leaves acting on the full distribution (risk-averse or risk-seeking choices) as future work. The distribution changes only what the network is trained to predict.

?

Is the learned distribution the agent's uncertainty about its value estimate?
No. It models the randomness of the return itself under the policy: rewards, transitions and the policy's own choices. An agent can be certain that a coin flip pays 0 or 1 and still predict a two-spike distribution. Uncertainty about the estimate (how much data backs it) is a separate quantity the paper does not model. In Atari, which is deterministic, the randomness comes from state aliasing, the changing policy and approximation error.

?

Why 51 atoms?
The paper ran 5, 11, 21 and 51 atoms on five training games, found performance rose with the count, and kept 51. At 51 atoms the TensorFlow implementation trained at about 75% of DQN's speed. The 51 values with dz = 0.4 between -10 and 10 are fixed; only their probabilities are learned.

?

What happens to returns above 10 or below -10?
They are clipped onto the end atoms, so the support cannot represent them and the learned mean is biased toward zero for states whose return exceeds 10. With rewards clipped to [-1, 1] and gamma = 0.99, a return could in principle reach 100. The paper chose V_MAX = 10 over 3 and 100 on its training games and reports that clipping DQN's values in a similar way made it worse on most games.

?

Does the convergence theory cover the algorithm that was run on Atari?
No. Lemma 3 covers exact policy evaluation with no projection. C51 adds a greedy policy (which Section 3.4 shows can fail to converge), a projection onto 51 atoms, sampled transitions and a neural network. Rowland et al. (2018) later proved convergence for sample-based categorical policy evaluation, in the Cramer distance rather than Wasserstein. The control case with function approximation has no guarantee.

?

How does QR-DQN differ from C51?
QR-DQN (Dabney et al., 2017) swaps what is fixed: the probabilities are fixed at 1/N each and the network learns where the N atoms sit, as quantiles of the return. Quantile regression has unbiased sample gradients and its minimizer is the 1-Wasserstein projection, so QR-DQN minimizes the metric the theory uses and needs no V_MIN or V_MAX.

?

Is the projection used outside distributional RL?
The same split of a value between its two neighbouring grid points, followed by a cross-entropy loss, is how DreamerV3 trains its reward and value heads (its "twohot" target). The DreamerV3 explainer covers that use.

Footnotes & further reading

  1. The paper: Bellemare, Dabney & Munos, A Distributional Perspective on Reinforcement Learning (ICML 2017). The arXiv version includes the erratum on the mean score and the appendix with proofs, the CliffWalk comparison and per-game scores.
  2. DQN: Mnih et al., Human-level control through deep reinforcement learning (Nature 2015), whose architecture and training regime C51 reuses; the earlier workshop version is covered in the DQN explainer.
  3. Rowland, Bellemare, Dabney, Munos & Teh, An Analysis of Categorical Distributional Reinforcement Learning (AISTATS 2018): the Cramér-distance analysis and convergence proof for the categorical algorithm.
  4. Bellemare et al., The Cramer Distance as a Solution to Biased Wasserstein Gradients (2017), and Dabney, Rowland, Bellemare & Munos, Distributional Reinforcement Learning with Quantile Regression (AAAI 2018), the QR-DQN paper.
  5. Lyle, Castro & Bellemare, A Comparative Analysis of Expected and Distributional Reinforcement Learning (AAAI 2019).
  6. Reference implementations: Dopamine's rainbow_agent.py (C51 is its Rainbow agent with uniform replay and one-step targets) and the Kaixhin/Rainbow PyTorch code, whose projection patches Algorithm 1's floor/ceiling case. The same projection appears in the Rainbow explainer, and its two-neighbour split as the twohot target in the DreamerV3 explainer.