Module contents
Lesson 21 of 37Core 90 min

Making deep RL work: debugging, statistical evaluation and reproducibility

Apply incremental RL debugging, account for seed variance, compare robust aggregate metrics, tune fairly and detect reward specification gaming.

After this lesson you can

  • Apply an incremental debugging ladder to an agent that does not learn.
  • Estimate seed requirements and report distributions rather than points.
  • Compare algorithms using IQM, performance profiles and probability of improvement with rliable.
  • Design comparisons with equal tuning budgets and report hyperparameter sensitivity.
  • Detect specification gaming with videos, auxiliary metrics and behavior tests.

Before you start

The agent is not learning: what went wrong?

A classifier receiving an out-of-range label can stop with an exception. A reinforcement-learning agent with an incorrect mask, by contrast, can run millions of transitions and produce an apparently plausible curve. Before comparing DQN or the PPO loop, distinguish a code problem, a configuration problem, and a task that does not express what you want. The reward signal is not proof of correct behavior, including in a custom environment.

The RL debugging ladder progressively reduces unknowns. First test the environment contract with known actions and check observations, rewards, bounds and resets. Then use probes whose value or optimal action you know, overfit a tiny batch and compare one update with a manual calculation. Only then introduce a network, multiple environments, normalization and repeated optimization. Compare with a reference implementation under the same protocol, inspect episodes and log internal diagnostics.

PPO metrics help locate a fault; none gives a unique diagnosis. Near-zero entropy can indicate a collapsed policy, but also a task with a clearly optimal action. Negative explained variance means critic error varies more than the target; it does not itself identify optimizer, data or reward as the cause. Examine values, advantages, gradients, KL, clipped fraction, returns and videos together. Also check bootstrap value is zero at true termination, while an external time limit requires the final observation’s value; the trace stops in both cases.

The experimental unit is the training run

Variation across seeds includes initialization, exploratory actions and transitions. A fixed seed does not necessarily control hardware nondeterminism or make different environment versions the same experiment. Record libraries, simulator version, hardware, configuration and seeds of all generators. Henderson and colleagues show in their figure 5 two groups of five TRPO runs on HalfCheetah-v1 with identical settings and different mean curves. This does not prove that five seeds always fail or every observed difference is significant.

InteractiveTen seeds, one PPO
  • Group A
  • Group B
0
Seeds A0, 1, 2, 3, 4
Seeds B5, 6, 7, 8, 9
Final difference A − B−31.4
Change the partition of ten seeds into two groups of five. Each curve averages one group's runs: these are two samples of the same procedure, not different algorithms.

The figure shows a short local run of the previous lesson’s discrete PPO implementation on CartPole-v1 with Gymnasium 1.4 and CPU. It used seeds 0 to 9, four environments, rollouts of 64 steps, 40 updates, two epochs and minibatches of 16. Each point is the mean of ten independent greedy episodes evaluated after 10, 20, 30 or 40 updates; evaluation seeds used 100000 + 1000 * semilla + episodio, where those variables mean seed and episode. The initial rate was 0.00025 with linear decay, γ=0.99\gamma=0.99, λ=0.95\lambda=0.95 and clip 0.2. This is a short variability test, not a performance comparison or reproduction of the HalfCheetah study. To repeat it adapt the first PPO lab to those settings and retain all ten trajectories, not only a chosen average.

Evaluate each trained policy in independent episodes and summarize those episodes to obtain one observation per training run and task. Ten episodes of one checkpoint are not ten independent training runs. Separate evaluation from training seeds, predefine budget and evaluated checkpoint, and retain individual results. Selecting the best seed or curve maximum afterward introduces optimistic selection.

There is no universal seed count. First define the minimum relevant effect, tolerable uncertainty, variance estimated by an independent pilot, and budget. Then calculate power or simulate the comparison procedure with explicit assumptions. If the interval remains too wide to decide, report the uncertainty. More bootstrap resamples do not create information about failure modes no run observed.

An initial estimate can start from a simple model: two independent groups with known common variance σ2\sigma^2, equal number nn of training runs per group, and minimum mean difference δ\delta. Their mean difference has standard error σ2/n\sigma\sqrt{2/n}. For a two-sided normal test at level α\alpha and target power approximately 1−β1-\beta in the direction of improvement, solving δ/(σ2/n)≈z1−α/2+z1−β\delta/(\sigma\sqrt{2/n}) \approx z_{1-\alpha/2}+z_{1-\beta} gives

