Deep Q-Networks: replay, target networks and Atari
The jump from table to pixels: DQN as online fitted Q iteration with convolutional networks, stabilized by replay and a target network. Analyze what each component addresses in the deadly triad, correct overestimation with Double DQN, and attend to engineering that determines results (efficient buffer, Huber loss, ε schedule, evaluation protocol). Implement from scratch and train on the RTX 4060.
After this lesson you can
- Explain how replay and a target network mitigate the deadly triad in DQN.
- Implement DQN and Double DQN in PyTorch with a memory-efficient buffer.
- Pass tests with probe environments and solve CartPole across several seeds.
- Train an Atari or MinAtar agent on the local GPU, measuring throughput and memory.
- Critically read the evaluation protocol of Atari results.
Before you start
- 22Q-learningFitted Q iterationDeadly triadDouble Q-learningGymnasium APITermination vs truncationEnvironment wrappersCustom and probe environments
- 15Micro framework to PyTorch correspondenceEpochs and shuffling
- 06Adam
- 16Multichannel convolutional layerConvolutional block pattern
- 00Canonical training and evaluation loopTraining memory budgetCaching allocator and OOM diagnosis
From table to pixels
A Q table does not generalize between similar images. A convolutional network can share parameters between them and output one value per action, but the estimate used as a target now changes during training. Consecutive frames are also similar and are generated by a changing policy.
Mnih and colleagues combined a convolutional network with experience replay and a target network. In their 2015 evaluation, DQN exceeded prior reinforcement-learning methods compared on 43 of 49 games and reached over 75% of the human reference on 29. The graph normalizes scores with random play as zero and the human tester as 100%. The protocol evaluated 30 episodes with varied starting conditions, and up to five minutes per episode. This is a result of that protocol, not a guarantee that the same recipe learns every game or that scores from different protocols can be compared without adjustment.
Regression with a changing target
A Deep Q-Network approximates using . For transition , where denotes true termination, the one-step DQN target is
belongs to a second network and is treated as constant when differentiating: in PyTorch it is computed without gradients. External truncation does not imply ; use the actual final observation before any reset. This update resembles fitted Q iteration: fit a regressor to targets built from an earlier estimate. The practical difference is that DQN alternates collection and optimization with a continuously updated network.
Huber loss with threshold is quadratic near zero and linear in the tails:
Huber loss limits slope with respect to TD error; it does not itself guarantee bounded gradients with respect to all parameters or bounded Q values. Reward clipping, gradient clipping and choosing Huber are different interventions.
Replay: reuse without pretending independence
Experience replay stores transitions in a buffer and samples minibatches from it. Consecutive samples may share nearly all pixels; mixing transitions from different experience regions often reduces temporal dependence. Uniform buffer sampling does not create data independent of the generating policy or guarantee coverage: transitions share history and the buffer is finite.
Preparing the replay simulation.
Capacity controls how much history is retained; replay ratio counts gradient updates per new environment transition. Do not confuse this with processed examples: with batch and ratio , approximately examples per new transition are used, counting repeats. When collecting multiple environments at once, the denominator must be total valid transitions, not vector calls.
In Fedus and colleagues’ study, increasing capacity from one to ten million at fixed ratio produced median relative changes of +0.1% for DQN and +28.7% for Rainbow in their comparison. Main experiments used 14 games and three seeds per game, with sticky actions; this is no law that a larger buffer always helps or harms. The work distinguishes capacity from data age and update ratio.
A target network that moves more slowly
In the hard version the target network is copied from the online network every certain number of updates. Another option updates with , known as Polyak updating. Both delay target changes, but the second is a design variant, not exactly equivalent to periodic copying.
Preparing the target network simulation.
Neither replay nor a target network automatically removes the deadly triad of approximation, bootstrapping and off-policy data. They reduce particular correlation and moving-target problems in many experiments; divergence, out-of-coverage extrapolation and systematic errors remain possible. A stable curve in a small MDP does not demonstrate universal stability.
Double DQN separates selection and evaluation
The DQN target maximum can favor positive errors. Double DQN selects the action using the online network and evaluates it using the target:
The networks are related by copying and shared data: they are not independent estimators by construction. In an ideal model with independent selection and unbiased evaluation, expected evaluation does not exceed the maximum mean value, although it can fall below it if a suboptimal action is selected. That proof does not ensure absence of overestimation in each trained network.
To interpret the gap, compare the same state and action, discount and reward definition, and continue with the policy whose value is being estimated. Use separate evaluation episodes and seeds; report uncertainty too. Comparing against returns of a different exploratory policy does not isolate estimation bias. Van Hasselt, Guez and Silver observed substantial overestimation in some games and reductions with Double DQN; that does not mean the gap disappears for every seed or task.
Pixels, memory and evaluation
In the Atari architecture of the 2015 paper, preprocessed input has four frames. Convolutions have 32 filters with stride 4, 64 filters with stride 2, and 64 filters with stride 1, followed by a 512-unit dense layer. Output has one component per available action. Memory and preprocessing choices for a new experiment must be documented: calling any network DQN is insufficient.
To form each image, the paper applies a componentwise maximum to two consecutive frames to reduce flicker, extracts luminance and resizes. It stacks four recent images and repeats each action for four emulator frames. During training it replaces positive rewards with 1, negative with −1 and retains zero; this standardizes scale but loses magnitude differences and can change which policy optimizes the transformed reward. In games with lives, the protocol also treats losing a life as a training boundary. It optimized with RMSProp and batches of 32, while the labs below use Adam and another environment: they do not present results as an exact Nature DQN reproduction.
Storing all four frames of each state and successor again duplicates many pixels. A shared-frame buffer can store each uint8 image once and reconstruct stacks, but must prevent episode crossing, invalidate overwritten indices and preserve the final successor of a truncation. Images, metadata, actions, rewards, flags and extra boundary images take memory; a pixel count is not the whole buffer size.
At evaluation, freeze learning and use separate environments and seeds. Report original reward even if training clips rewards, and declare whether the evaluation policy retains exploration. Atari protocols may also include initial no-op actions, action repetition and episode limits. Sticky actions add another source of stochasticity; Machado and colleagues explain why evaluation protocols matter. Results with and without that option are not automatically interchangeable.
The full runs below are for your machine. Reduced checks verify the code path with fewer data or steps and do not prove the agent solved CartPole or reached a published Atari score. GPU use, memory and time depend on device and load; measure each run and do not extrapolate exact time.
Labs
The experiments require a local environment with Python, NumPy, PyTorch and Gymnasium. ORYON_QUICK=1 reduces seeds, interactions and evaluations to check the path; its results do not demonstrate CartPole is solved. Parameters and seeds appear in the report, written to ORYON_DQN_OUT or oryon-dqn. Every evaluation uses environments separate from training and untransformed return.
The target uses the final observation even at truncation; only terminated cancels bootstrap. Bias evaluation compares Q of the first greedy action with observed discounted return following the same greedy policy from the same state and action. If evaluation ends by time limit, that return is finite and excludes the tail: it is recorded as such. It does not directly identify optimal-Q bias or promise Double DQN wins.
import copy
import json
import os
import random
from pathlib import Path
import gymnasium as gym
import numpy as np
import torch
from gymnasium import spaces
from torch import nn
quick = os.environ.get('ORYON_QUICK', '0') == '1'
out = Path(os.environ.get('ORYON_DQN_OUT', 'oryon-dqn'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
gamma = 0.9
# Contrato y soluciones tomados de la celda de sondas de m22-l13.
class Probe(gym.Env):
metadata = {'render_modes': []}
def __init__(self, kind):
if kind not in range(5): raise ValueError('Sonda desconocida')
self.kind = kind
self.observation_space = spaces.Discrete(2)
self.action_space = spaces.Discrete(2)
def reset(self, *, seed=None, options=None):
super().reset(seed=seed)
default = int(self.np_random.integers(2)) if self.kind in (1, 4) else 0
self.state = int(options.get('state', default)) if options else default
if not self.observation_space.contains(self.state): raise ValueError('Estado inválido')
return self.state, {}
def step(self, action):
if not self.action_space.contains(action): raise ValueError('Acción inválida')
if self.kind == 0: reward, terminated = 1.0, True
elif self.kind == 1: reward, terminated = (1.0 if self.state else -1.0), True
elif self.kind == 2: reward, terminated = (0.0, False) if self.state == 0 else (1.0, True)
elif self.kind == 3: reward, terminated = float(action), True
else: reward, terminated = float(action == self.state), True
if self.kind == 2 and not terminated: self.state = 1
return self.state, reward, terminated, False, {}
truth = {0: {0: [1., 1.]}, 1: {0: [-1., -1.], 1: [1., 1.]},
2: {0: [gamma, gamma], 1: [1., 1.]}, 3: {0: [0., 1.]},
4: {0: [1., 0.], 1: [0., 1.]}}
class Replay:
def __init__(self, capacity, obs_shape, seed):
self.capacity, self.size, self.pos = capacity, 0, 0
self.obs = np.empty((capacity, *obs_shape), dtype=np.float32)
self.next = np.empty_like(self.obs)
self.actions = np.empty(capacity, dtype=np.int64)
self.rewards = np.empty(capacity, dtype=np.float32)
self.terminated = np.empty(capacity, dtype=np.bool_)
self.truncated = np.empty(capacity, dtype=np.bool_)
self.rng = np.random.default_rng(seed)
def add(self, obs, action, reward, nxt, terminated, truncated):
i = self.pos
self.obs[i], self.actions[i], self.rewards[i] = obs, action, reward
self.next[i], self.terminated[i], self.truncated[i] = nxt, terminated, truncated
self.pos = (i + 1) % self.capacity
self.size = min(self.size + 1, self.capacity)
def sample(self, batch):
if self.size < batch: raise ValueError('Buffer insuficiente')
i = self.rng.choice(self.size, batch, replace=False)
return self.obs[i], self.actions[i], self.rewards[i], self.next[i], self.terminated[i]
def make_net(dim, actions):
return nn.Sequential(nn.Linear(dim, 64), nn.ReLU(), nn.Linear(64, 64),
nn.ReLU(), nn.Linear(64, actions)).to(device)
def update(online, target, optimizer, batch, discount, double):
obs, action, reward, nxt, terminated = (torch.as_tensor(x, device=device) for x in batch)
with torch.no_grad():
if double:
choice = online(nxt).argmax(dim=1, keepdim=True)
continuation = target(nxt).gather(1, choice).squeeze(1)
else:
continuation = target(nxt).max(dim=1).values
y = reward + discount * (~terminated).float() * continuation
selected = online(obs).gather(1, action[:, None]).squeeze(1)
loss = nn.functional.smooth_l1_loss(selected, y)
optimizer.zero_grad(set_to_none=True)
loss.backward()
nn.utils.clip_grad_norm_(online.parameters(), 10.0)
optimizer.step()
return float(loss.detach().cpu())
def probe_obs(s):
return np.eye(2, dtype=np.float32)[int(s)]
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)
def train_probe(kind, seed, double):
seed_everything(seed)
rng = np.random.default_rng(seed + 1)
env = Probe(kind); state, _ = env.reset(seed=seed)
net = make_net(2, 2); target = copy.deepcopy(net).eval()
optimizer = torch.optim.Adam(net.parameters(), lr=.001)
replay = Replay(5000, (2,), seed + 2)
steps = 400 if quick else 4000
try:
for t in range(steps):
obs = probe_obs(state)
if rng.random() < .3: action = int(rng.integers(2))
else:
with torch.no_grad(): action = int(net(torch.as_tensor(obs, device=device)).argmax().item())
nxt, reward, term, trunc, _ = env.step(action)
replay.add(obs, action, reward, probe_obs(nxt), term, trunc)
if replay.size >= 32: update(net, target, optimizer, replay.sample(32), gamma, double)
if (t + 1) % 100 == 0: target.load_state_dict(net.state_dict())
state, _ = env.reset() if term or trunc else (nxt, {})
errors = []
for state, expected in truth[kind].items():
with torch.no_grad(): actual = net(torch.as_tensor(probe_obs(state), device=device)).cpu().numpy()
errors.extend(np.abs(actual - expected).tolist())
return {'kind': kind, 'seed': seed, 'steps': steps,
'max_abs_error': max(errors), 'passed_0_05': max(errors) <= .05}
finally:
env.close()
del net, target, optimizer, replay
if device.type == 'cuda': torch.cuda.empty_cache()
def evaluate(net, seeds, discount):
records = []
env = gym.make('CartPole-v1')
try:
for seed in seeds:
obs, _ = env.reset(seed=seed)
with torch.no_grad(): q = net(torch.as_tensor(obs, dtype=torch.float32, device=device))
action = int(q.argmax().item()); first_q = float(q[action].item())
total = 0.; discounted = 0.; factor = 1.; steps = 0
while True:
nxt, reward, term, trunc, _ = env.step(action)
total += reward; discounted += factor * reward; factor *= discount; steps += 1
if term or trunc: break
with torch.no_grad():
action = int(net(torch.as_tensor(nxt, dtype=torch.float32, device=device)).argmax().item())
records.append({'seed': seed, 'return': total, 'discounted_return': discounted,
'initial_q': first_q, 'q_minus_finite_return': first_q-discounted,
'steps': steps, 'terminated': bool(term), 'truncated': bool(trunc)})
finally: env.close()
return records
def train_cartpole(seed, double):
seed_everything(seed)
rng = np.random.default_rng(seed + 11)
env = gym.make('CartPole-v1'); obs, _ = env.reset(seed=seed)
net = make_net(4, 2); target = copy.deepcopy(net).eval()
optimizer = torch.optim.Adam(net.parameters(), lr=.0005)
replay = Replay(50000, (4,), seed + 12)
steps = 600 if quick else 40000
eval_interval = 300 if quick else 5000
rows = []; losses = []
try:
for t in range(steps):
epsilon = max(.05, 1.0 - .95 * t / max(1, int(steps * .6)))
if rng.random() < epsilon: action = int(rng.integers(2))
else:
with torch.no_grad(): action = int(net(torch.as_tensor(obs, dtype=torch.float32, device=device)).argmax().item())
nxt, reward, term, trunc, _ = env.step(action)
replay.add(obs, action, reward, nxt, term, trunc)
if replay.size >= 256 and t % 4 == 0:
losses.append(update(net, target, optimizer, replay.sample(64), .99, double))
if (t + 1) % 500 == 0: target.load_state_dict(net.state_dict())
obs, _ = env.reset() if term or trunc else (nxt, {})
if (t + 1) % eval_interval == 0:
eval_seeds = [100000 + 1000 * seed + i for i in range(3 if quick else 10)]
rows.append({'step': t+1, 'epsilon_train': epsilon,
'loss_mean_since_last_eval': float(np.mean(losses)) if losses else None,
'episodes': evaluate(net, eval_seeds, .99)})
losses.clear()
return {'seed': seed, 'algorithm': 'Double DQN' if double else 'DQN',
'steps': steps, 'evaluations': rows}
finally:
env.close()
del net, target, optimizer, replay
if device.type == 'cuda': torch.cuda.empty_cache()
probe_results = [train_probe(kind, 1300 + kind, double)
for double in (False, True) for kind in range(5)]
seeds = list(range(2 if quick else 10))
cartpole_results = [train_cartpole(seed, double) for double in (False, True) for seed in seeds]
report = {'quick': quick, 'device': str(device), 'torch': torch.__version__,
'gymnasium': gym.__version__, 'probes': probe_results,
'probe_tolerance': .05,
'configuration': {
'probes': {'seeds_by_kind': [1300+k for k in range(5)],
'algorithms': ['DQN', 'Double DQN'], 'gamma': gamma,
'steps_per_run': 400 if quick else 4000,
'network_hidden': [64,64], 'optimizer': 'Adam', 'learning_rate': .001,
'replay_capacity': 5000, 'batch_size': 32, 'learning_starts': 32,
'update_frequency': 1, 'target_period': 100,
'epsilon': .3, 'gradient_clip_norm': 10.},
'cartpole': {'seeds': seeds, 'algorithms': ['DQN', 'Double DQN'], 'gamma': .99,
'steps_per_run': 600 if quick else 40000,
'network_hidden': [64,64], 'optimizer': 'Adam', 'learning_rate': .0005,
'replay_capacity': 50000, 'batch_size': 64, 'learning_starts': 256,
'update_frequency': 4, 'target_period': 500,
'epsilon_initial': 1., 'epsilon_final': .05, 'epsilon_fraction': .6,
'gradient_clip_norm': 10., 'evaluation_interval': 300 if quick else 5000,
'evaluation_episodes': 3 if quick else 10,
'evaluation_seed_rule': '100000 + 1000 * train_seed + episode_index',
'evaluation_epsilon': 0., 'reward': 'sin transformar'}},
'cartpole': cartpole_results}
(out / 'cartpole-report.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print('Sondas aprobadas:', sum(r['passed_0_05'] for r in probe_results), '/', len(probe_results))
for row in cartpole_results:
episodes = row['evaluations'][-1]['episodes']
print(row['algorithm'], 'semilla', row['seed'], 'retorno medio',
round(float(np.mean([e['return'] for e in episodes])), 2),
'Q menos retorno descontado finito',
round(float(np.mean([e['q_minus_finite_return'] for e in episodes])), 3),
'truncamientos', sum(e['truncated'] for e in episodes))npm run lab and open the connection link.The second experiment uses original MinAtar, not its scores as if they were Atari. Install minatar locally if you wish to run it. Its own API returns reward and terminal, not a truncation flag; the added step limit is external. The network receives four Boolean observations encoded as uint8, not Nature pixels or preprocessing. The buffer stores each frame once, checks identity and episode when reconstructing, and discards samples whose history was overwritten. The final next frame remains available to bootstrap a pure truncation. A new episode’s columns and neighbors are never used as history of the previous one.
import time
try:
from minatar import Environment
except ImportError:
Environment = None
class FrameReplay:
def __init__(self, capacity, frame_shape, seed):
if capacity < 10: raise ValueError('Capacidad insuficiente')
self.capacity = capacity
self.frames = np.empty((capacity, *frame_shape), dtype=np.uint8)
self.ids = np.full(capacity, -1, dtype=np.int64)
self.parents = np.full(capacity, -1, dtype=np.int64)
self.episodes = np.full(capacity, -1, dtype=np.int64)
self.transitions = np.full(capacity, -1, dtype=np.int64)
self.next_ids = np.full(capacity, -1, dtype=np.int64)
self.actions = np.empty(capacity, dtype=np.int64)
self.rewards = np.empty(capacity, dtype=np.float32)
self.terminated = np.empty(capacity, dtype=np.bool_)
self.truncated = np.empty(capacity, dtype=np.bool_)
self.serial = 0
self.rng = np.random.default_rng(seed)
def frame(self, image, episode, parent=-1):
i = self.serial; slot = i % self.capacity
self.frames[slot] = image
self.ids[slot], self.parents[slot], self.episodes[slot] = i, parent, episode
self.transitions[slot] = -1
self.serial += 1
return i
def add(self, previous, following, action, reward, terminated, truncated):
slot = previous % self.capacity
if self.ids[slot] != previous or self.ids[following % self.capacity] != following:
raise ValueError('Fotograma sobrescrito')
if self.episodes[slot] != self.episodes[following % self.capacity]:
raise ValueError('La transición cruza episodios')
if self.parents[following % self.capacity] != previous:
raise ValueError('El siguiente fotograma no es sucesor directo')
self.transitions[slot], self.next_ids[slot] = previous, following
self.actions[slot], self.rewards[slot] = action, reward
self.terminated[slot], self.truncated[slot] = terminated, truncated
def stack(self, frame_id):
images = []; current = frame_id; episode = None
for _ in range(4):
slot = current % self.capacity
if self.ids[slot] != current: return None
if episode is None: episode = self.episodes[slot]
if self.episodes[slot] != episode: return None
images.append(self.frames[slot])
previous = int(self.parents[slot])
if previous == -1:
while len(images) < 4: images.append(images[-1])
break
current = previous
return np.concatenate(images[::-1], axis=0)
def sample(self, batch):
rows = []
for _ in range(batch * 40):
candidate = int(self.rng.integers(max(0, self.serial-self.capacity), self.serial))
slot = candidate % self.capacity
frame_id = int(self.transitions[slot])
if frame_id != candidate or self.ids[slot] != frame_id: continue
first = self.stack(frame_id); second = self.stack(int(self.next_ids[slot]))
if first is not None and second is not None:
rows.append((first, self.actions[slot], self.rewards[slot], second, self.terminated[slot]))
if len(rows) == batch: break
if len(rows) < batch: raise RuntimeError('No hay suficientes historias íntegras en el buffer')
return tuple(np.asarray(x, dtype=dtype) for x, dtype in zip(zip(*rows),
(np.float32, np.int64, np.float32, np.float32, np.bool_)))
# Prueba circular y de separación entre episodios, sin depender del juego.
buffer_test = FrameReplay(12, (1, 2, 2), 77)
a = buffer_test.frame(np.full((1,2,2), 3, np.uint8), 0)
b = buffer_test.frame(np.full((1,2,2), 4, np.uint8), 0, a)
buffer_test.add(a, b, 0, 1., False, True)
c = buffer_test.frame(np.full((1,2,2), 9, np.uint8), 1)
assert np.all(buffer_test.stack(c) == 9)
assert list(buffer_test.stack(b)[:,0,0]) == [3,3,3,4]
try: buffer_test.add(b, c, 0, 0., False, False)
except ValueError: pass
else: raise AssertionError('Se aceptó una transición entre episodios')
d = buffer_test.frame(np.full((1,2,2), 10, np.uint8), 1, c)
e = buffer_test.frame(np.full((1,2,2), 11, np.uint8), 1, d)
try: buffer_test.add(c, e, 0, 0., False, False)
except ValueError: pass
else: raise AssertionError('Se aceptó un salto dentro del episodio')
for _ in range(12): buffer_test.frame(np.zeros((1,2,2), np.uint8), 2)
assert buffer_test.stack(a) is None
print('Buffer: historia, reset, truncamiento y sobrescritura comprobados')
def minatar_frame(env):
return np.asarray(env.state(), dtype=np.uint8).transpose(2,0,1).copy()
def cnn(channels, actions):
return nn.Sequential(nn.Conv2d(channels*4, 16, 3), nn.ReLU(),
nn.Conv2d(16, 32, 3), nn.ReLU(), nn.Flatten(start_dim=-3),
nn.Linear(32*6*6, 128), nn.ReLU(), nn.Linear(128, actions)).to(device)
def evaluate_minatar(net, seed, episodes, max_steps):
env = Environment('breakout'); env.seed(seed)
results = []
for _ in range(episodes):
env.reset(); frame = minatar_frame(env); history = [frame]*4
score = 0.; terminal = False
for length in range(1, max_steps+1):
x = np.concatenate(history, axis=0).astype(np.float32)
with torch.no_grad(): action = int(net(torch.as_tensor(x, device=device)).argmax().item())
reward, terminal = env.act(action); score += reward
history = history[1:] + [minatar_frame(env)]
if terminal: break
results.append({'return': float(score), 'steps': length,
'terminated': bool(terminal), 'truncated': not bool(terminal)})
return results
def train_minatar(seed):
seed_everything(seed); rng = np.random.default_rng(seed+40)
env = Environment('breakout'); env.seed(seed); env.reset()
image = minatar_frame(env); channels = image.shape[0]
net = cnn(channels, env.num_actions()); target = copy.deepcopy(net).eval()
with torch.no_grad():
one = torch.zeros((4*channels, 10, 10), dtype=torch.float32, device=device)
q_one = net(one); q_batch = net(one.unsqueeze(0))
assert q_one.shape == (env.num_actions(),) and q_batch.shape == (1, env.num_actions())
assert torch.isfinite(q_one).all() and torch.allclose(q_one, q_batch[0], atol=1e-6, rtol=1e-5)
optimizer = torch.optim.Adam(net.parameters(), lr=.00025)
replay = FrameReplay(50000, image.shape, seed+41)
episode = 0; frame_id = replay.frame(image, episode)
steps = 1200 if quick else 250000
warmup = 256 if quick else 5000
max_episode_steps = 1000
length = 0; losses = []; start = time.perf_counter()
if device.type == 'cuda': torch.cuda.reset_peak_memory_stats()
try:
for t in range(steps):
x = replay.stack(frame_id)
if x is None: raise RuntimeError('Historia activa sobrescrita')
epsilon = max(.05, 1 - .95*t/max(1,int(steps*.6)))
if rng.random() < epsilon: action = int(rng.integers(env.num_actions()))
else:
with torch.no_grad(): action = int(net(torch.as_tensor(x, dtype=torch.float32, device=device)).argmax().item())
reward, terminal = env.act(action); length += 1
truncated = length >= max_episode_steps and not terminal
next_id = replay.frame(minatar_frame(env), episode, frame_id)
replay.add(frame_id, next_id, action, reward, terminal, truncated)
frame_id = next_id
if t >= warmup and t % 4 == 0:
losses.append(update(net, target, optimizer, replay.sample(32), .99, True))
if (t+1) % 1000 == 0: target.load_state_dict(net.state_dict())
if terminal or truncated:
episode += 1; length = 0; env.reset()
frame_id = replay.frame(minatar_frame(env), episode)
seconds = time.perf_counter()-start
return {'seed':seed, 'steps':steps, 'game':'breakout', 'sticky_probability':.1,
'difficulty_ramping':True, 'loss_mean':float(np.mean(losses)) if losses else None,
'steps_per_second':steps/seconds, 'frame_array_bytes':int(replay.frames.nbytes),
'peak_cuda_bytes':int(torch.cuda.max_memory_allocated()) if device.type == 'cuda' else None,
'evaluation':evaluate_minatar(net, seed+20000, 2 if quick else 20, max_episode_steps)}
finally:
del net, target, optimizer, replay
if device.type == 'cuda': torch.cuda.empty_cache()
if Environment is None:
print('MinAtar no instalado: laboratorio omitido, instala minatar y vuelve a ejecutarlo')
else:
pixel_results = [train_minatar(seed) for seed in range(1 if quick else 3)]
pixel_report = {'quick': quick, 'device': str(device), 'torch': torch.__version__,
'configuration': {'seeds': list(range(1 if quick else 3)),
'algorithm': 'Double DQN', 'game': 'breakout',
'sticky_action_probability': .1, 'difficulty_ramping': True,
'gamma': .99, 'steps_per_run': 1200 if quick else 250000,
'optimizer': 'Adam', 'learning_rate': .00025,
'replay_frame_capacity': 50000, 'batch_size': 32,
'learning_starts': 256 if quick else 5000,
'update_frequency': 4, 'target_period': 1000,
'epsilon_initial': 1., 'epsilon_final': .05,
'epsilon_fraction': .6, 'gradient_clip_norm': 10.,
'frame_stack': 4, 'episode_step_limit': 1000,
'evaluation_seed_rule': 'train_seed + 20000',
'evaluation_episodes': 2 if quick else 20,
'evaluation_epsilon': 0.}, 'results': pixel_results}
(out / 'minatar-report.json').write_text(json.dumps(pixel_report,indent=2),encoding='utf-8')
print('MinAtar, mediciones de esta máquina:', pixel_results)npm run lab and open the connection link.In the following comparison all three implementations use CartPole, the same training and evaluation seeds, interaction budget, update frequency, batch size, target copy and exploration schedule. Implementations are not identical: SB3 and CleanRL have their own architecture, optimizer and internal buffer treatment. The comparison measures each recipe’s result, not one isolated difference. To enable CleanRL use an isolated environment compatible with repository revision fe8d8a03c41a7ef5b523e2e354bd01c363e786bb and Gymnasium 0.29.1. Its package declares Python earlier than 3.11; with Python 3.10 install that revision using python -m pip install "https://github.com/vwxyzjn/cleanrl/archive/fe8d8a03c41a7ef5b523e2e354bd01c363e786bb.zip" "stable-baselines3==2.4.1" "moviepy==1.0.3". The old CleanRL version on PyPI has a different interface and does not work for this snippet. The cell checks the dqn.py file fingerprint and Gymnasium version; if they differ it states that the branch was not measured. CleanRL keeps its own log and also performs an internal evaluation recording video, requiring MoviePy and dependencies; that evaluation does not replace this cell’s common greedy evaluation.
import importlib.util
import hashlib
import subprocess
import sys
import tempfile
steps = 600 if quick else 40000
eval_count = 3 if quick else 10
external = {
'quick': quick, 'budget': steps, 'results': [], 'unavailable': [],
# Configuración solicitada, no evidencia de que las ramas se hayan ejecutado.
'configuration': {
'environment': 'CartPole-v1', 'seeds': seeds, 'gamma': .99,
'steps_per_run': steps, 'learning_rate': .0005, 'replay_capacity': 50000,
'batch_size': 64, 'learning_starts': 256, 'update_frequency': 4,
'target_period': 500, 'epsilon_initial': 1., 'epsilon_final': .05,
'epsilon_fraction': .6, 'evaluation_epsilon': 0.,
'evaluation_episodes': eval_count,
'evaluation_seed_rule': '100000 + 1000 * train_seed + episode_index',
'stable_baselines3': {'network_hidden': [64,64], 'optimizer': 'Adam de SB3',
'loss': 'Huber de SB3', 'gradient_clip_norm': 10.,
'gradient_steps_per_update': 1},
'cleanrl': {'network_hidden': [120,84], 'optimizer': 'Adam de CleanRL',
'loss': 'MSE', 'gradient_clip_norm': None,
'first_update_condition': 'global_step > learning_starts y múltiplo de 4'}
}
}
if importlib.util.find_spec('stable_baselines3') is None:
external['unavailable'].append('stable-baselines3 no instalado')
else:
import stable_baselines3 as sb3
for seed in seeds:
env = gym.make('CartPole-v1')
model = None
try:
model = sb3.DQN('MlpPolicy', env, seed=seed, device=device,
learning_rate=.0005, buffer_size=50000, learning_starts=256,
batch_size=64, gamma=.99, train_freq=4, gradient_steps=1,
target_update_interval=500, exploration_fraction=.6,
exploration_initial_eps=1., exploration_final_eps=.05,
max_grad_norm=10., policy_kwargs={'net_arch':[64,64]}, verbose=0)
model.learn(total_timesteps=steps)
class SB3Q(nn.Module):
def forward(self, x): return model.q_net(x.unsqueeze(0)).squeeze(0)
episodes = evaluate(SB3Q(), [100000+1000*seed+i for i in range(eval_count)], .99)
external['results'].append({'library':'stable-baselines3', 'version':sb3.__version__,
'seed':seed, 'episodes':episodes})
finally:
env.close()
del model
if device.type == 'cuda': torch.cuda.empty_cache()
cleanrl_spec = (importlib.util.find_spec('cleanrl.dqn')
if importlib.util.find_spec('cleanrl') is not None else None)
expected_sha = 'a0effc7d087264da1644c3c79eb99cc3ab02b214a758ebf6e9c1443b21ad57d3'
try:
actual_sha = hashlib.sha256(Path(cleanrl_spec.origin).read_bytes()).hexdigest() if cleanrl_spec and cleanrl_spec.origin else None
except OSError:
actual_sha = None
external['configuration']['cleanrl']['source_sha256'] = actual_sha
if actual_sha is None:
external['unavailable'].append('No se encuentra el archivo cleanrl.dqn')
elif actual_sha != expected_sha:
external['unavailable'].append('La revisión de cleanrl.dqn no coincide con la versión verificada')
elif gym.__version__ != '0.29.1':
external['unavailable'].append('La revisión de CleanRL verificada requiere Gymnasium 0.29.1 en esta comparación')
else:
class CleanQ(nn.Module):
def __init__(self):
super().__init__()
self.network = nn.Sequential(nn.Linear(4,120), nn.ReLU(), nn.Linear(120,84),
nn.ReLU(), nn.Linear(84,2))
def forward(self, x): return self.network(x)
for seed in seeds:
# El directorio temporal evita mezclar modelos de otras ejecuciones.
with tempfile.TemporaryDirectory(prefix='cleanrl-', dir=out) as temp:
cmd = [sys.executable, '-m', 'cleanrl.dqn', '--env-id', 'CartPole-v1',
'--seed', str(seed), '--total-timesteps', str(steps),
'--learning-rate', '.0005', '--buffer-size', '50000',
'--gamma', '.99', '--target-network-frequency', '500',
'--batch-size', '64', '--start-e', '1', '--end-e', '.05',
'--exploration-fraction', '.6', '--learning-starts', '256',
'--train-frequency', '4', '--save-model']
run = subprocess.run(cmd, cwd=temp, capture_output=True, text=True, encoding='utf-8')
if run.returncode != 0:
raise RuntimeError('CleanRL no terminó correctamente: '+run.stderr[-3000:])
files = list(Path(temp).rglob('*.cleanrl_model'))
if len(files) != 1: raise RuntimeError('Se esperaba un único checkpoint CleanRL')
net = CleanQ().to(device)
net.load_state_dict(torch.load(files[0], map_location=device, weights_only=True))
net.eval()
episodes = evaluate(net, [100000+1000*seed+i for i in range(eval_count)], .99)
external['results'].append({'library':'CleanRL', 'seed':seed, 'episodes':episodes,
'network':'120,84', 'command':cmd})
del net
if device.type == 'cuda': torch.cuda.empty_cache()
(out / 'external-report.json').write_text(json.dumps(external,indent=2),encoding='utf-8')
print('Dependencias no disponibles:', external['unavailable'])
for row in external['results']:
print(row['library'], 'semilla', row['seed'], 'retorno voraz medio',
round(float(np.mean([e['return'] for e in row['episodes']])), 2))npm run lab and open the connection link.In the pinned CleanRL DQN revision, training uses MSE and looks for final_observation at truncation, while Gymnasium 1.x changed autoreset modes and keys. The branch is disabled if version or fingerprint differ; installing a similarly named package is insufficient. The short check ran all three implementations with Gymnasium 0.29.1, MoviePy 1.0.3 and decorator 4.4.2; that test does not demonstrate convergence. This snippet has not measured a branch if it prints missing dependencies or compatibility; CleanRL’s built-in evaluation may use another ε and should not be compared directly with the common greedy evaluation.
Exercises
Step 1 of 3. What happens when selecting and evaluating with X?
class ReplayBuffer:
pass
def double_dqn_targets(online_next, target_next, reward, terminated, truncated, gamma):
pass
N=10**6
pixels=84*84
naive=N*8*pixels
shared=(N+4)*pixels
print('Dos pilas:',naive,'bytes,',naive/2**30,'GiB')
print('Trayectoria única:',shared,'bytes,',shared/2**30,'GiB')