Learn how good each action is in each state, then take the best one. Each update moves one number toward a target, and the goal's reward of 10 flows back until the start cell reads 4.58.
Learn a value for every action, act on the largest, and make that work with neural networks, with every equation read aloud.
Press Step to move the agent once and update one value. Press Episode to run to the goal. Watch the numbers fill in from the goal backward. Then change gamma. Then we build it piece by piece: the argmax policy, the Bellman equation, the update, exploration, DQN, overestimation and its fix.
You need a little Python and what an average is. We build the rest from zero.
Re-taught from Lecture 6, Q-Learning, of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.
Illustrative toy. Each move costs 1. The move from D into the goal G pays 10 and ends the episode. Moving left at A bumps the wall. The agent explores with epsilon 0.2 and breaks ties at random. At gamma 0.9 the true values of moving right are 4.58, 6.20, 8.00 and 10.00.
Chapter 0
Read the critic's numbers and take the best action, and the new policy is never worse
A game has four arrow keys. A critic tells you what each key is worth from here: up 3.2, down 1.0, left 5.7, right 2.4. Which key do you press? Left. You needed no policy network to decide.
In actor-critic, an actor picks actions and a critic scores them. The critic's score is the Q-function: the average return if you take action a in state s, then follow the policy π (pi). The return is the sum of the rewards, each shrunk by a discount γ (gamma) once per step of delay. Q-learning keeps only the critic, and acts by taking the action with the largest Q.
Call the old policy pi and the new policy pi-prime. In state s, the new policy reads the critic's numbers and picks the largest.
Pi-prime of s equals the argmax over a of Q-pi of s and a.
List Q-pi of s and a for every action a. The action with the largest number is pi-prime of s.
With made-up numbers: Q-pi of left is 3 and of right is 7. Pi picks left 60% of the time, so it earns 0.6 × 3 + 0.4 × 7 = 4.6. Pi-prime always picks right and earns 7.
Warm bars are the critic's two values. The pink mark is what the old policy earns; the teal mark is what the argmax earns. Drag any slider: pink never passes teal.
One state, two actions, made-up values.
The policy improvement theorem makes this safe: pi-prime earns at least as much as pi in every state. In one state the reason shows above: an average of the Q values cannot beat the largest one.
The failure. Argmax needs a list of actions to try. Four keys cost four lookups. A robot arm with 7 joints, each cut into 11 torque levels, has 117, about 19.5 million actions. The symptom is an action choice slower than the robot. Measure Q evaluations per step. The fix is an actor network, or a sampled search (Chapter 9).
Chapter 1
Alternate between scoring a policy and acting greedily on the scores, and pay for every scoring
Where do the critic's numbers come from? The classic answer is policy iteration. It repeats two steps until the policy stops changing:
Evaluation uses a consistency rule. The value of a step is its reward plus the discounted value of where you land. Call the reward r of s and a, the next state s-prime, and the next action a-prime.
Q-pi of s and a equals r of s and a, plus gamma times the expected value, over s-prime and a-prime drawn from pi, of Q-pi of s-prime and a-prime.
Take the reward of this step. At the next state s-prime, average Q-pi over the actions pi would take. Shrink that average by gamma and add it.
The hero's corridor under a coin-flip policy: Q-pi of D-left is −1.51 and of D-right is 10. So Q-pi of C-right = −1 + 0.9 × (0.5 × −1.51 + 0.5 × 10) = 2.82.
Every Q is on both sides, so you solve it by sweeps. Start all values at 0, apply the rule to every entry, and repeat until the numbers stop moving.
Pink arrows are a coin-flip policy. Press Evaluate and count the sweeps. Then press Improve: teal arrows show the argmax.
The hero's corridor, gamma 0.9. A sweep updates all 8 entries once. Evaluation stops when no entry moves by more than 0.001.
Here one round is enough. The coin-flip policy needs 38 sweeps. Improve then picks right in every cell, which is the best policy. Checking that takes 6 more sweeps.
The failure. Each evaluation sweeps every state, many times. An Atari screen has more states than you can list, so the inner loop never ends. Measure the cost as states × actions × sweeps per improvement: 8 × 38 = 304 backups here. The fix is to stop evaluating fully (next chapter).
Chapter 2
Put the max inside the backup, and the best values satisfy one equation with no policy in it
Policy iteration scores a policy and then improves it. What if every backup improved as it went? Replace "average over what pi does next" with "take the best next action." The values that satisfy that rule are Q-star: the value of taking a in s, then acting perfectly.
The world sends you to s-prime with chance p of s-prime given s and a. At s-prime you take the best next action a-prime.
Q-star of s and a equals r of s and a, plus gamma times the expected value, over s-prime drawn from p given s and a, of the max over a-prime of Q-star of s-prime and a-prime.
Take the reward. For each place s-prime, read the best Q-star there. Average those by their chances, shrink by gamma, and add.
The corridor, gamma 0.9, no slip: Q-star of D-right is 10. So Q-star of C-right = −1 + 0.9 × max(6.20, 10) = 8.00, and Q-star of B-right = −1 + 0.9 × 8 = 6.20.
Q-star has no pi in it. It belongs to the world, and its argmax is the best policy. Value iteration applies the rule to every entry, sweep after sweep. Each sweep shrinks the largest error by at least a factor gamma, so it always converges.
Press Sweep. The values fill in from the goal, and the purple bars below show the largest change in each sweep. Then add slip.
The hero's corridor. With chance "slip", a move fails: the agent stays put and pays 1.
The failure. Value iteration needs p, the world's rules. Set slip to 0.2: Q-star of C-right falls from 8.00 to 7.13. A real robot does not know its slip. The symptom is a plan whose returns differ from what the robot gets. Measure that gap. The fix is to sample the world instead of reading p (next chapter).
Chapter 3
Replace the expectation with one observed step, and move each value part of the way to its target
You do not know p, but you can act and watch. A transition is one record (s, a, r, s-prime): the state, the action, the reward, and where you landed. It is one sample of the average in the Bellman equation.
Q-learning turns the sample into a target y: the reward plus gamma times the best Q at s-prime. It then moves the stored value a fraction α (alpha) toward y. Alpha is the learning rate, from 0 to 1.
Q of s and a becomes Q of s and a, plus alpha times the bracket: r, plus gamma times the max over a-prime of Q of s-prime and a-prime, minus Q of s and a.
Build y: r plus gamma times the best Q at s-prime. Subtract the old Q of s and a. Add alpha times that difference.
Alpha 0.5, gamma 0.9, all values 0. The agent at D moves right into the goal: y = 10, so Q(D, right) = 0 + 0.5 × (10 − 0) = 5.00.
Three updates in a row, with the same settings:
The reward reached D first, then C: values flow back one cell per visit. The target uses the max at s-prime, not the action the agent took next. So Q-learning is off-policy: it learns Q-star from any data, if the agent tries every pair often. Watkins introduced it in 1989; Watkins and Dayan proved in 1992 that the table converges to Q-star.
Yellow dots are 200 noisy rewards for one entry; the warm line is its value. Press Run, then try a small alpha and the shrinking schedule.
Illustrative: rewards of mean 10 and standard deviation 4. A new run draws new noise.
The failure. With a fixed alpha and noisy rewards, the value never settles. At alpha 0.5 it wanders about 2.3 around the mean. Measure the spread of an entry over recent visits. The fix is a shrinking alpha: 1/n turns the update into a running average.
Chapter 4
Take the best-looking action most of the time and a random one the rest, then lower the randomness
Q-learning learns from any data, but it needs data on every action. An agent that always takes its current best never tests the others. If its early numbers are wrong, it never finds out.
Epsilon-greedy fixes this with one number ε (epsilon), from 0 to 1. With chance 1 − ε, take the argmax. With chance ε, pick an action at random, each action equally likely.
A worked case: Q is up 3.2, down 1.0, left 5.7, right 2.4, and epsilon is 0.1. The random part gives each action 0.1 / 4 = 0.025. Left also gets the greedy 0.9.
| Action | Q | Greedy share | Random share | Chance |
|---|---|---|---|---|
| Left (the argmax) | 5.7 | 0.900 | 0.025 | 0.925 |
| Up, down, right | 3.2, 1.0, 2.4 | 0 | 0.025 | 0.025 each |
Anneal epsilon: start at 1, because early Q values are noise, and lower it as the table improves. DQN lowered it in a straight line from 1.0 to 0.1 over the first million frames, then held 0.1 (Mnih et al., 2015). At frame 500,000: 1.0 − 0.9 × 0.5 = 0.55.
Bars are the chance of each action: teal is the greedy share, yellow the random share. Drag the frame along DQN's schedule, then sample 100 actions.
The schedule is DQN's (Mnih et al., 2015). We made up the four Q values.
Boltzmann exploration is a common alternative. It picks each action with chance in proportion to e to the Q over a temperature. Better actions get more of the random tries.
The failure. Lower epsilon too soon, and the agent locks onto its first decent action. The symptom is a flat score and parts of the world never visited. Measure distinct state-action pairs visited per thousand steps. The fix is a slower decay or a higher floor.
Chapter 5
Swap the table for a network, regress on frozen targets, and train on old transitions drawn at random
A table needs one entry per state. An Atari input is 4 stacked frames of 84 × 84 grey pixels, and no table can hold that. So a neural network with weights θ (theta) outputs Q for every action in one forward pass. Fitted Q iteration trains it in rounds:
Call the frozen copy's weights φ′ (phi-prime) and the dataset D. The loss compares the network's value with the target.
L of theta equals the expected value, over transitions drawn from D, of Q-theta of s and a minus the target, squared. The target is r plus gamma times the max over a-prime of Q-phi-prime of s-prime and a-prime.
Draw a minibatch. Build each target with the frozen copy. Average the squared gaps and step theta downhill. Every N steps, copy theta into phi-prime.
With made-up numbers: Q-theta of (C, right) is 5.0, the frozen copy's best value at D is 4.8, r = 1 and gamma 0.99. Target = 1 + 0.99 × 4.8 = 5.752. Squared gap = (5.0 − 5.752)2 = 0.566.
Why freeze? Without the copy, the target also uses theta. The network shares its weights, so a step on C also moves D. That moves C's own target.
The warm line is Q(C, right); the purple line is its target, blue when frozen. Press Run, then freeze the target, then raise the leak.
Illustrative two-value model: a step of size 0.2 on C, a fraction "leak" of it added to D. Reward −1, gamma 0.9, D starts at 10. The frozen copy refreshes every 25 steps.
DQN (Mnih et al., 2015) trains this loss online. A replay buffer keeps the last 1 million transitions. DQN draws each minibatch of 32 at random, so near-identical neighbouring frames do not fill one step. It refreshes the target network every 10,000 updates. One network, three conv layers and a 512-unit layer, about 1.7 million weights, played 49 Atari games with the same settings. It reached at least 75% of a professional tester's score on 29 of them.
The failure. Raise the leak above 1.11. Both curves run away, frozen or not: each step feeds the target more than it closes the gap. This is the deadly triad: function approximation, bootstrapping and off-policy data together. Measure the largest Q against the largest possible return, 10 here. Fixes: smaller steps, a Huber loss, and Double DQN.
Chapter 6
The max of noisy guesses is too high on average, and bootstrapping passes the excess back
Two actions are both worth 5. The network's guesses are noisy. Three tries give (7, 4), (2, 7) and (6, 6). The max is 7, 7 and 6: an average of 6.67. The target rates the best action 1.67 too high.
The max keeps whichever guess got the luckiest noise. Call the network's guess for action a Q-hat of a: the true value plus noise that averages to 0.
The expected value of the max over a of Q-hat of a is at least the max over a of the expected value of Q-hat of a.
Draw a noisy Q-hat for every action and keep the largest. Repeat and average. That average sits at or above the best true value.
With made-up numbers: every action worth 5, noise of standard deviation 2. With 2 actions the average max is 5 + 0.56 × 2 = 6.13. With 18 actions, an Atari pad, it is 5 + 1.82 × 2 = 8.64.
Warm dots are one draw of guesses; the teal ring is their max. The line below is the running average of the max against the truth, 5. Press Draw 500, then add actions.
Illustrative: every action is truly worth 5; the noise is Gaussian.
Bootstrapping compounds it: the inflated max is the target for the state before, and so on back. Thrun and Schwartz described this in 1993. van Hasselt, Guez and Silver (2016) measured it in DQN on Atari. On several games, the value estimates rose far above the returns the agent got.
The failure. The symptom is Q values that keep rising while the score stays flat. To measure it, run the greedy policy, compute the real discounted return from a state, and compare it with Q there. The fix is to stop using one set of noisy numbers to both pick and score (next chapter).
Chapter 7
Pick the action with one set of estimates and score it with another
Overestimation comes from one set of noisy numbers doing two jobs: selection (which action is best) and evaluation (its value). If noise makes an action look best, the same noise makes its score high.
Double Q-learning (van Hasselt, 2010) splits the jobs between two estimates. Double DQN (van Hasselt, Guez and Silver, 2016) uses the two networks DQN already has. The online network theta selects, and the target network phi-prime evaluates.
y equals r plus gamma times Q-phi-prime of s-prime and the argmax over a-prime of Q-theta of s-prime and a-prime.
Ask the online network which action is best at s-prime: that is a-star. Ask the target network for the value of a-star. Use that number in the target.
With made-up numbers: both actions truly worth 5, r = 1, gamma 0.9. The online network says left 7, right 4. One set of numbers gives 1 + 0.9 × 7 = 7.30. Double: the online network picks left, the target network says 4.8, so 1 + 0.9 × 4.8 = 5.32. The truth is 5.50.
The fix works only when the two networks make different errors. The target network is an old copy of the online one, so their errors overlap. In this toy, the leftover bias is the correlation times the bias of the plain max.
Warm dots are the online guesses, blue dots the target network's. The teal ring marks a-star. Bars show the average bias of each target. Press Draw 2000, then raise the correlation.
Illustrative: 4 actions, each truly worth 5, Gaussian noise of standard deviation 2 in both networks.
The failure. Double DQN can underestimate. When rewards are rare and small, a low estimate can hide the one good action from the states before it. Measure the sign of the gap between Q and real returns. Other fixes average several target networks, or take the smaller of two critics, as TD3 and SAC do.
Chapter 8
Use several real rewards before you trust the table, and accept some bias from the explorer
Early in training, Q is mostly wrong. A one-step target leans on Q after one real reward. An n-step target uses n real rewards, then the table.
Call the reward k steps after time t r-t-plus-k, and the state n steps on s-t-plus-n.
y equals the sum, for k from 0 to n minus 1, of gamma to the k times r-t-plus-k, plus gamma to the n times the max over a-prime of Q of s-t-plus-n and a-prime.
Add the next n rewards, each shrunk by gamma once per step. Add the best Q at the state n steps on, shrunk n times.
With made-up numbers: rewards 1, 1, 10, then the end; gamma 0.9. The true value is 1 + 0.9 + 0.81 × 10 = 10.0. The table wrongly says 2 one step on. One step: 1 + 0.9 × 2 = 2.8. Three steps: 10.0, with no table at all.
Green rows are real rewards, the warm row is the table's part, and the purple row is their sum y. Move n, then let the explorer take a random step.
Illustrative. The table's values are 2 one step on and 3 two steps on; the true values are higher. The random step pays −4 instead of 1.
The catch: the n rewards come from the explorer's actions, not the greedy policy's. So for n above 1 the target carries a bias, unless the data is on-policy. Most systems accept that. Rainbow (Hessel et al., 2018) used n = 3, and in its ablation, removing multi-step returns was one of the two cuts that hurt most.
The failure. Turn on the random step. The three-step target falls to 1 + 0.9 × (−4) + 8.1 = 5.5, though the greedy policy earns 10. Measure how often a random action lands inside the window: 1 − (1 − ε)n−1, which is 0.19 at epsilon 0.1 and n = 3. The fix is a small n, or a sum cut at the first random action.
Chapter 9
Place Q-learning beside policy gradients, PPO and SAC, and choose by action type and data cost
Every online method in this course has three parts: where its data comes from, which value it learns, and how it picks actions.
| Method | Data | Value learned | Picks actions by | Key trick |
|---|---|---|---|---|
| Vanilla policy gradient | On-policy | None | Sampling π | Reward-to-go |
| PPO | Near on-policy | V-pi | Sampling π | Clipped ratio, GAE |
| SAC | Replay buffer | Q-pi | Sampling π | Entropy bonus |
| DQN | Replay buffer | Q-star | Argmax of Q | Target network, epsilon-greedy |
Down the table: less policy, more value. Each row trades flexibility, such as continuous actions, for data reuse.
The four methods sit on a line from more policy to more value. Choose the actions and the cost of data; the ring marks the fit.
The fits follow the course's advice; the torque count assumes 11 levels per joint.
The worked number: an Atari pad has 18 actions, and one forward pass returns all 18 Q values. A 7-joint arm with 11 torque levels per joint has 117 = 19,487,171 actions for each argmax.
QT-Opt (Kalashnikov et al., 2018) ran Q-learning on real robot arms for grasping. It finds the argmax over continuous actions with the cross-entropy method: sample actions, keep the best few, refit, repeat.
The failure. Cut a continuous action finely and the argmax searches millions of actions. Cut it coarsely and the robot jerks between levels. Measure actions per argmax and the gap between levels. The fix is an actor (SAC) or a sampled search (QT-Opt).
Chapter 10
Keep the equations, the numbers, a checklist and the core code on one page
Learn Q, act by its argmax. Each update moves Q toward the reward plus the discounted best Q one step on. Neural networks need a frozen target and a replay buffer to train stably. The max overestimates, so Double DQN picks with one network and scores with the other.
| Step | Target or rule | What it fixes |
|---|---|---|
| Policy iteration | Evaluate Q-pi, then argmax | Needs no policy gradient, but full evaluation each round |
| Value iteration | r + γ E[max Q] | Skips full evaluation, but needs the model |
| Q-learning | r + γ max Q(s′, ·), one sample | Needs no model; off-policy |
| DQN | r + γ max Qφ′(s′, ·) | Big state spaces, with stable regression |
| Double DQN | r + γ Qφ′(s′, argmax Qθ) | The max's upward bias |
| N-step | n real rewards, then γn max Q | Slow spread of reward early on |
| What | Number | Source |
|---|---|---|
| Corridor Q-star, moving right, gamma 0.9 | 4.58, 6.20, 8.00, 10.00 | This page's toy |
| Sweeps to evaluate a coin-flip policy | 38 | This page's toy |
| Average max, 2 and 18 actions, noise 2 | +1.13 and +3.64 too high | Gaussian maths |
| DQN epsilon | 1.0 to 0.1 over 1M frames | Mnih et al., 2015 |
| DQN buffer, minibatch, target refresh | 1M, 32, every 10,000 updates | Mnih et al., 2015 |
| DQN learning rate, gamma | 0.00025 (RMSProp), 0.99 | Mnih et al., 2015 |
| DQN weights | about 1.7 million | Our count of its layers |
| Rainbow's n | 3 | Hessel et al., 2018 |
One Double DQN step, with the shape of each tensor:
pythonimport torch import torch.nn.functional as F def double_dqn_loss(q_net, target_net, batch, gamma=0.99): s, a, r, s2, done = batch # s, s2: [B, obs]; a: [B] long; r, done: [B] q = q_net(s).gather(1, a.unsqueeze(1)).squeeze(1) # [B]: Q_theta(s, a) with torch.no_grad(): # the target gets no gradient a_star = q_net(s2).argmax(dim=1) # [B]: the online net selects q_next = target_net(s2).gather(1, a_star.unsqueeze(1)).squeeze(1) # the target net scores y = r + gamma * q_next * (1.0 - done.float()) # [B]: y = r at the end return F.smooth_l1_loss(q, y) # Huber loss: big errors give bounded gradients # every step: draw a batch of 32 from the buffer, loss.backward(), optimizer.step() # every 10,000 steps: target_net.load_state_dict(q_net.state_dict())
Now press Present or Teach and rebuild the chain from memory, from the argmax to the double target. Then go back to the corridor, set gamma to 0.5, and say why the start cell's value turns negative.
This lesson re-teaches Lecture 6, Q-Learning, of Stanford CS 224R: Deep Reinforcement Learning, taught by Chelsea Finn. The papers behind it: Watkins (1989) and Watkins and Dayan (1992), Q-learning; Thrun and Schwartz (1993), overestimation; van Hasselt (2010), Double Q-learning. Then Mnih et al., DQN (2013) and the Nature paper (2015); van Hasselt, Guez and Silver, Double DQN (2016); Hessel et al., Rainbow (2018); Kalashnikov et al., QT-Opt (2018). The toys and numbers here are our own.