Deep RL Review

Nine method families, one first question: what does your problem give you? Set the facts, and the instrument lights the family that fits and the family under it.

A review of the whole CS 224R course for a newcomer: each family's one idea, its key equations read aloud, one worked number and the classic trap.

Flip the facts: pick Fixed log only, then set the reward to None and switch on Expert demos. Read the reason under the map each time. Then we review the families in the course's order, one chapter each.

You need a little Python and what a probability is. Each chapter links to the full lesson that builds its family from zero.

Our own review of Stanford CS 224R: Deep Reinforcement Learning. It is not the course's exam. The questions, toys and numbers here are ours, and every toy number is illustrative.

Find the family that fits

New data
Reward
Actions
Each try

A rule of thumb, not a law: real projects mix families (clone first, then fine-tune with RL). "Cheap" means a fast simulator; "precious" means a few hundred real tries at most.

Chapter 0

Three Questions Place Every Method

Ask where the data comes from, what signal you have and what the method learns

A robot arm must put a mug on a coaster. You might have a log of human tries, or a scale under the coaster that pays a reward. Or a person can say which of two tries looked better. Each case needs a different method.

Three questions place any method from this course. Answer them first, and most wrong options fall away.

QuestionAnswersWhy it matters
Where does the data come from?On-policy: fresh tries of the current policy. Off-policy: a replay buffer of older tries. Offline: a fixed log, no new tries.Decides whether old data is usable
What signal is there?Demonstrations, a reward, or preferences between two outcomesDecides the loss
What does it learn?A policy, a value, both, or a model of the worldDecides how the agent acts

Every family except imitation chases one number. Call one episode's record of states, actions and rewards a trajectory, τ (tau). Call the reward at step t r-t, and the discount, a number from 0 to 1 that shrinks late rewards, γ (gamma). The policy's weights are θ (theta).

Say it aloud

J of theta equals the expected value, over tau drawn from p-theta, of the sum over t of gamma to the t times r-t.

J(θ)
J of theta the objective: the average discounted return of the policy with weights θ.
Eτ∼pθ
the expected value over tau drawn from p-theta the average over many episodes run with this policy.
Σt
the sum over t one term for each step of the episode.
γt
gamma to the t the discount multiplied by itself t times.
rt
r-t the reward at step t.
In plain words

Shrink each reward r-t by gamma once per step of delay and add them: that is one episode's return. Average the returns of many episodes: that is J of theta.

With numbers

With made-up rewards 1, 0 and 2 and gamma 0.9: the return is 1 + 0.9 × 0 + 0.81 × 2 = 2.62. J is the average of such returns over many episodes.

Place an algorithm

Pick a name. The lit cells answer the three questions for it.

Our coarse labels. "Both" lights policy and value.

The failure. PPO reuses each batch for a few passes, so people call it off-policy. Test it: could it learn from a week-old replay buffer? It cannot, so it is on-policy with a short reuse window.

The road

  1. Imitation: copy the expert, and mind the averaging and drift traps.
  2. Policy gradients: push up what paid, relative to usual.
  3. Actor-critic: a learned value replaces the noisy return.
  4. Off-policy actor-critic: reuse data with PPO's clip and SAC's buffer.
  5. Q-learning: learn each action's value, then take the max.
  6. Offline RL: learn from a fixed log without trusting guesses.
  7. Model-based RL: learn the world, plan in it, and watch the error grow.
  8. Multi-task, goals and meta-RL: one policy for many tasks.
  9. Rewards and RLHF: learn the reward from people.
  10. Which method when: the hero's rules, then a drill.
  11. The field guide: terms, numbers, code and links.
A robot has 1,000 teleoperated demonstrations, no reward and no time on the real robot. Which family applies?

Chapter 1

Imitation: Copy the Expert

Clone the demonstrations with supervised learning, then find where averaging and drift break the clone

A person drives a robot with a joystick 100 times. Each moment gives a pair: the state s and the expert's action a. Behaviour cloning (BC) fits a policy πθ that maps s to a, like any regression. It needs no reward. Full lesson: Imitation Learning.

Say it aloud

L of theta equals one over N times the sum over i of the squared distance between a-i and pi-theta of s-i.

L(θ)
L of theta the cloning loss for weights θ.
(1/N) Σi
one over N times the sum over i the average over the N demonstration pairs.
ai
a-i the expert's action in pair i.
πθ(si)
pi-theta of s-i the action the policy outputs at the same state.
‖ · ‖2
the squared distance the length of the gap between the two actions, squared.
In plain words

For each pair, measure how far the policy's action is from the expert's action a-i, and square it. Average over all N pairs. Training lowers L.

With numbers

With made-up demos: at one state the expert went +2 in 60 demos and −2 in 40. The squared loss is lowest at the mean, 0.6 × 2 + 0.4 × (−2) = +0.4, an action the expert never took.

Watch the clone average two good ways

Warm bumps are the expert's actions at one state: over the obstacle or under it. The marker is the squared-loss clone. Move the share, then switch on the mixture.

60%
±2.0

Illustrative: each way has a spread of 0.35. The mixture has one bump per way.

The clone also drifts. Call the chance of a mistake per step ε (epsilon), the horizon T, and the expected count of mistakes of a policy C. After one slip the clone meets states no demo covers, so it can keep slipping.

Say it aloud

C of pi-hat is at most C of pi-star plus T squared times epsilon.

