Module contents
Lesson 15 of 37Advanced 105 min

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 QQ, 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 V(s)V(s) and outputs A(s,a)A(s,a), aggregating them for example as

Q(s,a)=V(s)+A(s,a)−1∣A∣∑bA(s,b).Q(s,a)=V(s)+A(s,a)-\frac{1}{|\mathcal A|}\sum_b A(s,b).

If instead we summed V+AV+A without restriction, adding a constant cc to VV and subtracting it from every advantage would leave QQ unchanged. With centered aggregation, the aggregate value satisfies V(s)=∣A∣−1∑aQ(s,a)V(s)=|\mathcal A|^{-1}\sum_aQ(s,a) and centered advantage is Q(s,a)−V(s)Q(s,a)-V(s). That VV is the uniform mean of Q outputs, not necessarily VπV^\pi or maximum V∗V^*.

InteractiveA decomposition that shares information
LeftQ 3.0 · A 1.0StayQ 2.0 · A 0.0RightQ 1.0 · A −1.0

First bar: Q. Second: centered advantage. Uncentered outputs A = [1.00, 0.00, −1.00].

In the uncentered sum, V′=V+c and A′(a)=A(a)−c produce exactly the same Q values. The equivalent centered representation uses V̄=V+mean(A) and Ā=A−mean(A), with mean(Ā)=0. A dueling network computes Q=V+A−mean(A): its V output is the mean Q, but the raw A outputs still permit adding a constant without changing Q. Centering therefore fixes the effective advantage, but does not make raw outputs unique.

The original Enduro game maps appear in figure 2 of Wang et al., Dueling Networks.
2.0
1.0
0.0
−1.0
0.0
Uncentered V
2.00
Mean of uncentered A
0.00
Centered V = mean Q
2.00
Observed state
V gradient

A custom five-lane game; QUICK training with seed 22151, 2500 steps and 593 updates. Across 20 evaluation scenarios limited to 100 steps, mean survival was 82.0 with the greedy policy and 22.2 with random actions. This is one training seed in this game, not a general comparison or a reproduction of Enduro.

On the board, blue is the car and green marks obstacles. Actions 0, 1 and 2 move left, stay in lane or move right. Generator phase is 0 from 0 to 3. Snapshot after 8 steps. Each map sums absolute gradient values over the three input channels and normalizes by its own maximum to show shape; the number above allows magnitude comparison. The laboratory generates the maps and checks one component of each gradient by finite differences. A local gradient does not establish causality.

Branch
Greedy action
2
Map maximum
0.2786
Change value and advantages and observe which quantities are determined.

The mean centers the advantage entering QQ, but raw outputs of branch AA 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 QQ. 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 pi=∣δi∣+ε>0p_i=|\delta_i|+\varepsilon>0,

P(i)=piα∑jpjα,wi=(NP(i))−β,P(i)=\frac{p_i^\alpha}{\sum_jp_j^\alpha}, \qquad w_i=(NP(i))^{-\beta},

where NN is the number of valid entries. With α=0\alpha=0 uniform sampling is recovered; in the rank-based variant priority is defined by error rank, not direct magnitude. ε\varepsilon prevents zero priority and β\beta controls importance correction.

Sampling with replacement, P(i)>0P(i)>0 for all entries and β=1\beta=1 gives Ei∼P[wigi]=N−1∑igi\mathbb E_{i\sim P}[w_i g_i]=N^{-1}\sum_i g_i for fixed contributions gig_i. With β<1\beta<1 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 uu in the half-open interval [0,∑ipiα)[0,\sum_i p_i^\alpha): if uu 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.

InteractiveFollow a sample through the tree
46212510111213376593761234512345123451

Scroll the tree horizontally if it does not fit on screen. Each leaf i has mass pᵢ≥0 and each node sums its children. A uniform sample u∈[0, root) descends, subtracting the left mass when turning right; an update changes the leaf and its four ancestors. The update path costs O(log N); this figure also copies the array to update React state. Explicit initial masses: 1+(i mod 5), not measured. Counts after 0 samples: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0. The sequence uses seed 221501; changing a priority resets counts.

P(i)=pᵢ/Σp. For positive-mass leaves, the weight (N P(i))⁻ᵝ is shown normalized by the maximum over positive leaves. With β=1 and full positive support, correction recovers uniform weighting up to a fixed global scale N·Pₘᵢₙ due to that normalization. If the root is zero sampling is impossible. Source: Schaul et al., prioritized replay.