n≈2(z1−α/2+z1−β)2σ2δ2.n \approx 2\left(z_{1-\alpha/2}+z_{1-\beta}\right)^2\frac{\sigma^2}{\delta^2}.

For example, if δ=0.5σ\delta=0.5\sigma, α=0.05\alpha=0.05 and desired power is 0.8, the next cell rounds up to 63 runs per group. This is an approximation for one task and a mean, with negligible opposite tail under the alternative; it is not a recipe for IQM or a guarantee under heavy tails or variance estimated from a small pilot. Simulate the final procedure with plausible distributions and include tuning cost.

[ ]Approximate sample sizeBrowser
from statistics import NormalDist
from math import ceil
z = NormalDist()
n = 2 * (z.inv_cdf(.975) + z.inv_cdf(.8)) ** 2 / (.5 ** 2)
print('Entrenamientos por grupo:', ceil(n), 'aproximación sin redondear:', round(n, 3))

Summarizing a benchmark without hiding its distribution

Let xijx_{ij} be the normalized score of run ii on task jj. Choose normalization references before comparison and use the same scale for both methods. A different transformation per task changes a mean’s implicit weights; if the denominator is zero normalization is undefined. Also retain original returns.

Robust aggregate metrics answer different questions. The mean uses every score and can be dominated by an extreme. The median is resistant but ignores how many scores on either side change. The interquartile mean (IQM) averages the center of pooled scores. rliable removes the integer part of one quarter of the total number of scores from each end and averages the rest; other conventions use fractional weights when the total is not divisible by four. Its aggregate median is the median of per-task means, not the median of all pooled values. State the convention when comparing.

The performance profile at threshold τ\tau is the fraction of run–task pairs scoring above that threshold. If two profiles cross, preference depends on threshold: there is no uniform ordering. To compare A with B on each task, estimate the probability that an independent A run exceeds an independent B run, counting a tie as half, and average over tasks. This probability does not measure improvement magnitude. Agarwal and colleagues recommend profiles, IQM and stratified intervals for evaluations with few runs; their empirical calibration depends on the benchmark and is not a guarantee for every suite.

InteractiveWhich summary do you choose?
  • IRIS
  • TWM
5
Summary
IRIS, estimate [95% CI]0.501 [0.440, 0.565]
TWM, estimate [95% CI]0.459 [0.407, 0.527]
Tasks26
Change the number of runs and statistic. Curves show the fraction of scores above each threshold; readouts show estimates and intervals for the same tasks.

The figure uses per-run scores for IRIS and TWM on 26 Atari 100k games published in the Simulus repository. Each score is normalized as (x−xazar)/(xhumano−xazar)(x-x_{\mathrm{azar}})/(x_{\mathrm{humano}}-x_{\mathrm{azar}}) with references from that repository. Selection uses the first two to five entries per game, not newly randomized sets when the control moves; it does not interpret order as pairing methods. Percentile intervals use 500 deterministic resamples within each game with fixed tasks. They illustrate the procedure on these observations, but do not guarantee coverage with only five runs or resolve implementation-protocol differences. The chart shows only thresholds 0 to 3; higher scores still contribute to aggregates.

For the fixed-task stratified bootstrap, resample runs with replacement within each task, reconstruct the matrix and recalculate the statistic. Repeat and take desired percentiles of replicates. Runs within each task are assumed independent, comparable samples of the fixed procedure; duplicating a training run creates no new sample. Uncertainty concerns runs on those tasks, not a population of new tasks. If runs are truly paired by design and dependence matters, resample pairs jointly; using the same seed number alone does not guarantee effective pairing. An interval for the difference addresses the comparison more directly than observing overlap between separate intervals.

The percentile interval depends on observed data and resampling scheme. On tasks with genuinely shared examples, paired tests preserve that relationship. If data have additional levels, such as runs and episodes within runs, a hierarchical bootstrap can reflect them under its own assumptions. Decide which population to describe before choosing resampling.

Tuning is part of the algorithm

Hyperparameter sensitivity means comparison depends on configurations explored, selection measure and budget. Reserve part of the budget for tuning, equalize resources and information available to both methods, and use distinct seeds for the final report. Record all trials, including failures, and the selection criterion. If transferring a configuration chosen in one environment to others, say so and do not silently adapt only one method.