C(π̂)
C of pi-hat the expected mistakes of the clone over one episode.
C(π*)
C of pi-star the expected mistakes of the expert.
T2
T squared the horizon times itself.
ε
epsilon the clone's chance of a mistake per step, on the expert's states.
In plain words

A slip at step t can cost every one of the remaining steps, up to T. Each of the T steps slips with chance epsilon. So the extra cost is at most T times T times epsilon.

With numbers

With made-up epsilon 0.01: at T = 10 the extra cost is at most 1; at T = 100 it is at most 100, a mistake on every step.

The fix is DAgger: run the clone, ask the expert to label the states it visits, add those pairs and retrain. Its ceiling grows with T, not T squared: with u = 2, it is 2 × 100 × 0.01 = 2 at T = 100.

The failure. The averaging trap. The symptom: a clone that flies between two good paths into the obstacle. To measure it, plot the demo actions at one state and look for two bumps. The fix is a policy with several modes: a mixture, action bins, or a diffusion or flow policy.

Formula sheet

FormulaSay it aloudWhat it does
−(1/N) Σi log πθ(ai | si)minus one over N, sum over i of log pi-theta of a-i given s-iLikelihood loss: raises the chance of each demo action, so modes stay apart.
πθ(a|s) = Σk wk N(a; μk, σk2)pi-theta of a given s is the sum over k of w-k times a normal bump at mu-kA mixture policy: one bump per way of acting.
xt = t · a + (1 − t) · x0x-t equals t times a, plus one minus t times x-zeroFlow matching: a straight path from noise x-zero to the expert action.
‖ vθ(xt, s, t) − (a − x0) ‖2the squared gap between v-theta and a minus x-zeroFlow loss: the network learns the velocity from noise to action.
x ← x + Δt · vθ(x, s, t)x becomes x plus delta-t times v-thetaSampling: a few Euler steps turn noise into an action.
C(π̂) ≤ C(π*) + u T εC of pi-hat is at most C of pi-star plus u T epsilonDAgger's ceiling: linear in the horizon T.
wi = eRi/βw-i equals e to the R-i over betaFiltered cloning: demos with a higher return R-i count more.
At one state the expert goes +3 half the time and −3 half the time. What does a clone trained with squared loss output?

Chapter 2

Policy Gradients: Push Up What Paid

Raise the chance of each action by how much better than usual its future turned out

Now there are no demos, only a reward. A policy gradient method changes θ so the actions that paid become more likely. It needs no model of the world, only episodes and their rewards. Full lesson: Policy Gradients.

Three quantities build it. The score ∇θ log πθ(at|st) is the direction in θ that makes action a-t more likely. The reward-to-go G-t adds the rewards from step t on. The baseline b is the usual return.

Say it aloud

Nabla-theta of J is about one over N times the sum over i and t of nabla-theta log pi-theta of a-t given s-t, times G-t minus b.

∇θJ
nabla-theta of J the gradient: which way to turn each weight to raise the average return.
(1/N) Σi Σt
one over N, the sum over i and t average over N episodes, adding every step t of each.
∇θ log πθ(at|st)
the score of a-t given s-t the direction that makes the chosen action more likely.
Gt
G-t the reward-to-go: the discounted rewards from step t to the end.
b
b the baseline: a usual return, often the batch mean or a learned V(s).
In plain words

Run N episodes with the current policy. At each step, take the score of the chosen action and scale it by G-t minus b, how much better than usual the rest went. Average them.

With numbers

With made-up episodes returning 5, −2 and 1: b = 4/3 = 1.33. The step-0 weights are +3.67, −3.33 and −0.33. With a score of [1, 0], episode 1 adds [3.67, 0].

Why b changes nothing on average: the policy's chances add to 1, so their gradients add to 0.

Ea∼π[ ∇ log π(a|s) · b ] = b · Σa ∇π(a|s) = b · ∇1 = 0

Subtract the usual return

Each bar is one episode's weight on its actions. Every return here is positive. Switch on the baseline, then draw a new batch.

Illustrative returns, between about 8 and 20. The baseline is the batch mean.

The failure. All returns positive, no baseline. The symptom: the update pushes every action up, even the bad ones, and learning crawls. Measure the share of positive weights in a batch; near 100% is the sign. The fix is a baseline.

Formula sheet

FormulaSay it aloudWhat it does
∇θ pθ(x) = pθ(x) ∇θ log pθ(x)nabla p equals p times nabla log pThe log-derivative trick: turns the gradient of an average into an average you can sample.
∇θJ = E[ (Σt ∇ log π(at|st)) R(τ) ]nabla J equals the average of the summed scores times R of tauREINFORCE: every step weighted by the whole return. The world's dynamics drop out.
Gt = Σt′≥t γt′−t rt′G-t is the sum from t-prime equals t of gamma to the t-prime minus t times r-t-primeReward-to-go: an action cannot change past rewards, so drop them.
∂ log π(a)/∂θb = 1[b = a] − π(b)the score for logit b is one if b is a, minus pi of bSoftmax score: up for the taken action, down for the rest.
∇θJ = E[ Σt ∇ log π(at|st) A(st, at) ]nabla J equals the average of the scores times A of s-t and a-tThe same gradient with the advantage: the lowest-noise form.
A colleague subtracts b = 100 from every return and says this biases the policy gradient. Is the colleague right?

Chapter 3

Actor-Critic: A Critic Steadies the Push

