Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
DQN,
explained.
One network, one set of dials, and no idea what a "paddle" or a "brick" is — just raw pixels and a score. DQN learned to play dozens of Atari games from scratch, some better than any human, and it launched the entire field of deep reinforcement learning. The learning rule is a fifty-year-old idea, Q-learning: guess the future reward of each action, then correct the guess toward reality. The trick was making that idea stable when a neural network does the guessing — which took two deceptively simple fixes: remember your past, and don't chase a moving target. Here's the Bellman update, and the two tricks that tamed it.
What changes here: the value table becomes a network
Rung 1, so the comparison is against the Q-learning that preceded it. The algorithm was already understood and already provably convergent — keep a table of the expected return for every state-action pair, and repeatedly move each entry toward the reward you actually got plus the discounted best value available next. The catch is the table. For a game screen there are more states than could ever be enumerated, and no two are ever visited twice.
The change is to replace the table with a neural network taking raw pixels, which breaks the convergence argument in two specific ways worth naming because both fixes became universal. First, consecutive frames are almost identical, so training on experience in the order it arrives feeds the network a stream of highly correlated samples. Second, the network supplies its own target — the "best value available next" is its own output — so every update moves the target it is chasing.
The two stabilisers are the rung. Experience replay stores transitions in a large buffer and samples from it at random, which decorrelates the updates and lets each transition be learned from many times. A frozen target network is a periodically-updated copy used only to compute the target, so the target holds still between refreshes. The units to carry up: one architecture and one set of hyperparameters across roughly 49 Atari games, learning from pixels and score alone, reaching or beating a human on about half of them.
Value from pixels
Reinforcement learning frames a task as: in some state s, pick an action a, get a reward r, land in a new state, repeat — and try to maximize total reward over time. A clean way to solve it is to learn the Q-function: Q(s, a) is the expected total future reward of taking action a in state s and playing well afterward. Know Q and the policy is trivial — in any state, take the action with the highest Q.
Classic Q-learning stores Q in a table, one entry per state-action. That's hopeless when the state is an Atari screen — millions of pixels, astronomically many states, none seen twice. DQN (Mnih et al., 2013/2015) replaces the table with a convolutional neural network that maps pixels straight to a Q-value for each action. Now the agent can generalize across similar screens instead of memorizing each one. The catch: training a neural network with Q-learning's bootstrapped targets was known to be unstable and prone to diverging. The paper's real contribution is the two ideas that fixed that — but first, the target it's chasing.
Approximate Q(s,a) with a neural net trained toward the Bellman target r + γ·max Q(s',a'), and stabilize it with experience replay (train on random past transitions) and a frozen target network (compute the target with an old copy) — so a net can learn control from raw pixels.
The Bellman target
How do you train a value estimate when you never observe the "true" future reward directly? You bootstrap: build a target out of one real reward plus your own estimate of what comes next. That's the Bellman equation. The value of taking action a now should equal the immediate reward r plus the discounted value of acting optimally from the next state s':
The discount factor γ (near 1) makes distant rewards worth a bit less than immediate ones, keeping the sum finite and encoding "prefer reward sooner." The difference between the target and the current estimate is the temporal-difference (TD) error, and DQN's loss is simply the squared TD error — train the network to make each Q(s,a) match its Bellman target. The elegance is that you learn from single steps, correcting each guess with the very next reward, never needing to wait for an episode to end. The danger is equally clear: the target is built from the network's own estimates, so a network that drifts can feed itself bad targets and spiral. That's what the next two ideas prevent.
Two tricks that tamed it
Naive neural Q-learning diverges for two reasons, and DQN adds one fix for each. First, experience replay: instead of training on each transition as it happens, store transitions (s, a, r, s') in a large buffer and train on random minibatches sampled from it. Consecutive frames of a game are almost identical — training on them in order feeds the network a stream of highly correlated, non-independent samples that skews the gradient. Random sampling from the buffer breaks that correlation (restoring the i.i.d. assumption gradient descent wants) and lets each experience be reused many times, which is far more data-efficient.
Second, the target network: DQN keeps a second, frozen copy of the Q-network and uses it to compute the Bellman target y, updating this copy to match the online network only periodically (every 10,000 parameter updates in the paper). Why? If you compute the target with the same network you're updating, the target shifts the instant you take a gradient step — you're chasing a target that runs away from you, a feedback loop that easily diverges. Freezing the target for a stretch gives the online network a stationary goal to move toward, then updates the goal occasionally. These two tricks — decorrelated data and a stable target — are the difference between neural Q-learning that blows up and one that learns Atari. Neither is deep math; both are engineering insight about what makes the optimization well-posed.
The update rule
The Bellman target for a transition, with reward r, discount γ, and next-state values from the target network:
r=1, γ=0.9, and next-state Q-values [2, 5, 3] → y = 1 + 0.9·5 = 5.5. On a terminal transition the future term vanishes and y = 1. The squared gap to the current Q is the loss.
Learning is a step of the current estimate toward the target, by the learning rate α — the tabular view of the same gradient update:
From Q(s,a)=3 with target 5.5 and α=0.1: Q ← 3 + 0.1·2.5 = 3.25 — a small move toward the target. The greedy policy at test time just takes the arg max. The runnable version below computes the target, the TD error, the update, and the greedy action.
DQN step by step: preprocessing, ε-greedy play, replay and the target network
The agent sees only screen pixels and the game score. All 49 games use the same network design and the same settings; only the number of output actions changes from game to game.
- Preprocess each frame. Take the pixelwise maximum of the current and previous frame (some sprites only draw on alternate frames), convert color to brightness, and shrink the image to 84×84. Stack the last four processed frames into one 84×84×4 input. A single frame cannot show which way a ball is moving; four can.
- Repeat each action (frame-skip). The agent chooses an action only on every fourth frame and that action is repeated on the frames in between. That lets it play about four times as many steps for the same compute. One game, Space Invaders, uses three instead, because at four the lasers blink out of sight.
- Read all Q-values in one pass. The network has three convolutional layers, one fully connected layer of 512 units, and one output per legal action (between 4 and 18 depending on the game). One forward pass scores every action, which is cheaper than running the network once per action.
- Pick the action with ε-greedy. With probability ε take a random action; otherwise take the highest-scoring one. ε starts at 1.0, falls linearly to 0.1 over the first million frames, and then stays at 0.1. At evaluation time it is 0.05. Before any learning, about 50,000 frames of purely random play fill the memory.
- Store the transition. Each step writes (state, action, reward, next state) into a replay memory that keeps the most recent million transitions and drops the oldest.
- Learn from a random minibatch. Every fourth action, sample 32 transitions uniformly from the memory, compute a target for each with the frozen copy of the network, and take one RMSProp step on the online network. Rewards are clipped to −1, 0 or +1, and the error term is clipped to the range −1 to +1 so no single step produces a huge gradient. The discount is 0.99.
- Refresh the target copy. Every 10,000 parameter updates, copy the online weights into the target network. Between copies the target network does not move.
- Repeat for 50 million frames, roughly 38 days of game time per game.
Why off-policy learning permits replay
Transitions in the memory were produced by older versions of the network, with different ε. That is only usable because Q-learning is off-policy: its target takes the best next action according to the current estimate, whatever action the behavior policy actually took. The data may come from one policy while the quantity being learned describes another. A method that estimates the value of the policy that gathered the data would be learning from stale data about a policy that no longer exists, which is the problem the next paper has to design around.
What the clipping trades away
Game scores run from single digits to thousands. Clipping rewards to their sign keeps the error scale similar across games, so one learning rate works for all of them. The cost is that the agent cannot tell a small reward from a large one. Clipping the error term makes the loss behave like squared error for small mistakes and like absolute error for big ones.
The DQN loss and the human-normalized score
θ— weights of the online network, the only ones trained by gradient steps.θ^−— the frozen copy used for the target, overwritten with θ every 10,000 updates.U(D)— uniform sampling from the replay memory D.r— the clipped reward; on a terminal step the target is just r.γ— the discount, 0.99.
Worked example: r = 1, γ = 0.99 and target-network values [2, 5, 3] for the next state give y = 1 + 0.99 × 5 = 5.95. If the online network says Q(s, a) = 3, the error is 2.95, but the clipped error used for the gradient is 1.
Zero means a random player and 100 means the professional human tester used as the baseline. This is how results on games with very different score ranges get averaged.
Results across 49 games, and what the ablation removed
The setup was 49 Atari 2600 games, 50 million frames of training per game, evaluation with ε = 0.05, and a comparison against a professional human tester and against the best earlier linear-feature learner. The agent scored above 75 percent of the human level on 29 of the 49 games, and beat the best earlier learner on 43 of them. It did very badly on games that need long, deliberate exploration; Montezuma's Revenge is the standing example.
The ablation removed the two stabilizers one at a time on a handful of games. On Breakout the full agent averaged about 317 points. Without replay, but with the target network, it fell to about 241. Without the target network, but with replay, it fell to about 10. Without either it scored about 3. Other games in the ablation moved in the same direction, though by smaller factors.
| Breakout variant | Replay | Target net | Average score |
|---|---|---|---|
| Full DQN | yes | yes | about 317 |
| No replay | no | yes | about 241 |
| No target network | yes | no | about 10 |
| Neither | no | no | about 3 |
The pattern is the useful part. Both tricks matter, and neither is a small tuning detail: the same network and loss with either switched off is close to useless on this game. The one-recipe result also stands: a single set of hyperparameters, chosen on a few games, carried across all 49 without per-game changes.
What the authors admit, and what happened next
The reported failures are specific and were not hidden: the method does badly on games where reward is far from the action that earned it and exploration has to be deliberate rather than random — Montezuma's Revenge is the standing example, and it became a benchmark for exploration research on the strength of this paper naming it. The sample cost is also enormous, tens of millions of frames per game, which is many human lifetimes of play.
One defect was found rather than admitted. Taking a maximum over noisy value estimates systematically overestimates, because the max of several noisy numbers is biased upward — van Hasselt and colleagues showed this is not a small effect and fixed it by using one network to choose the action and another to value it. Double DQN, duelling architectures and prioritised replay followed in quick succession, which is the sign of a result that was correct enough to be worth improving.
How it held up: as an algorithm it is largely superseded; as infrastructure it is everywhere. Replay buffers are standard in every off-policy method, and a slowly-updated copy of a network used as a stationary target reappears far outside reinforcement learning — the momentum teacher on the vision ladder is the same device with a different purpose. Its structural limit is that it learns a value for each discrete action, so it cannot act in a continuous space at all, which is where rung 2 starts.
The Bellman update, from scratch
Q-learning trains Q(s,a) toward the Bellman target y = r + γ·max Q(s',a') — immediate reward plus the discounted best future value — and just the reward r on a terminal step. The TD error is the gap between the target and the current estimate; the update nudges Q toward the target by the learning rate. At test time the policy is greedy: take the action with the highest Q. Change the reward, discount, next-state values, or the terminal flag and watch the target, the TD error, and the update move.
Write the body of bellman_target. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 5 assertions below — they start red.
- The Bellman target is reward + discounted best next-state value
- On a terminal transition the future term drops out, leaving the reward
- The TD error is the gap between the target and the current estimate
- The Q-update nudges the estimate toward the target by the learning rate
- The greedy policy picks the highest-value action
The start of deep RL
DQN is the paper that kicked off deep reinforcement learning as a field. Before it, RL and deep learning were largely separate; after it, "a neural network learning to act from high-dimensional input by reward" became a research program that produced a decade of milestones. The direct line runs to AlphaGo and its successors, and to the value- and policy-learning ideas that underpin how we train agents today.
Its two engineering fixes also outlived their original setting. Replay buffers and target (or slowly-updated "Polyak-averaged") networks became standard components in off-policy RL far beyond DQN, and the general lesson — that bootstrapped self-referential targets need stabilization to be trainable — recurs whenever a model is trained against a target derived from itself. DQN handles discrete actions with a value function; the field's other main branch, policy-gradient methods like PPO, tackles continuous control and now the fine-tuning of language models. Between them, value-based and policy-based, sits nearly all of modern RL — and DQN is where the "deep" in it began.
The max in the Bellman target is both the engine and a bug: taking the max over noisy Q-estimates systematically overestimates values, because any estimate that happens to be too high gets selected. Double DQN fixes this by decoupling the choice of the best next action (online network) from the evaluation of its value (target network), which measurably improves stability and scores.
Questions people ask about DQN
How does DQN preprocess Atari frames?
Each frame is combined with the previous one by a pixelwise maximum to remove flicker, converted to brightness, and resized to 84 by 84. The last four processed frames are stacked into one 84×84×4 input so the network can see motion. On top of that the agent only chooses an action every fourth frame and repeats it in between, which is called frame-skip. Space Invaders used three instead of four because the lasers disappear at four.
How does DQN anneal epsilon for exploration?
Epsilon is the chance of taking a random action instead of the best-looking one. In DQN it starts at 1.0, so early play is entirely random, and falls linearly to 0.1 over the first million frames. After that it stays at 0.1 for the rest of training. When the trained agent is evaluated, epsilon is set to 0.05 so it is mostly greedy but still not completely deterministic.
Why can DQN reuse old experience when many methods cannot?
Q-learning is off-policy. Its target depends on the best next action under the current estimate, not on which action the older policy actually took. So a transition collected by a worse, more random version of the network is still a valid example for learning the value of acting greedily. Methods that estimate the value of the policy that produced the data, such as basic policy gradients, cannot safely reuse data that old.
Why does DQN clip rewards and errors?
Atari scores differ wildly between games, from single digits to thousands per episode. Clipping each reward to minus one, zero or plus one keeps error sizes comparable so one learning rate works everywhere. The downside is that the agent cannot distinguish a small reward from a large one. The error term in the loss is also clipped to the range minus one to one, which prevents a single large mistake from producing a huge gradient.
What happens if you remove the target network from DQN?
Training becomes unstable, because the target changes every time the network takes a step. In the paper's ablation on Breakout, keeping replay but removing the target network dropped the average score from roughly 317 to roughly 10, a much bigger loss than removing replay alone. Removing both left the agent near 3 points on that game. The frozen copy gives the online network a stationary goal between refreshes, which is why it matters so much.
What does human-normalized score mean?
It rescales a game score so that a random player is 0 and a professional human tester is 100, using the formula 100 times (agent minus random) over (human minus random). That allows averaging across games with very different score ranges. DQN exceeded 75 percent of the human level on 29 of 49 games. Values above 100 mean the agent beat the human baseline on that game.
3 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
With r = 1, γ = 0.99 and next-state target values [2, 5, 3], what is the target, and what error reaches the gradient if Q(s, a) is 3?
Show answer
The target is y = 1 + 0.99 × 5 = 5.95. The raw error is 5.95 − 3 = 2.95, but the error is clipped to the range −1 to +1, so the gradient sees an error of 1. If the transition were terminal, the target would simply be 1.
Why would training on the most recent 32 transitions in order work worse than sampling 32 at random?
Show answer
Consecutive frames are nearly identical, so the last 32 transitions are one narrow slice of one episode. Gradients from them point the same way and the network overfits to that moment. Random sampling mixes many episodes and eras of play, which makes the batch look more like independent data and lets each transition be used many times.
At frame 500,000 of training, what is ε, and at frame 5 million?
Show answer
ε falls linearly from 1.0 to 0.1 over the first million frames, so at 500,000 it is halfway down: 1.0 − 0.5 × 0.9 = 0.55. By 5 million frames it has long since reached its floor, so it is 0.1.
Learning by trial and error
Reward, policy, search. The line from Atari to a Go engine that was never shown a human game — and the algorithm (PPO) that RLHF later borrowed wholesale.
- 1DQN2015
- 2PPO2017
- 3AlphaGo2016
- 4AlphaZero2018
- 5MuZero2020
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- Word2VecHow words became math. Dense word vectors learned from the company a word keeps, so king − man + woman lands near queen. Skip-gram, CBOW, the distributional hypothesis, and the origin of every embedding model powering search and RAG.Read →
- ResNetThe skip connection that made deep learning deep. Why stacking layers made networks worse, and how residual learning let them reach 150+ layers and win ImageNet — the identity shortcut every Transformer still uses inside every block.Read →
- Vision Transformer (ViT)When an image became 16×16 words. Cut a picture into patches, treat each patch as a token, and feed them to a plain Transformer — no convolutions. Patch embeddings, the class token, and why data scale lets attention beat the CNNs that ruled computer vision for a decade.Read →
- Latent DiffusionThe paper behind Stable Diffusion. Compress an image into a small latent space with a VAE, run the diffusion denoising there instead of on pixels for a tens-of-times efficiency win, and steer it with text via cross-attention. The architecture that put text-to-image generation on consumer GPUs.Read →
- DDPMThe original denoising diffusion math — the paper that made diffusion work. A fixed forward process adds Gaussian noise over many steps; a U-Net learns the reverse. The masterstroke: train the network to simply predict the added noise with a plain MSE loss. The foundation under every modern image generator.Read →