Deep Reinforcement Learning

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.

Run the Bellman backup on a maze

0.90

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

One Number to Maximise

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.

PartSymbolIn the robot dog
Statesjoint angles and speeds
Actionatwelve motor torques
Transitionp(s′ | s, a)the physics: the chance of each next state s′
Rewardr(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.

Say it aloud

G equals the sum over t of gamma to the t, times r-t.

G
G the return: what the whole episode is worth.
Σt
the sum over t one term for each step, from step 0 to the end.
γt
gamma to the t the discount, a number below 1, multiplied by itself t times.
rt
r-t the reward at step t.
In plain words

Shrink each reward r-t by gamma once for every step you waited for it. Add them all. The total is G.

With numbers

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.

Wait for the bigger reward?

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.

0.900

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.

  1. The Bellman backup: a state's worth from the next state's worth. The hero's Play button.
  2. The policy gradient: improve the policy from episodes, with no model of the world.
  3. REINFORCE and the baseline: cut the noise without moving the average.
  4. Actor-critic and GAE: a learned critic, and the lambda knob.
  5. Trust regions and PPO: how far one update may go.
  6. Soft actor-critic: reuse old data, and pay the policy to stay random.
  7. DQN and the deadly triad: a network instead of a table, and why it can diverge.
  8. Offline RL: learn from a fixed dataset with IQL and CQL.
  9. RLHF and DPO: learn from human choices between two answers.
  10. The field guide: terms, numbers, code and links.
Rewards 0, 0 and 10 arrive at steps 0, 1 and 2, and gamma is 0.9. What is the return?

Chapter 1

The Bellman Backup

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.

Say it aloud

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.

Q*(s,a)
Q-star of s and a the best return you can expect after taking action a in state s.
r(s,a)
r of s and a the reward the move pays now.
γ
gamma the discount on everything one step later.
Σs′ p(s′|s,a)
the sum over s-prime of p of s-prime given s and a the average over where the move can land, weighted by each landing's chance.
maxa′ Q*(s′,a′)
the max over a-prime the worth of the best next move a-prime from the landing state s-prime.
In plain words

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.

With numbers

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.

Sweep the two rooms

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.

0.90

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.

Why each sweep shrinks the gap by gamma
  1. Take two guesses V and V′, and the largest gap between them over all states, written ‖V − V′‖.
  2. In one state, the two backups share the reward r(s, a), so it cancels.

    |maxa f(a) − maxa g(a)| ≤ maxa |f(a) − g(a)|

  3. What is left is gamma times an average of gaps V(s′) − V′(s′). An average of gaps is never above the largest gap.
  4. So every state's new gap is at most γ ‖V − V′‖. Repeat k times: the gap is at most γk times the first gap.
MethodOne roundRounds needed
Policy iterationscore the current policy fully, then pick the best action in every statefew, and it stops at the exact best policy
Value iterationone backup with a max in every statemany, 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.

Why does value iteration converge from any starting guess when gamma is below 1?

Chapter 2

The Policy Gradient

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.

Say it aloud

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.

∇θJ(θ)
nabla-theta of J the direction in theta that raises the average return fastest.
𝔼τ~πθ
the expected value over tau drawn from pi-theta the average over many episodes tau run with the current policy.
Σt
the sum over t one term for each step of the episode.
∇θ log πθ(at|st)
nabla-theta log pi-theta of a-t given s-t the score: the direction in theta that makes action a-t more likely in state s-t.
R(τ)
R of tau the return of episode tau.
In plain words

Run episodes. For each action taken, find its score. Weight the scores by the episode's return R. Average over episodes.

With numbers

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

The derivation, in five steps
  1. J is a sum over episodes of each episode's chance times its return. The return does not depend on theta.

    ∇J = Στ ∇pθ(τ) R(τ)

  2. Use ∇p = p ∇log p. The sum becomes an average you can sample.

    ∇J = 𝔼τ[ ∇log pθ(τ) R(τ) ]

  3. An episode's chance is a product, so its log is a sum.

    log pθ(τ) = log ρ0(s0) + Σt [ log πθ(at|st) + log p(st+1|st,at) ]

  4. The start chance ρ0 (rho-zero) and the physics p contain no theta, so their gradient is zero.
  5. Only the policy terms are left. Put them back into step 2 and you have the equation above.

Push the policy toward the arm that pays

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.

0.10

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.

Why does the policy gradient need no model of the world?

Chapter 3

REINFORCE and the Baseline

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.

Say it aloud

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.

ĝ
g-hat the gradient estimate from one episode.
Σt
the sum over t one term for each step.
∇θ log πθ(at|st)
the score of a-t given s-t the direction that makes the taken action more likely.
Gt
G-t the reward-to-go: the discounted rewards from step t to the end.
b(st)
b of s-t the baseline: the usual return from state s-t. It ignores the action.
In plain words

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.

With numbers

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

Measure the spread of the gradient

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.

20

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.

A critic overestimates every state by 50, and it serves as REINFORCE's baseline. What happens to the gradient?

Chapter 4

Actor-Critic and GAE

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

Say it aloud

A-hat-t equals the sum over l from zero of gamma lambda to the l, times delta at t plus l.

Ât
A-hat-t the advantage estimate for the action at step t.
Σl≥0
the sum over l from zero one term for each step l ahead, to the end of the episode.
(γλ)l
gamma lambda to the l a weight that shrinks by gamma times lambda for each step ahead. Lambda runs from 0 to 1.
δt+l
delta at t plus l the TD error l steps later.
In plain words

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.

With numbers

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.

Blend the TD errors with lambda

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.

0.95

Illustrative episode with gamma 0.99. We made up the critic's values.

Estimate of the advantageBiasNoise
G-t minus V-hat (lambda 1)nonehigh
GAE, lambda 0.95smallmedium
One delta (lambda 0)high if the critic is wronglow

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.

What does GAE give when lambda is 1?

Chapter 5

Trust Regions and PPO

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.

TRPO's bound, and why nobody uses it as is
  1. Let α be the largest total variation between the two policies in any state: half the sum of the gaps between their action chances. Let ε be the largest advantage.
  2. TRPO (Schulman et al., 2015, Theorem 1) proves: the true gain is at least the estimated gain minus 4εγα2/(1 − γ)2. The penalty grows with the square of the step.
  3. With ε = 10 and γ = 0.99: α = 0.01 costs 39.6, and α = 0.001 costs 0.40. Steps that small barely move.
  4. So TRPO keeps a fixed limit on the KL divergence, a measure of how far apart two distributions are. It solves for the step with the Fisher matrix and conjugate gradient: the natural gradient.

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.

Say it aloud

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.

LCLIP(θ)
L-clip of theta the objective PPO raises with gradient steps.
𝔼t
the average over t over all steps in the batch.
min
the minimum of keep the lower of the two terms: the cautious one.
rt(θ)
r-t of theta new chance over old chance of the action at step t. 1 means no change.
Ât
A-hat-t the advantage, usually from GAE.
clip(r, 1−ε, 1+ε)
r clipped between one minus epsilon and one plus epsilon r held inside a band; epsilon is usually 0.2.
In plain words

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 numbers

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.

Clip the ratio

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.

1.80
0.20

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.

PPO with epsilon 0.2 sees A-hat = +2 and a ratio of 1.5. What is this sample's objective term?

Chapter 6

Soft Actor-Critic

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.

Say it aloud

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.

π(a|s)
pi of a given s the chance that the policy picks action a in state s.
eQ(s,a)/α
e to the Q of s and a over alpha the action's Q-value, divided by the temperature alpha, made positive.
Σb eQ(s,b)/α
the sum over b the same term for every action b, so the chances add to 1.
In plain words

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 numbers

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

Turn the temperature

Warm ticks are the Q-values 2, 3 and 5. Teal bars are the policy's chances. Drag alpha and watch the entropy meter.

1.00

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.

In SAC's softmax policy, what happens as alpha goes toward zero?

Chapter 7

DQN and the Deadly Triad

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.

IngredientWhy it hurts
Function approximationone update moves the values of many similar states
Bootstrappingthe target uses the network's own guess, so an error feeds itself
Off-policy datathe 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.

Take the max of noisy estimates

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.

3
1.0

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.

Why does the max in DQN's target overestimate?

Chapter 8

Offline RL: IQL and CQL

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.

Say it aloud

L-tau of u equals the absolute value of tau minus one-if-u-is-below-zero, times u squared.

Lτ(u)
L-tau of u the expectile loss on one gap u = Q(s, a) − V(s).
τ
tau from 0.5 to 1: how hard V leans up. The bars around tau minus the indicator take its size, so the weight is tau when Q is above V and 1 minus tau when below.
𝟙(u<0)
one if u is below zero an indicator: 1 when V is above Q, else 0.
u2
u squared the squared gap.
In plain words

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 numbers

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.

Lean the value toward the best seen action

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.

0.90

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.

Why does IQL avoid the overestimation of offline Q-learning?

Chapter 9

RLHF and DPO

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.

  1. Fine-tune the language model on good demonstrations. The result is the reference policy, π-ref.
  2. Fit a reward model on pairs. The Bradley–Terry model says the chance of preferring the winner equals σ(reward of the winner minus reward of the loser). The sigmoid σ maps any number to a chance.
  3. Train the policy with PPO to raise reward, minus β (beta) times the KL from π-ref, so it does not drift into text that fools the reward model.

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.

Say it aloud

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.

LDPO
L-DPO the loss on one prompt x and its pair of answers.
−log σ
minus log sigma of small when the modelled chance of the human's choice is near 1.
β
beta how far from the reference the policy may move; often 0.1.
log πθ(yw|x)/πref(yw|x)
the winner's log-ratio how much more the policy likes the winning answer y-w than the reference does.
log πθ(yl|x)/πref(yl|x)
the loser's log-ratio the same for the losing answer y-l.
In plain words

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 numbers

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.

Where the DPO loss comes from
  1. Stage 3's goal: raise the average reward r(x, y), minus beta times the KL from π-ref.
  2. Its best policy reweights the reference by e to the reward over beta. Z(x) is the total that makes the chances add to 1.

    π*(y|x) = πref(y|x) er(x,y)/β / Z(x)

  3. Take logs and solve for the reward.

    r(x,y) = β log π*(y|x)/πref(y|x) + β log Z(x)

  4. Bradley–Terry uses only the reward of the winner minus that of the loser. Both share the same x, so β log Z(x) cancels.
  5. Replace π* with π-theta and minimise minus the log-chance of the human's choices.

Push one preference pair

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.

−0.2
0.10

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.

In the DPO derivation, why does Z(x) disappear?

Chapter 10

The Field Guide

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.

The methods

MethodLearnsDataKey idea
Value iterationV or Q tablea known modelrepeat the Bellman backup; a contraction
REINFORCEpolicyon-policy episodesscore times return, minus a baseline
A2Cpolicy and criticon-policy stepsTD error as the advantage
PPOpolicy and criticon-policy batches, a few epochsclipped ratio, GAE advantages
SACpolicy, two critics, alphareplay bufferentropy bonus, min of two critics
DQNQ networkreplay buffertarget network; Double DQN for the max
IQLQ, V, policyfixed datasetexpectile V; never query unseen actions
CQLQ, policyfixed datasetpush down Q off the data
DPOlanguage model policypreference pairsreward as beta times log-ratio

Numbers to remember

QuantityValueWhere
Planning horizonabout 1/(1 − γ): 10 at 0.9, 100 at 0.99Chapter 0
Sweeps to cut an error 100 timesabout 44 at γ 0.9, about 460 at 0.99Chapter 1
Spread with a good baseline5.52 down to 0.50 in the toy: 11 times lessChapter 3
GAE lambda0.95 is common; 0 is one TD error, 1 is Monte CarloChapter 4
PPO epsilon0.2 is commonChapter 5
TRPO penalty, ε 10, γ 0.99, α 0.0139.6: too strict to use as isChapter 5
Max of 3 noisy estimates, noise 1overshoots by 0.85 on averageChapter 7
IQL tau0.7 to 0.9 in common use; higher leans closer to the maxChapter 8
DPO beta0.1 is commonChapter 9

Which method

The core in code

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

Keep going

The takeaway. A state is worth its reward plus gamma times the next state's worth. Every algorithm here estimates that rule from samples, and each one adds a fix for the noise, the step size or the max that the estimate brings.
You train a robot arm on real hardware, where every step costs time. Which method fits best?

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.

Credit and source

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.

Deep Reinforcement Learning: The Complete Theory
CS 224R · CS 285 · PPO · DPO · Back to Gleams