Replace the noisy return with a learned guess, and trade noise for bias

G-t is one noisy sample of the future. A critic V̂(s), a network that predicts the return from state s, gives a steadier guess. The policy is now the actor. The critic scores each action by one step of surprise. Full lesson: Actor-Critic Methods.

Say it aloud

Delta-t equals r-t plus gamma times V-hat of s-t-plus-one, minus V-hat of s-t.

δt
delta-t the TD error: a one-step estimate of the advantage, A-hat.
rt
r-t the reward the action earned.
γ
gamma the discount, from 0 to 1.
V̂(st+1)
V-hat of s-t-plus-one the critic's guess for the next state.
V̂(st)
V-hat of s-t the critic's guess for the state where the agent took the action.
In plain words

Add the reward r-t to the critic's discounted guess for the next state: that is the TD target. Subtract the guess for this state. A positive delta-t means the action beat expectations.

With numbers

With made-up values V̂(s1) = 5, V̂(s2) = 8, r = 3 and gamma 0.9: the target is 3 + 0.9 × 8 = 10.2, so delta = 10.2 − 5 = +5.2. The actor raises the action; the critic moves V̂(s1) toward 10.2.

One reward plus a guess has little noise, but it inherits the critic's error. An n-step return uses n real rewards, then the guess. At n = 1 it is the TD target; run to the episode's end and it is the Monte Carlo return, with no guess at all.

Slide from TD to Monte Carlo

Dots are 40 sampled estimates of V(s0). The dashed line is the truth. Raise n and watch the bias shrink while the dots spread.

1
+3.0

Illustrative chain: 10 steps, mean reward 1 with noise of spread 1, gamma 0.9, so V(s0) = 6.51. The critic is off by the same amount at every state.

The failure. A brand-new critic gives bad targets. The symptom: the actor learns from advantages with the wrong sign. Measure it by comparing the critic's guesses with Monte Carlo returns on fresh episodes. The fix early on: a larger n, or GAE with lambda near 1.

Formula sheet

FormulaSay it aloudWhat it does
A(s, a) = Q(s, a) − V(s)A of s and a equals Q of s and a minus V of sThe advantage: how much better action a is than the policy's average.
V(s) = Ea∼π[ Q(s, a) ]V of s is the average over a from pi of Q of s and aA state's value averages its action values, so the advantages average to 0.
yt = Σk<n γk rt+k + γn V̂(st+n)y-t is the sum for k below n of gamma to the k r-t-plus-k, plus gamma to the n V-hat of s-t-plus-nThe n-step target: n real rewards, then the critic's guess.
L(φ) = ½ Σt ( V̂φ(st) − yt )2L of phi is one half the sum of V-hat minus y-t, squaredThe critic's loss: regress the guess onto the target.
Ât = Σl≥0 (γλ)l δt+lA-hat-t is the sum over l of gamma-lambda to the l, times delta of t plus lGAE: a blend of all n. Lambda 0 is TD; lambda 1 is Monte Carlo.
Ât = δt + γλ Ât+1A-hat-t equals delta-t plus gamma-lambda A-hat-t-plus-oneGAE in one backward loop over the episode.
V(sA) = 10, V(sB) = 6, the agent moves from sA to sB with r = 2, and gamma is 0.95. What is the TD advantage?

Chapter 4

Off-Policy Actor-Critic: Reuse Data Safely

Reuse one batch a few times with PPO's clip, or reuse everything with SAC's replay buffer

An on-policy method throws each batch away after one gradient step. Two fixes reuse data. PPO reuses a fresh batch for a few passes and limits how far each pass moves the policy. SAC keeps every transition in a replay buffer and learns Q from it. Full lesson: Off-Policy Actor-Critic.

PPO compares the new policy with the one that collected the data. The probability ratio r-t is the new policy's chance of the logged action divided by the old one's. Â-t is the advantage from Chapter 3. ε sets the width of the allowed band.

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 PPO's objective, raised by gradient steps.
Et
the average over t the mean over the logged steps in the batch.
min
the minimum of keep the smaller of the two terms.
rt
r-t the ratio πθ(at|st) / πold(at|st); 1 means no change.
Ât
A-hat-t the advantage estimate of the logged action.
clip(rt, 1−ε, 1+ε)
r-t clipped the ratio held inside the band, often 0.8 to 1.2 with epsilon 0.2.
In plain words

For each logged step, compute the plain term r-t times A-hat-t and the clipped term, and keep the smaller. Past the band in the direction the advantage wants, the clipped term wins and its slope is zero.

With numbers

With made-up chances: old 0.3, new 0.9, so r = 3.0. With A-hat = +2 and epsilon 0.2, the plain term is 6.0 and the clipped term is 1.2 × 2 = 2.4. PPO keeps 2.4.

Find where a sample stops pushing

The purple line is PPO's objective; the dashed line is the plain ratio term. Drag the ratio, then flip the advantage's sign.

3.00
0.20

One logged action, toy numbers.

SAC builds a target for Q from a stored transition: reward r and next state s′. It adds a fresh action ã′ from the current policy at s′. Two slow-moving target critics Q̄-1 and Q̄-2 guard against optimism. A bonus with weight α pays for randomness.

Say it aloud

y equals r plus gamma times, the minimum over j of Q-bar-j of s-prime and a-tilde-prime, minus alpha times log pi-theta of a-tilde-prime given s-prime.

