AI Wiki中文/EN

Distributional reinforcement learning: predict more than the mean return

分布式价值强化学习

Compare equal means with different risks; project a return distribution onto five atoms without losing probability mass.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

An average of zero can hide two different worlds

One action always returns zero. Another returns −2 or +2 with equal probability. Both have expected return zero, but only the second varies. An ordinary Q value records their shared mean; a return distribution can retain the difference. “Distributional” here refers to the distribution of returns, not computation spread across machines.

Distributional reinforcement learning predicts that richer object. The categorical method associated with C51 places probability on a fixed grid of possible returns, chooses actions by their predicted mean, and learns from a projected target distribution. Representing spread does not by itself make the policy risk-sensitive: choosing the largest mean still uses a mean-based objective. Return distributions and categorical method

Read DQN, expectation and variance and cross-entropy first. This chapter derives a five-atom teaching version of the projection and fits one fixed target. The original C51 configuration used 51 atoms; five makes every moved probability visible in a hand calculation.

Five-atom projection preserves total mass and, without clipping, the transformed mean; it need not preserve variance. A terminal reward on an exact atom keeps all its mass.
Five-atom projection preserves total mass and, without clipping, the transformed mean; it need not preserve variance. A terminal reward on an exact atom keeps all its mass.

Move a distribution, then fit it back onto the grid

Under a policy pi, the discounted return is a random variable. Write Z-pi(s,a) for its distribution after starting from state s and action a:

Gt=∑k=0∞γkRt+k+1,Zπ(s,a)=DGt∣(St=s,At=a),Qπ(s,a)=E[Zπ(s,a)].G_t=\sum_{k=0}^{\infty}\gamma^k R_{t+k+1},\qquad Z^\pi(s,a)\overset{D}=G_t\mid(S_t=s,A_t=a),\qquad Q^\pi(s,a)=\mathbb E[Z^\pi(s,a)].

The equality marked D means equality in distribution. For bounded rewards and discount below one, the return is well defined; finite episodes admit their own conditions. Randomness can come from rewards, transitions and subsequent policy actions. This is not a posterior over unknown model parameters. Two agents may agree on the return distribution while being differently uncertain about how well they have estimated it.

The distributional Bellman relation for a fixed policy combines the immediate reward with a discounted next return:

