One rule solves this maze: a cell is worth its reward plus gamma times the best next cell. At gamma 0.9, a reward ten steps away keeps 35% of its worth. Every method on this page estimates that rule when the table is too big.
Learn the theory under deep RL, from the Bellman equation to DPO, with every equation read aloud and worked with numbers.
Press Play and watch value flow back from the goal, one sweep at a time. Then drag gamma down and play again. Then we build each piece: the return, the Bellman backup, policy gradients, actor-critic, PPO, SAC, DQN, offline RL and DPO.
You need a little Python and what a probability and an average are. A derivative helps in Chapters 2 and 3. We build the rest from zero.
Covers the theory taught in Stanford CS 224R and CS 234 and Berkeley CS 285. The explanations, toys and numbers here are our own; every toy number is illustrative.
Illustrative maze. Moves are certain. Entering the goal pays +10 and entering the pit pays −10; both end the episode. Every other move pays 0. Each sweep updates every cell once from the values of the last sweep.
Chapter 0
Write the agent, the world and the score as an MDP, and add an episode's rewards into one number
A robot dog learns to walk. Each step, it reads its joint angles, picks motor torques, and gets a score: plus for forward speed, minus for a fall. Nobody gives it the right torques. It must find them from the scores alone.
That loop is a Markov decision process (MDP). Markov means the current state holds everything that matters for the future, so the path that led here adds nothing.
| Part | Symbol | In the robot dog |
|---|---|---|
| State | s | joint angles and speeds |
| Action | a | twelve motor torques |
| Transition | p(s′ | s, a) | the physics: the chance of each next state s′ |
| Reward | r(s, a) | forward speed, minus a penalty for a fall |
| Policy | π(a | s) | the robot's rule: a chance for each action in each state |
| Discount | γ | how much a later reward counts, from 0 to 1 |
What is one episode worth? Call the reward at step t r-t. A reward that comes later counts less, by a factor γ (gamma) for each step of delay. The total is the return, G.
G equals the sum over t of gamma to the t, times r-t.
Shrink each reward r-t by gamma once for every step you waited for it. Add them all. The total is G.
With made-up rewards 1, 0 and 2 and gamma 0.9: G = 1 + 0.9 × 0 + 0.81 × 2 = 2.62. The 2 counts as 1.62 because it came two steps late.
Stream A pays 1 every step. Stream B pays 0 for ten steps, then 2 every step. Drag gamma and find where B starts to win.
Illustrative streams, both endless. Worth of A = 1/(1 − γ). Worth of B = 2γ10/(1 − γ).
At gamma 0.9, A is worth 1/(1 − 0.9) = 10 and B is worth 0.910 × 2/(1 − 0.9) = 0.349 × 20 = 6.97. At gamma 0.99 the order flips: 100 against 181. The two are equal at gamma 0.933, where 2 × gamma10 = 1. Gamma also sets how far ahead the agent looks: about 1/(1 − gamma) steps, so 10 at 0.9 and 100 at 0.99.
The failure. Set gamma to 1 in a task with no end. The sum can grow without limit, and value estimates climb every update. Measure the largest value against the cap r-max/(1 − gamma). The fix is gamma below 1, or a time limit on episodes.
The whole field asks one question: which policy gives the largest average return? Each chapter gives one answer.
Chapter 1
Write a move's worth from the worth of where it lands, and repeat that rule until the numbers stop moving
Two rooms, A and B. In A you can stay (left, +1) or walk to B (right, +3). In B you can take the exit prize (right, +10, the end) or walk back to A (left, 0). Gamma is 0.9. Which move is best in B?
The value V(s) is the return you expect from state s on. The Q-value Q(s, a) is the return you expect if you take action a first. A star marks the best possible values, Q-star. A move is worth its reward now plus gamma times the worth of the best move where it lands. That recursion is the Bellman optimality equation.
Q-star of s and a equals r of s and a, plus gamma times the sum over s-prime of p of s-prime given s and a, times the max over a-prime of Q-star of s-prime and a-prime.
Take the move's reward. For each place s-prime it can land, find the best Q-star there. Average those by their chances, multiply by gamma, and add.
The two rooms at gamma 0.9, at the fixed point of the device below: Q-star(A, right) = 3 + 0.9 × max(14.21, 10) = 3 + 12.79 = 15.79.
Each sweep applies the backup to all four moves, using the last sweep's numbers. Teal arrows mark the best move in each room. Sweep, then lower gamma below 0.86.
Illustrative two-room MDP with certain moves. All four Q-values start at 0.
Sweep 3 gives Q(B, left) = 0.9 × 12 = 10.8, already above the exit's 10. It keeps rising to 14.21, because the loop A, B, A pays 3 every two steps. That repeated sweep is value iteration. Below gamma 0.861 the exit wins.
Why does it settle from any start? Each sweep shrinks the largest gap between two guesses by at least gamma: the operator is a contraction. Two guesses 20 apart at gamma 0.5 are at most 0.625 apart after 5 sweeps. At gamma 0.99, cutting an error 100 times takes about 460 sweeps.
|maxa f(a) − maxa g(a)| ≤ maxa |f(a) − g(a)|
| Method | One round | Rounds needed |
|---|---|---|
| Policy iteration | score the current policy fully, then pick the best action in every state | few, and it stops at the exact best policy |
| Value iteration | one backup with a max in every state | many, more as gamma nears 1 |
The failure. A table needs one entry per state and action. A camera image has more states than any table can hold, and most entries are never visited. Measure the share of states the data visits. The fix is a network in place of the table, which Chapter 7 builds.
Chapter 2
Turn "make the good actions more likely" into a gradient you can estimate from episodes, with no model of the world
Value iteration needs the transition chances p. A real robot has no such table. Can we improve the policy from episodes alone?
Give the policy weights θ (theta), and write it π-theta. The objective J(θ) is the average return of episodes run with π-theta. We want its gradient: the direction in theta that raises J fastest. The trouble is that theta changes which episodes happen, and we cannot differentiate the world.
The fix is the log-derivative trick: the gradient of a chance equals the chance times the gradient of its log. The gradient then becomes an average over episodes, and every term from the world drops out.
Nabla-theta of J equals the expected value, over tau drawn from pi-theta, of the sum over t of nabla-theta log pi-theta of a-t given s-t, times R of tau.
Run episodes. For each action taken, find its score. Weight the scores by the episode's return R. Average over episodes.
With made-up numbers: two actions with logits 0 and 0, so each has chance 0.5. The policy picks right and gets R = 3. The score of right is (−0.5, +0.5), so the push is (−1.5, +1.5). A step of 0.1 moves right from 50% to 57.4%.
∇J = Στ ∇pθ(τ) R(τ)
∇J = 𝔼τ[ ∇log pθ(τ) R(τ) ]
log pθ(τ) = log ρ0(s0) + Σt [ log πθ(at|st) + log p(st+1|st,at) ]
Left pays 1 and right pays 3. Each step samples one arm and pushes the logits by the return times the score. Press Sample and step, then try a large step size.
Illustrative bandit: one step per episode, rewards with no noise, a softmax over two logits that start at 0.
The failure. Every reward here is positive, so each sample of the left arm pushes it up too. Only the size of the push tells the arms apart, and with noisy rewards that signal drowns. The symptom is slow, jumpy learning. Measure the spread of the gradient across batches; Chapter 3 is the fix.
Chapter 3
Cut the noise of the gradient with reward-to-go and a baseline, and see why the average stays the same
REINFORCE (Williams, 1992) is the gradient of Chapter 2, estimated from a batch of episodes: sample, weight each score by the return, step. It is right on average and noisy in any one batch.
Two changes cut the noise. Reward-to-go: an action at step t cannot change the rewards before t, so weight it only by the rewards from t on, called G-t. A baseline b(s): subtract the usual return from that state. The difference G-t minus b is the advantage, how much better than usual the action turned out.
g-hat equals the sum over t of nabla-theta log pi-theta of a-t given s-t, times G-t minus b of s-t.
For each step t, take the score of the action. Weight it by G-t minus b: positive if the action beat the usual, negative if not. Add over the steps.
From the device's toy: the policy took right with chance 0.5, and right paid G = 12.4. The baseline is 11, so the weight is +1.4. The push on right's logit is (1 − 0.5) × 1.4 = +0.7.
Why is the baseline free? The chances add to 1 in every state, so the policy-weighted average of the score is the gradient of 1, which is 0. Any b that ignores the action multiplies that 0.
Σa π(a|s) ∇log π(a|s) = Σa ∇π(a|s) = ∇1 = 0
Each dot is one episode's estimate of the push on right's logit. The green line is the true value, 0.5. Pick a baseline and resample.
Illustrative toy: two arms paying 10 and 12, each plus noise with spread 1, and a 50/50 policy. Theory gives a spread of 5.52 with no baseline, 0.50 with b = 11, and 25.0 with b = 61.
With no baseline, one estimate is about plus or minus 5 or 6 while the truth is 0.5: a spread of 5.52. With b = 11 the spread is 0.50, 11 times smaller. That is worth about 120 times more episodes, since spread falls with the square root of the count.
The failure. A bad baseline stays unbiased and can be worse than none. At b = 61, fifty too high, every advantage is negative and the spread grows to 25. The symptom is a batch mean advantage far from 0, so log it each update. The fix is to refit the baseline, or subtract the batch mean.
Chapter 4
Replace the full return with a learned critic, and choose how far to trust it with one knob, lambda
REINFORCE waits for the episode to end before it knows G-t. An actor-critic method trains a second network, the critic V-hat, to predict the return from each state. The policy is the actor.
With a critic, one step is enough to estimate the advantage. The TD error δ-t (delta-t) is the reward, plus gamma times the critic's value of the next state, minus its value of this state.
δt = rt + γ V̂(st+1) − V̂(st)
Near a goal: r = 5, V-hat here 3, V-hat next 10, gamma 0.9. Delta = 5 + 9 − 3 = +11, much better than the critic expected. Delta has little noise, but it inherits the critic's errors: a bias. G-t minus V-hat has no bias and much noise. Generalized advantage estimation (GAE; Schulman et al., 2016) blends the two with a knob, λ (lambda).
A-hat-t equals the sum over l from zero of gamma lambda to the l, times delta at t plus l.
Compute every delta. Walk back from the last step: A-hat-t is delta-t plus gamma times lambda times A-hat at t + 1. Lambda 0 keeps one delta; lambda 1 gives G-t minus V-hat.
The device's episode: rewards 1, 2, 3, 0; critic values 5, 4, 6, 2, then 0 at the end; gamma 0.99, lambda 0.95. The deltas are −0.04, 3.94, −1.02, −2.00. Backwards: −2.00, then −1.02 + 0.9405 × (−2.00) = −2.90, then 1.21, then 1.10.
Top: each step's TD error. Bottom: the advantage GAE gives each step. Slide lambda from 0 to 1 and watch credit flow back from later steps.
Illustrative episode with gamma 0.99. We made up the critic's values.
| Estimate of the advantage | Bias | Noise |
|---|---|---|
| G-t minus V-hat (lambda 1) | none | high |
| GAE, lambda 0.95 | small | medium |
| One delta (lambda 0) | high if the critic is wrong | low |
The failure. A wrong critic poisons delta: if V-hat of the next state is 10 and the truth is 100, delta calls a great action poor. The symptom is a policy that stalls while the critic's loss stays high. Measure the critic's error against real returns. Raise lambda, or train the critic longer.
Chapter 5
Bound how far one update may move the policy, then get the same effect with a clipped ratio
The gradient gives a direction, not a distance. A step too long turns a good policy bad, and the next batch then comes from the bad policy. How far is safe?
The performance difference lemma (Kakade and Langford, 2002) gives the exact gain of a new policy. Take the new policy's actions, score them with the old policy's advantage, and average over the states the new policy visits. Multiply by 1/(1 − gamma). We only have states from the old policy. They are a fair stand-in only while the two policies stay close.
PPO (Schulman et al., 2017) gets a similar effect in one line. Its probability ratio r-t is the new policy's chance of the taken action over the old policy's chance.
L-clip of theta equals the average over t of the minimum of r-t times A-hat-t, and r-t clipped between one minus epsilon and one plus epsilon, times A-hat-t.
For each step, multiply the ratio r by the advantage. Also clip r into the band and multiply. Keep the smaller. Average over steps.
With made-up numbers: old chance 0.4, new 0.72, so r = 1.8; epsilon 0.2. If A-hat = +3: min(5.4, 3.6) = 3.6, the flat part, so no more push. If A-hat = −3: min(−5.4, −3.6) = −5.4, so the push to undo the change stays.
The dashed line is the plain ratio times the advantage. The purple line is PPO's objective. Move the ratio past the band and see where the slope goes flat.
One sample with a made-up advantage of plus or minus 3. A real batch averages thousands of such terms.
The failure. PPO is not a hard trust region. Many epochs on one batch can still drift the policy far, and returns crash. Log the approximate KL between old and new policy each epoch. Stop the epochs early when it passes a limit.
Chapter 6
Reuse old data from a replay buffer, pay the policy to stay random, and let the price tune itself
PPO uses each batch for a few epochs, then throws it away. An hour on a real robot costs too much for that. Soft actor-critic (SAC; Haarnoja et al., 2018) stores every transition in a replay buffer and trains on it again and again. It is off-policy: it learns from data that older policies collected.
SAC also changes the goal: reward plus α (alpha) times the entropy of the policy, a number that is high when the choices are spread out. Alpha is the temperature, the price of randomness. With that bonus, the best policy for given Q-values is a softmax of Q over alpha.
Pi of a given s equals e to the Q of s and a over alpha, divided by the sum over b of e to the Q of s and b over alpha.
Divide each action's Q by alpha. Raise e to each result. Divide each by the total. A high alpha gives near-equal shares; a low alpha gives nearly all to the best action.
With made-up Q-values 2, 3 and 5: at alpha 1 the shares are 4%, 11% and 84%. At alpha 2 they are 14%, 23% and 63%. At alpha 0.25 the best action takes almost 100%.
Warm ticks are the Q-values 2, 3 and 5. Teal bars are the policy's chances. Drag alpha and watch the entropy meter.
Illustrative Q-values. The slider is on a log scale from alpha 0.1 to 10. Entropy is in nats; three actions can reach at most 1.10.
SAC trains five networks: the actor, two critics, and a slow copy of each critic for targets. Each target uses the smaller of the two critics' guesses, a trick from TD3 that fights overestimation (Chapter 7). SAC also tunes alpha: if the policy's entropy falls below a target, often minus the number of action dimensions, alpha goes up.
The failure. With alpha fixed too high, the policy stays random and never commits. The symptom is entropy near its maximum while returns plateau. Measure the entropy against its target. The fix is to let SAC tune alpha.
Chapter 7
Replace the Q-table with a network, meet the three ingredients that make it diverge, and remove the bias of the max
An Atari screen has more possible states than any table can hold. DQN (Mnih et al., 2015) replaces the Q-table with a network. It trains the network toward the Bellman target of Chapter 1: the reward plus gamma times the largest Q of the next state.
Three ingredients together can make the values diverge. Sutton and Barto call them the deadly triad. Any two are usually safe.
| Ingredient | Why it hurts |
|---|---|
| Function approximation | one update moves the values of many similar states |
| Bootstrapping | the target uses the network's own guess, so an error feeds itself |
| Off-policy data | the data comes from other policies, so nothing corrects the states the current policy would visit |
DQN adds two patches. A replay buffer samples random old transitions, which breaks the run of near-identical frames. A target network, a copy refreshed every N steps, holds the target still between copies.
A second bias hides in the max. Each Q estimate has noise, and the max picks the action whose noise is highest. So the target is too high on average.
Every action's true Q is 5. Each run draws noisy estimates from two networks. Yellow is DQN's max; blue is Double DQN's. Press Run and raise the noise.
Illustrative: the noise is Gaussian and the same for every action. With 3 actions and noise 1, theory gives an average overshoot of 0.85 for the max and 0 for the double estimate.
Double DQN (van Hasselt et al., 2016) splits the job: the online network picks the action, and the target network scores it. True Q-values 5, 5, 5. The online network guesses 7, 4, 6; the target network guesses 4, 7, 5. DQN's max over the target network gives 7. Double DQN picks the first action, the online network's 7,, then scores it with the target network: 4. One network's noise no longer picks its own winner.
The failure. Q-values climb far above any return the agent gets. Compare the average Q on visited states with the average discounted return of real episodes. If the gap grows, use Double DQN, a slower target update, or a smaller learning rate.
Chapter 8
Learn from a fixed dataset without trusting actions the data never shows
A hospital has years of treatment records and cannot experiment on patients. Offline RL learns a policy from a fixed dataset collected by some behaviour policy, with no new interaction.
Q-learning breaks here. The max in its target asks about actions the data never tried. Their Q-values never meet a real reward, and the max picks the most inflated one. Online, the agent would try that action and learn the truth. Offline, it never does.
IQL (implicit Q-learning; Kostrikov et al., 2022) never asks about unseen actions. It fits a value V(s) to the Q-values of the dataset's own actions, with a lopsided loss that leans toward the high ones. Call the gap Q minus V u.
L-tau of u equals the absolute value of tau minus one-if-u-is-below-zero, times u squared.
If Q is above V, weight the squared gap u by tau. If Q is below V, weight it by 1 minus tau. With tau near 1, V moves up toward the best action in the data.
With made-up dataset Q-values 2, 5, 3 and 8: tau 0.5 gives the mean, 4.5. Tau 0.9 gives 6.83. Tau 0.99 gives 7.86, close to the data's best, 8, and never above it.
Pink dots are Q-values of actions in the data. The yellow ghost is an action the data never shows. Slide tau, then switch on the naive max.
Illustrative values. The unseen action's 12 stands for a Q-value that no real reward ever corrected.
IQL then trains Q toward r + gamma V of the next state. To get a policy, it weights each dataset action by e to the power of its advantage. CQL (conservative Q-learning; Kumar et al., 2020) takes the other road. Its penalty pushes Q down on actions the policy favours and up on the dataset's actions, so unseen actions look no better than they have earned.
The failure. The learned Q of chosen actions sits far above any return in the dataset. Compare predicted Q with dataset returns, and count how often the policy picks actions far from the data. The fix is a higher tau or CQL weight, or a policy kept closer to the behaviour policy.
Chapter 9
Learn a reward from human choices between two answers, then skip the reward model
No one can write a reward for "a good answer". People can say which of two answers they prefer. RLHF (reinforcement learning from human feedback) turns those choices into a reward, in three stages.
Rewards of 2.3 for the winner and 1.8 for the loser give a modelled chance of σ(0.5) = 0.62, and a loss of −log 0.62 = 0.47. DPO (direct preference optimization; Rafailov et al., 2023) observes that stage 3 has an exact best policy. Solved for the reward, it says the reward is beta times the log of policy over reference, plus a term that cancels in every pair. Put that into Bradley–Terry and no reward model is left.
L-DPO equals minus log sigma of beta times: log of pi-theta of y-w given x over pi-ref of y-w given x, minus the same log-ratio for y-l.
Take the winner's log-ratio minus the loser's. Multiply by beta. Pass it through the sigmoid and take minus the log. The loss falls as the policy favours the winner more than the reference does.
With made-up numbers: beta 0.1, winner's log-ratio 0.3, loser's 0.5. Beta times the gap is −0.02, and σ(−0.02) = 0.495, so the loss is 0.703. The pair is still ranked wrong, so its gradient weight, σ(+0.02) = 0.505, stays high.
π*(y|x) = πref(y|x) er(x,y)/β / Z(x)
r(x,y) = β log π*(y|x)/πref(y|x) + β log Z(x)
The margin is the winner's log-ratio minus the loser's. Purple is the loss; blue is the gradient weight. Drag the margin to the right and watch the push fade.
One illustrative pair. The weight σ(−β × margin) is what multiplies the push up on the winner and down on the loser.
The failure. With beta too small, the policy drifts far from the reference and its text can turn strange. The symptom is a KL to the reference that climbs fast. Measure the average log-ratio on held-out text. The fix is a larger beta.
Chapter 10
Keep the terms, the numbers, the core code and the map of methods in one place
Every method here starts from one idea: a state is worth its reward plus gamma times the worth of the next state. Value methods estimate that worth and act greedily. Policy methods push the probabilities of actions by how much better they turned out. Off-policy and offline methods reuse data and must fight the max. Preference methods learn the reward itself from human choices.
| Method | Learns | Data | Key idea |
|---|---|---|---|
| Value iteration | V or Q table | a known model | repeat the Bellman backup; a contraction |
| REINFORCE | policy | on-policy episodes | score times return, minus a baseline |
| A2C | policy and critic | on-policy steps | TD error as the advantage |
| PPO | policy and critic | on-policy batches, a few epochs | clipped ratio, GAE advantages |
| SAC | policy, two critics, alpha | replay buffer | entropy bonus, min of two critics |
| DQN | Q network | replay buffer | target network; Double DQN for the max |
| IQL | Q, V, policy | fixed dataset | expectile V; never query unseen actions |
| CQL | Q, policy | fixed dataset | push down Q off the data |
| DPO | language model policy | preference pairs | reward as beta times log-ratio |
| Quantity | Value | Where |
|---|---|---|
| Planning horizon | about 1/(1 − γ): 10 at 0.9, 100 at 0.99 | Chapter 0 |
| Sweeps to cut an error 100 times | about 44 at γ 0.9, about 460 at 0.99 | Chapter 1 |
| Spread with a good baseline | 5.52 down to 0.50 in the toy: 11 times less | Chapter 3 |
| GAE lambda | 0.95 is common; 0 is one TD error, 1 is Monte Carlo | Chapter 4 |
| PPO epsilon | 0.2 is common | Chapter 5 |
| TRPO penalty, ε 10, γ 0.99, α 0.01 | 39.6: too strict to use as is | Chapter 5 |
| Max of 3 noisy estimates, noise 1 | overshoots by 0.85 on average | Chapter 7 |
| IQL tau | 0.7 to 0.9 in common use; higher leans closer to the max | Chapter 8 |
| DPO beta | 0.1 is common | Chapter 9 |
pythonimport torch def gae(rewards, values, gamma=0.99, lam=0.95): # rewards: [T]; values: [T+1], the critic's V-hat with 0 after the last step T = len(rewards) adv, run = torch.zeros(T), 0.0 for t in reversed(range(T)): # walk back from the last step delta = rewards[t] + gamma * values[t + 1] - values[t] run = delta + gamma * lam * run adv[t] = run return adv # [1,2,3,0], [5,4,6,2,0] -> 1.10, 1.21, -2.90, -2.00 def ppo_loss(logp_new, logp_old, adv, eps=0.2): ratio = torch.exp(logp_new - logp_old) # new chance / old chance, per step clipped = torch.clamp(ratio, 1 - eps, 1 + eps) return -torch.min(ratio * adv, clipped * adv).mean() # minus: optimisers go downhill def dpo_loss(lw, lw_ref, ll, ll_ref, beta=0.1): # summed log-probs of the winner and loser under the policy and the frozen reference margin = (lw - lw_ref) - (ll - ll_ref) return -torch.nn.functional.logsigmoid(beta * margin).mean()
Now press Present or Teach. Explain the chain from memory: the return, the Bellman backup, the policy gradient, the baseline, GAE, the clip, the entropy bonus, the bias of the max, the expectile and the DPO loss. Then go back to the maze, set gamma to 0.6, and say why the far cells stay near zero.
This lesson covers the theory taught in Stanford CS 224R: Deep Reinforcement Learning, Stanford CS 234: Reinforcement Learning and Berkeley CS 285: Deep Reinforcement Learning. The papers behind it: Williams (1992), REINFORCE; Kakade and Langford (2002), the performance difference lemma. Then Schulman et al., TRPO (2015), GAE (2016) and PPO (2017). Then Haarnoja et al., SAC (2018); Mnih et al. (2015), DQN; van Hasselt et al. (2016), Double DQN. Then Kumar et al., CQL (2020); Kostrikov et al., IQL (2022); Rafailov et al., DPO (2023). The toys and numbers here are our own.