Equal interaction budgets do not necessarily mean equal compute cost: record both. Nor do they ensure search spaces are equivalent. Present sensitivity curves where possible and state whether the comparison asks “best configuration found under this budget” or “fixed transferred configuration.” Both questions are legitimate, but not interchangeable.

A high reward can favor the wrong behavior

Reward specification gaming occurs when optimizing the written signal produces behavior contrary to the intent. In CoastRunners, OpenAI documented an agent repeatedly circling a lagoon to collect respawned targets instead of finishing the race. The score rewarded targets, not progress directly. The article reports a 20% higher average score than human players in that case; it is not a general measure of racing ability.

In another failure, the agent exploits simulated physics that does not represent desired behavior. DeepMind documents a simulated robot hooking its legs and sliding forward instead of walking. These are distinct problems: the first exploits how game targets are paid; the second, a possibility of the simulation. Inspect movement and distance traveled alongside the training signal.

InteractiveA toy race
01234567Loop6Race3

Model: the loop hits three targets six times; the race hits three and finishes. Each target pays 1 point.

0
Loop: finishesNo
Race: finishesYes
Best rewardLoop
Try a finish bonus and limit repeat payments. When does racing beat looping, and when do they only tie?

The figure is an explicit model, not a reproduction of either system. It compares only two trajectories: the loop touches three targets six times and does not finish; the race touches three and finishes. Each touch pays one point, unless payment is limited to the first visit to each target. The bonus is paid once at the finish. With repeat payments, the race needs a bonus greater than 3 to beat the loop. If each target pays once, any positive bonus breaks the tie. This demonstrates a loophole in this limited set of trajectories, not that a modified reward is safe for every behavior.

A poorly defined progress bonus may pay repeatedly for moving back and forth. Watch videos and log net progress, completion, collisions and other metrics separate from the optimized reward. Design behavior tests with edge cases and compare policies across seeds and environments. Changing reward can close one loophole and open another: rerun tests, and do not declare the objective aligned from one curve.

Reproducible report

Save full configuration, code and versions, seeds, budgets, termination conditions, per-run metrics and evaluation episodes. Include failures, selection criterion, spread and analysis limits. Training and evaluation should use separate environments; freeze normalization statistics in evaluation and document whether the policy is stochastic or greedy. Videos and auxiliary metrics reveal behaviors return cannot distinguish. Logs should associate every result with a configuration and a training run, not only an aggregate curve: apply experiment tracking and configuration management.

Local evaluation benchmark

The benchmark trains custom, deliberately compact A2C and PPO versions with a shared network, GAE and discrete policy on CartPole-v1, MountainCar-v0, Acrobot-v1 and FrozenLake-v1. Each process has its own environment and seed; evaluation uses a greedy policy and independent environments. PPO performs four full-batch epochs and normalizes advantages; A2C performs one. Both use 64 steps per rollout, rate 0.0003, gradient clipping 0.5, value coefficient 0.5 and entropy 0.01. Bootstrap value is calculated before reset after truncation. These implementations are not identical to earlier lessons’: document differences before comparing results.

Install PyTorch, NumPy, Gymnasium 1.4 and rliable 1.2. To avoid the observed incompatibility between arch 7.2 and pandas 3, use an isolated environment with pandas 2.3.3 and verify from rliable import library, metrics before starting. Full mode uses ten seeds, 163840 transitions and ten evaluation episodes per run. It does not guarantee solving tasks. ORYON_QUICK=1 runs one seed, 256 transitions and two episodes: it only checks the entire pipeline works. ORYON_EVAL_OUT selects the directory, and ORYON_EVAL_WORKERS limits CPU processes; each uses one PyTorch thread. Code writes one result file per run and stops analysis if one is missing. Each run saves individual returns and versions. These are your own results only when you run this cell.

Workers here use CPU, facilitating isolation of these small networks. For sweeps requiring a shared GPU, explicitly limit concurrent processes, watch memory and resource-exhaustion failures, and record allocation: sharing changes timings and does not make runs comparable performance measurements across machines. Reserve distinct paths per run and retain failures, duration and compute cost in the experiment log.

[ ]Train A2C and PPO in four environmentsLocal GPU
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import json
import os
import subprocess
import sys
import time