y
y the target both critics regress onto.
r
r the stored reward of the transition.
minj
the minimum over j the smaller of the two target critics, j = 1 or 2.
Q̄j(s′, ã′)
Q-bar-j of s-prime and a-tilde-prime a slow copy of critic j, at the next state and the fresh action.
α
alpha the entropy weight: how much randomness is worth.
log πθ(ã′|s′)
log pi-theta of a-tilde-prime given s-prime the log-chance of the fresh action; negative, so minus alpha times it is a bonus.
In plain words

Draw a fresh next action from the current policy. Take the smaller target critic there, add the entropy bonus, discount by gamma and add the reward r.

With numbers

With made-up numbers: r = 1, gamma 0.99, critics 5.0 and 4.6, log pi = −1.2 and alpha 0.2. The bonus is 0.24, so y = 1 + 0.99 × (4.6 + 0.24) = 5.79.

The failure. Ratios multiply over a trajectory. A per-step ratio of 3 over 20 steps gives 320, about 3.5 billion, so one sample swamps the batch. To measure it, log the largest ratio, the average KL and the share of clipped samples. The fix: per-step ratios, the clip, and few passes per batch.

Formula sheet

FormulaSay it aloudWhat it does
Ea∼π[ f(a) ] = Ea∼μ[ (π(a)/μ(a)) f(a) ]the average under pi equals the average under mu of the ratio times fImportance sampling: reweight old samples from μ to score the new policy π.
ρ(τ) = Πt π(at|st) / μ(at|st)rho of tau is the product over t of the per-step ratiosA whole-trajectory ratio: explodes or vanishes with length.
Es[ DKL(πold ‖ πθ) ] ≤ δthe average KL from pi-old to pi-theta is at most deltaTRPO's trust region: a hard limit on each policy change.
J(π) = E[ Σt rt + α H(π(·|st)) ]J of pi is the average of the sum of r-t plus alpha times H of piSAC's maximum-entropy goal: reward plus randomness.
H(π(·|s)) = −Ea∼π[ log π(a|s) ]H of pi is minus the average log piEntropy: high when the policy spreads its bets.
φ̄ ← τφ + (1 − τ)φ̄phi-bar becomes tau phi plus one minus tau phi-barA slow target network: each step closes a share tau of the gap.
Htarget = −dim(A)the target entropy is minus the action dimensionSAC's common rule for tuning alpha automatically: −7 for a 7-joint arm.
PPO with epsilon 0.2. A sample has ratio 1.5 and advantage +3. What is its clipped objective?

Chapter 5

Q-Learning: Value Each Action, Take the Max

Learn what each action is worth, and let the policy be the action with the largest value

A game has four buttons. Q(s, a) is the return you expect if you press a in state s and then play well. If you knew it, the policy would be: press the button with the largest Q. There is no policy network. Full lesson: Q-Learning.

Learn Q one transition at a time: state s, action a, reward r, next state s′. The step size is α (alpha).

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's value for pressing a in s.
α
alpha the step size: the fraction of the gap closed per update.
r
r the reward of this transition.
γ
gamma the discount on the next state's value.
maxa′ Q(s′, a′)
the max over a-prime of Q of s-prime and a-prime the best value at the next state, whatever action came next.
In plain words

The target is the reward r plus the discounted best value at s-prime. Subtract the old Q of s and a: that is the TD error. Move Q a fraction alpha of the way.

With numbers

With a made-up table: Q(s1, R) = 4, r = 2, the next state's values are 6 and 3, gamma 0.9, alpha 0.5. The target is 2 + 0.9 × 6 = 7.4, the error is 3.4, and Q(s1, R) becomes 4 + 0.5 × 3.4 = 5.7.

Apply one update by hand

Pick a transition. The teal cell is the one that changes; the blue cell is the max at the next state. Press Update.

0.5

Made-up table, gamma 0.9. Only one cell changes per update.

Q-learning is off-policy: the max ignores which action the agent took next. SARSA uses the action taken, so it learns the value of the current policy and is on-policy. Deep Q-networks (DQN) add three fixes:

FixProblem it solves
Replay bufferSteps in a row are alike; random old samples break the pattern
Target networkThe target moves with every update; a frozen copy holds it still
Double QThe max of noisy guesses is too high; pick with one network, score with the other

The failure. Overestimation. The symptom: Q values climb above any return the agent has seen. Measure it by comparing Q with Monte Carlo returns from the same states. The fix is double Q.

Formula sheet

FormulaSay it aloudWhat it does
π(s) = argmaxa Q(s, a)pi of s is the argmax over a of Q of s and aThe greedy policy: the action with the largest value.
Q*(s, a) = r + γ Es′[ maxa′ Q*(s′, a′) ]Q-star equals r plus gamma times the average over s-prime of the max of Q-starThe Bellman optimality equation: the best values agree with themselves.
L(θ) = E[ (Qθ(s, a) − (r + γ maxa′ Qφ′(s′, a′)))2 ]L of theta is the average squared gap between Q-theta and the target from the frozen copyThe DQN loss, with a target network Q-phi-prime.
y = r + γ Qφ′(s′, argmaxa′ Qθ(s′, a′))y equals r plus gamma times the target network's value of the online network's pickDouble DQN: pick and score with different networks.
y = r + γ Q(s′, a′taken)y equals r plus gamma Q of s-prime and the action takenSARSA's target: the value of the policy you run.
‖TQ1 − TQ2‖∞ ≤ γ ‖Q1 − Q2‖∞the largest gap after a backup is at most gamma times the largest gap beforeThe backup is a contraction, so a table converges; the gap shrinks by gamma to the k after k backups.
Q(s1, a2) = 7. The agent takes a2 in s1, gets r = 1 and lands in s2, where Q(s2, a1) = 5 and Q(s2, a2) = 2. With gamma 0.9 and alpha 1.0, what is the new Q(s1, a2)?

