Imagine learning chess in a world where nobody ever points at a move and says "that was a mistake." You play out a whole game of about 40 moves, and only at the very end are you told that you won or lost. Somewhere in those moves were the ones that mattered. Maybe move 12 was brilliant and move 31 threw the game away, but all you have to go on is one number, and it arrives long after the moves that earned it.
That's the situation of a reinforcement learning agent, a program that learns by acting in an environment and receiving a numerical reward as feedback. There's no labelled "correct action" for it to copy, only a signal like "that whole sequence of decisions was worth +8", delivered many steps after the decisions responsible. Working out which decisions deserve the credit or the blame is called credit assignment, and most of this chapter is machinery for doing it.
We'll build that machinery on one small example: a robot on a 5×5 grid, starting in one corner, trying to reach the goal in the opposite corner, with a pit next to the shortest route. First we'll set up the loop between the robot and its world and the vocabulary that goes with it. Then we'll see how a recursive equation lets credit travel backwards from the goal one step at a time, how a second family of methods adjusts the robot's behaviour directly instead, and how an algorithm called PPO keeps that adjustment from going wrong.
Here's the history in brief. Early methods (dynamic programming, tabular Q-learning, SARSA) kept a table with one value estimate per state. That's exact, but a table can't say anything about a state it hasn't seen, so inputs like raw pixels were out of reach. Mnih et al. (2013) replaced the table with a neural network, the deep Q-network, which needed a replay buffer and a target network to train stably and learned Atari games from pixels. Schulman et al.'s PPO (2017) then made policy optimization stable and simple enough to become the default. PPO is the RL algorithm inside RLHF, which chapter 10 covers for language models, and the same machinery sits under robotics control (chapter 21) and systems like AlphaGo and MuZero.
01Learning from a score at the end
Feedback that comes late
In supervised learning, every example comes with the right answer, so the model learns from a separate error on every prediction. Our robot has nothing like that. Nearly every step it takes earns a reward of 0, and it gets +1 only when it finally steps into the goal. A shortest route across the grid takes eight moves (four right and four down), and a wandering robot might take dozens. When the +1 finally arrives, which of those moves was it for? It has to work that out from the pattern of rewards it collects over many attempts.
So the learner here is a trial-and-error one. At each step it observes where it is, picks an action, and the world answers with a reward and a new position, and then the loop repeats. Nothing whispers the right action at each step, which makes this a different problem from supervised learning, and it's why RL needs vocabulary of its own: states, actions, rewards, policies, value functions. We'll build that vocabulary in section 2. First there's a smaller problem hiding inside the big one, probably the simplest form of the difficulty, and it's easier to see with the grid stripped away.
Trying new things or repeating what works
Suppose there's only one position and three actions. You're facing three slot machines that win 20%, 50% and 80% of the time, and you don't know which is which. Every pull is an action and every payout is a reward. If you keep pulling whichever machine has paid best so far, you might lock onto a mediocre one and never find out that another is better. If you try machines at random forever, you learn the odds but never cash in on them. An agent has to balance exploration (trying something to learn about it) against exploitation (using what it already knows), and one simple way to do it is to explore with a small probability (epsilon) and exploit otherwise. That strategy is called epsilon-greedy.
Below, the code compares three settings of epsilon. For each machine it keeps est, a running average of the payouts seen so far. On each step, rng.integers(3) if rng.random() < eps else est.argmax() pulls a random machine with probability eps and otherwise pulls the one with the highest average. On the line est[a] += (r - est[a]) / n[a], a machine's average is updated after a pull without storing every past payout. Notice that all the estimates start at zero, and that argmax on a tie picks the first machine, the 20% one.
Try it Compare three exploration strategies on three slot machines
import numpy as np
rng = np.random.default_rng(1)
true = np.array([0.2, 0.5, 0.8]) # win rate of 3 slot machines
def run(eps, steps=5000):
est, n, total = np.zeros(3), np.zeros(3), 0
for _ in range(steps):
a = rng.integers(3) if rng.random() < eps else est.argmax()
r = float(rng.random() < true[a])
n[a] += 1
est[a] += (r - est[a]) / n[a] # running average of this machine
total += r
return total / steps
for eps in (0.0, 0.1, 1.0):
print(f"epsilon {eps:.1f}: average reward {run(eps):.3f}")
0.201, exploring 10% of the time earns 0.770, and exploring all the time earns 0.507. The purely greedy agent starts with every estimate at zero, picks machine 0, and never tries the others, so it settles for the worst machine. Random choice averages the three win rates, about 0.5. A little exploration finds the 80% machine and then mostly plays it. The best possible average is 0.8.The greedy agent (epsilon 0) pulls machine 0 on the first step, and from then on its estimate for machine 0 is either zero (after losses) or above zero (after a win), while the other two stay at zero. Machine 0 is never behind, and argmax breaks ties in its favour, so the agent never looks at the others. It settles for the worst machine and earns about 0.2, that machine's win rate. An agent that explores all the time pulls machines at random, so it averages the three win rates, about 0.5. One that explores 10% of the time finds the 80% machine early and then mostly plays it, and lands at 0.77, close to the best possible average of 0.8. That gap is the price of the exploring it keeps doing: 90% of its pulls earn 0.8 and the other 10% are random pulls that average 0.5, and 0.9 × 0.8 + 0.1 × 0.5 = 0.77.
Why not always pick the action that looks best so far?
Because what looks best is only an estimate built from the few pulls you've made, and a greedy agent never gets the chance to correct it. An action that was never tried keeps whatever estimate it started with, and an action that got unlucky early looks bad forever. A little exploration is usually the only way an agent can find out that its estimates are wrong.
With slot machines the payout arrives right after the pull, so each action can be judged on its own. In the grid it can't, and that's what the next section's vocabulary is for. We'll set it up precisely, still using the robot.
02The loop and its vocabulary
States, actions and the policy
Maybe the easiest way to hold all of this is to keep the robot in mind. Every RL problem is framed the same way. An agent sits in an environment. At each time step it observes a state (for our robot, which of the 25 cells it's standing in), chooses an action (up, down, left or right), and the environment returns a reward and a next state . Its rule for choosing actions is called its policy, written , the probability of choosing action when in state . This loop repeats thousands or millions of times during training, and learning means improving the policy.
A Markov decision process
To reason about this loop precisely, we write it down as a Markov decision process (MDP), which has five pieces. For the robot, each piece has an obvious meaning, and we'll attach it to the list as we go.
- , a set of states. For the robot, the 25 cells.
- , a set of actions. The four moves.
- , a transition function giving the probability of landing in state after taking action in state . In a plain grid a move goes where you aimed it, and a move into a wall leaves you where you were.
- , a reward function. Here
+1for entering the goal,-1for entering the pit and 0 otherwise. - , a discount factor, which we'll come to in a moment.
"Markov" means the future depends only on the current state and not on the full history that led there, so the state is assumed to already summarize everything relevant. Our robot's cell is enough to decide what to do next, and it doesn't matter which path brought it there.
Why later rewards count for less
Suppose the robot can collect a reward right now, or the identical reward ten steps from now. Most of us would take it now, and there are two separate reasons for that, though you may well have only thought of one. One is uncertainty: the world between now and then might change, the episode might end early, and you might never collect the later reward at all. The other is mathematical. In a task that can run forever, with no natural end point, the sum of an infinite sequence of undiscounted rewards can grow without bound, and then there's no meaningful way to say that one policy beats another.
Multiplying a reward that's steps in the future by handles both at once. It says that sooner is better, and as long as it makes the infinite sum converge to a finite number, because the weights form a geometric series. With (a value we'll use for the robot), the +1 for reaching the goal is worth 1 if it's collected right away, 0.9 if one step off, 0.81 if two steps off, and 0.729 if three. Add up all the discounted rewards from some point on and you have the return.
Why does the discount matter beyond keeping sums finite?
Because it's also what carries credit backwards. A cell three steps from the goal can only be worth something to the robot if the faraway +1 counts for something there, and the discount is what says how much. With a state's worth would depend only on the very next reward, and nothing would ever propagate back from the goal. Section 7's project tries exactly that.
Value functions, Q-functions and advantage
With discounting in place, we can ask the question the robot needs answered: how good is it, in total and going forward, to be in this cell? That's what a value function measures. is the expected return starting from state , assuming the agent acts optimally (or follows some fixed policy) from here on. It's a single number that summarizes the entire rest of the episode, so a cell near the goal gets a high one and a cell hemmed in beside the pit gets a lower one.
Sometimes we need to be more specific, about one particular first move. is how good it is to take action in state and then act optimally afterwards. and differ by exactly one decision. already assumes you'll pick the best action, while fixes the first action for you and lets the value function take over afterward. Knowing is enough to act, since the best action in any state is , and that's how Q-learning gets a full control policy out of Q-values alone.
Putting the two together gives the advantage, . It measures how much better this specific action is than what you'd get by following your usual policy in this state. A positive advantage means the action beat the state's baseline expectation, and a negative one means it underperformed. Standing next to the pit, the action that steps into it has a strongly negative advantage, and the action that steps away from it has a positive one.
Advantage matters in practice because policy-gradient methods use it, or an estimate of it, to decide how hard to push the policy toward or away from an action. Pushing based on raw reward is noisy, while pushing based on "better or worse than expected" is a much cleaner signal, and that's the motivation behind the actor-critic methods in section 5. But we haven't said where values come from yet. We defined as a sum over the whole future, and that's not something we can compute by looking at the grid.
03The Bellman equation, policy gradients and PPO's clip
The Bellman equation: credit one step at a time
A fact about value functions gets us out, and almost every value-based algorithm leans on it, including dynamic programming, Q-learning, TD learning and DQN. From state , the future is made of two things: the reward from the first step, and then the future from wherever that step lands you, shrunk by . So we don't need to look at the whole future to compute a value, only one step of it, if we trust our estimate for the next state. That's the Bellman equation.
- V(s) the value of the current state: the expected discounted sum of all future reward, starting here.
- r the immediate reward received for the transition out of state .
- γ the discount factor: how much less a unit of reward is worth one step in the future, versus right now.
- V(s') the value of wherever the agent ends up next, computed by exactly the same function, applied one step later.
- 𝔼[·] an expectation over the randomness in the transition (which next state you land in) and, for , over the policy's choice of action.
In words, today's value equals the reward you get right now plus the discounted value of wherever you end up next. Here's how that plays out on the grid with . A cell next to the goal, with the robot stepping in, has value 1 (the reward is +1 and nothing follows). The cell before it has a reward of 0 and a next state worth 1, so its value is . One more step back it's , and the next is 0.729. Value spreads backwards from the goal, one cell per round of this calculation. That's perhaps easiest to believe if you try a cell yourself. It also means you never need to know the value of the entire rest of an infinite future directly. You need one step of real reward plus your own current estimate of what comes after. Section 7's project prints exactly this wave.
Dynamic programming applies the equation exactly, sweeping over all states, and it needs a full model of the environment to do so. When there's no such model, Q-learning and TD learning apply an approximate, sampled version of it, updating one estimate at a time from lived experience: after each real step, the estimate for is nudged toward , the right-hand side of the equation computed from what just happened. Section 4 compares how that behaves with waiting for the full outcome.
Skipping the values: policy gradients
That equation is the backbone of value-based methods, and it has a limitation: the policy is only ever read off the values, with an argmax over actions. The other family takes the policy itself as the thing to learn. We make it a function with adjustable parameters , such as a neural network that takes the robot's state and outputs a probability for each of the four moves, and we write it . Then we do gradient ascent on the quantity we care about, the expected return . A single run of the policy, the full sequence of states, actions and rewards, is called a trajectory , and its return is .
There's an obstacle, though. We want the gradient of the expected return with respect to , but doesn't appear in the return of any given trajectory. It appears in how likely each trajectory is, and a probability isn't something you can just differentiate through when all you can do is sample. A derivation below gets around that with a short identity called the log-derivative trick, and it ends with something surprising: the unknown environment drops out of the gradient completely. Here it is in full.
Derivation The policy gradient theorem, and why the environment drops out
We want to maximise expected return over trajectories . The obstacle is subtle: does not appear in . It appears in the distribution we are averaging over. Assume an episodic task and the usual regularity conditions that let us exchange a gradient and an integral.
-
Why: the return of a fixed trajectory carries no , so the gradient passes straight through it and lands only on .
-
Why this is the problem: is not a probability distribution. It does not integrate to one and it goes negative. So we cannot estimate this integral by sampling trajectories, which is the only thing we can actually do.
-
Why: the log-derivative trick. Differentiating a log gives . Multiply both sides by and you have this identity. It is ordinary calculus, and it is the hinge the entire method turns on.
-
Why this rescues us: substituting step 3 puts back in front of the integrand. That makes it an expectation under the policy again, and expectations under the policy are exactly what rolling out the policy samples.
-
Why: a trajectory's probability is the start-state probability times the policy's action probabilities times the environment's transition probabilities. Taking a log turns that product into a sum.
-
Why this is the punchline: and belong to the environment. Neither contains , so both gradients are zero and both terms vanish. Only the policy survives.
-
Why this is usable: every quantity here is something you have. Run the policy, record which actions it took, compute the log-probabilities it assigned them, and weight by the return you observed. That estimate is unbiased.
Read the final line as a recipe. Run the policy and record what happened. For every action it took, raise the log-probability of that action in proportion to the return of the whole trajectory. If the robot's run ended in the goal, every move in it gets pushed up, and if it ended in the pit, every move gets pushed down. This estimator is called REINFORCE, and it needs no model of the world and no differentiable reward.
It also has a problem the robot makes obvious. After a lucky run into the goal, every move gets pushed up, including the wasted ones where it bumped into a wall, because the only thing the estimator knows is the final return. Averaged over many runs the useful moves win out, but it takes a lot of runs. We say the gradient estimate has high variance: it's correct on average, but any single estimate is noisy. Standard practice is to subtract a baseline from the return, a number that depends on the state but not on the action taken. Another derivation below shows why this is safe.
Why is subtracting a baseline allowed?
You'd expect it to change the answer, but the term you subtract averages to exactly zero, so it can't move the average of the gradient. It only removes noise. That derivation spells it out, and it also shows why the natural choice of baseline is the state's own value, which turns the weight on each action into the advantage from section 2.
Derivation Why a baseline is free, and why advantage is the right one
The REINFORCE estimator above is unbiased but brutally noisy. The standard fix is to subtract a baseline from the return before weighting. That looks like it should change the answer. It does not, provided depends on the state but never on the action. The sums below assume a discrete action space; for continuous actions every sum becomes an integral and the argument is unchanged.
-
Why: does not depend on , so it is a constant with respect to the expectation and factors straight out.
-
Why: the log-derivative trick again, run backwards this time. The in front cancels the one in the denominator.
-
Why: swap the finite sum and the gradient, which linearity permits. What is left inside is the total probability mass over all actions. That is by definition, for every . The gradient of a constant is zero.
-
Why this is now safe: the term you just subtracted has expectation exactly zero. Subtracting something with zero mean cannot shift the mean. The gradient stays unbiased for any action-independent .
-
Why this choice: setting the baseline to the state's own value recentres the weight around zero. Better-than-usual actions get a positive push, worse-than-usual ones a negative push. Without it, in a task where all rewards are positive, every sampled action gets pushed up and learning has to rely on differences in magnitude alone.
So the policy gradient pushes each action up or down in proportion to its advantage: better than usual from this state means a push toward it, worse than usual means a push away. Raw return can't do that, because in a task where every reward is positive it pushes every sampled action up. We still haven't said how far one push should go.
PPO's clipped surrogate objective
A policy-gradient step increases the probability of actions with high advantage and decreases it for those with low advantage. To score a candidate update we compute a ratio between the new policy's probability of an action and the old policy's probability of that same action, and scale the step by that ratio times the advantage. (The old policy is the one that collected the data, and the ratio reweights that data to stand in for what the new policy would have produced.)
The trouble is that nothing stops a single update from moving the policy enormously if the estimated advantage is large. A policy that has moved too far in one update can collapse: it starts producing actions so different from the ones that generated the training data that learning destabilizes and never recovers. PPO's answer is to clip the ratio.
- r_t(θ) the probability ratio between the new policy and the old policy for the action taken: how much the policy wants to shift toward or away from this action.
- A_t the estimated advantage of that action. Positive means push toward it, negative means push away.
- clip(·, 1-ε, 1+ε) caps the ratio so it can't move more than (typically 0.1–0.2) away from 1 in either direction. The new policy is not allowed to become more than roughly 20% more or less likely to take this action in a single update.
- min(·, ·) takes the more pessimistic of the unclipped and clipped objective, which means clipping only ever removes the incentive to keep pushing once you've already moved far enough. It never creates an incentive to push further.
Note that this is the probability ratio, a different thing from the reward . In one sentence, PPO takes a policy-improving step and clips it, so the new policy can't move too far from the old policy in a single update. It's a cheap, first-order stand-in for what TRPO, PPO's more complicated predecessor, enforced with an explicit and expensive constraint on how different the new and old policies are allowed to be. That constraint is measured with the KL divergence, a number that says how far apart two probability distributions are. One more derivation traces how the constraint turned into the clip, and it's frank about what was lost on the way.
Derivation How TRPO's constraint became PPO's clip
This one is more argument than algebra, and it is worth saying that plainly. The clip is not derived from the constraint. It is a cheaper thing that behaves similarly, and the steps below trace why anyone would settle for that.
-
Why we need the ratio at all: the data was collected under , but we want to score . Importance sampling reweights each sample by how much more or less likely the new policy makes it. This is what buys you several gradient steps from one batch of rollouts instead of one.
-
Why the naive version breaks: nothing in that objective bounds the ratio. Push arbitrarily high and the objective keeps improving. But the importance-sampling estimate is only trustworthy while stays near . Optimise it hard and you leave the region where it means anything.
-
TRPO's answer: make the trust region explicit. Bound the average KL between old and new policy, so the optimiser cannot leave the region where the surrogate is valid. The cost is real: this is a constrained problem needing conjugate gradient and a line search, with curvature information from Fisher matrix-vector products.
-
PPO's answer: drop the constraint and flatten the objective instead. Once leaves , the clipped branch stops changing with , so its gradient is zero. No constraint solver, just a clamp on a scalar.
-
Why the is load-bearing: it selects the more pessimistic of the two branches. With that caps the reward for raising . With the unclipped term actually grows as falls, so the is what stops the objective from paying you to drive the probability toward zero. Clipping only ever removes incentive. It never manufactures one.
04Why bootstrapping wins, and why PPO clips
Two questions come up constantly once you've seen these pieces, and both have clean answers. One is about the Bellman target. We said value-based methods nudge an estimate toward one real reward plus their own estimate of the next state. But that estimate is still being learned and is wrong right now, so why is building on it better than waiting to see how the episode ends?
Why does using a wrong estimate beat waiting for the real return?
The two approaches use different learning targets. Monte Carlo (the name for estimating something by sampling) waits for an entire episode to finish and uses the actual observed total reward. For the robot, that means running to the goal or the pit and looking back at what each cell led to. That target is unbiased, meaning it isn't systematically off in one direction, since it's the real quantity you're trying to estimate and not an approximation of it. It's also extremely noisy, probably more than you'd expect, because it depends on every random action and every random environment transition for the rest of the episode.
Temporal-difference (TD) learning doesn't wait. It bootstraps, using the immediate reward plus its own current estimate of the value of the next state, exactly as the Bellman equation describes. That estimate is biased, because it depends on a value function that's still being learned and is currently wrong. But it has far lower variance, because it depends on one step of randomness instead of an entire trajectory's worth.
Maybe the surprise is that the biased target comes out ahead. In practice, lower variance usually wins, and TD methods tend to learn faster and more stably from the same amount of experience. TD also has a structural advantage Monte Carlo can't offer: it works in continuing tasks that never terminate, since it never needs to wait for an episode to end at all.
The other question is about PPO. We described the clip as a safeguard, but how bad is a single oversized update? Without clipping, one large policy-gradient update, triggered by, say, one unusually high-advantage rollout, can shove the policy into a region of action space it has never explored well. Next, a batch of rollouts is collected under this new, poorly understood policy, the advantage estimates for that batch are unreliable, and the next update compounds the damage. Meanwhile the data for the next gradient step comes from the policy that just got wrecked.
This failure happens in practice. An RL run can look like it's training fine and then collapse in a handful of updates with no way back. Clipping prevents the update from moving the probability ratio more than away from 1, which caps how far any single step can push the policy. That gives most of the stability TRPO achieved with its explicit trust-region constraint, computed with a min and a clip on scalar ratios and no constrained optimization problem at all. PPO displaced almost everything before it because it offers close to TRPO's stability at a small fraction of the implementation complexity.
We now have value-based methods built on the Bellman equation and policy-gradient methods built on advantage. How do they compare, and where does each one break?
05Families of methods, and where each one fails
What we've built falls into three families of methods. Value-based methods such as DQN learn and act by argmax. Policy-gradient methods such as REINFORCE and PPO learn the policy directly. Actor-critic methods learn both. Four comparisons are in the table, and two of its terms need a word of explanation. A method is off-policy if it can learn from data collected by an older or different policy, and on-policy if it needs data from the policy it's currently training. Sample efficiency is how much learning you get per unit of experience collected.
| Value-based (DQN) | Policy gradient (REINFORCE / PPO) | Actor-critic | |
|---|---|---|---|
| What it learns directly | Q(s,a) for every action | The policy π(a|s) itself | Both a policy (actor) and a value function (critic) |
| Sample efficiency | Higher — off-policy, reuses old data via a replay buffer | Lower — classic REINFORCE is on-policy and high-variance | Better than plain REINFORCE — the critic reduces variance |
| Training stability | Can be unstable without replay buffer + target network | High variance gradients; PPO's clipping tames this substantially | Generally the most practical stability/efficiency balance |
| Action space fit | Naturally discrete — argmax over a finite action set | Works for both, but especially natural for continuous actions | Both — this is why it's the dominant modern recipe |
Maybe the neatest way to see actor-critic is as the direct fusion of the other two ideas, with two components and two jobs. One part, the actor, is the policy, improved by a policy-gradient update that uses the advantage the way REINFORCE uses raw return. The other part, the critic, is a learned value function, used in place of the raw, noisy Monte Carlo return to judge how good each action was, supplying a low-variance advantage estimate the way TD learning does. PPO is, precisely, an actor-critic method with a clipped policy-gradient update for the actor.
One more comment on the value-based column, because "DQN is just Q-learning with a neural network instead of a table" understates the change. Q-learning's convergence guarantees assume exact, tabular updates. Swap in a neural network and two things break: the updates become correlated, since consecutive experiences are highly similar, and the target you're regressing toward moves every time you update the network, so the network is chasing a target that shifts as it moves. DQN needed two specific fixes for these, a replay buffer and a target network, on top of a bigger function approximator. Section 7 explains each.
Where training breaks
Even with the right family, three failures show up again and again, and they're probably the ones you'll hit first. First comes the credit-assignment problem at its worst: sparse rewards. If the agent almost never receives a nonzero reward, as when it has to reach the end of a long maze or win a long game, then for a long stretch of training every action looks equally uninformative, and gradient-based learning has almost nothing to learn from. That's why reward shaping, curiosity-driven exploration bonuses and hierarchical RL exist as whole subfields.
Next is reward hacking. Here the agent optimizes what you told it to reward, which may differ from what you wanted. Think of a boat-racing agent that spins in circles collecting the same power-up over and over instead of finishing the race, because that scores higher under the literal reward function. Any time a reward function is a proxy for the real goal, and it almost always is, the optimizer will find the gap between the proxy and the goal if the gap is exploitable.
Last is offline RL's distribution-shift trap. Offline RL means learning a policy from a fixed, previously collected dataset, with no further interaction with the real environment at training time. Here the danger is that the learned policy can drift toward actions the data-collecting policy rarely or never took. For those actions, the training data gives no reliable signal about what would happen. Its value estimate there can be badly wrong and badly overoptimistic, with no way to catch the error since there's no environment left to test against.
That's the whole toolkit, and it's compact enough to summarize before we build it.
06Summary
- RL learns from late, unlabelled feedback. An agent observes a state, picks an action, and gets a reward and a new state, and the hard part is credit assignment: working out which earlier decisions deserve the reward that arrives later.
- Exploration is part of the problem. A purely greedy agent can lock onto a poor choice, so some random trying is needed. On the three slot machines, epsilon-greedy with 10% exploration earned 0.770, against 0.201 for never exploring and 0.507 for always exploring.
- An MDP gives the loop its parts: states, actions, a transition function, a reward function and a discount factor. The Markov assumption says the current state summarizes everything relevant.
- The discount makes later reward count for less. It reflects uncertainty, keeps infinite sums finite and carries credit backwards from the goal.
- V, Q and advantage measure different things. V(s) scores a state, Q(s,a) scores a state with a first action fixed, and the advantage Q(s,a) minus V(s) says how much better an action is than usual.
- The Bellman equation turns an infinite future into one step. V(s) is the immediate reward plus the discounted value of the next state, so value spreads backwards from the goal.
- Policy gradients need no model of the environment. Using the log-derivative trick makes the gradient an expectation we can sample, and the environment's dynamics drop out of it.
- A baseline cuts variance for free, and advantage is the right one. Subtracting any action-independent baseline leaves the gradient unbiased, and choosing V(s) turns the weight on each action into its advantage.
- PPO clips the probability ratio so that one update can't move the policy far from the one that collected the data. It approximates TRPO's trust region at a fraction of the complexity, without the same guarantee.
- TD bootstrapping usually beats Monte Carlo. Its target is biased but much lower in variance, and it works in tasks that never end.
- Training fails in known ways: sparse rewards, reward hacking, and in offline RL a drift toward actions the data never covered. DQN's replay buffer and target network, explained in section 7, address correlated updates and a moving target.
07Build this
Why DQN needs a replay buffer and a target network
Interviewers often ask why each fix exists, and each one solves a distinct instability.
Training a neural network with plain gradient descent assumes roughly independent, identically distributed training examples. But an agent playing through an environment produces a highly correlated stream. Consecutive frames of the same game look nearly identical. Training on them in that order badly biases the network toward whatever situation the agent happens to be in right now, then violently biases it toward the next situation.
A replay buffer breaks this correlation: store past transitions (state, action, reward, next state) in a large buffer, and train on randomly sampled batches from it and not on the live stream. It also improves sample efficiency, since each transition can be reused in many updates instead of being seen once and discarded.
Separately, Q-learning's update target is itself built from the network's own current Q-value estimate at the next state. You're regressing the network toward a target that's computed by the same network you're currently updating. Every gradient step changes the network, which changes the target, which changes what "correct" means for the very next step. The target keeps moving, so training can oscillate or diverge and may never settle.
DQN fixes this by keeping a separate target network, a lagging copy of the main network's weights that's only updated (or slowly blended in) every so many steps. The target used for each update comes from this frozen copy, so the regression target stays stable for a while, giving the main network something fixed to converge toward before the target itself shifts.
Both of those fixes are repairs to a method that already works in a table, with no network anywhere in it. Print that table after every episode and the Bellman equation stops being an equation.
Run tabular Q-learning on a 5×5 gridworld small enough to print in full. It uses no network, no Gym and no replay buffer, so the entire value function fits on one screen. You can watch reward travel backwards out of the goal cell and do not have to infer it from a reward curve.
- Write the world in about thirty lines. A 5×5 grid, start in one corner, goal in the opposite one, four actions, walls that clamp. Reward is
+1for entering the goal and0everywhere else. Put one pit next to the shortest route, worth-1and ending the episode. - Make
Qa zeros array of shape(25, 4). Write the update yourself from the Bellman equation in section 03: . That one line is all the learning in the project. - Train with ε-greedy action selection. After every episode, print for all 25 cells as a grid of two-decimal numbers. Then read the printouts in order.
- Read the greedy policy off the finished table with an argmax per cell, and print it as arrows.
- Break it by setting , retraining from zeros and printing the same grids.
- Restore and make the world stochastic instead. Give every action some chance of slipping into a random direction. First run the deterministic table's arrows in this world, then retrain in it and compare the two arrow maps.
Where this runs in production
The most common place PPO shows up in a 2026 interview is RLHF. A reward model, trained on human preference comparisons, stands in for the reward function. The language model itself is the policy. Generating a response token-by-token is the sequence of actions.
PPO takes the update step described above (improve the policy, but clip so it doesn't move too far from the previous policy in one step) with a KL penalty added on top, to keep the fine-tuned model from drifting too far from the original supervised-fine-tuned model it started from.
Page 10 covers RLHF's full pipeline in depth: reward modeling, the KL penalty, RLHF vs. DPO. What matters here is that everything RLHF does with PPO applies the MDP, advantage, and clipped-objective machinery on this page directly, with no new machinery at the LLM layer.
08Interview questions
BeginnerWhat's the difference between V(s) and Q(s,a)?
V(s) is the expected discounted return from state s, assuming the agent acts optimally (or under a fixed policy) from here on — a property of the state alone. Q(s,a) is the expected discounted return from taking a specific action a in state s, then acting optimally afterward — a property of the state-action pair. The difference is exactly one decision: Q fixes the first action for you, V assumes the best one is already chosen. Advantage, Q(s,a) − V(s), measures how much better this specific action is than the state's average.
BeginnerWhy do we discount future rewards?
Two reasons. A reward now is worth more than an identical reward later because of uncertainty — the environment could change, the episode could end, you might never actually collect it. And mathematically, discounting keeps the sum of an infinite sequence of future rewards finite (a convergent geometric series) rather than diverging, which is necessary to even compare policies in tasks with no natural end point.
IntermediateWhy does DQN need a replay buffer and a target network?
The replay buffer breaks the correlation between consecutive experiences in a live trajectory by sampling random past transitions to train on, which both stabilizes gradient descent (which assumes roughly i.i.d. data) and reuses data for better sample efficiency. The target network fixes a different problem: Q-learning's update target is built from the network's own current estimate at the next state, so without a frozen, lagging copy of the network to compute that target from, the regression target shifts every single update step, which can cause oscillation or divergence instead of convergence.
IntermediateMonte Carlo vs. temporal-difference learning — what's the actual tradeoff?
Monte Carlo waits for a full episode to end and uses the actual observed return as the learning target — unbiased, but high variance, since it depends on every random action and transition for the rest of the episode. TD bootstraps: it uses one real reward plus the current value estimate of the next state (the Bellman equation) as the target — biased, because that value estimate is still being learned and is currently wrong, but much lower variance, since it only depends on one step of randomness. In practice TD usually wins because lower variance means faster, more stable learning from the same data, and TD also works in continuing tasks that never terminate, which Monte Carlo structurally cannot handle.
IntermediateWhat does the advantage function buy you that raw reward doesn't?
Raw reward (or raw return) tells you an action's absolute outcome, which is noisy and depends heavily on which state you happened to be in. Advantage, Q(s,a) − V(s), tells you how much better or worse this action was than what you'd expect on average from this state — a relative, baseline-subtracted signal. Policy gradients that use advantage instead of raw return have substantially lower variance, because subtracting a well-chosen baseline (the state's own value) removes a large chunk of noise that doesn't actually depend on which action was chosen.
DeepExplain PPO's clipped objective and why it matters.
PPO computes the probability ratio between the new and old policy for the action taken, multiplies it by the estimated advantage, and takes the minimum of that unclipped term and a version where the ratio is clipped to [1−ε, 1+ε]. The min means clipping only ever removes the incentive to keep pushing the policy further once it's already moved enough — it never creates a new incentive to push harder. This matters because unconstrained policy-gradient updates can move the policy so far in one step that it starts producing actions unlike anything in its training data, destabilizing all subsequent updates (which use rollouts from that now-broken policy) with no way to recover. PPO gets most of TRPO's stability guarantee — bounding how far the policy moves per update — using a simple clip-and-min on scalar ratios instead of an explicit, expensive trust-region constraint, which is exactly why it displaced TRPO as the default and is the algorithm underneath RLHF.
DeepWhy might you reach for SAC or TD3 instead of PPO for a continuous-control robotics task?
SAC adds an entropy bonus to the objective, explicitly rewarding the policy for staying stochastic/exploratory rather than collapsing too early to a narrow, possibly-suboptimal behavior — valuable in continuous action spaces where naive exploration is easy to get stuck in. TD3 (and SAC) both use twin critics — train two separate Q-function estimators and take the minimum of the two when computing targets — specifically to counter the systematic overestimation bias that a single Q-function tends to develop, since taking a max/argmax over a noisy estimate tends to pick out the noise, not the true best action. Both are also typically more sample-efficient than PPO in continuous control because they're off-policy and can reuse a replay buffer, whereas PPO is on-policy and needs comparatively fresh rollouts.
DeepWhat's the core danger in offline RL, and why doesn't it show up in online RL the same way?
Offline RL learns entirely from a fixed, previously-collected dataset with no further environment interaction. If the learned policy drifts toward actions rarely or never taken by the policy that collected the data, the value function has no reliable evidence for what happens there and can become badly overoptimistic about exactly the actions the policy is being pushed toward — a compounding error with nothing to correct it, since there's no environment left to test against. Online RL doesn't have this problem in the same way because the agent can always go collect more real data about whatever action it's currently curious about, which grounds its estimates; offline RL loses that safety net entirely, which is why offline algorithms explicitly constrain the learned policy to stay close to the data-collecting policy's behavior.
09Go deeper
●Now write it yourself
Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.
Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.