worker = r'''import json
import os
import random
import sys
from pathlib import Path

import gymnasium as gym
import numpy as np
import torch
from torch import nn
from torch.distributions import Categorical

torch.set_num_threads(1)
method, env_id, seed_text, steps_text, episodes_text, dest = sys.argv[1:]
seed, steps, episodes = int(seed_text), int(steps_text), int(episodes_text)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
env = gym.make(env_id)
test_env = gym.make(env_id)
obs_space = env.observation_space
obs_size = obs_space.n if isinstance(obs_space, gym.spaces.Discrete) else int(np.prod(obs_space.shape))
actions = env.action_space.n

def encode(obs):
    if isinstance(obs_space, gym.spaces.Discrete):
        return np.eye(obs_size, dtype=np.float32)[int(obs)]
    return np.asarray(obs, dtype=np.float32).reshape(-1)

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.body = nn.Sequential(nn.Linear(obs_size, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh())
        self.actor = nn.Linear(64, actions)
        self.value = nn.Linear(64, 1)

    def forward(self, x):
        h = self.body(x)
        return self.actor(h), self.value(h).squeeze(-1)

def compute_gae(rewards, values, successors, terms, truncs):
    advantage = np.empty(len(rewards), dtype=np.float32)
    carry = 0.0
    for t in range(len(rewards) - 1, -1, -1):
        delta = rewards[t] + .99 * (not terms[t]) * successors[t] - values[t]
        carry = delta + .99 * .95 * (not (terms[t] or truncs[t])) * carry
        advantage[t] = carry
    return advantage

def normalize_adv(adv):
    return (adv - adv.mean()) / (adv.std(unbiased=False) + 1e-8)

def actor_objective(ratio, adv, value):
    return -torch.minimum(ratio * adv, ratio.clamp(.8, 1.2) * adv).mean()

def next_episode(env, seed):
    return env.reset()[0]

def evaluate(model, env, episodes, seed):
    returns = []
    for episode in range(episodes):
        observation, _ = env.reset(seed=100000 + seed * 1000 + episode)
        total = 0.0
        while True:
            with torch.no_grad():
                logits, _ = model(torch.tensor(encode(observation)).unsqueeze(0))
                action = int(logits.argmax(dim=-1).item())
            observation, reward, terminated, truncated, _ = env.step(action)
            total += float(reward)
            if terminated or truncated:
                break
        returns.append(total)
    return returns

model = Model()
optimizer = torch.optim.Adam(model.parameters(), lr=3e-4, eps=1e-5)
obs, _ = env.reset(seed=seed)
completed = 0
try:
    while completed < steps:
        obs_rows, action_rows, old_logp, value_rows, next_rows = [], [], [], [], []
        rewards, terms, truncs = [], [], []
        for _ in range(min(64, steps - completed)):
            encoded = encode(obs)
            with torch.no_grad():
                logits, value = model(torch.tensor(encoded).unsqueeze(0))
                distribution = Categorical(logits=logits)
                action = distribution.sample()
                logp = distribution.log_prob(action)
            successor, reward, terminated, truncated, _ = env.step(int(action.item()))
            with torch.no_grad():
                _, successor_value = model(torch.tensor(encode(successor)).unsqueeze(0))
            obs_rows.append(encoded)
            action_rows.append(int(action.item()))
            old_logp.append(float(logp.item()))
            value_rows.append(float(value.item()))
            next_rows.append(float(successor_value.item()))
            rewards.append(float(reward))
            terms.append(terminated)
            truncs.append(truncated)
            obs = next_episode(env, seed) if terminated or truncated else successor
            completed += 1

        advantage = compute_gae(rewards, value_rows, next_rows, terms, truncs)
        targets = torch.tensor(advantage + np.asarray(value_rows, dtype=np.float32))
        adv = torch.tensor(advantage)
        if method == 'PPO':
            adv = normalize_adv(adv)
        x = torch.tensor(np.asarray(obs_rows))
        act = torch.tensor(action_rows)
        old = torch.tensor(old_logp)
        for _ in range(4 if method == 'PPO' else 1):
            logits, value = model(x)
            dist = Categorical(logits=logits)
            new_logp = dist.log_prob(act)
            if method == 'PPO':
                ratio = (new_logp - old).exp()
                actor = actor_objective(ratio, adv, value)
            else:
                actor = -(new_logp * adv).mean()
            loss = actor + .5 * .5 * (value - targets).square().mean() - .01 * dist.entropy().mean()
            if not torch.isfinite(loss):
                raise FloatingPointError('Pérdida no finita')
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), .5, error_if_nonfinite=True)
            optimizer.step()

    returns = evaluate(model, test_env, episodes, seed)
    record = {'method': method, 'environment': env_id, 'seed': seed, 'steps': steps,
              'configuration': {'horizon': 64, 'gamma': .99, 'lambda': .95,
                                'epochs': 4 if method == 'PPO' else 1,
                                'ppo_clip': .2, 'learning_rate': 3e-4,
                                'gradient_clip': .5, 'value_coefficient': .5,
                                'entropy_coefficient': .01,
                                'advantage_normalized': method == 'PPO'},
              'evaluation_returns': returns, 'gymnasium': gym.__version__,
              'numpy': np.__version__, 'torch': torch.__version__,
              'evaluation_seed': '100000 + 1000 * seed + episode', 'device': 'cpu'}
    torch.save(model.state_dict(), Path(dest).with_suffix('.pt'))
    Path(dest).write_text(json.dumps(record, indent=2, allow_nan=False), encoding='utf-8')
finally:
    env.close()
    test_env.close()
'''
root = Path(os.environ.get('ORYON_EVAL_OUT', 'oryon-eval'))
root.mkdir(parents=True, exist_ok=True)
worker_path = root / 'worker.py'
worker_path.write_text(worker, encoding='utf-8')
quick = os.environ.get('ORYON_QUICK', '0') == '1'
methods = ('A2C', 'PPO')
tasks = ('CartPole-v1', 'MountainCar-v0', 'Acrobot-v1', 'FrozenLake-v1')
seeds = list(range(1 if quick else 10))
steps, episodes = (256, 2) if quick else (163840, 10)
workers = int(os.environ.get('ORYON_EVAL_WORKERS', '2'))
if workers < 1:
    raise ValueError('ORYON_EVAL_WORKERS debe ser positivo')
