Tabular Solution Methods/Dynamic Programming

Lesson 2.13,073 words

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.

The expected update for backs value up from all successors at once. From state the policy branches over actions (solid dots) and the model branches over next-state/reward pairs ; the new is the probability-weighted average of over the whole tree.

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 .

Algorithm:Iterative-Policy-Evaluation\textsc{Iterative-Policy-Evaluation} — in-place, estimate VvπV \approx v_\pi
  1. 1
    input: policy π\pi; threshold θ>0\theta > 0
  2. 2
    initialize V(s)V(s) arbitrarily for sSs \in \mathcal{S}, V(terminal)=0V(\text{terminal}) = 0
  3. 3
    repeat
  4. 4
    Δ0\Delta \gets 0
  5. 5
    for each sSs \in \mathcal{S} do
  6. 6
    vV(s)v \gets V(s)
    remember the old value
  7. 7
    V(s)aπ(as)s,rp(s,rs,a)[r+γV(s)]V(s) \gets \sum_a \pi(a \mid s) \sum_{s',r} p(s',r \mid s,a)\,[\,r + \gamma\,V(s')\,]
  8. 8
    Δmax(Δ,vV(s))\Delta \gets \max(\Delta,\, |v - V(s)|)
    track the largest change
  9. 9
    until Δ<θ\Delta < \theta
  10. 10
    return VV

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.

The gridworld of Example 4.1. Nonterminal states 1--14 are numbered; the two shaded corners are one terminal state. Actions move one cell deterministically (a move off-grid stays put), and every transition costs .

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 .

Iterative policy evaluation on the gridworld under the random policy. Left to right: (all zero), (every state ), and the limit , whose value at each state is the negation of the expected number of steps to termination under the random policy.

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

Policy improvement makes a new policy greedy with respect to : at each state it selects the action maximizing (bold bar), a one-step lookahead. The policy improvement theorem guarantees is no worse than everywhere.

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

Policy iteration alternates a full policy evaluation (E) with a greedy policy improvement (I). Each round produces a strictly better policy until the improvement step changes nothing, at which point and .

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.

Algorithm:Policy-Iteration\textsc{Policy-Iteration} — evaluation and improvement, estimate ππ\pi \approx \pi_\ast
  1. 1
    initialize V(s)RV(s) \in \mathbb{R} and π(s)A(s)\pi(s) \in \mathcal{A}(s) arbitrarily for all ss
  2. 2
    loop
  3. 3
    repeat
    policy evaluation
  4. 4
    Δ0\Delta \gets 0
  5. 5
    for each sSs \in \mathcal{S} do
  6. 6
    vV(s)v \gets V(s)
  7. 7
    V(s)s,rp(s,rs,π(s))[r+γV(s)]V(s) \gets \sum_{s',r} p(s',r \mid s,\pi(s))\,[\,r + \gamma\,V(s')\,]
  8. 8
    Δmax(Δ,vV(s))\Delta \gets \max(\Delta,\, |v - V(s)|)
  9. 9
    until Δ<θ\Delta < \theta
  10. 10
    stabletrue\textit{stable} \gets \mathbf{true}
    policy improvement
  11. 11
    for each sSs \in \mathcal{S} do
  12. 12
    oldπ(s)\textit{old} \gets \pi(s)
  13. 13
    π(s)argmaxas,rp(s,rs,a)[r+γV(s)]\pi(s) \gets \arg\max_a \sum_{s',r} p(s',r \mid s,a)\,[\,r + \gamma\,V(s')\,]
  14. 14
    if oldπ(s)\textit{old} \ne \pi(s) then
  15. 15
    stablefalse\textit{stable} \gets \mathbf{false}
  16. 16
    if stable\textit{stable} then
  17. 17
    return V,πV, \pi

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 two-state policy-iteration trace. Starting from the oscillating policy pi-0 (switch, switch), evaluation gives values (5.26, 4.74); improvement flips R to stay; re-evaluating the new policy gives (10, 10) and improvement changes nothing, so pi-1 is optimal. Each E step solves the linear system, each I step takes the greedy action.

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.

The optimal transfer policy for Jack's car rental (schematic of Figure 4.2). The axes are the overnight car counts at the two locations; each region is labeled with the number of cars to move overnight (negative moves cars the other way). The bands are the optimal action thresholds policy iteration converges to.

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.

Value iteration replaces policy evaluation's average over actions (left, weighted by ) with a over actions (right), backing up only the single best action's expected value; everything below the action layer — the model's branching over — is identical.

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 .

Algorithm:Value-Iteration\textsc{Value-Iteration} — estimate ππ\pi \approx \pi_\ast
  1. 1
    input: threshold θ>0\theta > 0
  2. 2
    initialize V(s)V(s) arbitrarily for sSs \in \mathcal{S}, V(terminal)=0V(\text{terminal}) = 0
  3. 3
    repeat
  4. 4
    Δ0\Delta \gets 0
  5. 5
    for each sSs \in \mathcal{S} do
  6. 6
    vV(s)v \gets V(s)
  7. 7
    V(s)maxas,rp(s,rs,a)[r+γV(s)]V(s) \gets \max_a \sum_{s',r} p(s',r \mid s,a)\,[\,r + \gamma\,V(s')\,]
  8. 8
    Δmax(Δ,vV(s))\Delta \gets \max(\Delta,\, |v - V(s)|)
  9. 9
    until Δ<θ\Delta < \theta
  10. 10
    return deterministic π\pi with π(s)=argmaxas,rp(s,rs,a)[r+γV(s)]\pi(s) = \arg\max_a \sum_{s',r} p(s',r \mid s,a)\,[\,r + \gamma\,V(s')\,]

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 gambler's problem for heads-probability 0.4 (Sutton & Barto, Figure 4.3). Top: the optimal value function is the probability of reaching USD 100 from capital ; it rises from 0 to 1 in a scalloped staircase that stays below the diagonal (a fair-coin gambler would sit on that line). The value is capped at because it is a probability. Bottom: the optimal stake is jagged, spiking to bet-everything at capital 50 and dropping sharply just past it, with self-similar spikes at 25 and 75.

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

  1. 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.
  2. 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.
  3. 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.
  4. 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).
  5. 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).
  6. 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 ╌╌