(TπZ)(s,a)=DR+γZ(S′,A′),(R,S′)∼p(⋅∣s,a),A′∼π(⋅∣S′).(\mathcal T^\pi Z)(s,a)\overset{D}=R+\gamma Z(S',A'), \qquad (R,S')\sim p(\cdot\mid s,a),\quad A'\sim\pi(\cdot\mid S').

The next return is drawn according to the sampled next state and action; the reward and next state can be related through their joint transition law. The original paper establishes fixed-policy contraction in an appropriate maximal Wasserstein metric under its discount and moment conditions. The corresponding control operator does not simply inherit that result. Neither statement is a general convergence guarantee for a neural-network optimizer. Distributional operators

For categorical prediction, choose N equally spaced atoms between fixed endpoints. A network emits a logit for each action-atom pair; softmax supplies probabilities:

zi=Vmin⁡+iΔz,Δz=Vmax⁡−Vmin⁡N−1,i=0,…,N−1,pi(s,a)=eℓi(s,a)∑jeℓj(s,a),Q(s,a)=∑izipi(s,a).z_i=V_{\min}+i\Delta z,\quad \Delta z=\frac{V_{\max}-V_{\min}}{N-1},\quad i=0,\ldots,N-1, \qquad p_i(s,a)=\frac{e^{\ell_i(s,a)}}{\sum_j e^{\ell_j(s,a)}},\quad Q(s,a)=\sum_i z_i p_i(s,a).

In a mean-greedy control update, select a next action by its expected value, then obtain that action’s target probabilities. The original categorical construction and a combination with Double DQN can use different networks for this selection. Specify the choice when building an agent. Our standalone projection takes the next probabilities as input and performs no action selection. Categorical update Combined targets

For a sampled reward r and terminal indicator d, transform each next atom and clip it to the supported interval:

z^j=r+γ(1−d)zj,z~j=clip⁡(z^j,Vmin⁡,Vmax⁡),bj=z~j−Vmin⁡Δz.\widehat z_j=r+\gamma(1-d)z_j,\qquad \widetilde z_j=\operatorname{clip}(\widehat z_j,V_{\min},V_{\max}),\qquad b_j=\frac{\widetilde z_j-V_{\min}}{\Delta z}.

The transformed atom usually falls between grid points. Distribute its probability to its two neighbors using linear interpolation. One convenient formulation avoids losing mass when the position is an integer:

lj=⌊bj⌋,uj=min⁡(lj+1,N−1),fj=bj−lj,mi=∑jpj[(1−fj)1[i=lj]+fj1[i=uj]].l_j=\lfloor b_j\rfloor,\quad u_j=\min(l_j+1,N-1),\quad f_j=b_j-l_j, \qquad m_i=\sum_j p_j\left[(1-f_j)\mathbf1[i=l_j]+f_j\mathbf1[i=u_j]\right].

The two coefficients sum to one, so the projection preserves total probability. At an exact grid point, f is zero and all mass stays on that atom, including at the upper endpoint. An implementation that uses floor and ceiling and then adds only their differences must handle the equal-index case; otherwise both increments become zero. The paper’s triangular projection formula preserves the mass, even though a literal reading of those two pseudocode increments needs this endpoint repair. Projection equation 7 and algorithm 1

Within the unclipped interval, interpolation also preserves the transformed mean: the weighted average of neighboring atoms is the original position. It does not preserve every higher moment. Clipping itself can change even the mean.

Treat m as a fixed target. Cross-entropy and its logit gradient are:

L=−∑imilog⁡pi,∂L∂ℓi=pi−mi,L=H(m)+DKL(m∥p)≥H(m).L=-\sum_i m_i\log p_i,\qquad \frac{\partial L}{\partial\ell_i}=p_i-m_i,\qquad L=H(m)+D_{\mathrm{KL}}(m\Vert p)\geq H(m).

Use log-softmax arithmetic rather than clipping predicted probabilities before taking logs. Subtracting the largest logit stabilizes exponentiation without changing softmax. A finite extreme input whose differences overflow still lies outside this implementation’s representable domain and is rejected.

For our five atoms z=[−2,−1,0,1,2], start with half the mass on each endpoint. Reward 0.5 and discount 0.5 move those endpoints to −0.5 and 1.5. Each splits evenly across its neighbors:

p=(1/2,0,0,0,1/2) ⟶ m=(0,1/4,1/4,1/4,1/4),E[Z^]=E[Z~grid]=1/2,Var⁡(Z^)=1,Var⁡(Z~grid)=5/4.p=(1/2,0,0,0,1/2)\ \longrightarrow\ m=(0,1/4,1/4,1/4,1/4), \qquad \mathbb E[\widehat Z]=\mathbb E[\widetilde Z_{\mathrm{grid}}]=1/2, \quad \operatorname{Var}(\widehat Z)=1, \quad \operatorname{Var}(\widetilde Z_{\mathrm{grid}})=5/4.

Here the notation for the grid variable describes the projected distribution, not just the clipped endpoints. The mean is preserved and the variance grows. A point mass at zero has the same original mean as the endpoint mixture but original variance zero instead of four.

Check the mass before training the logits

The complete Python/NumPy program below checks equally spaced, increasing finite support and nonnegative unit probability mass. It handles terminal transitions by setting the future contribution to zero. Projection and statistics use the same five-atom support. The separate logit fit starts from five zeros and performs 1,000 steps of gradient descent with learning rate 0.1 against the fixed projected target.

"""Original small categorical return projection and logit learning, not full C51 training."""
import math
import numpy as np


def checked_distribution(atoms, probabilities):
    z, p = np.asarray(atoms, dtype=float), np.asarray(probabilities, dtype=float)
    if z.ndim != 1 or len(z) < 2 or p.shape != z.shape or not np.isfinite(z).all() or not np.isfinite(p).all():
        raise ValueError('Matching finite atom and probability vectors required')
    with np.errstate(over='ignore', invalid='ignore'):
        gaps = np.diff(z)
    if not np.isfinite(gaps).all() or np.any(gaps <= 0) or not np.allclose(gaps, gaps[0], rtol=1e-12, atol=0):
        raise ValueError('Strictly increasing equally spaced support required')
    if np.any(p < 0) or not math.isclose(float(p.sum()), 1., rel_tol=0, abs_tol=1e-12):
        raise ValueError('Nonnegative unit probability mass required')
    return z, p


def project(atoms, probabilities, reward, gamma, terminated=False):
    z, p = checked_distribution(atoms, probabilities)
    if not math.isfinite(reward) or not math.isfinite(gamma) or not 0 <= gamma <= 1 or type(terminated) is not bool:
        raise ValueError('Finite reward, valid discount and boolean terminal flag required')
    with np.errstate(over='ignore', invalid='ignore'):
        transformed = reward + (0. if terminated else gamma) * z
    if not np.isfinite(transformed).all():
        raise ValueError('Transformed support is not representable')
    clipped = np.clip(transformed, z[0], z[-1])
    positions = np.clip((clipped - z[0]) / (z[1] - z[0]), 0., len(z) - 1)
    out = np.zeros_like(p)
    for mass, b in zip(p, positions):
        lower = int(np.floor(b))
        upper = min(lower + 1, len(z) - 1)
        fraction = b - lower
        out[lower] += mass * (1 - fraction)
        out[upper] += mass * fraction
    return out


def loss_gradient(logits, target):
    logits, target = np.asarray(logits, dtype=float), np.asarray(target, dtype=float)
    if logits.ndim != 1 or not len(logits) or target.shape != logits.shape or not np.isfinite(logits).all():
        raise ValueError('Matching finite logit vector required')
    if not np.isfinite(target).all() or np.any(target < 0) or not math.isclose(float(target.sum()), 1., rel_tol=0, abs_tol=1e-12):
        raise ValueError('Unit target distribution required')
    with np.errstate(over='ignore', invalid='ignore'):
        shifted = logits - logits.max()
    if not np.isfinite(shifted).all():
        raise ValueError('Logit differences are not representable')
    logp = shifted - np.log(np.exp(shifted).sum())
    probabilities = np.exp(logp)
    return float(-target @ logp), probabilities - target, probabilities


def statistics(atoms, probabilities):
    z, p = checked_distribution(atoms, probabilities)
    mean = float(z @ p)
    return dict(mean=mean, variance=float(((z - mean) ** 2) @ p))


def demo():
    z = np.arange(-2., 3.)
    spread = np.array([.5, 0., 0., 0., .5])
    point = np.array([0., 0., 1., 0., 0.])
    shifted = project(z, spread, .5, .5)
    terminal = project(z, spread, 0., .9, terminated=True)
    clipped = project(z, spread, 3., .5)
    logits = np.zeros(5)
    first = loss_gradient(logits, shifted)[0]
    for _ in range(1000):
        _, gradient, _ = loss_gradient(logits, shifted)
        logits -= .1 * gradient
    loss, _, fitted = loss_gradient(logits, shifted)
    return dict(atoms=z.tolist(), spread=spread.tolist(), point=point.tolist(),
                spread_stats=statistics(z, spread), point_stats=statistics(z, point),
                projected=shifted.tolist(), projected_stats=statistics(z, shifted),
                transformed_unprojected_mean=.5, transformed_unprojected_variance=1.,
                terminal=terminal.tolist(), clipped=clipped.tolist(), clipped_stats=statistics(z, clipped),
                unclipped_mean=3., initial_cross_entropy=first, final_cross_entropy=loss,
                fitted_probabilities=fitted.tolist(), training_steps=1000,
                scope='Five-atom projection and fixed-target logit optimization; no Atari policy training or Bayesian parameter posterior.')


if __name__ == '__main__':
    import json
    print(json.dumps(demo(), indent=2, allow_nan=False))

The projected probabilities are [0,0.25,0.25,0.25,0.25], with mean 0.5 and variance 1.25. A terminal reward of zero becomes [0,0,1,0,0]. With reward 3 and discount 0.5, transformed endpoints are 2 and 4; clipping puts all mass at 2. Its mean is 2, whereas the unclipped mean is 3. Increasing the support range could avoid that particular clipping, but at fixed atom count it would also widen the grid spacing.

The fixed-target cross-entropy decreases from log(5), about 1.6094379, to about 1.3942149. The fitted probabilities are approximately [0.00788927,0.24802768,0.24802768,0.24802768,0.24802768]. The loss remains above target entropy log(4), as required. Finite logits keep every softmax probability positive, so exact zero mass on the first atom is approached rather than reached at this finite fit.

Projection costs O(N) time and O(N) working space: each input atom contributes to at most two outputs. Statistics, log-softmax and the fixed-target logit gradient are also O(N). A full agent with A actions predicts A×N logits and needs the encoder, replay, target network and action-selection costs in addition. This example implements none of that training loop; its tests compare projection with an independent triangular-basis matrix over 40 random cases and check the logit gradient by finite differences.

A distribution has a support and an interpretation

Too narrow a support piles probability at the endpoints and can distort action means. Too wide a support with too few atoms loses resolution. Projection may change variance even without clipping, so the spread of the learned categorical approximation is not an exact risk measurement by construction.

Return variability is also different from uncertainty caused by limited data or unknown parameters. A broad return distribution is not automatically low confidence in its estimated mean, and a narrow one is not proof that the model is correct. A risk-sensitive objective must say how it uses the distribution; merely choosing the largest mean does not do so.

Finally, the fixed-policy contraction result concerns a specified distributional operator and metric. Greedy control, fixed-grid projection, nonlinear approximation and optimization introduce additional questions. Our five-atom arithmetic cannot verify general learning convergence or the benchmark advantages reported by a full C51 agent. Theoretical scope

Where does the probability go?

  1. On the five-atom support, a terminal reward is exactly zero. What must the projected distribution be, even if the next distribution is spread out?

Answer: All mass goes to atom zero: [0,0,1,0,0]. Termination removes the future return. Because zero lies exactly on the grid, its probability must not disappear through an equal-floor-and-ceiling bug.

  1. Why does the reward-0.5, discount-0.5 example preserve mean 0.5 but change variance from 1 to 1.25?

Answer: Each transformed endpoint lies halfway between adjacent grid atoms. Splitting its mass preserves its location in expectation but adds a conditional interpolation variance of 0.25. Averaging those added variances raises total variance by 0.25.

  1. With reward 3 and discount 0.5, can projection preserve the unclipped mean 3 on a support ending at 2? What support change could avoid this clipping, and what is the tradeoff at fixed atom count?

Answer: No distribution supported entirely at or below 2 can have mean 3. Clipping transforms the two positions 2 and 4 into 2 and 2, producing a point mass at 2. This is a representational limit, not an optimizer failure. Extending the support to include both transformed positions 2 and 4 avoids this particular clipping; keeping the atom count fixed widens spacing and reduces resolution.

  1. A fixed target has mass 1/4 on four atoms. Should successful cross-entropy training drive the loss to zero? Does its spread describe a posterior over network parameters?

Answer: No to both. The lowest possible cross-entropy is its entropy log(4), obtained when predicted and target probabilities agree; zero would require a zero-entropy target. These probabilities describe return outcomes, not a Bayesian parameter posterior.

From an operator to a categorical learner

Bellemare, Dabney and Munos presented the distributional perspective at ICML 2017, PMLR volume 70, pages 449–458. This chapter draws on PDF pages 2–3, the left column of 4, and pages 5–6 for the operator’s scope, categorical method and projection. It does not reproduce the complete proofs, benchmark tables or ablations. The five-atom program is an original mechanism study. Original paper

Rainbow v1, dated October 6, 2017, combines a categorical distribution with other methods. Its PDF pages 2–3 explain the method-level relation and use KL loss for distributional priorities; they do not justify treating every replay priority as a scalar TD error. Continue with prioritized replay to separate the priority from the sampling probability and correction weight. Combination methods

Make a prediction, then check

On support[-2,-1,0,1,2], a terminal transition pays exactly0. Where should all projected mass go?

Choose one answer

Learning objectives

  • Distinguish a random return distribution from uncertainty about unknown model parameters.
  • Implement categorical projection and cross-entropy, preserving exact atoms and exposing support clipping.

Prerequisites & connections

Explore related knowledge →

References

  1. A Distributional Perspective on Reinforcement Learning — scoped categorical-method reading
    Marc G. Bellemare; Will Dabney; Rémi Munos · 2017
  2. Rainbow: Combining Improvements in Deep Reinforcement Learning — arXiv v1 methods
    Matteo Hessel; Joseph Modayil; Hado van Hasselt; Tom Schaul; Georg Ostrovski; Will Dabney; Dan Horgan; Bilal Piot; Mohammad Azar; David Silver · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: ICML2017, PMLR70:449–458. Read PDF2–3,4 left column,5–6; viewed6. Return distributions, fixed-policy contraction assumptions, categorical projection Eq7 and cross-entropy. Preserve exact-atom mass even when the printed Algorithm1 floor and ceiling coincide. No full proof or score audit. Selected2017-10-06v1, then under review for AAAI2018; not verified final2018 bytes. Read PDF2–3 methods: Double Q, PER, dueling mean, categorical softmax and integrated targets. Distributional Rainbow uses KL priority. No later full architecture, benchmark or ablation audit. 7 paired equations and four explained exercises. Checked return distribution versus parameter posterior, fixed-policy contraction scope versus control, categorical support/softmax, exact-atom and terminal mass, clipping and interpolation moments, cross-entropy/logit finite differences and entropy floor. Forty random projections match an independent triangular-basis oracle. Five-atom fixed-target optimization is not full C51/Atari or a neural convergence proof.

  • Checked return distribution versus parameter posterior, fixed-policy contraction scope versus control, categorical support/softmax, exact-atom and terminal mass, clipping and interpolation moments, cross-entropy/logit finite differences and entropy floor. Forty random projections match an independent triangular-basis oracle. Five-atom fixed-target optimization is not full C51/Atari or a neural convergence proof.
  • Four computed SVG variants per topic;14 numeric/geometry tests and24 current responsive cases passed. All eight selected current captures directly viewed. Two unchanged groups retain initial captures, two revised groups use new captures; actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.