jobs = [(method, task, seed) for method in methods for task in tasks for seed in seeds]

def launch(job):
    method, task, seed = job
    path = root / (method + '-' + task + '-' + str(seed) + '.json')
    env = dict(os.environ, PYTHONUTF8='1', OMP_NUM_THREADS='1')
    start = time.monotonic()
    result = subprocess.run([sys.executable, str(worker_path), method, task, str(seed),
                    str(steps), str(episodes), str(path)], env=env, capture_output=True,
                    text=True, encoding='utf-8')
    elapsed = time.monotonic() - start
    if result.returncode:
        failure = {'method': method, 'environment': task, 'seed': seed,
                   'returncode': result.returncode, 'stderr': result.stderr,
                   'elapsed_seconds': elapsed}
        path.with_suffix('.failure.json').write_text(json.dumps(failure, indent=2), encoding='utf-8')
        raise RuntimeError('Falló una ejecución: ' + str(path.with_suffix('.failure.json')))
    report = json.loads(path.read_text(encoding='utf-8'))
    report['elapsed_seconds'] = elapsed
    path.write_text(json.dumps(report, indent=2, allow_nan=False), encoding='utf-8')
    return str(path)

with ThreadPoolExecutor(max_workers=workers) as pool:
    paths = list(pool.map(launch, jobs))
print('Ejecuciones terminadas:', len(paths), 'modo corto:', quick, 'carpeta:', root)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Each task uses different units. For this analysis fix reference pairs before looking at results: CartPole (0, 500), MountainCar (−200, −110), Acrobot (−500, −100) and FrozenLake (0, 1). The score is (retorno - referencia_inferior) / (referencia_superior - referencia_inferior), meaning (return − lower reference) / (upper reference − lower reference), and is not clipped. These pairs define a working scale, not guaranteed minima or maxima or human scores. Changing them changes tasks’ implicit weights. First average episodes within each training run, then construct a runs-by-tasks matrix. The analysis requires files to match the expected protocol and uses rliable for IQM, mean, median of per-task means, profiles and probability of improvement.

[ ]Analyze the benchmark with rliableLocal GPU
import json
import os
from pathlib import Path
import numpy as np
from rliable import metrics
from rliable import library as rly

root = Path(os.environ.get('ORYON_EVAL_OUT', 'oryon-eval'))
quick = os.environ.get('ORYON_QUICK', '0') == '1'
tasks = ('CartPole-v1', 'MountainCar-v0', 'Acrobot-v1', 'FrozenLake-v1')
methods = ('A2C', 'PPO')
seeds = list(range(1 if quick else 10))
expected_steps, expected_episodes = (256, 2) if quick else (163840, 10)
refs = {'CartPole-v1': (0., 500.), 'MountainCar-v0': (-200., -110.),
        'Acrobot-v1': (-500., -100.), 'FrozenLake-v1': (0., 1.)}
