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 LearningA 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:
- the return is a random variable, and the Bellman equation has a version for its distribution;
- for a fixed policy, repeated Bellman updates converge in the Wasserstein distance, and not in KL or total variation;
- with greedy action selection, a two-state example shows the distributions need not converge;
- the practical algorithm: 51 fixed return values, a projection onto them, and a cross-entropy loss;
- why the loss is a cross-entropy when the theory is stated in Wasserstein distance;
- 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 takes action , receives a reward, lands in a new state, and repeats. The return is the discounted sum of the rewards it collects, , with discount in DQN and C51: a reward 100 steps ahead counts as much as one received now. The paper writes for this return when the agent starts with in and follows policy afterwards, and for its expectation:
The return is random for three reasons: the reward can be random, the next state can be random, and the policy can choose randomly. averages all three away. Standard reinforcement learning works with because it satisfies Bellman's equation, which ties the value here to the value one step later:
DQN learns the optimal version of this, with a max over next actions, by regressing toward 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 , 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 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:
The symbol 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 , the random next state and action , and the return from there on. Taking the expectation of both sides gives back the ordinary equation for .
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 the return here is with probability 0.3 and with probability 0.7. Its mean, 6.04, equals , as the ordinary Bellman equation requires, but the distribution keeps both outcomes.
The paper writes the update as two operators. The transition operator replaces the return at with the return at a random next state-action pair, and the distributional Bellman operator discounts that and adds the reward:
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 (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 over and over, starting from any guess, ends at the true return distribution .
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 . Banach's fixed-point theorem then gives a unique fixed point, and the gap to it falls like after applications. To say the same of distributions, the paper needs a distance between distributions under which 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) and , line up their quantiles and average the gaps:
In this formula is the -quantile, the return below which a fraction of the probability lies. For this equals the area between the two CDFs. Think of each distribution as a pile of sand along the return axis: 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 , 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 . 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:
Lemma 3 states that the policy-evaluation operator contracts it by :
The proof uses two properties of . 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 , and the distance at is at most times the distance between the two next-step distributions and . 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, . Banach's theorem then gives a unique fixed point, , 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 . 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 , and the readouts for total variation and KL.
k to apply the operator again; drag γ to change the discount. The second guess is always the first shifted by times the starting gap, so falls by exactly per step. At both converge to the uniform distribution on [0, 2]; at they coincide after one step.The two guesses approach each other in Wasserstein distance at rate , while total variation stays at 1 and KL stays infinite for every : their atoms never coincide, so by those measures they are as far apart as two distributions can be. The paper's remark that 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 (it is the ordinary Bellman operator), and the variance contracts by , a result of Sobel (1982): with the reward independent of the next return, the variance of is . 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 . 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 , a distributional Bellman optimality operator:
where is the set of policies that, in every state, choose an action with the largest . Lemma 4 shows the means still behave: the largest gap between the means of two iterates shrinks by per application, so exponentially fast, as in Q-learning.
The distributions need not converge with them. Proposition 1 shows is not a contraction with a two-state example (the paper's Figure 2). State always moves to with no reward. At , action ends the episode with reward 0, and action ends it with reward or , each with probability 1/2. For small , has the higher mean and is optimal, so the optimal distributions and are both . Now take a guess that equals everywhere except . Its distance to is the cost of sliding both atoms by :
When is applied to , the greedy choice at uses the means under : action has mean , below 's 0, so it picks and the new becomes the point mass at 0. Its distance to is the cost of moving half the mass to and half to :
For that is larger than , so one application moved further from . With the distance goes from 0.2 to 1. The example is undiscounted; with 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.
ε 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 and then drops to 0, because the second application uses 's updated distribution (mean ), so the greedy choice switches back to . Set and both actions have mean 0. Proposition 2 uses a tie-break that picks if is the point mass at 0 and otherwise; the iterates at 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 : pays 1/2, pays 0 or 1 by a fair coin. Taking forever returns . Taking forever returns , a binary expansion with random digits, which is uniform on [0, 2]. Taking once and then returns with 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 atoms between and :
C51 uses , , so 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:
The grid creates a problem for the Bellman update. Moving atom to 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 , 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 and the greedy next action :
In (7), is the moved atom and clips to . The bracketed weight is a triangle centered on grid atom : 1 when the moved atom sits exactly on , falling linearly to 0 one grid step away. Only the two grid atoms within 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 , , take the atom . It moves to , which is 37.4 grid steps above −10, between and . Atom 37 gets 60% of its probability and atom 38 gets 40%, and : the split keeps the moved atom's position as its mean. The top atoms behave differently. 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 . 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 distance between CDFs, and that the projected operator is a -contraction in that distance. The projection breaks Lemma 3's Wasserstein contraction (for ), 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: (a terminal transition, where every atom collapses onto ), (the paper's one-parameter "Bernoulli" variant), and large with near 1, where mass piles up on the +10 atom.
The default view (11 atoms, , ) already shows the floor/ceiling problem when the toggle is on. Algorithm 1 in the paper computes the split with , , , and adds to atom and to atom . When the moved atom lands exactly on a grid point, is a whole number, , and both shares are 0. Here the top atom moves to 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 , computed with a frozen copy of the parameters (DQN's target network), and the model's prediction:
This is minus the entropy of , which does not depend on , so the two have the same gradient. With respect to the logits that gradient is , the same as for any softmax classifier. Section 3 measured everything in Wasserstein distance, which also handles distributions on different supports, so minimizing 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 is one component of the mixture over all possible next states that the true target 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 and 1 otherwise. The true distance is , minimized at . A sample of 0 gives distance , a sample of 1 gives , and their average is 1/2 for every , so the expected sampled loss is the same at every .
The cross-entropy runs settle around 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 weight tensor is the simplest way to write Eq. (7); Algorithm 1 does the same work in 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 . That epsilon and were the two hyperparameters tuned, on five training games: and five epsilons from down to .
With the grid is just −10 and +10, and the projected target is a single probability on +10 equal to , 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 . 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 in training, evaluated with 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:
The median over games is the more stable summary, because a few games normalize to thousands of percent and dominate the mean.
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 ".
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:
- Less chattering. Section 3.4 showed the greedy distributional update can oscillate. With function approximation this can keep the policy from converging, which Gordon (1995) called chattering; the paper suggests that gradient training on distributions averages the alternating targets instead.
- State aliasing. When different situations look identical to the network, as in the Pong example, their returns mix into one distribution, and modeling that distribution gives a more stable target than its mean.
- More predictions per state. 51 probabilities per action are extra prediction targets, related to the auxiliary tasks of UNREAL (Jaderberg et al., 2017), but tied directly to the return.
- A bounded support as an assumption. Treating every return above 10 as 10 changes the optimization problem. The paper reports that a similar clipping of DQN's values hurt it on most games.
- An easier loss. Cross-entropy between categorical distributions is easy to minimize; early tries with KL between continuous densities did not work.
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.
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
- 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.
- 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.
- 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.
- 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.
- Lyle, Castro & Bellemare, A Comparative Analysis of Expected and Distributional Reinforcement Learning (AAAI 2019).
- 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.
How could this explainer be improved? Found an error, or something unclear? I read every message.