Q-Learning

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.

Teach a corridor where the goal is

0.50
0.90

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

From Actor-Critic to Critic Only

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.

Say it aloud

Pi-prime of s equals the argmax over a of Q-pi of s and a.

π′(s)
pi-prime of s the action the new policy takes in state s.
argmaxa
the argmax over a try every action a and return the action with the largest value, not the value.
Qπ(s, a)
Q-pi of s and a the average return of taking a in s, then following pi.
In plain words

List Q-pi of s and a for every action a. The action with the largest number is pi-prime of s.

With numbers

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.

Compare a mixed policy with the argmax

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.

3.0
7.0
0.60

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).

The road

  1. Policy iteration: evaluate, improve, repeat.
  2. The Bellman optimality equation: put the max inside.
  3. The Q-learning update: the hero's Step button.
  4. Epsilon-greedy: the hero agent's random moves.
  5. Target networks and DQN: Q-learning with a neural network.
  6. Overestimation: why the max is too optimistic.
  7. Double Q-learning: pick with one, score with the other.
  8. N-step returns: more real rewards per target.
  9. The online RL landscape: when to use which method.
  10. The field guide: terms, numbers, code and links.
The critic says Q(up) = 2, Q(down) = 9 and Q(left) = 4. The old policy picks each with chance 1/3. What do the old policy and the argmax policy earn here?

Chapter 1

Policy Iteration

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:

  1. Evaluate: compute Q-pi of s and a for every state and action.
  2. Improve: make the argmax of those numbers the new policy.

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.

Say it aloud

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.

Qπ(s, a)
Q-pi of s and a the value of taking a in s, then following pi.
r(s, a)
r of s and a the reward of this step: −1 for a move, +10 into the goal.
γ
gamma the discount, 0.9 here.
Es′, a′∼π
the expected value over s-prime and a-prime from pi the average over where you land and what pi does next.
Qπ(s′, a′)
Q-pi of s-prime and a-prime the value of the next step.
In plain words

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.

With numbers

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.

Evaluate, then improve

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).

Policy iteration stops when Improve returns the same policy. Why is that policy then the best one?

Chapter 2

The Bellman Optimality Equation

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.

Say it aloud

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.

Q*(s, a)
Q-star of s and a the value of taking a in s, then acting perfectly.
r(s, a)
r of s and a the reward of this step.
γ
gamma the discount, 0.9.
Es′∼p(·|s,a)
the expected value over s-prime from p the average over the places the world can send you.
maxa′
the max over a-prime the largest value among the next actions.
Q*(s′, a′)
Q-star of s-prime and a-prime the best values one step on.
In plain words

Take the reward. For each place s-prime, read the best Q-star there. Average those by their chances, shrink by gamma, and add.

With numbers

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.

Sweep the optimal backup

Press Sweep. The values fill in from the goal, and the purple bars below show the largest change in each sweep. Then add slip.

0.00
0.90

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).

Gamma is 0.9, a move costs 1, and Q-star at D is 6.2 for left and 10 for right. What is Q-star of C-right?

Chapter 3

The Q-Learning Update

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.

Say it aloud

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.

Q(s, a)
Q of s and a the table entry for this state and action.
←
becomes overwrite the stored value with the right side.
α
alpha the learning rate, 0.5 in the hero.
[ … ]
the bracket the TD error: target minus current value.
r
r the reward you observed.
γ
gamma the discount, 0.9.
maxa′ Q(s′, a′)
the max over a-prime of Q of s-prime and a-prime the best stored value where you landed; 0 at the goal.
In plain words

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.

With numbers

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:

  1. (D, right, +10, goal): y = 10. Q(D, right) goes from 0 to 5.00.
  2. (C, right, −1, D): y = −1 + 0.9 × 5.00 = 3.50. Q(C, right) goes from 0 to 1.75.
  3. (D, right, +10, goal) again: y = 10. Q(D, right) goes from 5.00 to 7.50.

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.

Average a noisy reward

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.

0.50

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.

Q(C, right) is 1.75. At D, Q is 7.5 for right and 0 for left. The agent at C moves right, pays −1 and lands at D. With alpha 0.5 and gamma 0.9, what is the new Q(C, right)?

Chapter 4

Exploration: Epsilon-Greedy

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.

ActionQGreedy shareRandom shareChance
Left (the argmax)5.70.9000.0250.925
Up, down, right3.2, 1.0, 2.400.0250.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.

Explore along the schedule

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.

0.50

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.

Epsilon is 0.2 and there are 4 actions. What is the chance that the agent takes the greedy action?

Chapter 5

Target Networks and DQN

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:

  1. Collect transitions into a dataset.
  2. Compute each target y with a frozen copy of the network.
  3. Fit the network to the targets by regression.
  4. Repeat steps 2 and 3.