Chapter 6

Offline RL: Trust Only What the Log Shows

Learn from a fixed log, and keep the values away from actions the log never tried

A hospital has years of treatment records with outcomes. Nobody may run new trials. Offline RL learns the best policy it can from such a fixed log. Run plain Q-learning on it, and the max picks actions the log never tried. There Q is a guess, often too high, and the backup spreads it. Full lesson: Offline RL.

Implicit Q-learning (IQL) never asks Q about an unseen action. It learns V(s) as a high value among the logged actions' Q values, and uses it where the max was. Call the gap u = Q(s, a) − V(s) for a logged pair, and the tilt τ (tau), between 0.5 and 1.

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 for one logged pair.
| τ − 1(u < 0) |
tau minus one-if-u-is-below-zero, absolute the weight: tau when V is too low, one minus tau when V is too high.
u2
u squared the squared gap between the logged Q and V.
In plain words

If V sits below a logged Q value, the gap costs tau times its square; if above, one minus tau times its square. With tau above one half, V settles high among the logged values: a soft max.

With numbers

With tau 0.9: a gap of +2 costs 0.9 × 4 = 3.6, and a gap of −2 costs 0.1 × 4 = 0.4. For logged Q values 3, 5 and 8, the loss is smallest at V = 7.27, near the best logged value.

Raise V without touching the unseen

Warm dots are Q for three logged actions. The red ring is an action the log never tried: its Q of 11 is a guess. Drag tau and watch V.

0.90

Illustrative values. IQL's paper used tau 0.7 on locomotion tasks and 0.9 on the harder maze tasks.

IQL then fits Q to r + γV(s′) and extracts the policy by advantage-weighted regression: clone the logged actions, each weighted by e to its advantage. Every step touches logged pairs only.

The failure. The false peak. The symptom: Q of the learned policy's actions sits far above any return in the log, and the policy fails when run. Measure it by comparing Q on policy actions with Q on logged actions. The fix: IQL, CQL or AWR.

Formula sheet

FormulaSay it aloudWhat it does
π*(a|s) ∝ πβ(a|s) eA(s,a)/αpi-star is proportional to pi-beta times e to the A over alphaThe best policy that stays near the logging policy π-beta.
L(θ) = −Σ(s,a)∈D eA(s,a)/α log πθ(a|s)L of theta is minus the sum over logged pairs of e to the A over alpha times log pi-thetaAWR: weighted cloning; small alpha is greedy, large alpha is plain cloning.
α(Ea∼μ[Q] − Ea∼D[Q]) + ½ED[(Q − y)2]alpha times the average Q under mu minus under the data, plus half the squared TD errorCQL: push Q down where the policy looks, up on logged actions.
y = r + γ V(s′)y equals r plus gamma V of s-primeIQL's Q target: no max, no policy action.
Ek+1 = ε + γ EkE-k-plus-one equals epsilon plus gamma E-kHow a guess error grows through backups: limit ε/(1 − γ), 100 at gamma 0.99.
IQL is run with tau = 0.5. What does V(s) learn?

Chapter 7

Model-Based RL: Learn the World, Then Plan

Fit a model of the dynamics, plan or imagine with it, and keep its errors from compounding

A real robot gets a few hundred tries. Model-based RL fits a dynamics model fθ(s, a) that predicts the next state from logged transitions. Then it plans through the model, or trains a policy on imagined rollouts. The catch: each predicted state feeds the next prediction. Full lesson: Model-Based RL.

Call the model's error after one step ε. Call L the most that one model step can stretch an earlier error. Call the error after H steps e-H. Each step stretches the old error and adds a fresh one: ek+1 ≤ L ek + ε, starting from e0 = 0.

Say it aloud

e-H is at most epsilon times L to the H minus one, all over L minus one.

eH
e-H the gap between the predicted and the true state after H steps.
ε
epsilon the model's error on a single step from a true state.
LH
L to the H the stretch factor applied H times; above 1, errors grow.
L − 1
L minus one the divisor that sums the stretched errors 1 + L + … + LH−1. At L = 1 the sum is H.
In plain words

Each step adds a fresh error epsilon and stretches all earlier error by L. Add the stretched errors of the H steps. If L is above 1, the total grows like L to the H.

With numbers

With made-up epsilon 0.01 and L 1.5: the bound is 0.13 after 5 steps, 1.13 after 10 and 66.5 after 20. At L = 1, a model biased by 0.1 per step is off by 1.0 after 10 steps.

Watch the error compound

The pink curve is the error bound, on a log scale. The shaded zone is a short rollout of 5 steps. Raise L and watch the curve leave the zone.

0.010
1.50

Illustrative. The red line marks an error of 1, as large as a typical step of the state in this toy.

Three habits keep the error small:

HabitHow it works
Replan every step (MPC)Plan H steps, run only the first action, then plan again from the real state
Short rollouts (Dyna, MBPO)Branch a few imagined steps from real buffer states; train an off-policy learner on them
EnsemblesTrain several models; where they disagree, trust the imagined data less

