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.
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
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.
| Question | Answers | Why 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 outcomes | Decides the loss |
| What does it learn? | A policy, a value, both, or a model of the world | Decides 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).
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.
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 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.
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.
Chapter 1
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.
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.
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 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.
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.
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.
C of pi-hat is at most C of pi-star plus T squared times epsilon.
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 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 | Say it aloud | What it does |
|---|---|---|
| −(1/N) Σi log πθ(ai | si) | minus one over N, sum over i of log pi-theta of a-i given s-i | Likelihood 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-k | A mixture policy: one bump per way of acting. |
| xt = t · a + (1 − t) · x0 | x-t equals t times a, plus one minus t times x-zero | Flow matching: a straight path from noise x-zero to the expert action. |
| ‖ vθ(xt, s, t) − (a − x0) ‖2 | the squared gap between v-theta and a minus x-zero | Flow 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-theta | Sampling: 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 epsilon | DAgger's ceiling: linear in the horizon T. |
| wi = eRi/β | w-i equals e to the R-i over beta | Filtered cloning: demos with a higher return R-i count more. |
Chapter 2
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.
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.
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 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.
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 | Say it aloud | What it does |
|---|---|---|
| ∇θ pθ(x) = pθ(x) ∇θ log pθ(x) | nabla p equals p times nabla log p | The 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 tau | REINFORCE: 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-prime | Reward-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 b | Softmax 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-t | The same gradient with the advantage: the lowest-noise form. |
Chapter 3
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.
Delta-t equals r-t plus gamma times V-hat of s-t-plus-one, minus V-hat of s-t.
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 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.
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.
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 | Say it aloud | What it does |
|---|---|---|
| A(s, a) = Q(s, a) − V(s) | A of s and a equals Q of s and a minus V of s | The 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 a | A 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-n | The n-step target: n real rewards, then the critic's guess. |
| L(φ) = ½ Σt ( V̂φ(st) − yt )2 | L of phi is one half the sum of V-hat minus y-t, squared | The critic's loss: regress the guess onto the target. |
| Ât = Σl≥0 (γλ)l δt+l | A-hat-t is the sum over l of gamma-lambda to the l, times delta of t plus l | GAE: a blend of all n. Lambda 0 is TD; lambda 1 is Monte Carlo. |
| Ât = δt + γλ Ât+1 | A-hat-t equals delta-t plus gamma-lambda A-hat-t-plus-one | GAE in one backward loop over the episode. |
Chapter 4
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.
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 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 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.
The purple line is PPO's objective; the dashed line is the plain ratio term. Drag the ratio, then flip the advantage's sign.
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.
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.
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 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 | Say it aloud | What it does |
|---|---|---|
| Ea∼π[ f(a) ] = Ea∼μ[ (π(a)/μ(a)) f(a) ] | the average under pi equals the average under mu of the ratio times f | Importance 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 ratios | A whole-trajectory ratio: explodes or vanishes with length. |
| Es[ DKL(πold ‖ πθ) ] ≤ δ | the average KL from pi-old to pi-theta is at most delta | TRPO'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 pi | SAC's maximum-entropy goal: reward plus randomness. |
| H(π(·|s)) = −Ea∼π[ log π(a|s) ] | H of pi is minus the average log pi | Entropy: high when the policy spreads its bets. |
| φ̄ ← τφ + (1 − τ)φ̄ | phi-bar becomes tau phi plus one minus tau phi-bar | A slow target network: each step closes a share tau of the gap. |
| Htarget = −dim(A) | the target entropy is minus the action dimension | SAC's common rule for tuning alpha automatically: −7 for a 7-joint arm. |
Chapter 5
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).
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.
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 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.
Pick a transition. The teal cell is the one that changes; the blue cell is the max at the next state. Press Update.
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:
| Fix | Problem it solves |
|---|---|
| Replay buffer | Steps in a row are alike; random old samples break the pattern |
| Target network | The target moves with every update; a frozen copy holds it still |
| Double Q | The 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 | Say it aloud | What it does |
|---|---|---|
| π(s) = argmaxa Q(s, a) | pi of s is the argmax over a of Q of s and a | The 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-star | The 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 copy | The 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 pick | Double 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 taken | SARSA'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 before | The backup is a contraction, so a table converges; the gap shrinks by gamma to the k after k backups. |
Chapter 6
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.
L-tau of u equals the absolute value of tau minus one-if-u-is-below-zero, times u squared.
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 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.
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.
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 | Say it aloud | What it does |
|---|---|---|
| π*(a|s) ∝ πβ(a|s) eA(s,a)/α | pi-star is proportional to pi-beta times e to the A over alpha | The 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-theta | AWR: 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 error | CQL: push Q down where the policy looks, up on logged actions. |
| y = r + γ V(s′) | y equals r plus gamma V of s-prime | IQL's Q target: no max, no policy action. |
| Ek+1 = ε + γ Ek | E-k-plus-one equals epsilon plus gamma E-k | How a guess error grows through backups: limit ε/(1 − γ), 100 at gamma 0.99. |
Chapter 7
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.
e-H is at most epsilon times L to the H minus one, all over L minus one.
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 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.
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.
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:
| Habit | How 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 |
| Ensembles | Train 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 | Say it aloud | What it does |
|---|---|---|
| L(θ) = (1/N) Σi ‖ s′i − si − fθ(si, ai) ‖2 | L of theta is the average squared miss of the predicted state change | Fit 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 state | Plan a short horizon; a learned value covers the rest. |
| μ ← (1/M) Σj Aj | mu becomes one over M times the sum of the M best plans | The cross-entropy method: refit the plan sampler to the elite plans. |
| σ2(s, a) = (1/K) Σk ‖ fk(s, a) − μ(s, a) ‖2 | sigma squared is the average squared spread of the K models around their mean | Ensemble disagreement: a measure of where the model is unsure. |
| r̃(s, a) = r(s, a) − λ σ(s, a) | r-tilde equals r minus lambda sigma | A reward with a charge for uncertainty, so plans avoid unsure regions. |
Chapter 8
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.
r of s-prime and g equals one if the distance from s-prime to g is less than epsilon, and zero otherwise.
Measure how far the new state s-prime is from the goal g. Closer than epsilon pays 1; anything else pays 0.
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.
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.
Theta-prime-i equals theta plus alpha times nabla-theta of J-i of theta.
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 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 | Say it aloud | What it does |
|---|---|---|
| JMT(θ) = Σi wi Ji(θ) | J-M-T is the sum over tasks of w-i times J-i | The multi-task goal: a weighted sum of task returns. |
| r(s, g) = −‖s − g‖ | r equals minus the distance to the goal | A 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 g | The goal-conditioned backup: the goal rides along unchanged. |
| g′ = sT | g-prime equals s-T | HER'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 adapting | MAML'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 reward | Black-box meta-RL: a recurrent network adapts by reading its history. |
Chapter 9
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.
The probability that tau-w beats tau-l equals sigma of R of tau-w minus R of tau-l.
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 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.
The person preferred try w. Move the two totals and watch the chance, the loss and the size of the push.
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.
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.
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 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 | Say it aloud | What it does |
|---|---|---|
| L(φ) = −E(w,l)[ log σ(Rφ(τw) − Rφ(τl)) ] | L of phi is minus the average log sigma of the gap | The 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-ref | The 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 x | The 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's | DPO: trains the policy on preference pairs, no reward model, no sampling. |
| r(s) = σ(fφ(s)) | r of s equals sigma of f-phi of s | A success classifier as the reward, trained on example goal states. |
Chapter 10
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 has | Reach for | Chapter |
|---|---|---|
| Demos, no reward | Behaviour cloning; DAgger if the expert can label new states | 1 |
| Preferences, no reward | A reward model and RLHF; DPO on a fixed set of pairs | 9 |
| A reward and a fixed log | Offline RL: IQL, CQL or AWR | 6 |
| A reward, many goals | A goal-conditioned learner with HER | 8 |
| A reward, a few hundred real tries | Model-based RL: MPC or MBPO | 7 |
| A reward, discrete actions | Q-learning, DQN | 5 |
| A reward, continuous actions, costly tries | SAC, an off-policy actor-critic | 4 |
| A reward, continuous actions, a fast simulator | An on-policy actor-critic, such as PPO | 3, 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.
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.
Chapter 11
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.
| Term | One line | Number from this page |
|---|---|---|
| Behaviour cloning | Regress the expert's actions on states | 60/40 at +2/−2 gives a mean of +0.4 |
| Compounding error | A clone's slips multiply into states no demo covers | T²ε = 100 at T 100, ε 0.01; DAgger 2 |
| Baseline | Subtract a usual return; same average, less noise | Returns 5, −2, 1: b 1.33, weights +3.67, −3.33, −0.33 |
| TD error | Reward plus next guess minus this guess | 3 + 0.9 × 8 − 5 = +5.2 |
| PPO clip | Keep the smaller of plain and clipped | Ratio 3, A-hat +2: 2.4, not 6.0 |
| SAC target | Smaller critic plus an entropy bonus | 1 + 0.99 × (4.6 + 0.24) = 5.79 |
| Q-learning update | Move toward reward plus the best next value | 4 becomes 5.7 at alpha 0.5 |
| Deadly triad | Off-policy data, function approximation and bootstrapping together can diverge | Error limit ε/(1 − γ): 100 at γ 0.99 |
| Expectile | A tilted mean; tau above one half leans to the top | 3, 5, 8: 5.33, 6.15, 7.27 at tau 0.5, 0.7, 0.9 |
| Model error bound | Fresh error each step, old error stretched by L | ε 0.01, L 1.5: 0.13 at 5 steps, 66.5 at 20 |
| HER | Relabel failed tries with goals they reached | 0 paying transitions become at least 1 per episode |
| Bradley-Terry | The sigmoid of a reward gap is a preference chance | Gap 2: 0.881, loss 0.127; gap 0.1: loss 0.644 |
| Tension | One end | Other end |
|---|---|---|
| Bias and variance | Monte Carlo returns: unbiased, noisy | TD targets: steady, biased by the critic |
| Reuse and safety | On-policy: stable, wasteful | Off-policy and offline: thrifty, can diverge |
| Explore and exploit | Entropy bonus, epsilon-greedy | Greedy argmax, low alpha at deployment |
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
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.
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.