Call the frozen copy's weights φ′ (phi-prime) and the dataset D. The loss compares the network's value with the target.

Say it aloud

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.

L(θ)
L of theta the loss that gradient descent lowers.
E(s,a,r,s′)∼D
the expected value over transitions from D the average over a random minibatch from the replay buffer D.
Qθ(s, a)
Q-theta of s and a the online network's value: the one you train.
r + γ max Qφ′
the target built with the target network Q-phi-prime, a frozen copy refreshed every N steps.
( … )2
squared so large gaps count more and signs do not cancel.
In plain words

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 numbers

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.

Chase the 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.

0.30

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.

What does drawing minibatches at random from a replay buffer fix?

Chapter 6

Q-Value Overestimation

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.

Say it aloud

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.

E
the expected value the average over many draws of the noise.
maxa
the max over a the largest of the action values.
Q̂(a)
Q-hat of a the network's noisy guess for action a.
≥
is at least equal only when the noise can never change the winner.
In plain words

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 numbers

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.

Take the max of noisy guesses

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.

2
2.0

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).

Every action is truly worth 5 and the noise stays the same. You add more actions. What happens to the average of the max?

Chapter 7

Double Q-Learning

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.

Say it aloud

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.

y
y the target for Q-theta of s and a.
r
r the observed reward.
γ
gamma the discount.
Qφ′
Q-phi-prime the target network: it scores the chosen action.
argmaxa′ Qθ(s′, a′)
the argmax over a-prime of Q-theta the online network's choice, called a-star: an action, not a value.
In plain words

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 numbers

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.

Split selection from evaluation

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.

0.50

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.

In Double DQN, which network picks the action at s-prime, and which one scores it?

Chapter 8

N-Step Returns

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.

Say it aloud

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.

y
y the n-step target.
Σk=0n−1
the sum for k from 0 to n minus 1 one term per real step.
γk
gamma to the k the shrink for a reward k steps late.
rt+k
r-t-plus-k the real reward k steps after t.
γn
gamma to the n the shrink on the table's part.
maxa′ Q(st+n, a′)
the max over a-prime of Q of s-t-plus-n the best table value n steps on; 0 if the episode ended.
In plain words

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 numbers

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.

Choose how many real rewards

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.

1

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.

n = 3, gamma 0.99, rewards 1, 0, 0, and the best Q three steps on is 100. What is the target?

Chapter 9

The Online RL Landscape

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.

MethodDataValue learnedPicks actions byKey trick
Vanilla policy gradientOn-policyNoneSampling πReward-to-go
PPONear on-policyV-piSampling πClipped ratio, GAE
SACReplay bufferQ-piSampling πEntropy bonus
DQNReplay bufferQ-starArgmax of QTarget network, epsilon-greedy

Down the table: less policy, more value. Each row trades flexibility, such as continuous actions, for data reuse.

Pick a method for the problem

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).

A robot with 7 continuous joint torques, and each hour of robot time is costly. Which method fits best?

Chapter 10

The Field Guide

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.

The chain of fixes

StepTarget or ruleWhat it fixes
Policy iterationEvaluate Q-pi, then argmaxNeeds no policy gradient, but full evaluation each round
Value iterationr + γ E[max Q]Skips full evaluation, but needs the model
Q-learningr + γ max Q(s′, ·), one sampleNeeds no model; off-policy
DQNr + γ max Qφ′(s′, ·)Big state spaces, with stable regression
Double DQNr + γ Qφ′(s′, argmax Qθ)The max's upward bias
N-stepn real rewards, then γn max QSlow spread of reward early on

The numbers

WhatNumberSource
Corridor Q-star, moving right, gamma 0.94.58, 6.20, 8.00, 10.00This page's toy
Sweeps to evaluate a coin-flip policy38This page's toy
Average max, 2 and 18 actions, noise 2+1.13 and +3.64 too highGaussian maths
DQN epsilon1.0 to 0.1 over 1M framesMnih et al., 2015
DQN buffer, minibatch, target refresh1M, 32, every 10,000 updatesMnih et al., 2015
DQN learning rate, gamma0.00025 (RMSProp), 0.99Mnih et al., 2015
DQN weightsabout 1.7 millionOur count of its layers
Rainbow's n3Hessel et al., 2018

Before you trust a DQN run

The core code

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())

Keep going

The takeaway. Q-learning is value iteration with the expectation replaced by one sampled step. Everything after the table, from target networks to Double DQN, keeps that sampled backup stable and honest.
Which change removes most of the max's upward bias at almost no cost in DQN?

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.

Credit and source

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.

CS 224R: Q-Learning
The course site · DQN · Double DQN · Back to Gleams