Distributional RL: learning the return distribution
Learn the full return distribution rather than only expected value. Study the distributional Bellman operator and its Wasserstein contraction, categorical (C51), quantile (QR-DQN) and implicit (IQN) representations, risk-sensitive policies with CVaR, and the now-central large-network idea of learning values as classification (two-hot, HL-Gauss), also used in MuZero and DreamerV3.
After this lesson you can
- Define the distributional Bellman operator and prove its contraction for evaluation.
- Implement C51 categorical projection and QR-DQN quantile Huber loss.
- Construct risk-sensitive policies with IQN and CVaR and discuss time consistency.
- Train value functions as classification with two-hot or HL-Gauss targets.
- Explain why learning the distribution can improve even the mean.
Before you start
- 22Deep Q-NetworkHuber TD lossRainbowBellman operator contractionRisk attitude and certainty equivalent
- 07Cross-entropyKullback-Leibler divergence (relative entropy)
- 04Wasserstein distance
- 19Wasserstein GAN
- 28Value at RiskExpected Shortfall
- 11Regression loss functionsStatistical functional elicited by a loss
A mean does not tell the whole story
Imagine two routes with the same expected return: one always yields zero, the other −1 or 1 with equal probability. A risk-neutral decision maker sees the same mean. Someone needing to avoid losses does not. Even if maximizing only the mean, learning distribution shape can change the signals used to train a shared representation.
The distribution studied is that of random return under a policy: it captures randomness in rewards, transitions and future actions. It is not automatically a distribution of epistemic uncertainty over unknown parameters. This distinction matters: collecting more data can reduce the latter but need not eliminate the former.
Preparing policy comparison.
A tail measure expresses a preference the mean misses. Under the return convention, lower CVaR at level is
If there is an atom at the boundary, only the necessary fraction of its mass is taken. Thus for returns −10 with probability 0.05 and 2 with probability 0.95, lower 10% CVaR is . Mean return is 1.4. The sign changes under the usual loss rather than return convention.
Bellman for laws, not only expectations
Fix a stationary policy in a discounted MDP with . Assume bounded rewards and uniformly bounded moments of order for the laws compared. Write for a family of distributions over . The distributional evaluation operator is defined by the law
Reward and next state are sampled jointly where appropriate; conditioned on the transition, the future sample is drawn from the law associated with . Its expectation recovers the usual Bellman operator. Equality is between distributions, not between a sample and its mean.
To measure distance between two families use . Then is a contraction with factor . The proof shows exactly where it comes from:
- For the same initial pair, couple both updates using the same transition, reward and next action.
- Conditioned on each next pair, couple both future variables with cost arbitrarily close to between their laws. The common reward cancels in the difference.
- This coupling’s cost is at most . Optimal distance does not exceed the cost of a particular coupling. Taking root and supremum gives
For general spaces measurable selection of approximate couplings must be guaranteed; a finite MDP has no such difficulty. The contraction identifies a fixed evaluation law under these assumptions. It does not assert a neural network trained on samples converges, or replace Wasserstein with KL. The result and evaluation–control distinction appear in Bellemare, Dabney and Munos.
Control selects the highest-mean action. Selection can switch abruptly between actions with nearly tied means even if their distributions have very different shapes. One action might be nearly deterministic and the other distribute mass between extremes: a small mean perturbation changes which law propagates. The distributional control operator is not generally a contraction in maximum Wasserstein distance. Scalar control-operator contraction does not guarantee contraction of the full distribution.
C51: move atoms and return them to the support
In C51 a network assigns probabilities to fixed equally spaced positions , . The Bellman target transforms each atom to , where denotes true terminal. First clip to the support interval. Then distribute mass between lower and upper neighbors in proportion to distance. If it lands exactly on an atom, deposit all mass there; an implementation multiplying both weights by zero loses it.
Preparing categorical projection.
Projection preserves mass. Without clipping it also preserves each atom’s mean by linear interpolation; with clipping the mean can change. External truncation does not automatically imply zero future return: retain the final observation and decide bootstrap according to the modeled horizon.
The network is fitted with cross-entropy to the projected distribution, equivalent to minimizing the parameter-dependent part of . This does not mean every step directly minimizes : they are different objectives. Categorical projection has evaluation contraction properties in a Cramér metric under the assumptions studied by Rowland and colleagues; this is not a general deep-control guarantee.
Quantiles instead of fixed probabilities
For laws on the line with finite first moment, is the area between their quantile functions:
QR-DQN fixes masses at and learns locations . For , target sample and error , pinball loss is . Its expectation is minimized at a quantile, possibly with an interval of minimizers if the distribution has a flat region.
The quantile Huber version uses
Losses are averaged over every predicted quantile and target atom, with implementation-declared normalization. Smoothing changes the objective near zero: do not promise that exactly recovers the same quantiles as pinball for every distribution. The relationship between quantile projection and is developed in QR-DQN.
Preparing samples and quantile fit.
IQN learns a function and samples levels rather than restricting them to a fixed set. With uniform , averaging outputs estimates the mean; sampling in estimates lower CVaR if the learned function correctly represents the quantile function. An unconstrained network may produce crossings: sorting outputs on a grid corrects that estimate, not proves the underlying function monotonic. IQN studies policies from distorting the level distribution.
Risk and sequential decisions
Risk optimization requires specifying what variable is evaluated and when. Total-return CVaR computed initially may prefer a policy whose later plan is no longer optimal when reevaluated at the same level after observing a state. This time inconsistency prevents simply applying a scalar Bellman operator maximizing local CVaR at every step. Suitable dynamic formulations or state augmentation with necessary risk information are needed; greedy selection on an IQN approximation alone does not guarantee the initial-CVaR optimum.
A policy choosing remains risk-neutral even if the network represents a full distribution. Attributing gains to risk requires changing and evaluating the decision rule while controlling environment, data and budget.
Value as classification and learning signals
Classifying a scalar target is related but distinct from modeling the return law. With two-hot, a scalar target is interpolated between the two neighboring support centers; cross-entropy trains logits. HL-Gauss spreads mass across multiple bins using a Gaussian around the target. Comparison requires declaring bounds, bin width, scale and tail handling. The weighted mean of centers supplies a scalar prediction.
Farebrother and colleagues compare these losses against regression and C51: online RL uses 60 Atari games and 200 million training frames, summarized by human-normalized IQM and 95% bootstrap intervals. In that aggregate comparison HL-Gauss exceeds alternatives despite not modeling the full return distribution. This is evidence that parametrization and loss can help, not proof of a universal cause or superiority in every game. MuZero and DreamerV3 also use categorical representations for scalar quantities, with their own transformations and details not to confuse with C51.
The neuroscience link is an experimental hypothesis, not an identity between neurons and algorithms. Dabney and colleagues observe heterogeneous dopamine responses consistent with a distributional code; their model connects to asymmetric expectile regression. It does not identify each neuron as an IQN quantile.
Lab: a chain whose law we can calculate
First build a reference without a neural network. State is 0 or 1; from each state reward is Bernoulli with probability 0.2 or 0.7 respectively, and next state equals reward. The episode lasts six steps and . Enumerate sequences with probabilities, simulate Monte Carlo, and propagate categorical and quantile approximations. The reference is exact up to floating-point rounding and describes only this finite horizon.
import numpy as np
gamma, horizon = .8, 6
probability = np.array([.2, .7])
support = np.linspace(0., 1/(1-gamma), 51)
levels = (np.arange(51)+.5)/51
def exact(state, remaining):
if remaining == 0:
return np.array([0.]), np.array([1.])
values, weights = [], []
for reward in (0, 1):
child, child_weight = exact(reward, remaining-1)
chance = probability[state] if reward else 1-probability[state]
values.extend(reward+gamma*child)
weights.extend(chance*child_weight)
return np.array(values), np.array(weights)
def project(values, weights, grid):
spacing = grid[1]-grid[0]
position = np.clip((np.clip(values, grid[0], grid[-1])-grid[0])/spacing, 0, len(grid)-1)
lower = np.floor(position).astype(int)
upper = np.ceil(position).astype(int)
result = np.zeros(len(grid))
same = lower == upper
np.add.at(result, lower[same], weights[same])
np.add.at(result, lower[~same], weights[~same]*(upper[~same]-position[~same]))
np.add.at(result, upper[~same], weights[~same]*(position[~same]-lower[~same]))
return result
def weighted_quantiles(values, weights, qs):
order = np.argsort(values)
cumulative = np.cumsum(weights[order])
cumulative[-1] = 1.0
return values[order][np.searchsorted(cumulative, qs, side='left')]
def w1(values_a, weights_a, values_b, weights_b):
# Integra |F_a(x)-F_b(x)| entre todos los saltos de las CDF.
points = np.unique(np.r_[values_a, values_b])
if len(points) < 2:
return 0.
def cdf(values, weights):
order = np.argsort(values)
x, w = values[order], weights[order]
prefix = np.r_[0., np.cumsum(w)]
return prefix[np.searchsorted(x, points[:-1], side='right')]
return float(np.sum(np.abs(cdf(values_a, weights_a)-cdf(values_b, weights_b))*np.diff(points)))
categorical = np.zeros((2, len(support)))
categorical[:, 0] = 1.
quantiles = np.zeros((2, len(levels)))
uniform = np.full(len(levels), 1/len(levels))
for _ in range(horizon):
cat_next = np.empty_like(categorical)
quant_next = np.empty_like(quantiles)
for state in (0, 1):
p = probability[state]
cat_values = np.r_[gamma*support, 1+gamma*support]
cat_weights = np.r_[(1-p)*categorical[0], p*categorical[1]]
cat_next[state] = project(cat_values, cat_weights, support)
q_values = np.r_[gamma*quantiles[0], 1+gamma*quantiles[1]]
q_weights = np.r_[(1-p)*uniform, p*uniform]
quant_next[state] = weighted_quantiles(q_values, q_weights, levels)
categorical, quantiles = cat_next, quant_next
reference, reference_weights = exact(0, horizon)
assert np.isclose(reference_weights.sum(), 1.)
assert np.allclose(categorical.sum(axis=1), 1.)
rng = np.random.default_rng(2216)
count = 20_000
state = np.zeros(count, dtype=int)
returns = np.zeros(count)
for t in range(horizon):
reward = (rng.random(count) < probability[state]).astype(int)
returns += gamma**t*reward
state = reward
print('Media exacta:', np.dot(reference, reference_weights))
print('Media Monte Carlo:', returns.mean())
print('W1 Monte Carlo:', w1(reference, reference_weights, returns, np.full(count, 1/count)))
print('W1 categórica:', w1(reference, reference_weights, support, categorical[0]))
print('W1 cuantílica:', w1(reference, reference_weights, quantiles[0], uniform))
print('Masa categórica y masa de referencia:', categorical[0].sum(), reference_weights.sum())Categorical and quantile representations approximate a distribution after each application: their errors propagate. Comparing one Monte Carlo seed does not establish a general method ranking or reproduce neural-network training.
In this supervised problem the conditional mean is known: is uniform on , and observed target is , with uniform on and independent. Thus . Training and evaluation use different samples and seeds. Two linear logit classifiers on the same three features learn by gradient descent: one receives two-hot labels, the other HL-Gauss. Scalar output is their centers’ mean, not a claim the learned categorical distribution is the law of or a Bellman return distribution.
import math
import numpy as np
def draw(seed, n):
random = np.random.default_rng(seed)
x = random.uniform(-1., 1., n)
true_mean = 1.1*x + .4*(x*x - 1/3)
y = true_mean + random.uniform(-.18, .18, n)
features = np.stack([np.ones(n), x, x*x - 1/3], axis=1)
return features, y, true_mean
train_x, train_y, train_mean = draw(2216, 256)
test_x, test_y, test_mean = draw(2217, 256)
centers = np.linspace(-2., 2., 41)
width = centers[1]-centers[0]
sigma = width
assert train_y.min() > centers[0] and train_y.max() < centers[-1]
assert test_y.min() > centers[0] and test_y.max() < centers[-1]
def two_hot(y):
position = np.clip((y-centers[0])/width, 0, len(centers)-1)
low = np.floor(position).astype(int)
high = np.minimum(low+1, len(centers)-1)
frac = position-low
result = np.zeros((len(y),len(centers)))
rows = np.arange(len(y))
np.add.at(result, (rows,low), 1-frac)
np.add.at(result, (rows,high), frac)
return result
def hl_gauss(y):
# 41 centros y 42 bordes; integra la gaussiana y normaliza en ese rango.
edges = np.r_[centers[0]-width/2, centers+width/2]
cdf = np.array([[.5*(1+math.erf((edge-value)/(sigma*math.sqrt(2))))
for edge in edges] for value in y])
mass = np.diff(cdf,axis=1)
return mass/mass.sum(axis=1,keepdims=True)
def softmax(logits):
e = np.exp(logits-logits.max(axis=1,keepdims=True))
return e/e.sum(axis=1,keepdims=True)
def metrics(features, observed, true_mean, weights):
predicted = softmax(features@weights)@centers
return {'mse_mean':float(np.mean((predicted-true_mean)**2)),
'mse_observed':float(np.mean((predicted-observed)**2)),
'mae_mean':float(np.mean(np.abs(predicted-true_mean)))}
def train(labels):
weights = np.zeros((train_x.shape[1],len(centers)))
initial = metrics(test_x,test_y,test_mean,weights)
learning_rate, steps = 4., 240
for _ in range(steps):
probability = softmax(train_x@weights)
# Gradiente de la entropía cruzada media para logits lineales.
gradient = train_x.T@(probability-labels)/len(train_x)
weights -= learning_rate*gradient
return initial, metrics(test_x,test_y,test_mean,weights), weights
labels_two = two_hot(train_y)
labels_gauss = hl_gauss(train_y)
assert np.allclose(labels_two.sum(axis=1),1.)
assert np.allclose(labels_two@centers,train_y)
assert np.allclose(labels_gauss.sum(axis=1),1.)
assert np.all(labels_gauss>=0.)
print('Train/test: 256/256; semillas: 2216/2217; centros:',len(centers),
'sigma/ancho:',round(sigma/width,2))
for name, labels in [('two-hot',labels_two),('HL-Gauss',labels_gauss)]:
initial, final, weights = train(labels)
assert np.isfinite(weights).all() and final['mse_mean']<initial['mse_mean']
print(name, '| MSE contra media condicional, antes/después:',
round(initial['mse_mean'],6),round(final['mse_mean'],6),
'| MSE contra observaciones test:',round(final['mse_observed'],6),
'| MAE contra media condicional:',round(final['mae_mean'],6))The conditional mean is known because we defined the mechanism; in real data it normally is unavailable and held-out observations would be needed. Gaussian smoothing integrates mass per bin and renormalizes on the finite range; near boundaries it can shift the decoded mean. Cross-entropy of labels with different entropies is not a common metric for comparing the scalar error of both models. Improvement in this simulation does not demonstrate general superiority in RL or large networks. Construction follows Farebrother and colleagues, with explicit custom parameters and data.
The next experiment learns an implicit quantile function per action for a one-step bandit. The safe action returns −7; risky returns −20 with probability 0.1 and −5 otherwise. Both distributions are known, allowing comparison with exact mean and lower CVaR. This model uses cosine features and a linear output to keep computation small; it has no deep network or Bellman target and does not demonstrate sequential-control optimality.
Each update samples uniform τ levels and an independent return for each action. A quantile Huber loss with κ=0.5 is minimized. To evaluate risk, output is averaged over lower-tail levels; if the learned function crosses or is nonmonotonic, that integral is a distorted reading of its outputs and not necessarily CVaR of a valid distribution. The program counts crossings and does not assume the network learns the correct policy.
import numpy as np
seed = 221605
random = np.random.default_rng(seed)
features = 16
batch = 128
updates = 1200
learning_rate = .3
kappa = .5
def cosine(tau):
"""Base fija: 1, cos(πτ), ..., cos(15πτ)."""
tau = np.asarray(tau, dtype=np.float64)
return np.cos(np.pi * tau[:, None] * np.arange(features)[None, :])
def quantile_huber(u, tau, kappa):
magnitude = np.abs(u)
huber = np.where(magnitude <= kappa, .5*u*u, kappa*(magnitude-.5*kappa))
return np.abs(tau - (u < 0)) * huber / kappa
def gradient_prediction(u, tau, kappa):
# u = retorno − predicción; derivada respecto de la predicción.
return -np.abs(tau - (u < 0)) * np.clip(u, -kappa, kappa) / kappa
def exact_risky(alpha):
bad = min(.1, alpha)
return (-20*bad - 5*(alpha-bad)) / alpha
# Prueba de derivada en ambas ramas y comprobación de los CVaR discretos.
for target, prediction, tau_value in [(-2., .2, .2), (3., .1, .8), (.2, .1, .6)]:
eps = 1e-6
finite = (quantile_huber(target-(prediction+eps), tau_value, kappa)
- quantile_huber(target-(prediction-eps), tau_value, kappa)) / (2*eps)
assert np.isclose(finite, gradient_prediction(target-prediction, tau_value, kappa), atol=1e-8)
assert np.isclose(exact_risky(.1), -20.)
assert np.isclose(exact_risky(.5), -8.)
assert np.isclose(exact_risky(1.), -6.5)
weights = np.zeros((2, features), dtype=np.float64)
for iteration in range(updates):
taus = random.random(batch)
phi = cosine(taus)
# Se supervisan ambas acciones con distribuciones conocidas, no con una política exploratoria.
returns = np.column_stack((np.full(batch, -7.),
np.where(random.random(batch) < .1, -20., -5.)))
predictions = np.sum(phi[:, None, :] * weights[None, :, :], axis=2)
residual = returns - predictions
grad_q = gradient_prediction(residual, taus[:, None], kappa)
grad_w = np.mean(phi[:, None, :] * grad_q[:, :, None], axis=0)
weights -= learning_rate * grad_w
if not np.isfinite(weights).all(): raise FloatingPointError('Parámetros no finitos')
# Cuadratura determinista en puntos medios, común a todas las comparaciones.
def tail_estimate(alpha, count=512):
taus = alpha * (np.arange(count, dtype=np.float64) + .5) / count
return np.mean(cosine(taus) @ weights.T, axis=0)
taus_grid = (np.arange(512, dtype=np.float64) + .5) / 512
predicted = cosine(taus_grid) @ weights.T
crossings = np.sum(np.diff(predicted, axis=0) < 0, axis=0)
print('Semilla:', seed, 'actualizaciones:', updates, 'base coseno:', features)
print('Descensos adyacentes en la malla de 512 τ, segura y arriesgada:', crossings.tolist())
for alpha in (.1, .5, 1.):
estimate = tail_estimate(alpha)
exact = np.array([-7., exact_risky(alpha)])
learned_action = 'arriesgada' if estimate[1] > estimate[0] else 'segura'
exact_action = 'arriesgada' if exact[1] > exact[0] else 'segura'
print('α =', alpha,
'| lectura de cola aprendida:', np.round(estimate, 3).tolist(),
'| CVaR exacto:', np.round(exact, 3).tolist(),
'| acción aprendida:', learned_action, '| acción exacta:', exact_action)Return CVaR uses the lower tail, including fractional mass of the boundary atom. The chosen action maximizes that tail mean; ties choose safe. When α=1 the exact criterion is expectation. IQN often combines a learned state representation with a cosine embedding of level τ; here fixed basis and supervised regression isolate only querying different levels. Sources: IQN and quantile Huber regression in RL.
This lab turns the previous lesson’s CartPole network into two self-contained distributional agents. Both use Double selection by distribution mean, uniform replay and a target network. C51 learns 51 probabilities on fixed support and QR-DQN learns 51 uniformly weighted locations. Location ordering is not forced: the report counts adjacent inversions and retains values in output order. Evaluation and actions are risk-neutral.
Both agents train from scratch with five common seeds in full mode; each has its own network and trajectories, so sharing a seed does not equalize data. They are evaluated without exploration in separate environments; for two episodes both actions and their distributions are saved at the initial state and first observation with pole angle at least 0.12 radians in absolute value, if reached before termination. A truncated episode’s return is what was observed until the limit. ORYON_QUICK=1 reduces budget to one seed and 300 interactions per agent to check the path; neither those steps nor absence of divergence demonstrates CartPole is solved. You run full training; the reduced test checks operation, not results.
import copy
import json
import os
import random
from pathlib import Path
import gymnasium as gym
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
quick = os.environ.get('ORYON_QUICK', '0') == '1'
out = Path(os.environ.get('ORYON_DISTRIBUTIONAL_OUT', 'oryon-distributional'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
gamma, atoms = .99, 51
support = torch.linspace(0., 100., atoms, device=device)
tau = (torch.arange(atoms, device=device, dtype=torch.float32) + .5) / atoms
def categorical_projection(prob, rewards, terminated, gamma, z):
"""Proyecta cada átomo desplazado sobre sus vecinos; acepta lotes (B,N)."""
n = z.numel()
dz = (z[-1]-z[0])/(n-1)
transformed = rewards[:, None] + gamma*(~terminated[:, None]).float()*z[None, :]
clipped = transformed.clamp(z[0], z[-1])
b = ((clipped-z[0])/dz).clamp(0, n-1)
lower, upper = b.floor().long(), b.ceil().long()
equal = lower == upper
lower_weight = torch.where(equal, torch.ones_like(b), upper.float()-b)
upper_weight = torch.where(equal, torch.zeros_like(b), b-lower.float())
result = torch.zeros_like(prob)
result.scatter_add_(1, lower, prob*lower_weight)
result.scatter_add_(1, upper, prob*upper_weight)
return result
def quantile_huber(pred, target, levels, kappa=1.):
"""Media sobre predicciones y muestras objetivo; errores target−pred."""
u = target[:, None, :] - pred[:, :, None]
abs_u = u.abs()
huber = torch.where(abs_u <= kappa, .5*u.square(), kappa*(abs_u-.5*kappa))
asymmetric = (levels[None, :, None]-(u.detach()<0).float()).abs()
return (asymmetric*huber/kappa).mean()
def verify_math():
# Referencia de proyección por bucles, independiente de scatter_add_.
z = torch.tensor([0., 1., 2.], device=device)
prob = torch.tensor([[.2,.3,.5],[.1,.6,.3],[.4,.4,.2]], device=device)
reward = torch.tensor([.5, 1., 3.], device=device)
terminal = torch.tensor([False, True, False], device=device)
projected = categorical_projection(prob, reward, terminal, .5, z)
expected = torch.zeros_like(projected)
for i in range(3):
for j in range(3):
x = min(2., max(0., float(reward[i]) + (0. if terminal[i] else .5*float(z[j]))))
lo = int(np.floor(x)); hi = int(np.ceil(x)); p = float(prob[i,j])
if lo == hi: expected[i,lo] += p
else:
expected[i,lo] += p*(hi-x)
expected[i,hi] += p*(x-lo)
assert torch.allclose(projected, expected, atol=1e-6)
assert torch.allclose(projected.sum(1), torch.ones(3,device=device), atol=1e-6)
assert torch.allclose(projected[1], torch.tensor([0.,1.,0.],device=device))
assert torch.allclose(projected[2], torch.tensor([0.,0.,1.],device=device))
# El corte conserva bootstrap: solo el indicador de terminación entra en la proyección.
assert not torch.allclose(projected[0], categorical_projection(prob[:1], reward[:1],
torch.tensor([True],device=device), .5, z)[0])
pred = torch.tensor([[0., 1.]], device=device, requires_grad=True)
goal = torch.tensor([[0., 2.]], device=device)
levels = torch.tensor([.25,.75], device=device)
loss = quantile_huber(pred, goal, levels)
# Cuatro pares: 0, 0.375, 0.125, 0.375; media 0.21875.
assert torch.allclose(loss, torch.tensor(.21875,device=device))
loss.backward()
assert pred.grad is not None and torch.isfinite(pred.grad).all() and pred.grad.abs().sum()>0
print('Proyección: referencia, masa, bordes, terminal y corte; pérdida y gradiente: correctos')
class Replay:
def __init__(self, capacity, seed):
self.capacity, self.size, self.pos = capacity, 0, 0
self.obs = np.empty((capacity,4), np.float32)
self.nxt = np.empty_like(self.obs)
self.action = np.empty(capacity, np.int64)
self.reward = np.empty(capacity, np.float32)
self.terminated = np.empty(capacity, np.bool_)
self.truncated = np.empty(capacity, np.bool_)
self.rng = np.random.default_rng(seed)
def add(self, obs, action, reward, nxt, terminated, truncated):
i = self.pos
self.obs[i], self.action[i], self.reward[i], self.nxt[i] = obs, action, reward, nxt
self.terminated[i], self.truncated[i] = terminated, truncated
self.pos = (i+1)%self.capacity
self.size = min(self.size+1,self.capacity)
def sample(self, batch):
idx = self.rng.choice(self.size, batch, replace=False)
return tuple(torch.as_tensor(x[idx],device=device) for x in
(self.obs,self.action,self.reward,self.nxt,self.terminated,self.truncated))
class DistNet(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(4,64), nn.ReLU(), nn.Linear(64,64), nn.ReLU(),
nn.Linear(64,2*atoms))
def forward(self, x):
return self.net(x).reshape(-1,2,atoms)
def q_values(output, method):
if method == 'C51': return (output.softmax(-1)*support).sum(-1)
return output.mean(-1)
def update(online, target, optimizer, replay, method):
obs, actions, rewards, nxt, terminal, truncated = replay.sample(32)
logits = online(obs)
chosen = logits[torch.arange(actions.shape[0],device=device),actions]
with torch.no_grad():
next_actions = q_values(online(nxt), method).argmax(1)
target_output = target(nxt)[torch.arange(actions.shape[0],device=device),next_actions]
if method == 'C51':
next_prob = target_output.softmax(-1)
transformed = rewards[:,None]+gamma*(~terminal[:,None]).float()*support[None,:]
outside = ((transformed<support[0]) | (transformed>support[-1])).float()
outside_mass = (next_prob*outside).sum(1).mean().item()
desired = categorical_projection(next_prob,rewards,terminal,gamma,support)
else:
desired = rewards[:,None]+gamma*(~terminal[:,None]).float()*target_output
outside_mass = None
if method == 'C51':
loss = -(desired*F.log_softmax(chosen,-1)).sum(-1).mean()
else:
loss = quantile_huber(chosen,desired,tau)
if not torch.isfinite(loss): raise FloatingPointError('Pérdida no finita')
optimizer.zero_grad(set_to_none=True)
loss.backward()
if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in online.parameters()):
raise FloatingPointError('Gradiente no finito')
nn.utils.clip_grad_norm_(online.parameters(),10.)
optimizer.step()
return float(loss.detach()), outside_mass
def evaluate(net, method, seeds):
env = gym.make('CartPole-v1')
episodes, snapshots = [], []
def capture(obs, seed, label, step):
with torch.no_grad():
raw = net(torch.as_tensor(obs,device=device).unsqueeze(0))[0]
q = q_values(raw.unsqueeze(0),method)[0]
row = {'seed':seed,'kind':label,'step':step,'observation':obs.tolist(),
'action_means':q.cpu().tolist()}
if method == 'C51':
row['probabilities'] = raw.softmax(-1).cpu().tolist()
else:
row['quantiles_raw'] = raw.cpu().tolist()
row['adjacent_crossings'] = (raw[:,1:]<raw[:,:-1]).sum(-1).cpu().tolist()
snapshots.append(row)
try:
for episode, seed in enumerate(seeds):
obs, _ = env.reset(seed=seed)
if episode < 2: capture(obs,seed,'initial',0)
captured_tilt = False
score, disc_return, factor, length = 0., 0., 1., 0
while True:
if episode < 2 and not captured_tilt and abs(float(obs[2])) >= .12:
capture(obs,seed,'tilt_0_12_rad',length)
captured_tilt = True
with torch.no_grad():
x = torch.as_tensor(obs,device=device).unsqueeze(0)
action = int(q_values(net(x),method).argmax(1).item())
obs, reward, terminated, truncated, _ = env.step(action)
score += reward; disc_return += factor*reward; factor *= gamma; length += 1
if terminated or truncated: break
episodes.append({'seed':seed,'return':score,'discounted_finite_return':disc_return,
'steps':length,'terminated':bool(terminated),'truncated':bool(truncated)})
finally:
env.close()
return episodes, snapshots
def train(method, seed):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
rng = np.random.default_rng(seed+10)
env = gym.make('CartPole-v1')
obs, _ = env.reset(seed=seed)
online = DistNet().to(device); target = copy.deepcopy(online).eval()
optimizer = torch.optim.Adam(online.parameters(),lr=.0005)
replay = Replay(50000,seed+11)
steps, warmup, interval = (300,32,150) if quick else (50000,256,5000)
records, loss_values, clipping, updates, copies = [], [], [], 0, 0
target_period = 100 if quick else 500
try:
for t in range(steps):
epsilon = max(.05,1.-.95*t/max(1,int(steps*.6)))
if rng.random()<epsilon: action = int(rng.integers(2))
else:
with torch.no_grad():
action = int(q_values(online(torch.as_tensor(obs,device=device).unsqueeze(0)),method).argmax(1).item())
nxt, reward, terminated, truncated, _ = env.step(action)
# nxt es el estado final real, antes del reset, incluso en truncamiento.
replay.add(obs,action,reward,nxt,terminated,truncated)
if t>=warmup and t%4==0 and replay.size>=32:
loss, outside = update(online,target,optimizer,replay,method)
loss_values.append(loss); updates += 1
if outside is not None: clipping.append(outside)
if (t+1)%target_period==0:
target.load_state_dict(online.state_dict())
copies += 1
obs, _ = env.reset() if terminated or truncated else (nxt,{})
if (t+1)%interval==0 or t+1==steps:
seeds = [100000+1000*seed+i for i in range(3 if quick else 10)]
episodes, examples = evaluate(online,method,seeds)
records.append({'step':t+1,'updates':updates,'epsilon_train':epsilon,
'mean_loss_since_evaluation':float(np.mean(loss_values)) if loss_values else None,
'mean_c51_outside_mass':float(np.mean(clipping)) if clipping else None,
'episodes':episodes,'state_distributions':examples})
loss_values.clear(); clipping.clear()
assert copies > 0
return {'method':method,'seed':seed,'steps':steps,'updates':updates,
'target_copies':copies,'evaluations':records}
finally:
env.close()
del online, target, optimizer, replay
if torch.cuda.is_available(): torch.cuda.empty_cache()
verify_math()
seeds = [0] if quick else list(range(5))
results = [train(method,seed) for method in ('C51','QR-DQN') for seed in seeds]
report = {'quick':quick,'device':str(device),'torch':torch.__version__,'gymnasium':gym.__version__,
'environment':'CartPole-v1','seeds':seeds,'evaluation_seed_rule':'100000 + 1000 * train_seed + episode',
'evaluation_episodes':3 if quick else 10,'gamma':gamma,'atoms':atoms,
'c51_support':support.cpu().tolist(),'quantile_levels':tau.cpu().tolist(),
'configuration':{'steps_per_run':300 if quick else 50000,'warmup':32 if quick else 256,
'batch_size':32,'replay_capacity':50000,'update_frequency':4,
'target_period':100 if quick else 500,'learning_rate':.0005,'optimizer':'Adam',
'double_selection':True,'gradient_clip_norm':10.,
'epsilon_initial':1.,'epsilon_final':.05,'epsilon_fraction':.6,
'quantile_huber_kappa':1.,'loss_reduction':'media de pares de cuantiles'},
'results':results}
(out/'distributional-report.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
for row in results:
final = row['evaluations'][-1]
print(row['method'],'semilla',row['seed'],'retorno medio',
float(np.mean([e['return'] for e in final['episodes']])),
'actualizaciones',row['updates'],'masa fuera de soporte',final['mean_c51_outside_mass'])npm run lab and open the connection link.Initial tests compare projection against a loop, including exact atoms, clipping, termination and bootstrap at a cutoff, and check a hand-computed value and quantile-loss gradient. Projection uses the final state before reset; only terminated cancels bootstrap. Mass outside support is measured before projection on training minibatches: a clipping indicator, not environmental failure probability. Both networks’ values are learned estimates, not the exact return distribution. In QR-DQN, Huber smooths pinball and does not guarantee the exact quantile for every problem; division by and averaging all pairs fixes this implementation’s gradient scale. See C51 and QR-DQN.
Exercises
Step 1 of 3. Which variables are shared in coupling both updates?
import numpy as np
def categorical_projection(next_probs, rewards, dones, gamma, support):
pass
import numpy as np
observations = np.array([0., 2., 4.])
residual = observations - 2.
losses = residual * (.9 - (residual < 0))
example_mean = .05 * (-10.) + .95 * 2.
example_cvar = (.05 * (-10.) + .05 * 2.) / .1
exercise_cvar = (.04 * (-20.) + .06 * 5.) / .1
print('Pinball individual y media:', losses, losses.mean())
print('Ejemplo: media y CVaR inferior:', example_mean, example_cvar)
print('Ejercicio: CVaR inferior:', exercise_cvar)