0
1.0
0.40
Total mass
46.0
Leaf probability
2.2 %
Normalized weight
1.000
Last leaf
no sample
Change priorities and observe how the sum and traversal change.

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 μ\mu differing from target policy π\pi: observed intermediate actions follow μ\mu. Without correction the nn-step return is generally not an unbiased sample of the π\pi target. It can work well empirically, as replay studies show, without removing theoretical bias.

For the following convention, hold QQ fixed during calculation and define Vπ(s)=∑aπ(a∣s)Q(s,a)V^\pi(s)=\sum_a\pi(a\mid s)Q(s,a) and

δkπ=Rk+1+γVπ(Sk+1)−Q(Sk,Ak),Gt=Q(St,At)+∑k=tT−1γk−t(∏j=t+1kcj)δkπ.\delta_k^\pi=R_{k+1}+\gamma V^\pi(S_{k+1})-Q(S_k,A_k),\qquad G_t=Q(S_t,A_t)+\sum_{k=t}^{T-1}\gamma^{k-t} \left(\prod_{j=t+1}^{k}c_j\right)\delta_k^\pi.

The sum ends at true termination, when terminal VπV^\pi 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 0≤λ≤10\leq\lambda\leq1, examples are ρj\rho_j for full IS without additional decay, λρj\lambda\rho_j for its trace version, λ\lambda for Q(λ), λπ(Aj∣Sj)\lambda\pi(A_j\mid S_j) for tree backup and λmin⁡(1,ρj)\lambda\min(1,\rho_j) for Retrace, with ρj=π(Aj∣Sj)/μ(Aj∣Sj)\rho_j=\pi(A_j\mid S_j)/\mu(A_j\mid S_j). Other texts absorb λ\lambda or shift indices: check definitions before comparing.

InteractiveHow much of a trace survives
0.001.793.57k=0k=6
Full ISQ(λ)Tree backupRetrace

Fixed trajectory A₁…A₆ = [1,0,1,1,0,1]; π and μ are constant binary policies, with μ between 0.05 and 0.95 to ensure support. For each action ρᵢ=π(Aᵢ)/μ(Aᵢ). The selected method coefficients are [0.80, 0.34, 0.80, 0.80, 0.34, 0.80]. In a TD expansion the weight of term k is γᵏ∏ᵢ₌₁ᵏ cᵢ, with empty product 1 at k=0: the coefficient of the initial action A₀ does not appear.

We use c=ρ for full IS, c=λ for Q(λ), c=λπ(A) for tree backup and c=λ min(1,ρ) for Retrace. The displayed sum of weights summarizes this finite trajectory, not a universal horizon. Variance is exact only for the final factor over six independent μ actions under the stated binary model; it is not return variance, which depends on rewards and correlations. Source: Munos et al., Retrace.

0.70
0.30
0.80
Detailed view
Weight of the final term
0.026
Sum of the seven weights
2.278
Exact variance of the final factor
0.000
Adjust probabilities and compare coefficients and products along an explicit trajectory.

Coverage is required: if π(a∣s)>0\pi(a\mid s)>0 for a relevant pair, μ(a∣s)\mu(a\mid s) 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 ρˉ\bar\rho, its fixed point generally corresponds to an interpolated policy

πˉ(a∣s)=min⁡{ρˉ μ(a∣s),π(a∣s)}∑bmin⁡{ρˉ μ(b∣s),π(b∣s)},\bar\pi(a\mid s)= \frac{\min\{\bar\rho\,\mu(a\mid s),\pi(a\mid s)\}} {\sum_b\min\{\bar\rho\,\mu(b\mid s),\pi(b\mid s)\}},

when the denominator is positive. Clipping ρ\rho affects the evaluated policy; trace clipping affects propagation and proof conditions. The paper’s result requires, among other assumptions, thresholds ρˉ≥cˉ\bar\rho\geq\bar c and a positive lower bound on expected clipped ratio. Do not claim arbitrarily clipped V-trace evaluates π\pi exactly.

Learnable noise and Rainbow

In NoisyNet, a layer can parametrize W=μW+σW⊙εWW=\mu_W+\sigma_W\odot\varepsilon_W and learn both μ\mu and σ\sigma. In factorized noise, two random vectors generate a matrix by outer product after transformation f(x)=sgn⁡(x)∣x∣f(x)=\operatorname{sgn}(x)\sqrt{|x|}. Noise changes outputs and produces state-dependent exploration; specify when it is resampled and how evaluation works. An additional ε\varepsilon-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 [−10,10][-10,10], three-step returns, priority exponent 0,50{,}5 and β\beta increasing from 0,40{,}4 to 11. 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.

