A planner with the map solves this maze in a few sweeps. Q-learning has no map. It wanders, collects rewards, and ends with the same arrows.
Pick a solver and press Run. Watch where each one gets its numbers. Then we build, piece by piece, the sampled update, fitted Q-iteration, the off-policy max, and the two tricks that let a neural network do it from pixels.
You need states, actions, rewards and the discount from Lecture 7, and a little Python. We build the rest from zero.
Lecture 8 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Previous: Lecture 7. Next: Lecture 9, Policy Gradients.
Illustrative toy. Moves are certain. A step costs 0.04, the goal pays +1, the pit costs 1, discount 0.92. Q-learning uses ε = 0.2, starts each episode in a random cell, and uses α = 1, since with certain moves one sample is the exact answer. The arrow count compares each cell's learned greedy action with the planner's best action.
Chapter 0
See which number value iteration needs that a real robot never has, and replace it with a sample
Drop a robot into a building it has never seen. It does not know where a door leads. It learns the reward of a move only after it makes the move.
Lecture 7 solved this kind of problem with Q-value iteration: start with a guess for every Q-value and improve all of them at once, again and again. A Q-value Q(s,a) is the total discounted reward you expect if you take action a in state s, then act well forever after. Name the quantities first. Call the chance that action a in state s lands in next state s′ with reward r p(s′,r | s,a). Call the discount γ and the guess after k rounds Qk.
Q k-plus-one of s, a equals the sum over every s-prime and r of p of s-prime and r given s and a, times r plus gamma times the max over a-prime of Q-k of s-prime, a-prime.
For each outcome of the step, add the reward r to gamma times the best old Q-value at s-prime. Weight each outcome by its chance p. The weighted total is the new Q.
With made-up numbers: γ = 0.9. With chance 0.8 the robot lands where the best Q is 10, reward 0. With chance 0.2 it lands where the best Q is 2, reward −1. Q = 0.8 × (0 + 9) + 0.2 × (−1 + 1.8) = 7.2 + 0.16 = 7.36.
The robot cannot compute the 0.8 and the 0.2. It can only take the step and see where it lands. Each landing gives one sample of the bracket: 9 or 0.8. Nudge an estimate toward each sample, and the average of many nudges is the sum.
Each dot is one sampled step: 9 when the robot lands in the good place, 0.8 in the bad one. The yellow line is the estimate. Take steps and watch it find the dashed sum it never computed.
Illustrative toy with the numbers above. The estimate starts at 0. The chances 0.8 and 0.2 drive the dice; the update never reads them.
That substitution, a sample in place of a sum, is the first idea of the lecture. The second comes from size: when there are too many states for a table, a function replaces the table. The rest of the lecture combines the two and repairs what breaks.
The symptom is an estimate that never settles. Measure it by plotting the estimate against the number of samples. If it keeps jumping by the size of one sample, α is too large; lower it, or let it shrink over time.
Chapter 1
Count the states of an Atari screen, then let a function fill the cells a table never visits
The hero's maze has 25 cells and 4 actions, so its Q-table has 100 numbers. A robot's camera is not a maze. Its state is a picture.
Count an Atari screen. The DQN paper shrinks each frame to 84 × 84 grey pixels and stacks the last 4 frames, so 28,224 pixels with 256 grey levels each. The number of possible inputs is 256 to the power 28,224, about 10 to the power 67,970. The universe has about 10 to the power 80 atoms. The table size is |S| × |A|, and you will never see the same screen twice. Richard Bellman called this the curse of dimensionality.
The lecture's good news: Q has patterns. Nearby states have similar values. A ball one pixel to the left is worth about the same. Learning patterns from examples is what deep learning does. So replace the table with a function approximator Qφ(s,a): a network with weights φ (phi) that takes a state and returns a value for each action.
The dashed yellow curve is the true value over 40 states. Blue dots are the states the robot visited. Switch between a table and a fitted function, then change how many states the robot saw.
Illustrative toy. The table leaves unvisited cells at 0. The function is a least-squares fit of a degree-5 polynomial with a small penalty, standing in for a network.
Work the number at 8 visited states. The table is right at those 8 and wrong at the other 32, so its average error is large. The fit uses the same 8 points and lands near the curve everywhere. On a screen, every state is an unvisited state, so only the function can say anything.
The price is coupling. One weight change moves the value of many states at once. Chapter 6 shows how that coupling can make Q-learning blow up.
The symptom is a table agent that plays well only on states it has seen. Measure it by testing on fresh starting states. The fix is a function with the right structure: convolutions for pixels, so a pattern learned in one place works in another.
Chapter 2
Turn each stored step into a regression target, fit, and repeat, with data from any policy
A warehouse robot logged a week of driving under an old controller. Can you learn a better controller from that log alone? Fitted Q-iteration (FQI) says yes, if the log covers enough.
The log is a dataset of steps. Step i holds a state si, the action taken ai, the reward ri and the next state s′i. FQI builds a target for each step from the current network Qφ. Call that target yi.
y-i equals r-i plus gamma times the max over a-prime of Q-phi of s-prime-i, a-prime.
Take the recorded reward r-i. Ask the network for the best value at the recorded next state, and multiply by gamma. Add them. That is y-i.
With made-up numbers: r-i = 0, γ = 0.9, and at s′i the network says left 0.5, right 0.81. y-i = 0 + 0.9 × 0.81 = 0.729.
Then fit: change φ so that Qφ(si,ai) is close to yi on every step, by least squares. Freeze the new φ, rebuild the targets, fit again.
φ ← argminφ Σi ( Qφ(si,ai) − yi )²: the weights that make the squared misses smallest.
Look at what yi uses: the recorded step and the max. It never asks which policy chose ai. That policy only decides which steps are in the log. So FQI is off-policy: it learns the best policy from data any policy collected.
A corridor of 6 states with the goal on the right. Set how often the collector steps right, collect 40 steps, then run fitting rounds. Each cell pair is Q(left) and Q(right); “?” means the log never tried it.
Illustrative toy. The goal pays 1, other steps 0, γ = 0.9. A round sets each seen Q(s,a) to the average target of its logged steps, the exact least-squares fit for a table.
Each round pushes value one more state back from the goal. At 0% the collector never moves right, so the log has no reward and FQI learns nothing. At 100% it never tries left, so left stays unknown. The lecture's condition is coverage: the log must contain the pairs that matter.
The symptom is a policy that looks good in fitting and fails when run. Measure coverage: count how often each state and action appears in the log. The lecture names both bad ends. A collector that is too random learns slowly; one that is too fixed leaves holes. Fix the data, not the fit.
Chapter 3
Shrink FQI to one step and one small move, and push real numbers through it
FQI waits for a whole log and solves a full regression each round. The lecture lists the problems: the log is fixed, and the full fit is hard. Online Q-learning does the smallest version instead. Take one action, see one step, move one estimate a little.
For a table, write the step out. Call the step size α (alpha). The gap between target and old value is the TD error δ (delta), the surprise of this step.
Q of s, a becomes Q of s, a plus alpha times the bracket: r plus gamma times the max over a-prime of Q of s-prime, a-prime, minus Q of s, a.
Build the target r plus gamma times the best Q at s-prime. Subtract the old Q of s, a to get the surprise delta. Add alpha times delta to the old value.
With made-up numbers: γ = 0.9, α = 0.5, r = 1, old Q(s,a) = 4, and at s′ Q(up) = 5, Q(down) = 8. Target = 1 + 0.9 × 8 = 8.2. δ = 8.2 − 4 = 4.2. New Q = 4 + 0.5 × 4.2 = 6.1.
This is the network update of the next chapters with a table inside. For a table, the gradient of Q(s,a) is 1 for its own cell and 0 for every other cell. So the gradient step touches one cell.
One cell starts at 4. Its true target averages 8.2, but each step's reward is noisy. Apply updates and slide α: small moves slowly and smoothly, large jumps to every noisy sample.
Illustrative toy with the numbers above. The first reward is exactly 1; later rewards are 1 plus uniform noise between −1.5 and +1.5.
Now write the update and let it solve a corridor from samples alone.
The symptom is values that rise for a while, then wobble. Measure the spread of the last 50 values of one cell. If the spread is as big as the reward noise, α is too large; lower it or decay it.
Chapter 4
Change one term in the target, and watch two robots pick different paths along a cliff
The max in the target is a choice. SARSA makes the other choice. It uses the action the robot takes next, a′. Its name lists the five things it needs: state, action, reward, next state, next action.
| Method | Target | Learns the value of | Class |
|---|---|---|---|
| Q-learning | r + γ maxa′ Q(s′,a′) | the greedy policy | off-policy |
| SARSA | r + γ Q(s′,a′), a′ the action taken | the policy it follows, exploration included | on-policy |
Use the numbers from Chapter 3, and say the robot explored and took up next. SARSA's target is 1 + 0.9 × 5 = 5.5, so Q moves from 4 to 4.75. Q-learning's target is 8.2, so Q moves to 6.1. Same step, one term apart.
The cliff walk from Sutton and Barto (Example 6.6) makes the difference visible. Start bottom left, goal bottom right, a cliff between. Each step costs 1. Stepping into the cliff costs 100 and sends you back to the start. Both robots train with ε = 0.1, so one move in ten is random.
Purple is Q-learning's learned path, grey is SARSA's. Both trained 500 episodes. Slide the exploration used while walking, and compare falls and reward over 2,000 walks.
Toy after Sutton and Barto, Example 6.6: 4 × 12 grid, α = 0.5, γ = 1, one fixed random seed. Fall rates and returns are computed live from 2,000 walks.
Q-learning's target assumes perfect steps from s′ on, so it learns the 13-step edge path. SARSA's target includes its own random slips, so the edge looks bad and it learns a longer path away from it. At ε = 0 Q-learning wins, 13 steps to 17. At ε = 0.1 it falls in about one walk in four, SARSA in about 3 in 100.
With ε fixed, SARSA converges to the best policy that still explores, not to Q*. Shrink ε toward 0 over training and both reach the optimal path.
The symptom is a robot whose learned policy is optimal on paper and crashes in practice. Measure the reward while acting with real noise, not the greedy reward. If a real slip is costly, learn on-policy, or plan a margin from the edge.
Chapter 5
Spend a fixed share of actions on random tries, and decay that share as the values firm up
Online Q-learning must choose its own actions. If it always takes the best-looking action, it never learns that another action was better. If it always acts at random, it wastes reward. This is the exploration and exploitation trade.
The lecture's answer is ε-greedy (epsilon-greedy). With chance 1 − ε, take the action with the largest Q. With chance ε, take a random action, any of the n actions with equal chance. The random draw can also land on the greedy action. Call the chance of taking the greedy action P(greedy).
P of greedy equals one minus epsilon, plus epsilon over n.
The greedy action wins in two ways. The exploit branch picks it with chance one minus epsilon. The random branch picks it with chance epsilon over n. Add the two.
With made-up numbers: n = 4 and ε = 0.4. P(greedy) = 0.6 + 0.4 / 4 = 0.7. Each other action gets 0.1.
Five slot-machine arms; arm 4 pays most. The curve is the average reward per pull over 500 pulls at each ε. Slide ε, then switch on decay.
Illustrative toy. Arm means 0.2, 0.5, 0.3, 1.0, 0.4; each pull adds noise with standard deviation 1. Averages over 200 runs. Decay goes linearly from 1 to ε over the first 100 pulls.
At ε = 0 the agent locks onto the first arm that paid well. At ε = 1 it finds arm 4 and keeps wasting pulls. The best fixed ε is small. The lecture's tip is to explore a lot first, then less: early on the Q-values are guesses, later they are stable. The 2013 DQN paper annealed ε linearly from 1 to 0.1 over the first million frames, then held it at 0.1.
For Q-learning, exploration changes only which steps get sampled. The max in the target ignores how the action was chosen, so random tries do not bias what is learned.
The symptom is an agent stuck on a mediocre habit. Measure how many times each action was tried in each common state. If some counts stay near zero, raise ε early or decay it more slowly.
Chapter 6
Write the network update, see that its target moves with the weights, and make it diverge with two states
Put the network back in. The weights are φ. Call the learning rate η (eta) and the target y = r + γ maxa′ Qφ(s′,a′). Call the gradient ∇φ Qφ(s,a): the direction in weight space that raises Q(s,a) fastest.
phi becomes phi minus eta, times Q-phi of s, a minus y, times the gradient with respect to phi of Q-phi of s, a.
Measure the miss, Q-phi of s, a minus y. Multiply by the gradient to get which way to move phi. Step phi a little that way, scaled by eta.
With made-up numbers: Qφ(s) = φ × 1 and Qφ(s′) = φ × 2, r = 0, γ = 0.9, φ = 1, η = 0.1. y = 0.9 × 2 = 1.8. New φ = 1 − 0.1 × (1 − 1.8) × 1 = 1.08. The true value is 0, and φ went up.
The lecture's point: this is not gradient descent. The target y also depends on φ, but the update treats it as a constant. A true gradient would include it. The lecture calls this a semi-gradient method, and says its analysis is hard.
In the example, every step raises φ, and the higher φ raises the target 1.8φ. That loop has three parts. Sutton and Barto (Chapter 11) call them the deadly triad: bootstrapping (the target uses an estimate), function approximation (one weight serves s and s′), and off-policy data (the updates rarely visit s′). Updates on s′ itself pull φ down, because s′ ends with reward 0.
The line is φ over 200 updates, starting at 1; it turns red when it runs away from the truth, 0. Slide the share of updates that land on s′. Then freeze the target and see what that buys here.
Toy after the two-state example in Sutton and Barto, Chapter 11. η = 0.05, γ = 0.9. Updates on s′ are spread evenly through the run.
Below about 15% the weight runs away; above it, φ falls to 0. Freezing the target makes each stretch a fixed regression, so the climb comes in steps, but it still climbs. The fix that holds is data that covers s′.
The symptom is Q-values that grow far beyond any possible return. Measure it by logging the mean max Q on a fixed batch of states and comparing it with the largest return you could earn. Fix the data mix first, then add the stabilisers of Chapter 7.
Chapter 7
Make Q-learning look like supervised learning with two changes, and trace one step through the network
In 2013 DeepMind trained one network to play seven Atari games from pixels and the score. With no change between games, it beat earlier methods on six and a human expert on three. This is the Deep Q-Network (DQN). The lecture's summary: every idea in DQN makes Q-learning closer to supervised learning with SGD.
Idea 1, experience replay. Consecutive frames are nearly the same, so training on the stream feeds SGD correlated samples. Random draws from a big buffer, the last one million frames, break the correlation and reuse each step many times. The paper notes why this is allowed: replayed steps came from old weights, so the learner must be off-policy. That is why they chose Q-learning.
The strip holds the last 48 steps, newest on the right. The lower plot shows where each picked step sits in state space. Press Step to add a step and draw a batch of 8, then switch replay on.
Illustrative toy. The state drifts slowly, like consecutive frames. The real DQN buffer held one million frames and drew batches of 32.
Idea 2, the target network. The target still moves with φ. So keep a second copy of the network with lagging weights φ− (phi-minus), and build every target with it.
y equals r plus gamma times the max over a-prime of Q phi-minus of s-prime, a-prime.
Feed s-prime to the frozen copy phi-minus. Take its largest output, multiply by gamma, add r. Train the live network toward that y; the copy does not move.
With made-up numbers: r = 1, γ = 0.99, and the copy outputs 2.0, 3.5, 3.0 at s′. y = 1 + 0.99 × 3.5 = 4.465, whatever the live network says.
Every C steps, copy φ into φ−. The lecture also gives a smooth version, with λ = 0.999:
φ− ← λ φ− + (1 − λ) φ: keep 99.9% of the copy, mix in 0.1% of the live weights. With φ− = 1.0 and φ = 2.0, the copy becomes 1.001.
Between refreshes the targets stand still, as in FQI. The 2013 paper used replay alone; the target network came with the 2015 Nature version.
The symptom is a loss that falls while the score does not rise. Measure the age of sampled steps and the gap between live and target outputs. If batches are all fresh, the buffer is too small; if the gap explodes, refresh less often. The lecture's tips: be patient, test on Pong or Breakout first, use a tested library.
Chapter 8
See why the max of noisy guesses is too high, and fix it by picking with one network and scoring with the other
Ten actions are all worth −0.1. Your estimates of them are noisy: each is off by a random amount. Take the largest estimate. Is it near −0.1?
No. The max picks whichever estimate got the luckiest noise, so it lands above the truth. The lecture calls the target term a guess of a guess. maxa′ Q(s′,a′) equals Q(s′, argmaxa′ Q(s′,a′)). So one noisy function picks the action and also scores it. This is overestimation, or maximization bias. The lecture's example is Sutton and Barto's Section 6.7: many actions with rewards drawn around −0.1, beside a safe action worth 0.
Yellow bars are one network's estimates; the dashed line is the truth, −0.1. Red marks the plain max. Green marks the double estimate: pick with yellow, score with a second, independent set. Draw again and change the number of actions.
Illustrative toy after Sutton and Barto, Section 6.7: every estimate is −0.1 plus noise with standard deviation 1. Averages over 4,000 draws.
With 10 actions the plain max averages about +1.44, so a robot would rate this branch above the safe 0. The fix is Double Q-learning: one function picks, another scores. DQN already has two networks. Double DQN (van Hasselt et al., 2016) picks with the live weights φ and scores with the target weights φ−.
y equals r plus gamma times Q phi-minus of s-prime and the argmax over a-prime of Q-phi of s-prime, a-prime.
Ask the live network phi which next action is best. Ask the target network phi-minus what that action is worth. Multiply by gamma and add r.
With made-up numbers: r = 0, γ = 0.9. Live network at s′: 2.6, 1.9, 2.2, so it picks action 1. Target network: 2.0, 2.4, 2.1, so action 1 is worth 2.0. Double DQN y = 0.9 × 2.0 = 1.8. Plain DQN would take the copy's max, 0.9 × 2.4 = 2.16.
The lecture calls it a change of under 3 lines in PyTorch. The two networks share data, so their errors are not fully independent. Double DQN removes most of the bias, not all of it.
The symptom is a predicted value well above the returns the agent earns. Measure both: average Q at the start state, and the average discounted return of real episodes from it. If Q sits far above, switch to the Double DQN target.
Chapter 9
Replay the surprising steps more, split value from advantage, and search for the max when actions are continuous
Prioritized experience replay (Schaul et al., 2016). Plain DQN treats every stored step as equal. But a step the network already predicts well teaches little. So sample each step with chance that grows with its |δ|, the size of its TD error. Update a step's δ each time it is sampled.
Dueling architecture (Wang et al., 2016). In many states the action barely matters: on an empty road, every steering choice is fine. So the network ends in two heads. One gives a state value V(s). The other gives an advantage A(s,a) for each action, how much better that action is than the average. Call the number of actions n.
Q of s, a equals V of s, plus A of s, a, minus one over n times the sum over a-prime of A of s, a-prime.
Take the state value V of s. Add the advantage of action a. Subtract the mean advantage over all n actions. The result is Q of s, a.
With made-up numbers: V(s) = 5 and advantages 1, 0, −1, 2 with mean 0.5. Q = 5.5, 4.5, 3.5, 6.5. One update to V moves all four Q-values at once.
Continuous actions. A robot arm's action is a vector of joint torques. The max over infinitely many actions cannot be listed. The lecture gives four options.
| Option | How | Catch |
|---|---|---|
| Discretize | Cut each joint's range into bins. | Bins multiply across joints: not scalable. |
| Optimize | Search for the max: gradient steps, or CEM and CMA-ES. | Slow, and can stop at a local peak. |
| Easy-to-max Q | NAF (Gu et al., 2016): Q is quadratic in the action, so the max is known. | Less expressive. |
| Learn the argmax | DDPG (Lillicrap et al., 2016): a network μθ(s) trained by gradient ascent on Q(s, μθ(s)). | An actor-critic; next lectures. |
The cross-entropy method (CEM) is the simplest search. Sample actions from a bell curve, keep the best few, refit the curve to them, repeat.
The yellow curve is Q(s,a) over one continuous action. Each round samples 20 actions (dots), keeps the best 4 (filled), and refits the purple bell curve. Move the starting guess, then step.
Illustrative toy. Q has a high peak at a = 1.1 and a lower one at a = −0.9. The starting spread is 0.5.
From 0 it finds the high peak in a few rounds. From −1.5 it settles on the low peak: the local-peak catch from the table.
In robotics, the lecture shows Spatial Action Maps (Wu et al., RSS 2020). A mobile robot's action is a pixel to drive to, and a fully convolutional network outputs a Q-value per pixel. The learned policy pushes blocks against a wall to move several at once.
Chapter 10
Keep the update ladder, the numbers and the core loop in one place
Q-learning replaces the expected next value with sampled steps, and DQN replaces the table with a network. Replay, a target network and a double target keep that combination stable enough to work.
| Method | Target | Data | Needs the model? |
|---|---|---|---|
| Q-value iteration | Σ p(s′,r|s,a)[r + γ max Q] | none, all states | yes |
| FQI | r + γ maxa′ Qφ(s′,a′) | a fixed log, any policy | no |
| Online Q-learning | r + γ maxa′ Q(s′,a′) | one step at a time | no |
| SARSA | r + γ Q(s′,a′), a′ taken | on-policy steps | no |
| DQN | r + γ maxa′ Qφ−(s′,a′) | replay buffer | no |
| Double DQN | r + γ Qφ−(s′, argmax Qφ) | replay buffer | no |
| Term or number | Meaning |
|---|---|
| TD error δ | target minus old value; the surprise of one step |
| Off-policy | the target ignores which policy chose the action |
| Coverage | the data contains the state and action pairs that matter |
| Deadly triad | bootstrapping + function approximation + off-policy data |
| 84 × 84 × 4 | DQN's input: 4 stacked grey frames |
| 1 → 0.1 | DQN's ε over the first million frames |
| 32, 1 million | DQN's minibatch size and replay memory, in frames |
| λ = 0.999 | the lecture's smooth target-network update |
python# one DQN training step (PyTorch); batch from the replay buffer s, a, r, s2, done = buffer.sample(32) # s: [32, 4, 84, 84], a: [32] long q = qnet(s).gather(1, a[:, None]).squeeze(1) # Q_phi(s, a): [32] with torch.no_grad(): # the target is a constant: semi-gradient a2 = qnet(s2).argmax(1, keepdim=True) # Double DQN: live net picks q2 = target_net(s2).gather(1, a2).squeeze(1) # target net scores y = r + gamma * (1 - done) * q2 # no future after a terminal step loss = F.smooth_l1_loss(q, y) opt.zero_grad(); loss.backward(); opt.step() if step % C == 0: target_net.load_state_dict(qnet.state_dict()) # refresh phi-minus
This lesson follows Lecture 8, "Q Learning and Variants", of CMU 16-831 Introduction to Robot Learning, Spring 2024, taught by Guanya Shi. The slides are on the lectures page; some of them come from Berkeley CS 285 and CMU 10-703. The readings are Mnih et al., Playing Atari with Deep Reinforcement Learning (2013), and Sutton and Barto, Reinforcement Learning: An Introduction, Chapters 5 to 7. Further papers: Double DQN, Prioritized Experience Replay, Dueling Networks, NAF, DDPG. The cliff walk and the deadly triad come from the Sutton and Barto reading, not the slides.
Now press Present or Teach and explain from memory: the sample in place of the sum, why FQI is off-policy, one update by hand, and the two DQN tricks. Then go back to the maze, run Q-learning, and say where its numbers came from.