scores = {}
versions = set()
for method in methods:
    matrix = np.empty((len(seeds), len(tasks)))
    for i, seed in enumerate(seeds):
        for j, task in enumerate(tasks):
            path = root / (method + '-' + task + '-' + str(seed) + '.json')
            record = json.loads(path.read_text(encoding='utf-8'))
            if (record['method'], record['environment'], record['seed'], record['steps']) != (method, task, seed, expected_steps):
                raise ValueError('Protocolo incorrecto en ' + str(path))
            expected_config = {'horizon': 64, 'gamma': .99, 'lambda': .95,
                'epochs': 4 if method == 'PPO' else 1, 'ppo_clip': .2,
                'learning_rate': 3e-4, 'gradient_clip': .5, 'value_coefficient': .5,
                'entropy_coefficient': .01, 'advantage_normalized': method == 'PPO'}
            if record.get('configuration') != expected_config:
                raise ValueError('Configuración incorrecta en ' + str(path))
            returns = np.asarray(record['evaluation_returns'], dtype=float)
            if returns.shape != (expected_episodes,) or not np.isfinite(returns).all():
                raise ValueError('Evaluación incompleta en ' + str(path))
            versions.add((record['gymnasium'], record['numpy'], record['torch']))
            low, high = refs[task]
            matrix[i, j] = (returns.mean() - low) / (high - low)
    scores[method] = matrix
if len(versions) != 1:
    raise ValueError('Las versiones de los procesos no coinciden')

aggregate = lambda x: np.array([metrics.aggregate_mean(x), metrics.aggregate_median(x), metrics.aggregate_iqm(x)])
thresholds = np.linspace(0., 1., 11)
print('columnas: media, mediana de medias por tarea, IQM')
for name, matrix in scores.items():
    print(name, 'agregados:', aggregate(matrix))
    print(name, 'perfil en umbrales', thresholds, ':', [np.mean(matrix > t) for t in thresholds])
print('Probabilidad de mejora PPO frente a A2C:', metrics.probability_of_improvement(scores['PPO'], scores['A2C']))
if quick:
    print('Una sola semilla por tarea: sin intervalos entre entrenamientos ni conclusión de rendimiento.')
