Beyond DQN: dueling, prioritized replay, multi-step, noisy nets and Rainbow
Six independent ideas improving DQN and their combination in Rainbow, with attention to ablation evidence. Implement dueling, prioritized replay with a sum tree, n-step targets with off-policy corrections (Retrace and V-trace), and noisy nets; review data efficiency in Atari 100k (DER, SPR, BBF) and its battle against loss of plasticity.
After this lesson you can
- Implement dueling, prioritized replay, n-step targets and noisy nets as interchangeable components.
- Build a sum tree and correct prioritized-replay bias with importance weights.
- Explain off-policy bias in n-step targets and Retrace and V-trace corrections.
- Run and interpret a multi-seed ablation.
- Summarize components of data-efficient Atari 100k agents.
Before you start
Improving pieces does not mean adding their gains
A DQN update involves several decisions: which transition to retrieve, how to represent , how many steps to use in the target, and how to explore. We can change each part and observe its effect, but two changes may overlap or interfere. An ablation removing one component from a complete agent measures its contribution in that combination, not its universal value.
Rainbow brings together six ideas: Double DQN, prioritized replay, dueling architecture, multistep returns, distributional learning and noisy networks. Some can be studied separately; the full combination adds details such as projecting return distributions, not implemented simply by enabling dueling and priorities.
Dueling: sharing value between actions
A dueling architecture separates scalar output and outputs , aggregating them for example as
If instead we summed without restriction, adding a constant to and subtracting it from every advantage would leave unchanged. With centered aggregation, the aggregate value satisfies and centered advantage is . That is the uniform mean of Q outputs, not necessarily or maximum .
The mean centers the advantage entering , but raw outputs of branch still allow adding the same constant to every component without changing aggregation. Do not confuse this internal freedom with centered advantage, which is determined by . Wang and colleagues study information sharing between actions and show sensitivity maps on Enduro. These are absolute gradient magnitudes with respect to input frames; the advantage map corresponds to the highest-advantage action. They do not causally demonstrate which pixels the policy needs.
Choosing what to remember
Prioritized replay assigns greater probability to high-priority transitions. In the usual proportional variant, with ,
where is the number of valid entries. With uniform sampling is recovered; in the rank-based variant priority is defined by error rank, not direct magnitude. prevents zero priority and controls importance correction.
Sampling with replacement, for all entries and gives for fixed contributions . With the weighting is generally biased relative to that uniform mean; special cases such as uniform priorities have no such bias. Dividing all weights by a fixed global maximum changes update scale: it may help but is unnecessary for the unscaled identity. Dividing by the minibatch’s random maximum introduces a sample-dependent factor and generally does not preserve unbiasedness. Schaul and colleagues analyze priorities and correction.
A sum tree stores transformed priorities in leaves and their sums in internal nodes. To sample, take in the half-open interval : if is below the left sum, descend left; otherwise subtract it and descend right. Updating a leaf propagates the difference to the root. In a balanced tree both operations traverse logarithmic height.
Priorities often become stale between visits: normally they are recalculated for sampled transitions using the error available from the current update. The target network can legitimately form part of that target; the problem is failing to specify which error is used or confusing stale priorities with updated ones. In distributional Rainbow priority relates to discrepancy between distributions, not necessarily the absolute value of one scalar TD error.
Multiple steps under an old policy
Multistep targets propagate rewards before a one-step backup. But a buffer segment may have been generated by behavior differing from target policy : observed intermediate actions follow . Without correction the -step return is generally not an unbiased sample of the target. It can work well empirically, as replay studies show, without removing theoretical bias.
For the following convention, hold fixed during calculation and define and
The sum ends at true termination, when terminal is zero. The empty product equals one. An external cutoff needs correct bootstrap from the final state, not declaring the cutoff terminal. Trace coefficients control how much each future error contributes; for this convention and , examples are for full IS without additional decay, for its trace version, for Q(λ), for tree backup and for Retrace, with . Other texts absorb or shift indices: check definitions before comparing.
Coverage is required: if for a relevant pair, must be positive to form the ratio. Retrace clips coefficients, controlling contributions from large ratios, but run variance and error depend on the entire trajectory distribution. Munos and colleagues study the operator and convergence under tabular hypotheses; those results do not certify every network implementation.
V-trace, used in IMPALA, separately clips the ratio weighting each error and the ratio propagating the trace. With finite bound , its fixed point generally corresponds to an interpolated policy
when the denominator is positive. Clipping affects the evaluated policy; trace clipping affects propagation and proof conditions. The paper’s result requires, among other assumptions, thresholds and a positive lower bound on expected clipped ratio. Do not claim arbitrarily clipped V-trace evaluates exactly.
Learnable noise and Rainbow
In NoisyNet, a layer can parametrize and learn both and . In factorized noise, two random vectors generate a matrix by outer product after transformation . Noise changes outputs and produces state-dependent exploration; specify when it is resampled and how evaluation works. An additional -greedy policy changes the exploration mixture, but does not mathematically cancel the noise effect. See Fortunato and colleagues.
Rainbow combines those parts with distributional learning. Instead of approximating only the expectation, C51 represents a categorical distribution on fixed supports and projects the shifted discounted target onto them. The paper uses 51 atoms on , three-step returns, priority exponent and increasing from to . The original combination’s multistep return is not automatically a complete off-policy correction. Projection, support clipping and distributional priority are part of the algorithm; an ablation enabling only some pieces is a partial variant, not full Rainbow.
In Hessel and colleagues’ ablation, removing a Rainbow part measures its effect conditioned on the rest of the combination and studied protocol. According to the authors’ summary, the complete agent exceeded each variant without priorities or without multistep returns on 53 of 57 games by area under the learning curve; median curves use a five-point moving average. The protocol interrupted learning every million environment steps for evaluation over 500,000 frames. Contributions may interact; a game median does not determine which three parts are optimal for each game or budget. A small own curve must be identified as such and shown only when measurements exist.
Learning from fewer interactions
Data-efficient value RL combines intensive reuse, representation and measures against loss of plasticity. The Atari 100k protocol counts 100,000 agent actions; with fourfold repetition these are 400,000 emulator frames if all repetitions run. The usual benchmark includes 26 games. Environment version, sticky actions, seeds and normalization remain part of the result.
DER combines architecture and replay choices in one implementation; SPR adds a predictive loss for future representations; BBF studies larger networks and other choices for efficiency with few interactions. A high replay ratio may extract more from each transition but intensify overfitting or plasticity loss. Partial resets are a studied intervention, not proof of a single solution; Nikishin and colleagues investigate early-data bias and resets.
To read a cross-game table, distinguish human- and random-reference-normalized score from raw reward, and do not interchange mean, median and IQM. The median can depend heavily on a few games near the center; interquartile mean (IQM) averages after discarding extreme quartiles according to the stated aggregation procedure. Compare seed count and uncertainty, and do not mix versions with and without sticky actions without saying so. Protocol differences may exceed differences between agent variants.
Labs
A sum tree changes mass in logarithmic time and locates a prefix query without scanning all leaves. Here masses are already transformed priorities, e.g. . Zero means a leaf cannot be sampled. Each stratified batch divides the total interval into seven segments and samples uniformly in each; a particular batch position need not follow the full distribution, but average frequencies reproduce it in expectation. Samples from different segments are not identically distributed: uncertainty below uses each segment’s intersection with each leaf, not a fictitious binomial error.
import numpy as np
class SumTreeLab:
def __init__(self, capacity):
if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity < 1:
raise ValueError('Capacidad inválida')
self.n = capacity
self.base = 1 << (capacity-1).bit_length()
self.nodes = np.zeros(2*self.base, dtype=np.float64)
def total(self):
return float(self.nodes[1])
def update(self, i, mass):
if isinstance(i, bool) or not isinstance(i, int) or not 0 <= i < self.n:
raise ValueError('Índice inválido')
mass = float(mass)
if not np.isfinite(mass) or mass < 0 or mass > 1e12:
raise ValueError('Masa inválida')
node = self.base+i
self.nodes[node] = mass
while node > 1:
node //= 2
self.nodes[node] = self.nodes[2*node]+self.nodes[2*node+1]
def find(self, prefixes):
x = np.asarray(prefixes, dtype=np.float64).copy()
if x.ndim != 1 or self.total() <= 0 or not np.isfinite(x).all() or np.any(x < 0) or np.any(x >= self.total()):
raise ValueError('Consulta fuera de [0,total) o árbol vacío')
node = np.ones(x.shape, dtype=np.int64)
while np.any(node < self.base):
left = 2*node
mass = self.nodes[left]
right = x >= mass
x -= np.where(right, mass, 0.)
node = left+right.astype(np.int64)
# La resta puede redondearse al extremo superior del hijo.
x = np.minimum(x, np.nextafter(self.nodes[node], -np.inf))
return node-self.base
tree = SumTreeLab(5)
for i, mass in enumerate([0., 1., 2., 5., 8.]):
tree.update(i, mass)
assert tree.total() == 16.
assert np.array_equal(tree.find([0., 1., 3., 8., np.nextafter(16., 0.)]), [1, 2, 3, 4, 4])
for bad in ([-1.], [16.], [float('nan')]):
try: tree.find(bad)
except ValueError: pass
else: raise AssertionError('Se aceptó un prefijo inválido')
tree.update(3, 0.)
assert tree.total() == 11. and np.array_equal(tree.find([0., 1., 3.]), [1, 2, 4])
tree.update(3, 5.)
seed, batches, segments = 2215, 5000, 7
rng = np.random.default_rng(seed)
total = tree.total()
edges = np.linspace(0., total, segments+1)
u = edges[:-1] + rng.random((batches, segments)) * (total/segments)
# Evita que un redondeo aislado produzca el extremo excluido.
u = np.minimum(u, np.nextafter(edges[1:], edges[:-1]))
indices = tree.find(u.ravel()).reshape(batches, segments)
observed = np.bincount(indices.ravel(), minlength=tree.n)/(batches*segments)
masses = tree.nodes[tree.base:tree.base+tree.n]
leaf_edges = np.r_[0., np.cumsum(masses)]
overlap = np.maximum(0., np.minimum(edges[1:,None], leaf_edges[None,1:])
- np.maximum(edges[:-1,None], leaf_edges[None,:-1]))
per_segment = overlap/(total/segments)
expected = masses/total
se = np.sqrt(np.sum(per_segment*(1-per_segment), axis=0)/(batches*segments**2))
assert np.all(np.abs(observed-expected) <= 5*se + 1e-12)
assert observed[0] == 0.
print('Semilla:', seed, '| lotes:', batches, '| segmentos por lote:', segments)
print('Hoja | masa | probabilidad | frecuencia | EE estratificado')
for i in range(tree.n):
print(i, '|', round(float(masses[i]), 3), '|', round(float(expected[i]), 6),
'|', round(float(observed[i]), 6), '|', round(float(se[i]), 6))
print('Fronteras, masa cero, actualización y prueba de frecuencias: correctas')The five-standard-error bound is a reproducible check for this seed, not a universal convergence guarantee for every realization. The update does not yet implement a transition buffer or importance correction; those have their own contracts. In floating point, masses too small relative to the sum may become indistinguishable despite being mathematically positive.
This lab combines four parts on MinAtar Breakout: dueling, proportional replay, returns of up to three steps and noisy layers. It keeps Double DQN as a common option and does not implement C51, so is not full Rainbow and does not reproduce its Atari scores. It uses the previous lesson’s native MinAtar API, with uint8 states, four frames per observation and an external episode limit. This self-contained implementation stores full stacks instead of sharing frames: simpler, but more memory than the m22-l14 buffer.
Full mode runs the four-part configuration and four ablations with five common seeds and the same interaction count per condition. Evaluation is separate with fixed seeds and no exploration noise. Equal seeds and budgets do not equalize trajectories traversed by different agents. When noisy layers are removed, this variant uses decaying ε-greedy exploration instead of learned noise with zero ε: that ablation also changes the exploration mechanism and does not isolate architecture alone. ORYON_RAINBOW_DOUBLE=0 disables Double selection in every condition; it is enabled by default. Each configurations entry can switch parts on or off. ORYON_QUICK=1 merely checks the circuit with one seed and few steps: scores cannot establish which component improves performance. Uncorrected multistep returns can be off-policy biased; here they are deliberately the simple n-step target, not Retrace.
import copy
import importlib.metadata
import json
import os
import random
from collections import deque
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
try:
from minatar import Environment
except ImportError as exc:
raise RuntimeError('Instala minatar para ejecutar el laboratorio') from exc
quick = os.environ.get('ORYON_QUICK', '0') == '1'
output = Path(os.environ.get('ORYON_RAINBOW_OUT', 'oryon-rainbow'))
output.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
gamma = .99
double_setting = os.environ.get('ORYON_RAINBOW_DOUBLE', '1')
if double_setting not in ('0', '1'): raise ValueError('ORYON_RAINBOW_DOUBLE debe ser 0 o 1')
use_double = double_setting == '1'
steps = 600 if quick else 250_000
warmup = 64 if quick else 5_000
capacity = 2_048 if quick else 50_000
batch_size = 32
limit = 1_000
seed_list = [0] if quick else list(range(5))
configurations = {
'cuatro_piezas': dict(dueling=True, per=True, n=3, noisy=True),
'sin_dueling': dict(dueling=False, per=True, n=3, noisy=True),
'sin_per': dict(dueling=True, per=False, n=3, noisy=True),
'un_paso': dict(dueling=True, per=True, n=1, noisy=True),
'sin_noisy': dict(dueling=True, per=True, n=3, noisy=False),
}
def seed_everything(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
class SumTree:
def __init__(self, capacity):
if capacity < 1: raise ValueError('Capacidad inválida')
self.capacity = capacity
self.base = 1 << (capacity - 1).bit_length()
self.tree = np.zeros(2 * self.base, dtype=np.float64)
@property
def total(self): return float(self.tree[1])
def update(self, index, value):
if not 0 <= index < self.capacity or not np.isfinite(value) or value < 0:
raise ValueError('Prioridad inválida')
i = self.base + int(index)
self.tree[i] = value
while i > 1:
i //= 2
self.tree[i] = self.tree[2*i] + self.tree[2*i+1]
def find(self, u):
if not np.isfinite(u) or not 0 <= u < self.total:
raise ValueError('Prefijo fuera de rango')
i = 1
while i < self.base:
left = 2*i
if u < self.tree[left]: i = left
else:
u -= self.tree[left]
i = left + 1
index = i - self.base
if index >= self.capacity: raise RuntimeError('Hoja vacía elegida')
return index
class Replay:
def __init__(self, capacity, shape, seed, prioritized):
self.capacity, self.size, self.pos = capacity, 0, 0
self.obs = np.empty((capacity, *shape), dtype=np.uint8)
self.next = np.empty_like(self.obs)
self.action = np.empty(capacity, dtype=np.int64)
self.reward = np.empty(capacity, dtype=np.float32)
self.discount = np.empty(capacity, dtype=np.float32)
self.terminated = np.empty(capacity, dtype=np.bool_)
self.truncated = np.empty(capacity, dtype=np.bool_)
self.tree, self.rng = SumTree(capacity), np.random.default_rng(seed)
self.prioritized, self.max_raw = prioritized, 1.0
self.alpha, self.eps = .6, 1e-6
def add(self, obs, action, reward, nxt, discount, terminated, truncated):
i = self.pos
self.obs[i], self.next[i], self.action[i] = obs, nxt, action
self.reward[i], self.discount[i] = reward, discount
self.terminated[i], self.truncated[i] = terminated, truncated
self.tree.update(i, self.max_raw ** self.alpha if self.prioritized else 1.)
self.pos = (i+1) % self.capacity
self.size = min(self.size+1, self.capacity)
def sample(self, batch, beta):
if self.size < batch or self.tree.total <= 0: raise ValueError('Buffer insuficiente')
total = self.tree.total
# Un valor uniforme por segmento: el lote en conjunto sigue la masa del árbol.
u = (np.arange(batch) + self.rng.random(batch)) * (total / batch)
u = np.minimum(u, np.nextafter(total, 0.))
indices = np.array([self.tree.find(float(x)) for x in u], dtype=np.int64)
probabilities = self.tree.tree[self.tree.base + indices] / total
weights = (self.size * probabilities) ** (-beta) if self.prioritized else np.ones(batch)
weights /= weights.max()
return (indices, weights.astype(np.float32), self.obs[indices], self.action[indices],
self.reward[indices], self.next[indices], self.discount[indices],
self.terminated[indices], self.truncated[indices])
def priorities(self, indices, errors):
if not self.prioritized: return
for i, error in zip(indices, errors):
raw = float(abs(error) + self.eps)
if not np.isfinite(raw): raise FloatingPointError('Error TD no finito')
self.max_raw = max(self.max_raw, raw)
self.tree.update(int(i), raw ** self.alpha)
class NStep:
def __init__(self, n, discount, replay):
self.n, self.gamma, self.replay, self.queue = n, discount, replay, deque()
def emit(self):
first = self.queue[0]
total, factor, last = 0., 1., None
for item in list(self.queue)[:self.n]:
total += factor * item[2]
factor *= self.gamma
last = item
if item[4] or item[5]: break
self.replay.add(first[0], first[1], total, last[3], factor, last[4], last[5])
self.queue.popleft()
def append(self, obs, action, reward, nxt, terminated, truncated):
self.queue.append((obs, action, reward, nxt, terminated, truncated))
if len(self.queue) >= self.n: self.emit()
if terminated or truncated:
while self.queue: self.emit()
class NoisyLinear(nn.Module):
def __init__(self, inputs, outputs, sigma=.5):
super().__init__()
self.weight_mu = nn.Parameter(torch.empty(outputs, inputs))
self.weight_sigma = nn.Parameter(torch.full((outputs, inputs), sigma / np.sqrt(inputs)))
self.bias_mu = nn.Parameter(torch.empty(outputs))
self.bias_sigma = nn.Parameter(torch.full((outputs,), sigma / np.sqrt(outputs)))
self.register_buffer('weight_epsilon', torch.zeros(outputs, inputs))
self.register_buffer('bias_epsilon', torch.zeros(outputs))
bound = 1 / np.sqrt(inputs)
nn.init.uniform_(self.weight_mu, -bound, bound)
nn.init.uniform_(self.bias_mu, -bound, bound)
self.reset_noise()
def reset_noise(self):
def transform(x): return x.sign() * x.abs().sqrt()
x = transform(torch.randn(self.weight_mu.shape[1], device=self.weight_mu.device))
y = transform(torch.randn(self.weight_mu.shape[0], device=self.weight_mu.device))
self.weight_epsilon.copy_(torch.outer(y, x))
self.bias_epsilon.copy_(y)
def forward(self, x):
w = self.weight_mu + self.weight_sigma * self.weight_epsilon if self.training else self.weight_mu
b = self.bias_mu + self.bias_sigma * self.bias_epsilon if self.training else self.bias_mu
return F.linear(x, w, b)
class QNet(nn.Module):
def __init__(self, channels, actions, dueling, noisy):
super().__init__()
self.dueling = dueling
self.encoder = nn.Sequential(nn.Conv2d(channels, 16, 3), nn.ReLU(),
nn.Conv2d(16, 32, 3), nn.ReLU(), nn.Flatten(),
nn.Linear(32*6*6, 128), nn.ReLU())
linear = NoisyLinear if noisy else nn.Linear
self.advantage = linear(128, actions)
self.value = linear(128, 1) if dueling else None
def reset_noise(self):
for layer in self.modules():
if isinstance(layer, NoisyLinear): layer.reset_noise()
def forward(self, obs):
features = self.encoder(obs)
advantage = self.advantage(features)
if self.value is None: return advantage
return self.value(features) + advantage - advantage.mean(dim=-1, keepdim=True)
def frame(env): return np.asarray(env.state(), dtype=np.uint8).transpose(2, 0, 1).copy()
def stack(history): return np.concatenate(history, axis=0)
def evaluate(net, seed, episodes):
env = Environment('breakout', sticky_action_prob=.1, difficulty_ramping=True)
env.seed(seed)
net.eval()
results = []
try:
for _ in range(episodes):
env.reset()
image = frame(env)
history = deque([image]*4, maxlen=4)
score = 0.
terminal = False
for length in range(1, limit+1):
x = torch.as_tensor(stack(history)[None], dtype=torch.float32, device=device)
with torch.no_grad(): action = int(net(x).argmax(dim=1).item())
reward, terminal = env.act(action)
score += reward
history.append(frame(env))
if terminal: break
results.append({'return': float(score), 'steps': length,
'terminated': bool(terminal), 'truncated': not bool(terminal)})
finally:
net.train()
return results
def train(seed, name, cfg):
seed_everything(seed)
random_actions = np.random.default_rng(seed+1000)
env = Environment('breakout', sticky_action_prob=.1, difficulty_ramping=True)
env.seed(seed)
env.reset()
image = frame(env)
history = deque([image]*4, maxlen=4)
initial = stack(history)
online = QNet(initial.shape[0], env.num_actions(), cfg['dueling'], cfg['noisy']).to(device)
target = copy.deepcopy(online).to(device)
optimizer = torch.optim.Adam(online.parameters(), lr=.00025)
replay = Replay(capacity, initial.shape, seed+2000, cfg['per'])
nstep = NStep(cfg['n'], gamma, replay)
evaluations, loss_sum, updates, length = [], 0., 0, 0
interval = 300 if quick else 25_000
for t in range(steps):
obs = stack(history)
online.train()
if cfg['noisy']: online.reset_noise()
epsilon = 0. if cfg['noisy'] else max(.05, 1 - .95*t/max(1, int(steps*.6)))
if random_actions.random() < epsilon: action = int(random_actions.integers(env.num_actions()))
else:
with torch.no_grad():
action = int(online(torch.as_tensor(obs[None], dtype=torch.float32, device=device)).argmax(dim=1).item())
reward, terminated = env.act(action)
length += 1
truncated = length >= limit and not terminated
history.append(frame(env))
nxt = stack(history)
nstep.append(obs, action, float(reward), nxt, bool(terminated), bool(truncated))
if t >= warmup and t % 4 == 0 and replay.size >= batch_size:
beta = .4 + .6 * t / max(1, steps-1)
indices, weights, obs_b, actions_b, rewards_b, next_b, discounts_b, terminal_b, truncated_b = replay.sample(batch_size, beta)
x = torch.as_tensor(obs_b, dtype=torch.float32, device=device)
xn = torch.as_tensor(next_b, dtype=torch.float32, device=device)
act = torch.as_tensor(actions_b, device=device)
rew = torch.as_tensor(rewards_b, device=device)
disc = torch.as_tensor(discounts_b, device=device)
term = torch.as_tensor(terminal_b, device=device)
weight = torch.as_tensor(weights, device=device)
online.reset_noise()
target.train()
target.reset_noise()
with torch.no_grad():
if use_double:
chosen = online(xn).argmax(dim=1, keepdim=True)
continuation = target(xn).gather(1, chosen).squeeze(1)
else:
continuation = target(xn).max(dim=1).values
desired = rew + disc * (~term).float() * continuation
predicted = online(x).gather(1, act[:, None]).squeeze(1)
error = desired - predicted
if not torch.isfinite(error).all(): raise FloatingPointError('TD no finito')
loss = (weight * F.smooth_l1_loss(predicted, desired, reduction='none')).mean()
optimizer.zero_grad(set_to_none=True)
loss.backward()
nn.utils.clip_grad_norm_(online.parameters(), 10.)
optimizer.step()
replay.priorities(indices, error.detach().abs().cpu().numpy())
loss_sum += float(loss.item())
updates += 1
if (t+1) % (100 if quick else 1000) == 0: target.load_state_dict(online.state_dict())
if terminated or truncated:
env.reset()
image = frame(env)
history = deque([image]*4, maxlen=4)
length = 0
if (t+1) % interval == 0 or t+1 == steps:
evaluations.append({'step': t+1, 'episodes': evaluate(online, seed+20000, 2 if quick else 20),
'updates': updates, 'mean_training_loss': loss_sum/updates if updates else None})
result = {'configuration': name, 'features': cfg, 'seed': seed, 'steps': steps,
'updates': updates, 'discarded_pending_nstep_at_budget': len(nstep.queue),
'evaluations': evaluations, 'observation_array_bytes': replay.obs.nbytes + replay.next.nbytes}
del online, target, optimizer, replay
if torch.cuda.is_available(): torch.cuda.empty_cache()
return result
# Las hojas vacías no deben recibir masa y los prefijos del borde son semiabiertos.
tree_test = SumTree(3)
for i, p in enumerate([1., 0., 2.]): tree_test.update(i, p)
assert tree_test.total == 3. and tree_test.find(0.) == 0 and tree_test.find(1.) == 2
assert tree_test.find(np.nextafter(3., 0.)) == 2
# El corte externo conserva bootstrap; un terminal lo anula.
class Sink:
def __init__(self): self.rows = []
def add(self, *args): self.rows.append(args)
sink = Sink()
n_test = NStep(3, .9, sink)
n_test.append('s0', 0, 1., 's1', False, False)
n_test.append('s1', 1, 2., 's2', False, True)
assert len(sink.rows) == 2 and not sink.rows[0][5] and sink.rows[0][6]
assert np.isclose(sink.rows[0][2], 2.8) and np.isclose(sink.rows[0][4], .81)
assert sink.rows[0][3] == 's2' and not n_test.queue
n_test.append('s3', 0, 3., 'final', True, False)
assert sink.rows[-1][5] and not sink.rows[-1][6] and sink.rows[-1][3] == 'final'
results = [train(seed, name, cfg) for name, cfg in configurations.items() for seed in seed_list]
try: minatar_version = importlib.metadata.version('minatar')
except importlib.metadata.PackageNotFoundError: minatar_version = 'no disponible'
report = {'quick': quick, 'device': str(device), 'torch': torch.__version__,
'minatar_version': minatar_version, 'game': 'MinAtar breakout',
'sticky_action_probability': .1, 'difficulty_ramping': True,
'steps_per_run': steps, 'seeds': seed_list,
'gamma': gamma, 'double_dqn': use_double, 'distributional_c51': False,
'target_period': 100 if quick else 1000,
'priority_alpha': .6, 'priority_epsilon': 1e-6, 'beta': 'lineal de 0,4 a 1',
'priority_weight_normalization': 'máximo del lote',
'evaluation_seed_rule': 'semilla de entrenamiento + 20000',
'evaluation_episodes': 2 if quick else 20, 'episode_limit': limit,
'nstep_off_policy_correction': 'ninguna', 'results': results}
(output / 'rainbow-pieces-report.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
for row in results:
final = row['evaluations'][-1]['episodes']
print(row['configuration'], 'semilla', row['seed'], 'retorno medio',
float(np.mean([x['return'] for x in final])), 'actualizaciones', row['updates'])npm run lab and open the connection link.Importance correction is normalized by each batch’s observed maximum, introducing variable scaling. Evaluation does not use training exploration, and a cut-off episode contributes only return observed until cutoff. The condition without NoisyNet replaces learned-noise exploration and ε=0 with decaying ε-greedy: this contrast changes both decisions. Compare per seed and inspect spread before assigning causal importance to a component; policies, accumulated data and lengths can differ despite equal interaction budgets.
Saliency in a custom driving game
The next lab trains a dueling agent on a five-lane road. State has three 10-by-10 channels: car, obstacles and obstacle-spawn phase. A collision terminates the episode; the external 100-step limit preserves bootstrap. Each collision-free step rewards 0.02 and collision −1. Actions change lanes or stay. Observation includes phase so time until the next spawn is not hidden.
The full run uses 100,000 interactions; ORYON_QUICK=1 reduces budget to 2,500 to verify the circuit. Evaluation uses 20 seeds distinct from training, the same for greedy and random policies, limiting each episode to 100 steps. One short own run with a single training seed produced mean survival 82.0 and 22.2 respectively. This is a limited comparison in this game, not a result on Enduro or a cross-seed guarantee.
The lab saves the state and maps of the V and centered-advantage branches for the greedy action. Each map sums absolute gradient values across all three channels. To check implementation it compares one component of each gradient with finite differences; local saliency does not show a cell is causally necessary.
"""Prototipo de saliencia dueling en un juego propio de tráfico, sin activos externos."""
import copy,json,os,random
from pathlib import Path
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'
seed=22151
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
steps=2500 if quick else 100000
class Traffic:
def __init__(self,seed):
self.rng=np.random.default_rng(seed)
def reset(self):
self.lane=2;self.cars=[];self.t=0;return self.observation()
def observation(self):
image=np.zeros((3,10,10),dtype=np.float32)
image[0,8,2*self.lane]=1
for row,lane in self.cars:
if 0<=row<10:image[1,row,2*lane]=1
image[2,0,self.t%4]=1
return image
def step(self,action):
self.lane=int(np.clip(self.lane+action-1,0,4))
self.cars=[(row+1,lane) for row,lane in self.cars if row+1<10]
self.t+=1
if self.t%4==0:self.cars.append((0,int(self.rng.integers(5))))
crash=any(row==8 and lane==self.lane for row,lane in self.cars)
return self.observation(),(-1. if crash else .02),crash
class Net(nn.Module):
def __init__(self):
super().__init__()
self.encoder=nn.Sequential(nn.Conv2d(3,8,3,padding=1),nn.ReLU(),
nn.Flatten(),nn.Linear(800,64),nn.ReLU())
self.value=nn.Linear(64,1);self.advantage=nn.Linear(64,3)
def forward(self,x):
h=self.encoder(x);a=self.advantage(h)
return self.value(h)+a-a.mean(dim=1,keepdim=True)
online=Net().to(device);target=copy.deepcopy(online)
opt=torch.optim.Adam(online.parameters(),lr=.0005)
memory=[];position=0;rng=np.random.default_rng(seed+1)
env=Traffic(seed+2);state=env.reset();updates=0
for t in range(steps):
epsilon=max(.05,1-.95*t/max(1,int(.75*steps)))
if rng.random()<epsilon:action=int(rng.integers(3))
else:
with torch.no_grad():
action=int(online(torch.as_tensor(state[None],device=device)).argmax().item())
nxt,reward,done=env.step(action)
transition=(state,action,reward,nxt,done)
if len(memory)<10000:memory.append(transition)
else:memory[position]=transition
position=(position+1)%10000
state=env.reset() if done or env.t>=100 else nxt
if len(memory)>=128 and t%4==0:
ids=rng.choice(len(memory),32,replace=False)
batch=[memory[int(i)] for i in ids]
obs=torch.as_tensor(np.stack([x[0] for x in batch]),device=device)
acts=torch.as_tensor([x[1] for x in batch],device=device)
rew=torch.as_tensor([x[2] for x in batch],device=device,dtype=torch.float32)
obs2=torch.as_tensor(np.stack([x[3] for x in batch]),device=device)
terminals=torch.as_tensor([x[4] for x in batch],device=device)
with torch.no_grad():
selected=online(obs2).argmax(dim=1,keepdim=True)
goal=rew+.99*(~terminals).float()*target(obs2).gather(1,selected).squeeze(1)
loss=F.smooth_l1_loss(online(obs).gather(1,acts[:,None]).squeeze(1),goal)
opt.zero_grad(set_to_none=True);loss.backward();opt.step();updates+=1
if t%250==249:target.load_state_dict(online.state_dict())
def evaluate(policy,seed):
env=Traffic(seed);state=env.reset();r=np.random.default_rng(seed+100000)
for t in range(100):
if policy=='random':action=int(r.integers(3))
else:
with torch.no_grad():action=int(online(torch.as_tensor(state[None],device=device)).argmax().item())
state,_,done=env.step(action)
if done:return t+1
return 100
score={method:[evaluate(method,seed+1000+i) for i in range(20)] for method in ('random','dueling')}
probe=Traffic(seed+777);state=probe.reset()
for _ in range(8):
with torch.no_grad():a=int(online(torch.as_tensor(state[None],device=device)).argmax().item())
state,_,done=probe.step(a)
if done:
state=probe.reset()
break
x=torch.as_tensor(state[None],device=device).requires_grad_(True)
h=online.encoder(x);v=online.value(h)[0,0];a=online.advantage(h);center=a-a.mean(1,keepdim=True)
greedy=int((v+center).argmax().item())
gv=torch.autograd.grad(v,x,retain_graph=True)[0]
ga=torch.autograd.grad(center[0,greedy],x)[0]
for name,g in [('V',gv),('A',ga)]:
i=int(g.abs().reshape(-1).argmax().item());delta=torch.zeros_like(x);delta.reshape(-1)[i]=.0005
def branch(y):
z=online.encoder(y);a=online.advantage(z)
return online.value(z)[0,0] if name=='V' else a[0,greedy]-a.mean(1)[0]
with torch.no_grad():fd=(branch(x+delta)-branch(x-delta))/.001
print('derivada',name,float(g.reshape(-1)[i]),float(fd))
data={'quick':quick,'steps':steps,'updates':updates,'seed':seed,
'probe_steps':probe.t,'greedy_action':greedy,'scores':score,
'observation':state[:2].max(axis=0).tolist(),
'player':state[0].tolist(),'cars':state[1].tolist(),'phase':state[2].tolist(),
'value_gradient':gv.detach().abs().sum(dim=1).cpu().numpy()[0].tolist(),
'advantage_gradient':ga.detach().abs().sum(dim=1).cpu().numpy()[0].tolist()}
out=Path(os.environ.get('ORYON_DRIVE_OUT','oryon-dueling-driving'));out.mkdir(parents=True,exist_ok=True)
(out/'report.json').write_text(json.dumps(data,indent=2),encoding='utf-8')
print('Tráfico: pasos',steps,'actualizaciones',updates,'supervivencia media', {k:float(np.mean(v)) for k,v in score.items()})
del online,target,opt
if torch.cuda.is_available():torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
class SumTree:
pass
Step 1 of 3. Why does identifiability fail in Qᵢ=V+Aᵢ?
priorities=[1,2,4,8]
alpha,beta=.6,.4
mass=[p**alpha for p in priorities]
probabilities=[p/sum(mass) for p in mass]
weights=[(4*probabilities[i])**(-beta) for i in (0,2,3)]
print('Probabilidades:',probabilities)
print('Pesos brutos:',weights,'normalizados:',[w/max(weights) for w in weights])