Bellman equations and dynamic programming
At the end of §15.1 we estimated the value of a random walker in the gridworld by running it 2,000 times and averaging the returns. That worked, but it was wasteful in a way that should bother you. The value of the start cell and the value of the cell just above it are not unrelated numbers. Once you have taken one step from the start, the rest of your return is a return from the cell you landed in. So the values of neighboring states must be consistent with each other, and that consistency condition is strong enough to pin them down exactly, without a single simulation.
The condition is the Bellman equation (Bellman 1957), and it is the most important equation in reinforcement learning. This section derives it in its two forms, for evaluating a policy and for finding the best one, proves that the obvious way of solving each form converges, and uses them to solve the gridworld exactly. Then we drop the assumption that we know the environment, and the same equations give us temporal-difference learning and Q-learning, which learn from experience alone.
The Bellman expectation equation
Fix a policy . As in §15.1, is the expected return from state , where is the discounted return, is the expected reward for action in state , and is the probability of moving to . We want an equation that satisfies.
Start from the recursion for returns, , and take the expectation given ,
The first term averages the immediate reward over the action, . For the second term we condition on what happens next, the action and the next state , and use the law of total expectation,
This is the step where the Markov property earns its keep. Everything that happens from time on (the actions, drawn from , and the transitions, drawn from ) depends on the past only through . So conditioning on and as well changes nothing, and the inner expectation is just the value of ,
Putting the pieces together gives the Bellman expectation equation,
In plain words, the value of a state is the average, over what the policy does and where the world sends you, of the reward you get now plus the discounted value of where you land.
The same argument for the action-value function, now with the first action fixed, gives
which is the pair of relations from §15.1, and , substituted into each other.
The matrix form, and solving it exactly
With finitely many states, the Bellman expectation equation is a system of linear equations in unknowns. Collect the policy's average reward and average transitions,
where is a row-stochastic matrix (nonnegative entries, each row summing to 1), the transition matrix of the Markov chain you get by running . Writing for the vector of values , the Bellman equation reads
Is the inverse guaranteed to exist? Yes, when . For any vector , each entry of is an average of entries of , so and every eigenvalue of has magnitude at most (its spectral radius, in the language of §0.10, is at most ). Then has no zero eigenvalue, and its inverse is the convergent Neumann series,
In plain words, the -th term is the expected reward steps from now ( is the -step transition matrix), discounted by , which is the definition of the value read off term by term. This is the "exact value" we used in §15.1. It costs one linear solve, , which is nothing for 11 states and hopeless for a game of Go.
Those are the values of the random walker in every cell, all negative, because a random walk in this world blunders into the pit far more often than it finds the goal. The two terminal cells show 0 because the episode is over there (the is paid on the step that enters them).
Evaluate a policy exactly
Implement evaluate_policy(P, R, pi, gamma) for a finite MDP with P of shape (S, A, S), R of shape (S, A), a stochastic policy pi of shape (S, A) whose rows sum to 1, and . Return of shape (S,) by solving the Bellman expectation equation as a linear system. Do not iterate.
Iterative policy evaluation and contraction
The linear solve does not scale, and it does not generalize to the case where we cannot write down. The alternative is to treat the right-hand side of the Bellman equation as an operator on value functions and apply it repeatedly. Define the Bellman expectation operator , which takes any value vector (a guess, not necessarily anyone's true value) and returns
The Bellman equation says is a fixed point, . Iterative policy evaluation starts anywhere, say , and repeats . Why should that converge, and to the right answer? Because is a contraction.
Claim. For any two value vectors and ,
where is the largest absolute entry.
Proof. The rewards cancel, so . Entry of the right side is times a weighted average of the entries of , with weights that sum to 1. An average is never larger in magnitude than the largest thing being averaged, so every entry is at most in magnitude.
In plain words, one application of the operator brings any two guesses at least a factor closer together, measured by their worst disagreement.
That one inequality gives everything. Apply it with and (using ),
So the error shrinks geometrically, by at least a factor per sweep, from any starting point. The fixed point is also unique. If and were both fixed points, the claim would give , which forces . This is the Banach fixed-point theorem in action. A contraction on a complete space has exactly one fixed point, and iterating it from anywhere converges there. Every convergence result in this section is that theorem applied to a different operator.
How many sweeps do you need? To shrink an initial error by a factor you need , so . With , a millionfold reduction takes about 131 sweeps. With it takes about 1,375. Long horizons are slow to evaluate, which is the effective horizon of §15.1 showing up as a convergence rate.
The error always sits at or below the line, as the proof promises, and in this world it falls faster, because the walker is absorbed by a terminal cell well before the discount alone would wash the future out.
The Bellman optimality equation
Evaluating policies is half the job. We want the best one. Recall from §15.1 that and . An optimal agent in state takes the action that maximizes immediate reward plus the discounted optimal value of where it lands, so the optimal values should satisfy the Bellman optimality equations,
In plain words, the best you can do from here is the best first move followed by the best you can do from wherever it takes you. The averaging over the policy's actions in the expectation equation has become a maximum.
That paragraph is a heuristic (Bellman's principle of optimality), and it hides a real question, since is defined by a maximum over all policies separately in each state. Here is a complete proof that the equation has exactly one solution, that the solution is , and that acting greedily with respect to it is optimal in every state at once. It is short, and it uses only the contraction idea from above.
∂ Proof that the Bellman optimality equation characterizes the optimal policy
Define the Bellman optimality operator , and for brevity write , so that . We restrict attention to stationary policies (the same rule at every time step). Puterman (1994, Chapter 6) shows that history-dependent policies can do no better, so nothing is lost.
Step 1, a fact about maxima. For any two functions of the action, . To see it, let maximize . Then , and swapping the roles of and bounds the difference from the other side.
Step 2, is a -contraction. By Step 1, for every state,
So, exactly as for , there is a unique fixed point, which we call , and iterating from anywhere converges to it geometrically.
Step 3, monotonicity. Both operators preserve order. If entrywise, then and , because and have nonnegative entries. Also for every policy and every , because an average over actions is at most the maximum over actions.
Step 4, no policy beats . Take any policy . Using its own Bellman equation and Step 3,
Apply the monotone operator to both sides again and again, . The right side converges to the fixed point by Step 2, so in every state.
Step 5, the greedy policy achieves . Let be the deterministic policy that picks . By construction , so is a fixed point of . That operator has only one fixed point, , so .
Conclusion. Steps 4 and 5 together say , with the maximum attained in every state by the single deterministic policy . So is the unique solution of the Bellman optimality equation, and any policy that is greedy with respect to it is optimal. Since , the greedy policy is , as claimed in §15.1.
Value iteration
The proof is also an algorithm. Value iteration starts from and applies the optimality operator, , until the values stop changing, then reads off the greedy policy. Each sweep costs for a dense .
When should it stop? We cannot measure the distance to the unknown , but we can bound it by the change in the last sweep. By the triangle inequality and the contraction,
and moving the last term to the left gives
In plain words, if a sweep changes no value by more than , you are within of the optimum, a guarantee you can check without knowing the answer. The greedy policy usually becomes optimal long before the values settle, so in practice value iteration finds the right policy early and then spends many sweeps polishing numbers.
With these are exactly the utilities printed in Russell and Norvig's textbook for this world (0.812, 0.868, 0.918 along the top row, and so on), a good check that our transition model matches theirs. Value iteration converges here even though breaks the contraction proof, because every sensible policy ends up in a terminal cell. The optimal policy is worth studying. From the start cell it goes up and around the top, the long way. In the cell left of the pit it moves up, never right, since right walks straight into the pit, and it accepts the 10% chance that an upward move slips sideways into the pit because every safer route costs more steps. And in the bottom-right corner, at , it goes left, the long way round, rather than risking the walk up past the pit. At the agent is more impatient. The cell just left of that corner now goes up, past the pit, instead of taking the long way, and the cell to its left heads right to join it. The discount changed the optimal behavior, just as in the two-state example of §15.1.
Value iteration with a provable stopping rule
Implement value_iteration(P, R, gamma, tol) for an MDP with P of shape (S, A, S) and R of shape (S, A). Start from , apply with no Python loop over states or actions, and stop at the first where tol. Return (V, pi, n_sweeps) with V of shape (S,), pi the greedy actions with respect to the Q table computed in the last sweep (an int array of shape (S,)), and n_sweeps , the number of times you applied the operator.
Policy iteration
Value iteration improves values a little at a time and lets the policy emerge. Policy iteration (Howard 1960) alternates two complete steps on the policy itself.
- Evaluate. Compute exactly, with the linear solve of Exercise 15.2a.
- Improve. Replace by the greedy policy , where .
Stop when the policy no longer changes. Why does the improvement step never make things worse? This is the policy improvement theorem, and its proof is three lines with the tools above. By the definition of , . Applying the monotone operator repeatedly gives . So in every state. If the greedy step changes nothing, then , so solves the Bellman optimality equation and is optimal. If is not optimal, then exceeds in some state, and so does . So each round strictly improves the policy until it is optimal, no policy can be visited twice, and since there are only finitely many deterministic policies, policy iteration terminates in a finite number of rounds. In practice that number is tiny.
Policy iteration finishes in a handful of rounds, each one an exact linear solve, where value iteration needed 32 cheaper sweeps (and would need far more for near 1). The initial "always up" policy is terrible (from the start cell it climbs to the top-left corner and keeps bumping into the top edge, paying the step cost and reaching the goal only through lucky sideways slips), and the very first improvement step changes the action in six of the nine states.
| each step costs | steps needed | when to use | |
|---|---|---|---|
| value iteration | one backup, | about | large state spaces, cheap sweeps |
| policy iteration | a linear solve, , plus a backup | a few (finite, often under 10) | small state spaces, exact answers |
| modified policy iteration | evaluation sweeps plus a backup | in between | the practical compromise |
All three are instances of what Sutton and Barto call generalized policy iteration, two processes running against each other, one making the values consistent with the policy and one making the policy greedy with respect to the values. Almost every RL algorithm, including actor-critic methods (§15.4) and PPO (§15.6), has this shape, with a critic that evaluates and an actor that improves.
Policy iteration
Implement policy_iteration(P, R, gamma) returning (V, pi, n_rounds). Start from the policy that takes action 0 in every state. Each round, evaluate the current deterministic policy exactly (a linear solve), then improve it greedily with argmax over actions. Stop when the improved policy equals the current one, and return that policy, its values, and the number of evaluation rounds performed (including the last one, which found no change).
Learning without a model, temporal differences
Everything so far needed and in hand. That is called planning or dynamic programming. In most problems the agent does not have them. It can only act and observe what happens. Can it still use the Bellman equation?
It can, by replacing the expectation over next states with a single sample. Suppose the agent, following , is in state , receives reward , and lands in . The Bellman equation says equals the expected value of . So , computed with the current estimate , is a one-sample guess of what should be, and we can nudge the estimate toward it with the incremental-mean update from §15.1,
with a step size (we follow Sutton and Barto in writing for tabular step sizes). This is TD(0), temporal-difference learning (Sutton 1988), and is the TD error, the difference between the bootstrapped target and the current estimate. If is terminal, its value is zero by definition, and the target is just . In plain words, after every single step, move your estimate of where you were toward what you got plus your estimate of where you are now.
Compare it with the Monte Carlo update, , which waits for the episode to end and uses the actual return.
| Monte Carlo target | TD target | |
|---|---|---|
| bias | unbiased, | biased while is wrong (it trusts its own guess) |
| variance | high, a sum of many random rewards | low, one random reward and one random transition |
| needs | the end of the episode | only the next step, works online and in continuing tasks |
| uses the Markov structure | no | yes, it bootstraps from the next state's estimate |
This bias-variance trade-off between the full return and a one-step bootstrap is one of the deepest themes in RL. §15.5 builds a continuous dial between the two, generalized advantage estimation, and PPO uses it on every step. With step sizes that shrink appropriately (the Robbins and Monro conditions and , met for instance by per state), tabular TD(0) converges to with probability 1 (Dayan 1992).
The result depends on the step size, and both halves of the bias-variance table show up. With a small step (), Monte Carlo is ahead after 100 episodes, because TD's knowledge of the terminal rewards has to creep backward one state per update while its early, wrong estimates bias every target. By 400 episodes TD has overtaken it. With a larger step (), TD is ahead throughout, by a factor of two to three, because each Monte Carlo update chases a single noisy return and the large step lets that noise kick the estimate around. TD's targets are quieter, so it can afford the larger step. That is the usual pattern, though not a law. When the value estimates are poor and stay poor, bootstrapping from them hurts.
Q-learning
TD(0) evaluates a fixed policy. To control, we need action values, because, as §15.1 noted, choosing an action from needs a model to look ahead, while choosing from needs only an argmax. Two TD methods learn .
SARSA applies the Bellman expectation equation for to the sample , using the next action the agent actually takes,
Q-learning (Watkins 1989) applies the Bellman optimality equation instead,
with the target reduced to when is terminal. In plain words, move the estimate toward the reward plus the value of the best next action, whatever action the agent will actually take next.
That one change, a max instead of the next sampled action, makes Q-learning off-policy. It learns , the values of the optimal policy, while the agent behaves according to some other policy (for example -greedy, which keeps exploring), because the target never refers to the behavior policy's choices. Watkins and Dayan (1992) proved that tabular Q-learning converges to with probability 1, provided every state-action pair keeps being tried and the step sizes satisfy the Robbins and Monro conditions. SARSA is on-policy. It learns the value of the policy it follows, exploration included, which makes it more cautious near cliffs, since it accounts for its own random steps.
The Q-learning update
Implement q_learning_update(Q, s, a, r, s_next, terminated, alpha, gamma) for a tabular Q of shape (S, A). Return (Q_new, td_error), where Q_new is a new array (leave the input unchanged) with only entry (s, a) updated by the Q-learning rule, and td_error is computed before the update. If terminated is true, s_next is a terminal state and must not be bootstrapped from.
Here is Q-learning solving the gridworld from experience alone. The agent never sees . It explores with -greedy actions and starts each episode in a random non-terminal cell, so that every state-action pair keeps being visited, as the convergence theorem requires. We compare what it learned with the that value iteration computed from the model.
After about 16,000 steps the greedy policy is optimal in every cell, though some action values are still off by more than 0.1. Finding the right ranking of actions is much easier than finding their exact values, which is also why value iteration's policy settled long before its values did.
From tables to networks
Real problems have far too many states for a table, so becomes a network with parameters , trained to regress onto the Q-learning target. Doing this naively is unstable, and DQN (Mnih et al. 2015), which learned to play 49 Atari games from pixels, needed two stabilizers. An experience replay buffer stores past transitions and trains on random minibatches of them, which breaks the correlation between consecutive samples. A target network, a periodically refreshed copy , computes the targets , so the regression target does not move with every gradient step. Two further problems are worth knowing by name. The max in the target is biased upward when the estimates are noisy (the maximum of noisy estimates overestimates the maximum of the true values), which double Q-learning fixes by choosing the action with one estimate and evaluating it with another (van Hasselt 2010). And combining function approximation, bootstrapping, and off-policy data, which Sutton and Barto call the deadly triad, can make the values diverge even on tiny problems.
Offline RL, learning from a fixed dataset
Off-policy learning suggests a tempting extreme. If Q-learning can learn from data that some other policy collected, why collect any new data at all? Learning entirely from a fixed log of transitions, with no further interaction, is offline (or batch) RL, and it is what you would want wherever exploring is dangerous or expensive, in medicine, in driving, or with a recommender serving real users.
It is much harder than it looks, and the max in the Q-learning target is the reason. At the next state the max picks whichever action the network rates highest, including actions the dataset never contains, whose values are pure extrapolation. Online, an overrated action gets tried, disappoints, and is corrected. Offline it is never tried, so the error stays, and bootstrapping copies it backward to every state that leads there. The usual result is a policy that heads confidently for exactly the actions the data knows least about, and a deep Q-network trained this way can do worse than just imitating the logged actions (behavior cloning).
The fixes all keep the learned policy close to the data. BCQ (Fujimoto, Meger, and Precup 2019) only considers actions that a model of the logging policy makes likely. Conservative Q-learning (Kumar et al. 2020) adds a penalty that pushes down the values of actions the learned policy favors and pushes up the values of actions in the data, so unseen actions are underrated instead of overrated. Implicit Q-learning (Kostrikov, Nair, and Levine 2022) never evaluates an unseen action at all, replacing the max by an upper expectile of the values of the actions that do appear. Levine et al. (2020) survey the field. The same tension returns with language models. Training on a fixed set of preference pairs, as DPO does, is learning from someone else's samples, and the comparison of online and offline preference learning shows what that costs, while the KL penalty toward a reference model in §15.7 is the same stay-near-the-data idea in another form.
Value-based methods dominate when actions are few and data is cheap to reuse. Language models are the opposite case. They start from a strong pretrained policy (the next-token distribution) that we want to adjust gently, and the policy-gradient methods of §15.3 to §15.6 do exactly that. The Bellman equations do not go away, though. The critic in PPO is a learned trained with TD-style targets, and its TD errors are the raw material of the advantage estimates in §15.5.
In PyTorch
Here is the loss DQN optimizes, written the way production code writes it, with a target network, a batch of transitions, and a terminal mask. We fill a replay buffer with random gridworld transitions and take a few gradient steps on a small network.
Read more
- Sutton & Barto (2018). Reinforcement Learning: An Introduction, 2nd edition. Chapters 3, 4, and 6 cover the Bellman equations, dynamic programming, and TD learning, with the gridworld examples that made them famous.
- Bellman (1957). Dynamic Programming. The book that introduced the principle of optimality.
- Watkins & Dayan (1992). Q-learning. The convergence proof for tabular Q-learning.
- Sutton (1988). Learning to Predict by the Methods of Temporal Differences. TD learning and TD(), the idea we will turn into GAE in §15.5.
- Mnih et al. (2015). Human-level control through deep reinforcement learning. DQN, with experience replay and a target network.
- Levine, Kumar, Tucker & Fu (2020). Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems. Why learning from a fixed dataset is hard, and the conservative and constrained methods that make it work.
- Szepesvári (2010). Algorithms for Reinforcement Learning. A short, rigorous monograph, with the contraction arguments of this section in full generality.