else:
    # rliable 1.2 usa np.random global para los índices estratificados.
    np.random.seed(2026)
    point, intervals = rly.get_interval_estimates(scores, aggregate, reps=5000, method='percentile')
    np.random.seed(2026)
    profiles, profile_ci = rly.create_performance_profile(scores, thresholds, reps=5000, method='percentile')
    np.random.seed(2026)
    prob, prob_ci = rly.get_interval_estimates({'PPO>A2C': (scores['PPO'], scores['A2C'])},
        lambda a, b: np.array([metrics.probability_of_improvement(a, b)]), reps=5000, method='percentile')
    for name in methods:
        print(name, 'IC 95 % por estadístico:', intervals[name])
        print(name, 'perfil e IC puntuales:', profiles[name], profile_ci[name])
    print('PPO>A2C e IC 95 %:', prob['PPO>A2C'], prob_ci['PPO>A2C'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The comparison uses independent resampling between algorithms: sharing a seed number does not establish paired realizations. Profile bands are pointwise intervals, not a simultaneous band for every threshold. With only ten runs and four tasks, report each return too and avoid interpreting narrow intervals as proof that rare failures do not exist. The verified quick run does not provide a performance comparison.

Each process also saves final weights in a .pt file. This independent cell loads them without training and runs a fresh CartPole evaluation. Enable ORYON_EVAL_VIDEO=1 to record episodes with RecordVideo; this requires Gymnasium rendering and video dependencies. The quick pipeline was verified with pygame-ce 2.5.8 and MoviePy 2.2.1. Inspection seeds differ from benchmark seeds. The cell generates no videos unless enabled, and one selected video does not represent the full distribution.

[ ]Separate evaluation of a checkpointLocal GPU
import os
from pathlib import Path
import gymnasium as gym
import numpy as np
import torch
from torch import nn

root = Path(os.environ.get('ORYON_EVAL_OUT', 'oryon-eval'))
method = os.environ.get('ORYON_EVAL_METHOD', 'PPO')
if method not in ('A2C', 'PPO'):
    raise ValueError('Elige A2C o PPO')
seed = int(os.environ.get('ORYON_EVAL_SEED', '0'))
video = os.environ.get('ORYON_EVAL_VIDEO', '0') == '1'
env = gym.make('CartPole-v1', render_mode='rgb_array' if video else None)
if video:
    env = gym.wrappers.RecordVideo(env, video_folder=str(root / 'videos'), episode_trigger=lambda _: True)
class EvaluationModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.body = nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh())
        self.actor = nn.Linear(64, 2)
        self.value = nn.Linear(64, 1)
    def forward(self, x):
        h = self.body(x)
        return self.actor(h), self.value(h).squeeze(-1)

try:
    model = EvaluationModel()
    model.load_state_dict(torch.load(root / (method + '-CartPole-v1-' + str(seed) + '.pt'),
                                     map_location='cpu', weights_only=True))
    model.eval()
    returns = []
    for episode in range(2 if os.environ.get('ORYON_QUICK', '0') == '1' else 10):
        obs, _ = env.reset(seed=200000 + seed * 1000 + episode)
        total = 0.
        while True:
            with torch.no_grad():
                logits, _ = model(torch.tensor(np.asarray(obs, dtype=np.float32)).unsqueeze(0))
                action = int(logits.argmax(dim=-1).item())
            obs, reward, terminated, truncated, _ = env.step(action)
            total += float(reward)
            if terminated or truncated:
                break
        returns.append(total)
    print('Evaluación independiente, retornos:', returns, 'vídeo activado:', video)
finally:
    env.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Hunting PPO bugs

This exercise creates two copies of the earlier program, one with five bugs and a control. The faulty copy reverses the actor-loss sign, allows advantage gradients into the value, treats truncation as termination, removes protection when normalizing constant advantages, and resets the generator with the same seed every episode. First use the next cell’s probes to identify each failing contract. Then open worker_defectuoso.py, find and correct each line; compare each correction separately with the control. The faults are shown here so you can check hypotheses, but do not assume a short curve reveals all of them.

[ ]Prepare and test both implementationsLocal GPU
from pathlib import Path
import os
import subprocess
import sys
import json

root = Path(os.environ.get('ORYON_EVAL_OUT', 'oryon-eval'))
mutations = [
    ('(not terms[t])', '(not (terms[t] or truncs[t]))'),
    ('adv.std(unbiased=False) + 1e-8', 'adv.std(unbiased=False)'),
    ('return env.reset()[0]', 'return env.reset(seed=seed)[0]'),
    ('return -torch.minimum(ratio * adv, ratio.clamp(.8, 1.2) * adv).mean()',
     'return torch.minimum(ratio * (adv + value - value.detach()), ratio.clamp(.8, 1.2) * (adv + value - value.detach())).mean()'),
]
broken = worker
for old, new in mutations:
    if broken.count(old) != 1:
        raise RuntimeError('No se pudo insertar el fallo exactamente una vez: ' + old)
    broken = broken.replace(old, new, 1)
bad_path = root / 'worker_defectuoso.py'
bad_path.write_text(broken, encoding='utf-8')
quick = os.environ.get('ORYON_QUICK', '0') == '1'
steps = 256 if quick else 4096
child_env = dict(os.environ, PYTHONUTF8='1', OMP_NUM_THREADS='1')
for name, script in [('control', root / 'worker.py'), ('defectuoso', bad_path)]:
    report_path = root / ('sonda-' + name + '.json')
    try:
        subprocess.run([sys.executable, str(script), 'PPO', 'CartPole-v1', '23', str(steps), '2', str(report_path)],
                       check=True, env=child_env)
        result = json.loads(report_path.read_text(encoding='utf-8'))
        print(name, 'retornos de evaluación:', result['evaluation_returns'])
    except subprocess.CalledProcessError:
        print(name, 'se detuvo: comprueba las pérdidas y gradientes no finitos')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

These runs check only the pipeline and do not themselves identify which line caused a difference. The following probes extract and execute both copies’ actual functions through the syntax tree, without rerunning training. They isolate contracts: a positive advantage should increase the action probability after a descent step; the actor should not update the critic through the advantage; truncation should retain bootstrap; normalizing a constant batch should not yield NaN; successive resets should not always repeat the same state due to accidental reseeding.

[ ]Probes for sign, gradient, masks and seedsLocal GPU
import ast
import gymnasium as gym
import numpy as np
import torch

def load_probes(source):
    names = {'compute_gae', 'normalize_adv', 'actor_objective', 'next_episode'}
    tree = ast.parse(source)
    nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names]
    if {node.name for node in nodes} != names:
        raise RuntimeError('Faltan funciones bajo prueba')
    namespace = {'np': np, 'torch': torch}
    exec(compile(ast.Module(body=nodes, type_ignores=[]), '<sondas>', 'exec'), namespace)
    return namespace

