Dynamic Programming
Dynamic programming computes optimal policies when a perfect model of the MDP is given, by turning the Bellman equations into assignment statements. We build up iterative policy evaluation (the expected update), the policy improvement theorem, and the two classic algorithms that alternate them — policy iteration and value iteration — worked on the gridworld, a two-state MDP, Jack's car rental, and the gambler's problem.
╌╌╌╌
Dynamic programming (DP) is the collection of algorithms that compute optimal policies given a perfect model of the environment as a Markov decision process.1 That assumption — that the dynamics are fully known — names what a learning agent lacks, so classical DP is of limited direct use in reinforcement learning. Its importance is theoretical. DP defines, exactly and by construction, the optimal value functions and policies that every model-free method in the rest of the course only approximates. Read this way, Monte Carlo and temporal-difference learning are attempts to achieve the same effect as DP with less computation and without a model. To understand what they approximate, first see how DP computes it directly.
Throughout, assume a finite MDP: the state, action, and reward sets are finite, and the dynamics are a known set of probabilities . The single idea behind DP, and behind reinforcement learning generally, is to use value functions to organize the search for good policies.
The plan, in outline: a value function scores how good each state is. If we knew the best possible score for every state, acting optimally would be easy: at each state, take the action that leads to the best-scored successors. So the whole problem reduces to computing those best scores. We already have optimal policies the moment we have the optimal value functions or , because they satisfy the Bellman optimality equations
DP algorithms are obtained by turning Bellman equations like these into assignments — into update rules for improving approximations of the desired value functions. That one move, equation becomes assignment, is the whole method.
Policy evaluation (prediction)
Start with the easier of the two tasks: given a fixed policy , compute its state-value function . In the DP literature this is policy evaluation; it is also the prediction problem. Recall the Bellman equation for ,
for all . If the dynamics are completely known, this is a system of simultaneous linear equations in unknowns — the values . In principle its solution is a straightforward, if tedious, linear-algebra computation. For our purposes an iterative method is more suitable, and it is the same move applied to a whole sequence of approximations.
The intuition: start with a rough guess for every state's value, then repeatedly sharpen it. Each pass replaces every state's guess with a better one computed from its neighbors' current guesses. Do this enough times and the guesses stop moving — they have settled onto . Here is that loop written out.
Consider a sequence of approximate value functions , each a map from (the states plus, in an episodic task, a terminal state) to the reals. The initial is chosen arbitrarily, except that a terminal state must be given value ; each successive approximation is obtained by using the Bellman equation for as an update rule:
Clearly is a fixed point of this rule, because the Bellman equation for asserts equality in exactly this case. And the sequence can be shown to converge to as under the same conditions that guarantee the existence of (either or guaranteed eventual termination under ). This algorithm is iterative policy evaluation.2
The expected update is what separates DP from the sampling methods to come. A Monte Carlo or TD update pushes value toward one sampled successor; the DP update sweeps every successor, weighted by its probability. That is only possible because the model is in hand.
To turn the update into a program you might keep two arrays, one for the old and one for the new , computing each new value from the old ones. It is simpler, and usually faster, to use one array and update in place, overwriting each value as soon as it is computed, so later updates in the same pass already see some fresh values. We think of one pass over the whole state set as a sweep. For the in-place version the order of states within a sweep affects the rate of convergence, and it is the in-place version we normally have in mind.
Formally the iteration converges only in the limit, so in practice we stop it short: after each sweep, test the largest change in any state's value, , and halt when it drops below a small threshold .
- 1input: policy ; threshold
- 2initialize arbitrarily for ,
- 3repeat
- 4
- 5for each do
- 6remember the old value
- 7
- 8track the largest change
- 9until
- 10return
A gridworld sweep
Take the gridworld below.
The nonterminal states are ; the two shaded
corner cells are one terminal state. Four actions — up, down, right, left —
move the agent deterministically one cell, except that any move off the grid leaves
the state unchanged. Every transition pays reward until termination. This is an
undiscounted (), episodic task.
Evaluate the equiprobable random policy — each action with probability . Initialize everywhere and apply the expected update in place, sweep after sweep. The first sweep sets every nonterminal state to (each of the four equally likely moves costs and lands on a state still valued ). Later sweeps let the penalties accumulate outward from the terminal corners, and the estimates fan out toward .
The limit gives, at each state, the negation of the expected number of steps to termination under the random policy. Every one of those numbers satisfies the Bellman equation exactly: a state's value equals plus the average of its four (in-place, deterministic) neighbors' values.
Policy improvement
We compute in order to find better policies. Suppose we have for a deterministic policy , and at some state we consider deviating — taking an action once, then following ever after. The value of that deviation equals the action-value
The test is whether this is greater or less than . If it is greater — taking once and then following beats following from the start — then one would expect it to be better still to take every time comes up. That this intuition is correct is the content of a general result.
The idea of the proof is simple even if the algebra looks dense. If deviating to
for one step and then reverting to never hurts, then deviating for
two steps cannot hurt either — apply the same fact at the next state. Keep pushing
the revert to
point one step further into the future and, in the limit, the
agent follows forever. That limit is . Here is the same argument as
a telescoping expansion: start from the premise ,
expand by its definition, and reapply the premise at the successor, again
and again.
Each application of the premise trades one step of 's continuation for one step of 's, and in the limit the entire tail is 's — which is .
The natural way to use the theorem is to improve at every state at once. Consider the new greedy policy that, in each state, takes the action that looks best under one step of lookahead on :
By construction , so the greedy policy meets the theorem's condition and is at least as good as . Making a new policy greedy with respect to the value function of the old one is policy improvement.3
What if the greedy is only as good as , not strictly better? Then , and the greedy equation reads
which is precisely the Bellman optimality equation. So , and both and are optimal. Policy improvement gives a strictly better policy unless the original one is already optimal. (Everything here extends to stochastic policies; when several actions tie for the max, any apportioning of probability among them is a valid greedy policy.)
Policy iteration
Once a policy is improved to a better , we can evaluate and improve it again, and again. This produces a chain of monotonically improving policies and value functions:
where is an evaluation and an improvement. Each policy is a strict improvement over the last (unless already optimal). A finite MDP has only finitely many deterministic policies, so this chain must reach an optimal policy and value function in a finite number of iterations. This is policy iteration.4
The evaluation of each policy is itself the iterative sweep from before, and it is started from the value function of the previous policy rather than from scratch. Because the value function usually changes little from one policy to the next, this warm start makes evaluation converge much faster.
- 1initialize and arbitrarily for all
- 2loop
- 3repeatpolicy evaluation
- 4
- 5for each do
- 6
- 7
- 8
- 9until
- 10policy improvement
- 11for each do
- 12
- 13
- 14if then
- 15
- 16if then
- 17return
On the gridworld above, greedy-with-respect-to- policies point toward the terminal corners along shortest paths, and in that small case the greedy policy becomes optimal after only a few evaluation sweeps — well before has converged to . That observation is precisely the opening for the next algorithm.
A policy iteration solved by hand
For example, take a two-state MDP with states
and two actions, stay and switch, discount . The
dynamics are deterministic: stay keeps the current state, switch moves to the
other. Rewards depend only on the landing state — arriving in pays ,
arriving in pays — so from , stay pays and switch pays ;
from , stay pays and switch pays . The optimal policy is obviously
reach and stay,
but watch policy iteration discover it.
Start from the deliberately bad policy : switch in both states, so the
agent oscillates . Evaluate it. Since the policy is
deterministic the Bellman equations are two linear equations,
Substitute the second into the first: , so and . Now improve. Compute both action values at each state from :
The greedy choice at is switch (unchanged), but at it is stay
() — the policy changed, so .
Evaluate : now is absorbing under the policy, giving
and
. Improve again:
ties
, so keeps switch; and
, so
keeps stay. No action changed: the policy is stable, and with
. Two evaluations and two improvements, and the chain terminated.
The same problem run as value iteration from needs several sweeps to crawl the value up toward (, , , converging geometrically to as ), but the greedy policy it reads off is already after the very first sweep. This is the general pattern: the greedy policy stabilizes long before the values do.
Jack's car rental: policy iteration at scale
The two-state solve fits on a napkin; policy iteration also handles problems with thousands of states in a handful of iterations. In Jack's car rental (Example 4.2), Jack runs two rental locations. Each night he may move up to five cars between them at a cost of USD 2 per car; each morning, customers arrive at each location as Poisson random variables (means and for requests, and for returns) and each car rented pays USD 10. With at most cars per location, the state is the pair of overnight inventories — states — and the action is the signed number of cars moved, from to . Discount ; the task is continuing.5
Policy iteration starts from the do-nothing policy (never move a car), evaluates it by solving the -state Bellman system to tolerance, then improves greedily — each state's new action is the transfer that maximizes expected reward-plus-value under the known Poisson dynamics. The policy that emerges after the first improvement already moves cars from the busier location toward the one more likely to run dry; a few more evaluate–improve rounds refine the transfer thresholds, and the process converges to the optimal policy in about four iterations.
Jack's rental is the standard demonstration that policy iteration's finite-step guarantee is not just theoretical comfort: on a -state problem with a nontrivial stochastic model, it converges in single-digit iterations. That Poisson-dynamics model carries the arbitrary nonlinearity that direct optimization struggles with but DP handles without difficulty, because DP only ever queries the model for one-step transition probabilities.
Value iteration
A drawback of policy iteration is that each round waits for a full policy evaluation, itself a protracted iterative computation. Must we wait for exact convergence to before improving? The gridworld says no: the greedy policy often stops changing long before the values do. So truncate the evaluation.
The extreme case stops policy evaluation after just one sweep — one update of each state. The result is value iteration, which folds improvement and truncated evaluation into a single update by simply putting a where policy evaluation had a policy-weighted average:
For arbitrary , the sequence converges to under the same conditions that guarantee exists. This is nothing but the Bellman optimality equation turned into an update rule — the same equation-becomes-assignment move, now applied to the optimality equation rather than the policy Bellman equation. The update is identical to iterative policy evaluation's except that it takes the maximum over all actions instead of averaging over the policy's.
Like policy evaluation, value iteration formally needs infinitely many iterations, so in practice we stop when a sweep changes the values by less than and read off a deterministic policy greedy with respect to the final .
- 1input: threshold
- 2initialize arbitrarily for ,
- 3repeat
- 4
- 5for each do
- 6
- 7
- 8
- 9until
- 10return deterministic with
Value iteration effectively does one sweep of policy evaluation and one sweep of policy improvement per pass. More generally, one can interpose several evaluation sweeps between improvement sweeps; the whole family of truncated policy iteration algorithms is a sequence of sweeps, some using evaluation updates and some using value-iteration updates. Since the is the only difference, they all converge to an optimal policy for discounted finite MDPs.
The gambler's problem: value iteration on a probability
A worked value-iteration example that yields a surprising policy is the gambler's problem (Example 4.3). A gambler bets on coin flips: on each flip he stakes some integer number of dollars from his current capital; heads pays even money (he gains his stake), tails loses it. The game ends when his capital reaches USD 100 (win) or USD 0 (lose). The state is the capital ; the actions are stakes . All rewards are zero except on the transition that reaches USD 100, which pays . The task is undiscounted and episodic, so gives the probability of eventually winning from capital under optimal play.6
Let be the probability of heads. The value-iteration update at each capital sweeps over all stakes:
with and held fixed. Run this to convergence for (a losing coin). The value function rises monotonically from to in a scalloped curve, and the optimal policy is jagged and non-obvious: at capital the gambler stakes everything (a stake of gives one shot at the goal), at he stakes only , and the stake pattern repeats a self-similar structure at , , and their subdivisions.
The lesson of the gambler's problem is that value iteration recovers optimal behavior even when that behavior is counterintuitive. A human might bet a steady fraction; the optimal policy for a losing coin is to make aggressive lump bets that reach the goal in as few flips as possible, because every extra flip of an unfavorable coin loses probability. Value iteration finds this by mechanically sweeping the Bellman optimality update — no insight about coin-flip strategy is programmed in.
This continues in Dynamic Programming: Asynchronous DP and Generalized Policy Iteration, which loosens the full-sweep schedule, names the evaluation-improvement pattern that underlies almost every RL method, and traces DP forward to its modern approximate and neural descendants.
Footnotes
- Sutton & Barto, Reinforcement Learning: An Introduction (2nd ed.), Ch. 4 — Dynamic Programming: DP as computing optimal policies given a perfect model of a finite MDP, obtained by turning the Bellman optimality equations (4.1)–(4.2) into update rules; classically of limited utility for RL but the theoretical foundation for it. ↩
- Sutton & Barto, §4.1 — Policy Evaluation (Prediction): the Bellman equation (4.4) as a linear system, iterative policy evaluation (4.5) with its fixed point and convergence, the expected update, in-place sweeps, and the halting test on ; Example 4.1 is the gridworld. ↩
- Sutton & Barto, §4.2 — Policy Improvement: the action-value test (4.6), the policy improvement theorem (4.7)–(4.8) with its telescoping proof, and the greedy policy (4.9) whose fixed point is the Bellman optimality equation. ↩
- Sutton & Barto, §4.3 — Policy Iteration (the chain and its finite-step convergence) and §4.4 — Value Iteration (update 4.10 as the Bellman optimality equation turned into an assignment, one-sweep truncated evaluation). ↩
- Sutton & Barto, §4.3, Example 4.2 (Jack's Car Rental) and Figure 4.2: the two-location rental as a continuing finite MDP with Poisson request/return dynamics ( requests and returns), USD 10 per rental and USD 2 per car moved, , states, and the sequence of policies policy iteration finds (converging in a few iterations to the optimal transfer policy). ↩
- Sutton & Barto, §4.4, Example 4.3 (Gambler's Problem) and Figure 4.3: value iteration on capital states – with stakes as actions, reward only on reaching USD 100, as the probability of winning, and the jagged optimal policy for (bet-all at capital ). ↩
╌╌ END ╌╌