The failure. The planner exploits the model. The symptom: plans score high in the model and fail on the robot. Measure the gap between predicted and real returns of the same plan. The fix: short horizons, replanning, and a penalty where the ensemble disagrees.

Formula sheet

FormulaSay it aloudWhat it does
L(θ) = (1/N) Σi ‖ s′i − si − fθ(si, ai) ‖2L of theta is the average squared miss of the predicted state changeFit the model to predict the change of state, not the state.
Score = Σt<H r(ŝt, at) + V̂(ŝH)the score is the sum of imagined rewards plus V-hat at the last imagined statePlan a short horizon; a learned value covers the rest.
μ ← (1/M) Σj Ajmu becomes one over M times the sum of the M best plansThe cross-entropy method: refit the plan sampler to the elite plans.
σ2(s, a) = (1/K) Σk ‖ fk(s, a) − μ(s, a) ‖2sigma squared is the average squared spread of the K models around their meanEnsemble disagreement: a measure of where the model is unsure.
r̃(s, a) = r(s, a) − λ σ(s, a)r-tilde equals r minus lambda sigmaA reward with a charge for uncertainty, so plans avoid unsure regions.
Why does MPC run only the first action of its best plan, then plan again?

Chapter 8

Multi-Task, Goals and Meta-RL: One Policy for Many Tasks

Give the task as an input, turn failed tries into lessons, and learn a start that adapts fast

One arm should reach any point you name. A goal-conditioned policy π(a | s, g) takes the goal g as an input next to the state. A multi-task policy does the same with a task label. The natural reward is sparse. Full lessons: Multi-Task and Goal-Conditioned RL, Meta-RL.

Say it aloud

r of s-prime and g equals one if the distance from s-prime to g is less than epsilon, and zero otherwise.

r(s′, g)
r of s-prime and g the reward for landing in s-prime while chasing goal g.
1
one a success.
‖s′ − g‖
the distance from s-prime to g how far the state landed from the goal.
ε
epsilon the tolerance that counts as arrived.
In plain words

Measure how far the new state s-prime is from the goal g. Closer than epsilon pays 1; anything else pays 0.

With numbers

With made-up points: s′ = (0.5, 0.8), g = (1.0, 1.0). The distance is √(0.25 + 0.04) = 0.54, more than ε = 0.1, so r = 0.

Random tries almost never hit a far goal, so most rewards are 0 and the agent learns nothing. Hindsight experience replay (HER) keeps each failed try twice: once with the real goal, once with a goal the agent did reach. HER recomputes the reward with the formula above. That needs three things: a reward you can compute, the same dynamics for every goal, and an off-policy learner.

Turn a failed try into lessons

The yellow star is the real goal; the path never reaches it. Switch the goal to one the agent reached and count the transitions that pay.

Illustrative grid, 6 moves per episode, reward 1 only on the goal cell. "Future" gives each transition one goal drawn from the states reached later.

Meta-RL trains on many tasks so that a new task takes few tries. MAML learns a starting point θ from which one gradient step on task i, with step size α, already does well.

Say it aloud

Theta-prime-i equals theta plus alpha times nabla-theta of J-i of theta.

θ′i
theta-prime-i the weights after adapting to task i.
θ
theta the shared starting weights that meta-training learns.
α
alpha the inner step size.
∇θ Ji(θ)
nabla-theta of J-i of theta the policy gradient of task i's return, at the start.
In plain words

From the shared start theta, take one gradient step on task i's return. The outer loop then moves theta so this one step works well on every task.

With numbers

With a made-up one-weight task: at theta = 0 the return is 0.135 and its slope is 0.271. With alpha 7.4, theta-prime = 0 + 7.4 × 0.271 = 2.00, where the return is 1.00, its peak.

The failure. Sparse rewards starve learning. The symptom: success stays at 0 and every Q value is 0. Measure the share of rewarded transitions in the buffer. The fix is HER with an off-policy learner.

Formula sheet

FormulaSay it aloudWhat it does
JMT(θ) = Σi wi Ji(θ)J-M-T is the sum over tasks of w-i times J-iThe multi-task goal: a weighted sum of task returns.
r(s, g) = −‖s − g‖r equals minus the distance to the goalA dense goal reward: a hint every step, at the risk of local traps.
Q(s, a, g) = r(s, a, g) + γ maxa′ Q(s′, a′, g)Q of s, a and g equals r plus gamma max over a-prime of Q at s-prime with the same gThe goal-conditioned backup: the goal rides along unchanged.
g′ = sTg-prime equals s-THER's final strategy: relabel with the last state reached.
θ ← θ + β ∇θ (1/N) Σi Ji(θ′i)theta becomes theta plus beta times the gradient of the average return after adaptingMAML's outer step: improve the start through the inner step.
ht = fθ(ht−1, ot, at−1, rt−1)h-t equals f-theta of the last memory, observation, action and rewardBlack-box meta-RL: a recurrent network adapts by reading its history.
Why does HER need an off-policy learner such as SAC or DQN, and not PPO?

Chapter 9

Rewards and RLHF: Learn the Reward From People

Turn "this one is better" into a reward model, then optimise against it on a leash