control, defect = load_probes(worker), load_probes(broken)
def actor_probe(functions):
    theta = torch.tensor(0., requires_grad=True)
    value = torch.tensor(0., requires_grad=True)
    probability = torch.sigmoid(theta)
    ratio = probability / .5
    advantage = torch.tensor(1.)
    loss = functions['actor_objective'](ratio, advantage, value)
    gradients = torch.autograd.grad(loss, (theta, value), allow_unused=True)
    return [None if g is None else float(g) for g in gradients]

print('Gradientes actor control y fallo:', actor_probe(control), actor_probe(defect))
args = ([1.], [0.], [2.], [False], [True])
print('Ventaja en truncamiento, control y fallo:', control['compute_gae'](*args), defect['compute_gae'](*args))
constant = torch.ones(4)
print('Normalización constante finita, control y fallo:',
      bool(torch.isfinite(control['normalize_adv'](constant)).all()), bool(torch.isfinite(defect['normalize_adv'](constant)).all()))
env = gym.make('CartPole-v1')
try:
    env.reset(seed=23)
    good = [control['next_episode'](env, 23) for _ in range(3)]
    bad = [defect['next_episode'](env, 23) for _ in range(3)]
    print('Reinicios idénticos: control', all(np.array_equal(good[0], x) for x in good[1:]),
          'resembrado', all(np.array_equal(bad[0], x) for x in bad[1:]))
finally:
    env.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The control’s second gradient component is None because the actor does not depend on the separate value; that does not mean the critic never receives gradients from its own loss. In the shared-trunk program, actor loss can update the trunk: what is avoided is the additional path through advantage. After correcting the sign, the preferred action’s gradient should reverse direction. Isolate the two objective corrections before combining the others. A deterministic environment could legitimately repeat initial states: use a probe with known initial variation, as here, and record the seed sequence too.

Exercises

NumericAn extreme run
The twelve ordered scores are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and 50. What is their interquartile mean?
QuizComparison with a fixed budget
You have 40 training runs in total to compare two methods. Which design reduces optimistic selection?
QuizOne symptom, several hypotheses
The policy fails when a short time limit is imposed. Which first check is most informative?
QuizSix observations
Six facts have been isolated in an experiment. Which demonstrate an implementation error relative to the declared contract?

More than one answer may be correct.

CodeResample without mixing tasks
Implement stratified_bootstrap_ci(scores, stat, n_boot, seed). scores is a finite matrix of shape (runs, tasks), with at least two runs and one task. stat accepts a matrix and returns a finite scalar. For each replicate independently resample rows within each column with replacement, calculate stat, and return the 2.5th and 97.5th percentiles using NumPy linear interpolation. Use default_rng(seed) and do not modify scores. Reject invalid shapes or values and n_boot below 2 with ValueError.
import numpy as np
def stratified_bootstrap_ci(scores, stat, n_boot, seed):
  pass
Shift+Enter to run

Coverage is checked with simulations whose population mean is known, not with one interval. This experiment uses a normal task with mean zero, generates 300 independent sets of 40 runs, and counts intervals containing the true value. This checks the procedure for that distribution and size, not a guarantee for RL.

[ ]Coverage under a known distributionBrowser
import numpy as np
rng_coverage = np.random.default_rng(2026)
covered = 0
for _ in range(300):
    sample = rng_coverage.normal(size=40)
    indices = rng_coverage.integers(0, 40, size=(500, 40))
    lower, upper = np.percentile(sample[indices].mean(axis=1), [2.5, 97.5])
    covered += lower <= 0 <= upper
print('Intervalos que contienen la media verdadera:', covered, 'de 300')
[ ]Check the interquartile meanBrowser
import numpy as np
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50], dtype=float)
print('media', x.mean(), 'mediana', np.median(x), 'IQM', np.sort(x)[3:9].mean())

Summary

Key idea
A reliable comparison begins by checking the agent, retains individual runs, and separates selection, evaluation and observed behavior.