InteractiveWhat an ablation shows
0 %100 %200 %0200 million frames
RainbowWithout prioritized replayDQN

Median human-normalized score across 57 games. Curves digitized from the vector traces in figure 3 of Hessel et al., page 6: these approximate the graph, not the original records. The paper smooths each curve with a five-point moving average. Digitization calibrates coordinates using axes from 0 to 200 million frames and 0%, 100% and 200% marks; do not interpret small differences as exact measurements or statistical uncertainty.

Removed component
100
Rainbow
≈ 180 %
at 100 M
Without prioritized replay
≈ 119 %
at 99 M
DQN
≈ 37 %
at 100 M
0.00.51.00600 pasos
Cuatro piezas: 0.00; cortes 0/2Sin dueling: 0.00; cortes 0/2Sin PER: 0.00; cortes 0/2Un paso: 0.00; cortes 0/2Sin noisy: 0.00; cortes 0/2

En esta prueba corta todas las evaluaciones registraron retorno cero. Los resultados comprueban el circuito, pero no permiten decidir qué pieza mejora el aprendizaje.

Ablación propia de cuatro piezas en MinAtar breakout versión 1.0.15, no Rainbow completo: C51 ausente, Double DQN activo. Modo QUICK reducido; 600 interacciones por condición, probabilidad de acción persistente 0.1 y dificultad progresiva activada; 2 episodios de evaluación con semilla de entrenamiento + 20000, sin ruido de exploración y límite 1000. Las curvas representan retornos finitos medios de cada evaluación. Sin NoisyNet también se sustituye ε=0 por exploración ε-voraz decreciente: el contraste modifica ambas decisiones. Semillas comunes no garantizan las mismas trayectorias; la validación comprueba estructura y magnitudes, no certifica procedencia.

Las curvas publicadas de Hessel y otros aparecen en el panel anterior; corresponden a Atari y no son directamente comparables con este experimento de MinAtar.

Examine available results and the conditions under which they are compared.

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. piαp_i^\alpha. 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.

[ ]Sum tree and stratified samplingBrowser
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.

[ ]Component ablation in MinAtarLocal GPU
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'])
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Dueling and driving saliencyLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

CodePrefix-sum sampling
Implement SumTree(capacity) with a complete binary tree in a NumPy float64 array: capacity is an integer from 1 to 65536, excluding Booleans; leaves are padded to the next power of two and excess leaves remain zero. update(index, priority) replaces a finite scalar priority between 0 and 10¹² inclusive; index is an integer from 0 to capacity−1 excluding Booleans. total() returns the root sum. find(prefixes) takes a one-dimensional array of finite real numbers, each u in [0,total); return an equally shaped array of integer indices where each u belongs to the leaf's half-open interval: a shared endpoint belongs to the leaf on the right. Zero-length intervals are never chosen. Raise ValueError for zero total or invalid input. Empty input is valid if total is positive. update propagates only through ancestors and find descends simultaneously for the entire batch without a per-sample loop: O(log capacity) per update and O(B log capacity) for B queries. Use float64 arithmetic and treat tree sums as defining boundaries; do not modify the query array.
class SumTree:
  pass
Shift+Enter to run
ProofWhat do centered advantages fix?
Prove: Fix a state and a finite set of m actions. Analyze the different decompositions of a known Q vector.
0
V and A₁,…,Aₘ are real numbers. First define Qᵢ=V+Aᵢ; then use Qᵢ=V+(Aᵢ−meanⱼ Aⱼ).

Step 1 of 3. Why does identifiability fail in Qᵢ=V+Aᵢ?

NumericImportance weight for PER
Four transitions have positive priorities p=[1,2,4,8]. With α=0.6 sampling uses P(i)=pᵢ^α/Σⱼpⱼ^α. The batch contains transitions 1, 3 and 4, numbered from 1. For β=0.4 calculate wᵢ=(4P(i))^(−β), divide each by the largest batch weight, and give transition 3's normalized weight.
QuizMultistep returns from replay
You want to evaluate target policy π using old transitions generated by b. After fixing the first action, you construct a three-step target without importance ratios. What conclusion is valid?
QuizDeciding from a conditional ablation
You can keep only three Rainbow components. You have a published ablation removing one at a time from the full combination, and a different budget for a new game. What decision is justified?
[ ]Checking exercise weightsBrowser
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])