[2.2.1] - DQN
Please send any problems / bugs on the #errata channel in the Slack group, and ask any questions on the dedicated channels for this chapter of material.
If you want to change to dark mode, you can do this by clicking the theme toggle button (sun / moon icon) in the top navigation bar.
Links to all other chapters: (0) Fundamentals, (1) Transformer Interpretability, (2) RL, (3) LLM Evaluations, (4) Alignment Science.

System RequirementsGPU⬜ Not neededTime⏱️ CPU ~1 minColab🟩 Free (T4)Download⬜ <10 MBKeys🔑 Weights & Biases
- 🖥️ GPU: ⬜ Not needed. CPU is faster.
- ⏱️ Runtime (ex. downloads/API): CPU ~1 min
- ☁️ Colab? 🟩 Free (T4)
- 💾 Downloads: ⬜ Under 10 MB
- 🔑 API keys:
- 🟥 Mandatory: Weights & Biases, for the training runs that set
use_wandb=True(or setWANDB_MODE=offline)
- 🟥 Mandatory: Weights & Biases, for the training runs that set
- 🐏 RAM: ~1.6 GB at peak
GPU times measured on a 16 GB RTX A4000. Compare every day →
Introduction
In this section, you'll implement Deep Q-Learning, often referred to as DQN for "Deep Q-Network". Presented in Playing Atari with Deep Reinforcement Learning, this was one of the first successful applications of Deep Learning to Reinforcement Learning.
Content & Learning Objectives
1️⃣ DQN
You'll implement DQN and use it to master the famous CartPole environment (below), and then (if you have time) move on to harder challenges like MountainCar.
Learning Objectives
- Understand the DQN algorithm
- Learn more about RL debugging, and build probe environments to debug your agents
- Create a replay buffer to store environment transitions
- Implement DQN using PyTorch, on the CartPole environment
Setup (don't read, just run!)
import arena_lib
exercises_dir, section_dir = arena_lib.setup("2.2.1")
import time
import warnings
from collections import namedtuple
from dataclasses import dataclass
from typing import Any, Callable, Optional
import gymnasium as gym
import numpy as np
import torch as t
import torch.nn.functional as F
import wandb
from eindex import eindex
from gymnasium.spaces import Box, Discrete
from jaxtyping import Bool, Float, Int
from torch import Tensor, nn
from torchinfo import summary
from tqdm.auto import tqdm
warnings.filterwarnings("ignore")
from gpu_env import CartPole, MountainCar
from gpu_probe import Probe1, Probe2, Probe3, Probe4, Probe5
from rl_utils import ENVS, AtariEnvs, LiveVideo, log_greedy_rollout_video, log_grid_video, make_envs
import part21_dqn.tests as tests
from part1_intro_to_rl.utils import set_global_seeds
from arena_lib.plot import line
from plotly_utils import plot_cartpole_obs_and_dones
# The networks in this section are tiny, and if you train on the CPU with
# PyTorch's default of one thread per core, threads spend longer
# coordinating than computing. Adjust if needed.
t.set_num_threads(min(4, t.get_num_threads()))
device = t.device("mps" if t.backends.mps.is_available() else "cuda" if t.cuda.is_available() else "cpu")
MAIN = __name__ == "__main__"