A boat-racing agent rewarded for collecting boosts learned to circle and never finish. Hand-written rewards get gamed. People find it easier to compare two outcomes than to score one. Full lessons: Reward Learning, RLHF and DPO.

Show a person two tries: the winner τ-w and the loser τ-l. A reward model gives each a total, R(τ-w) and R(τ-l). The Bradley-Terry model turns the gap into a chance with the sigmoid σ, which squashes any number into 0 to 1.

Say it aloud

The probability that tau-w beats tau-l equals sigma of R of tau-w minus R of tau-l.

P(τw ≻ τl)
the probability that tau-w beats tau-l the chance a person picks the winner.
σ
sigma the sigmoid, 1 / (1 + e−x).
R(τw)
R of tau-w the reward model's total for the preferred try.
R(τl)
R of tau-l its total for the other try.
In plain words

Take the gap between the two totals and squash it into a chance. Training lowers minus the log of that chance for every labelled pair.

With numbers

With made-up totals 5 and 3: σ(2) = 0.881 and the loss is 0.127. With 3.1 and 3: σ(0.1) = 0.525 and the loss is 0.644, five times larger. Close calls teach most.

Where the sigmoid comes from: give each try a weight of e to its total. The winner's share of the two weights is the sigmoid of the gap.

eRw / (eRw + eRl) = 1 / (1 + e−(Rw − Rl)) = σ(Rw − Rl)

Score a preference pair

The person preferred try w. Move the two totals and watch the chance, the loss and the size of the push.

5.0
3.0

The push is the loss gradient on each total: 1 − σ of the gap, up for the winner and down for the loser.

RLHF then trains the policy πθ to score high on the reward model rφ, for prompts x and answers y. A leash, the KL divergence to the starting policy πref with weight β, keeps it where the reward model is reliable.

Say it aloud

Maximize over theta the average, over answers y drawn from pi-theta, of r-phi of x and y, minus beta times the KL from pi-theta to pi-ref.

maxθ
maximize over theta tune the policy's weights.
Ey∼πθ
the average over y drawn from pi-theta over answers the policy itself writes.
rφ(x, y)
r-phi of x and y the learned reward for answer y to prompt x.
β
beta the leash strength.
DKL(πθ ‖ πref)
the KL from pi-theta to pi-ref how far the policy has drifted from the reference, in nats.
In plain words

Average the learned reward over the policy's own answers. Subtract beta times its drift from pi-ref. Raise the difference, usually with PPO.

With numbers

With made-up chances over two answers: reference 0.6 and 0.4, policy 0.2 and 0.8, rewards 1 and 3, beta 2. The reward averages 2.6, the KL is 0.335, so the objective is 2.6 − 0.67 = 1.93, above the reference's 1.8.

The failure. The policy games the learned reward. The symptom: the reward model's score rises while people rate the outputs worse. Measure it with held-out human ratings next to the model's score. The fix: a larger beta, and fresh preference labels on the new outputs.

Formula sheet

FormulaSay it aloudWhat it does
L(φ) = −E(w,l)[ log σ(Rφ(τw) − Rφ(τl)) ]L of phi is minus the average log sigma of the gapThe reward model's loss: binary cross-entropy on each pair.
DKL(π ‖ πref) = Ey∼π[ log π(y|x) − log πref(y|x) ]the KL is the average over y from pi of log pi minus log pi-refThe drift: 0 when the two policies match.
π*(y|x) = πref(y|x) er(x,y)/β / Z(x)pi-star equals pi-ref times e to the r over beta, over Z of xThe exact best policy for the KL objective.
−E log σ( β log (πθ(yw)/πref(yw)) − β log (πθ(yl)/πref(yl)) )minus the average log sigma of beta times the winner's log-ratio minus beta times the loser'sDPO: trains the policy on preference pairs, no reward model, no sampling.
r(s) = σ(fφ(s))r of s equals sigma of f-phi of sA success classifier as the reward, trained on example goal states.
Why does RLHF fit a reward model instead of asking people at every policy update?

Chapter 10

Which Method When

Read the facts of a problem in order, and let each fact remove families

The hero applies a few rules in a fixed order. The signal comes first, because it decides the loss. Then the data, because a fixed log rules out every method that needs new tries. Then the shape of the task.

If the problem hasReach forChapter
Demos, no rewardBehaviour cloning; DAgger if the expert can label new states1
Preferences, no rewardA reward model and RLHF; DPO on a fixed set of pairs9
A reward and a fixed logOffline RL: IQL, CQL or AWR6
A reward, many goalsA goal-conditioned learner with HER8
A reward, a few hundred real triesModel-based RL: MPC or MBPO7
A reward, discrete actionsQ-learning, DQN5
A reward, continuous actions, costly triesSAC, an off-policy actor-critic4
A reward, continuous actions, a fast simulatorAn on-policy actor-critic, such as PPO3, 4

Policy gradients from Chapter 2 sit under the actor-critic rows and under RLHF, which runs PPO. Real projects often chain two rows: clone the demos, then fine-tune with RL.

Drill: pick the family

Read the scenario and press the family you would use. The tiles keep your score for each family.

Our scenarios, 15 in all, in a shuffled order. Each has one best answer by the table above.

The failure. Solving the wrong problem. The symptom: a method that needs new tries, run on a fixed log, or a reward method run with no reward. To measure it, write the three answers from Chapter 0 before you pick. The fix is to pick from the table only after that.

You have five years of clinic records with outcomes, from doctors of mixed skill. No new patients may be treated by the learner. Which family fits best?

