Skip to main content

DQN from first principles

Building DQN in PyTorch, then again by hand in numpy, and the two bugs that made it worse than random along the way.
reinforcement learning
numpy
debugging
Published

December 1, 2026

I’ve been reimplementing RL algorithms from scratch, roughly in the order of Sutton and Barto, on the way to the methods used for LLM post-training (PPO, GRPO and friends). This post is about DQN on CartPole: first in PyTorch, then again by hand in numpy. The numpy version scored worse than a random policy before it worked, and the way it got there taught me more than the version that worked first try.

What DQN is

DQN starts from tabular Q-learning. You keep a table of \(Q(s,a)\), the expected return of taking action \(a\) in state \(s\) and acting well afterwards, and nudge each entry toward a one-step target:

\[ Q(s,a) \leftarrow Q(s,a) + \alpha\,\big[\,r + \gamma \max_{a'} Q(s',a') - Q(s,a)\,\big] \]

CartPole’s state is four continuous numbers (cart position and velocity, pole angle and angular velocity), so there is no table to keep. Instead, a neural network takes the state and outputs one Q value per action, and we train it by regression: push \(Q(s,a)\) toward \(y = r + \gamma \max_{a'} Q(s',a')\).

Done naively this is unstable, for two reasons, and DQN (Mnih et al., 2015) adds one fix for each. Consecutive transitions are strongly correlated, so transitions go into a replay buffer and training uses random batches from it. And the target \(y\) is computed by the same network you are updating, so every step moves the goalposts. DQN computes \(y\) with a target network, a frozen copy of the weights that gets re-synced every N steps.

Two smaller details matter in practice. The agent explores with ε-greedy, where ε decays from 1 to 0.05 over the first 10k steps. And when an episode ends because of CartPole’s 500-step time limit, the pole hasn’t actually fallen, so the target should still bootstrap from \(s'\). The buffer stores terminated, not done.

flowchart LR
    E[CartPole] -- "s" --> A["ε-greedy<br/>argmax Q(s, ·)"]
    A -- "a" --> E
    E -- "(s, a, r, s', terminated)" --> B[(replay buffer)]
    B -- "batch of 64" --> L["loss = mean (Q(s,a) − y)²"]
    T["target net<br/>y = r + γ max Q⁻(s', ·)"] --> L
    L -- "gradient" --> N[Q-network]
    N -. "copy every 100 steps" .-> T

First pass: torch

I built it in PyTorch first: dqn.py, with a three-layer MLP of 128 hidden units (lines 25–37). It learned. With the target network re-synced every 100 steps, the last-20-episode average was about 420 over two seeds (every 500 steps only got about 155). The notebook has a side-by-side animation of a random policy and the trained one.

To be honest, though, I had editor autocomplete on, it filled in a lot, and autograd did the rest. It worked, but I couldn’t have told you what the gradient of the TD loss actually was.

The whole learning step, with autograd doing the hard part:

q_values_next = target_net(next_obs_batch).max(dim=1)[0]
targets = rewards_batch + gamma * q_values_next * (1 - terminated_batch)
q_values_current = q_net(obs_batch).gather(1, actions_batch.unsqueeze(1)).squeeze(1)
loss = criterion(q_values_current, targets.detach())
loss.backward()

Second pass: by hand in numpy

So I wrote it again in numpy: dqn_np.py. The principles are the same: replay buffer, target network, ε-greedy, same TD target. This time the forward pass, the backward pass and the parameter update are mine.

I kept the first design deliberately small, just to check that the plumbing worked: two linear layers, no biases, a ReLU in between, and plain SGD. I remember wondering whether I even needed the biases and deciding I didn’t. Keep that in mind.

The part I found most interesting is the gradient of the loss with respect to the network’s outputs. The network outputs a Q value for both actions, but each transition only tells you about the action that was actually taken. So dQ is zero in the other column. The other action’s value still changes, through the shared hidden layer, just not directly.

flowchart LR
    X["s<br/>(4)"] -- "W1 (4×128)" --> H["ReLU<br/>(128)"]
    H -- "W2 (128×2)" --> Q["Q(s, left)<br/>Q(s, right)"]

The first version:

def q_forward(net, X):
    h = np.maximum(X @ net["W1"], 0)
    return h @ net["W2"], h

def td_loss_grad(Q, actions, targets):
    n = len(Q)
    diff = Q[np.arange(n), actions] - targets
    dQ = np.zeros_like(Q)
    dQ[np.arange(n), actions] = 2 * diff / n      # only the action that was taken
    return np.mean(diff ** 2), dQ

def q_backward(net, h, X, dQ):
    dh = dQ @ net["W2"].T
    dh[h <= 0] = 0                                 # ReLU
    return {"W1": X.T @ dh, "W2": h.T @ dQ}

# in the training loop
for k in net:
    net[k] -= lr * grads[k]                        # SGD
eps_diff = (eps_end - eps_start) / eps_decay_steps
eps = max(eps - eps_diff, eps_end)                 # linear ε decay

The gradient check (finite differences against q_backward) passed, so I ran it.

experiment harness: my train_dqn, with switches to put each bug back
import warnings
import numpy as np, gymnasium as gym, matplotlib.pyplot as plt
import rl_basics.dqn_np as dqn
from rl_basics.optim import Adam
warnings.simplefilter("ignore")

class SGD:
    def __init__(self, params, lr): self.lr = lr
    def step(self, params, grads):
        for k in grads: params[k] -= self.lr * grads[k]

_backward, _loss = dqn.q_backward, dqn.td_loss_grad

def run(lr=5e-4, seed=0, opt="adam", bias=True, eps_bug=False):
    qmax = []
    def loss_spy(Q, a, y):
        qmax.append(np.abs(Q).max())
        return _loss(Q, a, y)
    def backward(net, h, X, dQ):
        g = _backward(net, h, X, dQ)
        if not bias:                      # biases start at 0 and never move
            g["b1"], g["b2"] = 0 * g["b1"], 0 * g["b2"]
        return g
    dqn.Adam = Adam if opt == "adam" else SGD
    dqn.q_backward, dqn.td_loss_grad = backward, loss_spy
    decay = -10_000 if eps_bug else 10_000   # the sign bug: epsilon grows instead of decaying
    _, R = dqn.train_dqn(gym.make("CartPole-v1"), lr=lr, seed=seed, eps_decay_steps=decay)
    return np.array(R), np.array(qmax, dtype=float)[::100]

BLUE, ORANGE, AQUA, GREY = "#257de0", "#f47230", "#00b894", "#8a8a8a"
plt.rcParams.update({
    "figure.dpi": 110, "font.size": 10, "axes.spines.top": False, "axes.spines.right": False,
    "axes.edgecolor": "#bbbbbb", "axes.grid": True, "grid.color": "#ececec",
    "axes.titlesize": 11, "axes.titleweight": "bold", "axes.titlelocation": "left",
    "lines.linewidth": 1.8, "legend.frameon": False,
})

def rolling(R, w=20):
    return np.convolve(R, np.ones(w) / w, "valid")

def curve(R, w=20):
    return np.cumsum(R)[w - 1:], rolling(R, w)

def note(ax, x, y, text):
    ax.text(x, y, text, fontsize=8.5, color="#555555")

The first run: an overflow warning

The first full run printed RuntimeWarning: overflow encountered in square, in the loss. My first instinct was to divide by the batch size, until I noticed I already was.

Printing the largest |Q| in each batch was more useful: 4, then 90, then 330, then 8,780, then nan. There is a simple sanity bound here. The reward is +1 per step and γ = 0.99, so no state can be worth more than \(1/(1-\gamma) = 100\). Once Q goes past that, it isn’t learning values anymore, it’s feeding on its own overestimates. The overflow was a symptom. The real problem was divergence.

The obvious next move was a lower learning rate, so I tried three:

code
eps = {lr: run(lr, 0, "sgd", bias=False, eps_bug=True) for lr in [1e-4, 5e-5, 2e-5]}

fig, (a, b) = plt.subplots(1, 2, figsize=(9, 3.4))
for (lr, c, ls) in [(1e-4, BLUE, "-"), (5e-5, ORANGE, "--"), (2e-5, AQUA, ":")]:
    R, q = eps[lr]
    a.plot(rolling(R), color=c, ls=ls, label=f"lr {lr:g}")
    b.plot(np.arange(len(q)) * 100, q, color=c, ls=ls)
a.set(title="Return", xlabel="episode", ylabel="return (rolling 20)")
b.axhline(100, color=GREY, lw=1, ls="--"); note(b, 0, 170, "max possible Q = 100")
b.set(title="Max |Q| in each batch", xlabel="gradient update", yscale="log")
a.legend(loc="upper right"); fig.tight_layout(); plt.show()
Figure 1: Three learning rates, identical returns. Max |Q| (right) shows the networks really were different.

Lowering the learning rate changed nothing. Literally nothing.

The right panel says what I expected: a lower learning rate only delays the blow-up.

The left panel is the strange one. The three return curves are not just similar, they are identical: the same 2,237 episodes and the same last-20 average of 25, including the run whose network was nan for half of training. That can only happen if the network never gets to choose an action. And about 22 steps per episode is exactly what CartPole gives a random policy.

When a setting that should matter produces identical numbers, the setting isn’t connected to the part of the code you think it is.

The bug: ε was going up

Go back to the two ε lines in the first version. eps_end - eps_start is negative, and eps - eps_diff subtracts a negative number. ε started at 1.0 and went up, so every action was random. The network trained on the buffer, and diverged, but never drove the cart. With the same seed, the random actions and therefore the episodes were identical across runs.

The fix is one sign:

eps_diff = (eps_start - eps_end) / eps_decay_steps

Fixed. Now it’s worse than random.

With ε decaying properly, the network finally acts, and the return drops to about 10 (orange in the figure below). Random gets about 22.

Doing worse than random is informative. It means the agent pushes the same way every time, so the greedy policy has collapsed to a single action. The Q values now stayed between 10 and 50, so this wasn’t divergence. It looked more like something the network could not represent.

The second bug: no biases

It was the biases. Without them, a ReLU network is positively homogeneous: \(Q(c\,s) = c\,Q(s)\) for any \(c > 0\), and in particular \(Q(0) = 0\). The upright, centred state is \(s \approx 0\), which is exactly where a good agent spends its time. There, both Q values, and the difference between them, are forced toward zero, when that state should be worth close to 100.

Before rewriting anything, I checked this by appending a constant 1 to every observation, which is a bias in disguise, and leaving the code otherwise unchanged. The return went from 11 to between 410 and 470. Then I added real biases. That’s b1 and b2 in the forward pass and two lines in the backward pass, since a bias gradient is just the upstream gradient summed over the batch.

The torch version never had this problem because nn.Linear includes a bias by default. Writing it by hand, I had removed something the framework had been quietly giving me.

def q_forward(net, X):
    h = np.maximum(X @ net["W1"] + net["b1"], 0)
    return h @ net["W2"] + net["b2"], h

# q_backward, additionally:
db2 = dQ.sum(axis=0)
db1 = dh.sum(axis=0)
code
bias = {(b, s): run(5e-4, s, "sgd", bias=b) for b in [False, True] for s in range(3)}

fig, ax = plt.subplots(figsize=(7.5, 3.6))
for b, c, name in [(False, ORANGE, "no biases"), (True, BLUE, "with biases")]:
    for s in range(3):
        x, y = curve(bias[(b, s)][0])
        ax.plot(x, y, color=c, lw=1.4, label=name if s == 0 else None)
    ax.annotate(name, (x[-1], y[-1]), xytext=(4, 0), textcoords="offset points", va="center", fontsize=9)
ax.axhline(22, color=GREY, lw=1, ls="--"); note(ax, 30000, 34, "random policy ≈ 22")
ax.set(title="Return", xlabel="environment steps", ylabel="return (rolling 20)", xlim=(0, 56000))
ax.legend(loc="upper left"); fig.tight_layout(); plt.show()
Figure 2: Plain SGD, lr 5e-4, 3 seeds each. The only difference is two bias vectors.

Then: SGD vs Adam

With everything working, I wrote Adam (about ten lines) and swapped it in for SGD, expecting a clear win. It wasn’t that simple.

At a learning rate of 1e-3, SGD’s Q values ran away in two of three seeds while Adam’s stayed bounded. Adam’s step is roughly the learning rate no matter how large the gradient is, which breaks the loop of big error, big step, bigger error. At 5e-4, Adam reached a return of 200 about twice as fast and with much less variation across seeds, but it plateaued lower than SGD. Its Q values also overshot 100 earlier, which is the overestimation that Double DQN is meant to fix.

Comparing the two at the same learning rate isn’t entirely fair, since SGD’s step is the learning rate times the gradient and Adam’s is roughly the learning rate itself. The honest summary is that Adam didn’t make this DQN better, it made it harder to break.

code
div = {(o, s): run(1e-3, s, o) for o in ["sgd", "adam"] for s in range(3)}
spd = {("sgd", s): bias[(True, s)] for s in range(3)}
spd.update({("sgd", s): run(5e-4, s, "sgd") for s in range(3, 5)})
spd.update({("adam", s): run(5e-4, s, "adam") for s in range(5)})

grid = np.linspace(2000, 50000, 200)
fig, (a, b) = plt.subplots(1, 2, figsize=(10, 3.6))
for o, c, name in [("sgd", ORANGE, "SGD"), ("adam", BLUE, "Adam")]:
    for s in range(3):
        q = div[(o, s)][1]
        a.plot(np.arange(len(q)) * 100, q, color=c, lw=1.3, label=name if s == 0 else None)
    ys = np.array([np.interp(grid, *curve(spd[(o, s)][0])) for s in range(5)])
    b.fill_between(grid, ys.min(0), ys.max(0), color=c, alpha=0.15, lw=0)
    b.plot(grid, ys.mean(0), color=c, label=name)
a.axhline(100, color=GREY, lw=1, ls="--"); note(a, 30000, 60, "max possible Q = 100")
a.set(title="Max |Q|, lr 1e-3", xlabel="gradient update", yscale="log")
b.set(title="Return, lr 5e-4", xlabel="environment steps", ylabel="return (rolling 20)")
a.legend(loc="upper left"); b.legend(loc="upper left"); fig.tight_layout(); plt.show()
Figure 3: Left: max |Q| at lr 1e-3 (3 seeds). Right: return at lr 5e-4, mean and min–max over 5 seeds.

What I’d tell myself before starting

  • Know your bounds. If max Q goes above \(1/(1-\gamma)\), it’s diverging, whatever the warning says.
  • Identical results across different settings mean the setting is disconnected from the code you think it controls.
  • Worse than random usually means the policy has collapsed, so look at what the network can represent.
  • Writing it by hand shows you what the framework was doing for you. Here, that was biases.
  • Change one thing at a time. The constant-1 experiment took one line and answered the question faster than any amount of staring at the code.

Next up is PPO in numpy, and then GRPO.