Chapter 11

The Field Guide

Keep the terms, the numbers, a checklist and the core code on one page

Every family answers three questions: where the data comes from, what signal it uses and what it learns. Imitation copies, policy gradients push, critics steady the push and off-policy methods reuse. Q-learning takes a max, offline methods distrust the unseen, models imagine, goals multiply tasks and preferences replace hand-written rewards.

Terms and numbers

TermOne lineNumber from this page
Behaviour cloningRegress the expert's actions on states60/40 at +2/−2 gives a mean of +0.4
Compounding errorA clone's slips multiply into states no demo coversT²ε = 100 at T 100, ε 0.01; DAgger 2
BaselineSubtract a usual return; same average, less noiseReturns 5, −2, 1: b 1.33, weights +3.67, −3.33, −0.33
TD errorReward plus next guess minus this guess3 + 0.9 × 8 − 5 = +5.2
PPO clipKeep the smaller of plain and clippedRatio 3, A-hat +2: 2.4, not 6.0
SAC targetSmaller critic plus an entropy bonus1 + 0.99 × (4.6 + 0.24) = 5.79
Q-learning updateMove toward reward plus the best next value4 becomes 5.7 at alpha 0.5
Deadly triadOff-policy data, function approximation and bootstrapping together can divergeError limit ε/(1 − γ): 100 at γ 0.99
ExpectileA tilted mean; tau above one half leans to the top3, 5, 8: 5.33, 6.15, 7.27 at tau 0.5, 0.7, 0.9
Model error boundFresh error each step, old error stretched by Lε 0.01, L 1.5: 0.13 at 5 steps, 66.5 at 20
HERRelabel failed tries with goals they reached0 paying transitions become at least 1 per episode
Bradley-TerryThe sigmoid of a reward gap is a preference chanceGap 2: 0.881, loss 0.127; gap 0.1: loss 0.644

Three tensions run through every chapter

TensionOne endOther end
Bias and varianceMonte Carlo returns: unbiased, noisyTD targets: steady, biased by the critic
Reuse and safetyOn-policy: stable, wastefulOff-policy and offline: thrifty, can diverge
Explore and exploitEntropy bonus, epsilon-greedyGreedy argmax, low alpha at deployment

Before you answer a review question

The core code

One small function per family, in NumPy. The last lines reproduce this page's worked numbers.

pythonimport numpy as np

def reward_to_go(r, gamma):                  # Ch 2: G_t for one episode
    G, out = 0.0, np.zeros(len(r))
    for t in reversed(range(len(r))):
        G = r[t] + gamma * G
        out[t] = G
    return out

def td_error(r, v, v_next, gamma):           # Ch 3: one-step advantage
    return r + gamma * v_next - v

def ppo_clip(ratio, adv, eps=0.2):           # Ch 4: per-sample objective
    return np.minimum(ratio * adv, np.clip(ratio, 1 - eps, 1 + eps) * adv)

def q_update(Q, s, a, r, s2, alpha, gamma):  # Ch 5: tabular Q-learning
    Q[s, a] += alpha * (r + gamma * Q[s2].max() - Q[s, a])

def expectile_loss(u, tau):                  # Ch 6: IQL's tilted loss
    return np.abs(tau - (u < 0)) * u ** 2

def bt_loss(R_w, R_l):                       # Ch 9: Bradley-Terry
    return np.log1p(np.exp(-(R_w - R_l)))    # = -log sigma(R_w - R_l)

# the page's worked numbers
print(reward_to_go([1, 0, 2], 0.9)[0])                    # 2.62
print(td_error(3, 5, 8, 0.9))                             # 5.2
print(ppo_clip(3.0, 2.0), ppo_clip(0.5, -2.0))            # 2.4 -1.6
Q = np.array([[2., 4], [6, 3], [1, 5]]); q_update(Q, 0, 1, 2, 1, 0.5, 0.9); print(Q[0, 1])   # 5.7
print(expectile_loss(np.array([2., -2]), 0.9))            # [3.6 0.4]
print(bt_loss(5, 3), bt_loss(3.1, 3))                     # 0.127 0.644

Keep going

The takeaway. Name the data, the signal and what gets learned. Then each family is one idea and one or two equations, and each trap is a wrong answer to one of those questions.
Which of these can learn from transitions collected by a different, older policy?

Now press Present or Teach and review the course from memory: one idea and one equation per family, said aloud. Then go back to the hero, set the facts of a problem you care about, and say why the lit family fits.

Credit and source

This page reviews Stanford CS 224R: Deep Reinforcement Learning. It is our review, not the course's exam. The papers behind it, by family. Imitation: Ross, Gordon and Bagnell (2011), DAgger. Policy gradients and actor-critic: Williams (1992), REINFORCE; Schulman et al., GAE (2016). Off-policy: Schulman et al., PPO (2017); Haarnoja et al., SAC (2018).

Q-learning: Mnih et al. (2015), DQN. Offline: Kostrikov, Nair and Levine, IQL (2021). Models: Janner et al., MBPO (2019). Goals and meta: Andrychowicz et al., HER (2017); Finn, Abbeel and Levine, MAML (2017). Preferences: Christiano et al. (2017); Rafailov et al., DPO (2023). The toys and numbers here are our own.

CS 224R: Deep RL Review
The course site · Policy Gradients · Offline RL · Back to Gleams