Dynamic Programming — Value Iteration, Policy Iteration, and Q-Learning
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Markov Decision Processes — covered in Lecture 4 (states, actions, transitions, rewards, discount factor, policy, value functions)
- Bellman Equations — covered in Lecture 5 (Bellman expectation equation, Bellman optimality equation, value iteration basics)
- Policy and Value Functions — covered in Lecture 5 (state-value V(s), action-value Q(s,a), deterministic vs stochastic policies)
- Model-Based vs Model-Free RL — covered in Lecture 2 (distinction between planning with a model and learning from experience)
# Dynamic Programming — Value Iteration, Policy Iteration, and Q-Learning
6.1 Review: MDP and Bellman Equations
6.1.1 MDP Framework and Bellman Equations
A Markov Decision Process (MDP) is the formal framework for stating a Reinforcement Learning problem. The word "Markov" refers to the Markov property: the future depends only on the current state, not on how you got there. Think of it like a board game where only your current position matters — your history of moves is irrelevant to what happens next.
An MDP consists of five components:
- S — a finite set of states (the possible situations)
- A — a finite set of actions (the possible decisions)
- — the transition function: probability of reaching state s' from state s by taking action a
- — the reward function: immediate reward received when transitioning from s to s' via action a
- (gamma) — the discount factor: a scalar in [0,1) that controls how much the agent values future rewards relative to immediate ones
The agent follows a policy — a rule that says what action to take (or with what probability) in each state. A deterministic policy is simply (a fixed action for each state). A stochastic policy specifies probabilities for each action in each state.
We evaluate a policy using a value function , which tells us how good it is to be in state s if we follow policy from then on. The value function satisfies the Bellman expected update equation.
The Bellman expected update says: the value of a state under policy equals the expected immediate reward plus the discounted value of the next state, where the expectation is taken over the actions chosen by and the transition probabilities.
Symbol breakdown:
- — value of state s under policy (how good it is to be in s following )
- — probability of taking action a in state s under policy
- — probability of transitioning to state s' from s via action a
- — immediate reward for the transition s → s' via action a
- — discount factor (how much we value future rewards)
- — value of the next state s' under the same policy
Professor's verbal description: "This part says what's the probability of taking an action as per the policy? And the second part says what is the value of that action? And you keep repeating it."
The Bellman optimality equation replaces the policy-weighted expectation with a max over actions:
The key difference from Bellman expected update:
- In Bellman expected update: you see weighting each action — averaging over what the policy tells you to do
- In Bellman optimality: you see — you pick the single best action rather than averaging over the policy's choices
In Bellman optimality there is no policy weighting; you look at all actions and choose the one giving the maximum value. That value becomes the value of the state.
Professor's verbal description: "In the Bellman optimality expression, instead of the sigma weighted update, you would actually see a max. The optimal policy is about picking an action that takes you to the best state, instead of doing expectation."
Consider a simple MDP with 2 states (S₁, S₂) and 2 actions (left, right). From S₁:
- Action "left" leads to S₁ with probability 1, reward = 0
- Action "right" leads to S₂ with probability 1, reward = +1
Policy gives: = 0.7, = 0.3
Bellman expected update (with , assuming = 5):
Solving:
Bellman optimality (choosing the best action):
Since 5.5 > 0.9 for reasonable values, the optimal action is "right" and .
Sense-check: Under the policy, the agent goes right only 30% of the time, so the value is lower. Under optimality, the agent always goes right and gets the full value.- A finite MDP (finite states and actions)
- The Markov property: the future depends only on the current state, not the history
- The discount factor ensures infinite sums converge
- For the Bellman expected update, a fixed policy must be specified
- For the Bellman optimality equation, we are seeking the best possible policy
- Confusing with : is the value under a specific policy ; is the value under the best possible policy. They are equal only when is already optimal.
- Forgetting the discount factor: Without , the total reward can be infinite. The discount factor makes the sum finite and models the idea that future rewards are worth less than immediate ones.
- Confusing the backup diagrams: The expected-update diagram averages over actions per (chance node); the optimality diagram takes the max over actions (max node). Mixing them up leads to wrong computations.
6.2 Value Iteration — Algorithm and Race Car Example
6.2.1 Symbol Registry — Value Iteration
- s — current state — — element of state space S
- a — action — — element of action space A
- s' — next state after taking action a — — element of S
- — probability of taking action a in state s under policy — — scalar in [0,1]
- — discount factor — — scalar in [0,1)
- — transition probability from s to s' given action a — — scalar in [0,1]
- — immediate reward — — scalar
- — optimal value of state s — — scalar
6.2.2 The Race Car MDP
The race car example has three states: cool, warm, and overheated. Overheated is a terminal state — once the car overheats, it is done and the value of that state is zero. From cool, two actions are available: slow and fast. From warm, two actions are also available: slow and fast.
Transition dynamics for the race car:
- Cool → slow: With probability 1, the car remains cool. Immediate reward = +1.
- Cool → fast: With probability 0.5 the car stays cool (reward +2), and with probability 0.5 the car goes to warm (reward +2). So fast has two branches, each with probability 0.5 and reward +2.
- Warm → slow: With probability 0.5 the car goes to cool (reward +1), and with probability 0.5 the car stays warm (reward +1).
- Warm → fast: With probability 1 the car goes to overheated. Immediate reward = −10.
Red lines in the diagram indicate driving fast. The objective is to estimate the value of being in each state — what is the value of being cool, warm, or overheated — using value iteration.
Race Car MDP — State Transition Diagram
Red lines: Driving Fast (Risky, High Reward / Overheat Risk) | Blue lines: Driving Slow (Safe, Lower Reward)
Interactive Value Iteration Workbench
Watch state values converge sweep-by-sweep under the Bellman optimality update.
6.2.3 Value Iteration Algorithm
The value iteration algorithm has two loops:
Outer loop: "Repeat until convergence" — initialize delta (the maximum change in value across all states in one iteration) to 0. Delta tracks the largest difference between the old and new value estimates. If delta becomes smaller than a threshold θ, the values have converged and the algorithm stops. Inner loop: For each state s ∈ S, apply the Bellman optimality equation to revise the value estimate. That is, for each state, compute the value of each available action (summing over possible next states weighted by their probabilities and including the discounted previous value of each next state), then take the maximum over actions as the new value.The update rule for each state is:
This is simply the Bellman optimality equation turned into an iterative update: at each step k, we use the current estimates to compute new estimates .
Professor's advice: "To begin with, you need not really worry about this delta and theta. In your mind, all you need to know is if the difference between the values of subsequent iterations is not much, you can stop."
Sweeps. In dynamic programming terminology, going through all states once and updating each value is called a sweep. Value iteration performs multiple sweeps across the state space until convergence.- Value iteration requires complete knowledge of the MDP (the model P and reward R)
- The state space must be finite (or discretized)
- The discount factor must be in [0,1)
- The algorithm is guaranteed to converge to under these conditions
- Convergence is asymptotic — in practice, we stop when changes are below threshold θ
6.2.4 Worked Example: Race Car Value Iteration (Sweep 1)
For the slow action from cool: there is only one outcome (stay in cool) with probability 1. The formula gives:
Take the max: V1(cool) = max(1, 2) = 2.
Sweep 1 — Computing V1(warm).For the fast action from warm: with probability 1, the car goes to overheated (reward −10):
For the slow action from warm: two branches, each with probability 0.5. One branch goes to cool (reward +1), the other stays warm (reward +1):
Take the max: V1(warm) = max(−10, 1) = 1.
V1(overheated) remains 0 (terminal). Summary after sweep 1: V1(cool) = 2, V1(warm) = 1, V1(overheated) = 0. Sense-check: After one sweep with all-zero initial values, the values reflect only the immediate expected reward. Cool is worth 2 (the fast action gives +2), warm is worth 1 (the slow action gives +1). These values will grow as future rewards propagate through subsequent sweeps.- Forgetting terminal states: Terminal states always have value 0 and are never updated. Do not include them in the inner loop.
- Using wrong iteration values: When computing , use (s') — the values from the previous iteration, not the most recently updated values (that would be the in-place variant, covered in Section 6.3).
- Miscounting branches: For actions with multiple outcomes, each outcome has its own probability and reward. Don't aggregate them incorrectly.
6.3 In-Place vs Not-In-Place Value Iteration
6.3.1 The Two Variants
- V1(cool) = max{1, 2} = 2 (using V0 values)
- V1(warm) = max{−10, 1} = 1 (using V0 values)
- V1(overheated) = 0
- V1(cool) = max{1, 2} = 2 (using V0 values)
- Now update V(cool) to 2 in the single array
- V1(warm) = max{−10, 1} = 1 (using V0 values — = 0, = 0)
Wait — in this case, the in-place result is the same because we used for warm's own value, and for cool's value in the warm computation. The difference appears when we reference a state whose value was already updated in this sweep.
Sweep 2 (showing the difference): Not-in-place: V1(cool) = 2, V1(warm) = 1- V2(cool) = max{1 + 0.9×2, 0.5×(2+0.9×2) + 0.5×(2+0.9×1)} = max{2.8, 3.25} = 3.25 (using V1 values)
- V2(warm) = max{−10 + 0.9×0, 0.5×(1+0.9×2) + 0.5×(1+0.9×1)} = max{−10, 2.35} = 2.35 (using V1 values)
- V2(cool) = 3.25 (same as not-in-place — cool is processed first)
- Now update V(cool) to 3.25
- V2(warm) = max{−10, 0.5×(1+0.9×3.25) + 0.5×(1+0.9×1)} = max{−10, 0.5×3.925 + 0.5×1.9} = max{−10, 2.9125} = 2.9125
(uses the updated V(cool) = 3.25, not the old V1(cool) = 2)
Key difference: The in-place version gets V2(warm) = 2.9125 while not-in-place gets V2(warm) = 2.35. The in-place version converges faster because it uses the freshest information.This means: if you are computing for some state s, and another state s' has already been updated in this sweep (i.e., has been overwritten with (s')), then you MUST use (s') — the updated value — not .
- Both versions converge to the same optimal values .
- They differ in the speed and pattern of convergence.
- Experimentally, the in-place version converges faster (because it uses fresher information).
- The in-place version is also known as the Gauss-Seidel method in numerical linear algebra.
- The not-in-place version is also known as the Jacobi method.
- Confusing the two in exams: If asked for "in-place," you must show that updated values are used. If asked for "standard" or "not-in-place," use only values from the previous iteration.
- Forgetting the order matters: In the in-place version, the order in which you process states affects the convergence pattern (though not the final answer). Processing states in a smart order can speed up convergence.
- Assuming both give identical intermediate values: They don't — only the final converged values are the same. The intermediate values during iteration differ.
6.4 Policy Extraction from Value Iteration
6.4.1 Symbol Registry — Policy Extraction
- — deterministic policy for state s — — action
- a — action being evaluated — — element of action space A
- — converged optimal value of next state — — scalar
- — discount factor — — scalar in [0,1)
6.4.2 Extracting the Policy
After the value iteration converges, you need to extract the optimal policy for each state. The algorithm's final step says "output a deterministic policy ."
For each state s, consider every available action a. Compute the value of taking action a using the same Bellman optimality formula but now with the converged values. Use the argmax over actions — the action that yields the highest value becomes the policy for that state:
This is exactly the same computation as in value iteration, but instead of taking the max to get a value, we take the argmax to get the action that achieves that maximum.
Professor's verbal description: "For each action, compute the values of their outcomes, and choose the action that gives the highest outcome."
Using the converged values V(cool) = 3.35, V(warm) = 2.35, V(overheated) = 0, and :
For cool — slow action:For cool — fast action:
Comparing: fast (4.565) > slow (4.015), so . For warm — slow action:
For warm — fast action:
Comparing: slow (3.565) > fast (−10), so . For overheated: Terminal state, no policy defined. Final policy:
- Deterministic policy only: Value iteration always produces a deterministic policy = a. It will NOT give you probabilities like "drive slow is 0.7, drive fast is 0.3." If the argmax has ties, you can break them arbitrarily — the resulting policy is still optimal.
- Notation matters: Write (deterministic), NOT = probability. The professor emphasized: "You must be very clear that this algorithm is outputting a deterministic policy ."
- Terminal states excluded: No policy is defined for terminal states — they have no outgoing actions.
- Policy extraction cost: Computing the policy for all states costs — the same as one iteration of value iteration.
6.5 Policy Evaluation
6.5.1 Definition and Intuition
The same state can have very different values depending on the policy. A good policy leads to positive values; a poor policy leads to negative values even from the same starting state.
6.5.2 Policy Evaluation Formula
Policy evaluation uses the Bellman expected update equation with the fixed policy :
This is the same equation from Section 6.1, applied iteratively: initialize all values, then repeatedly update each state's value using this equation until convergence.
Key distinction from value iteration: In policy evaluation, the policy is FIXED. We use the expected update (weighted average over actions per ) rather than the optimality update (max over actions). We are not trying to find the best action — we are evaluating a given policy.6.5.3 Policy Evaluation Algorithm
Iterative Policy Evaluation Algorithm
- Initialization: Set arbitrarily (e.g., 0) for all non-terminal states , and .
- Iterative Update: Repeat until convergence ():
- For each non-terminal state :
- Output: Converged value function .
Professor's summary: "For each state, you estimate the value based on Bellman expected update equation. Keep computing value of S for each state using the Bellman equation. Keep repeating it. Once it converges, you know the value of each of the states."
6.5.4 Worked Example: 5-State Grid Problem
Worked Example: 5-State Grid Policy Evaluation
Consider five states arranged linearly. The agent starts at state 3 and can move Left (L) or Right (R) at each step:
Environment Rules: Non-terminal states: . Initial values for all states. Terminal states throughout. All step transition rewards are 0, except entering Bad () or Good ().
Scenario 1: Left-Biased Policy ()
"Wherever you are, you are strongly inclined to move Left."
Sweep 1 Calculations:
- State 2: Going L (0.8) Bad (); Going R (0.2) Start ()
- Start (3): Going L (0.8) State 2 (); Going R (0.2) State 4 ()
- State 4: Going L (0.8) Start (); Going R (0.2) Good ()
After Sweep 1:
Converged Values (): .
⚠️ ALL NEGATIVE: Because the policy heavily prefers Left, the agent is consistently driven toward the Bad terminal state.
Scenario 2: Right-Biased Policy ()
"Wherever you are, you are strongly inclined to move Right."
Sweep 1 Calculations:
- State 2:
- Start (3):
- State 4:
After Sweep 1:
Converged Values (): State 4 achieves a high positive value (), and positive reward flows back through Start to State 2.
✓ MOSTLY POSITIVE: Favoring Right makes proximity to the Good terminal valuable.
Scenario 3: Equal Policy ()
"Unbiased random walk in both directions."
Sweep 1 Calculations:
- State 2:
- Start (3):
- State 4:
Converged Values (): Values stabilize symmetrically. State 2 is slightly negative (), State 4 is slightly positive (), and Start stays near 0.
Policy Comparison Matrix
| Policy Scenario | Sweep 1 | Converged | Key Insight | |
|---|---|---|---|---|
| Left-Biased | 0.8 / 0.2 | Drives toward BAD state; entire state space becomes negative. | ||
| Right-Biased | 0.2 / 0.8 | Drives toward GOOD state; positive value flows backwards. | ||
| Equal (Unbiased) | 0.5 / 0.5 | Symmetric evaluation reflecting equal distance to terminals. |
Key Takeaway: The exact same MDP (same states, actions, rewards) yields completely different value functions depending on the policy being evaluated. Value functions measure the quality of a specific behavior in an environment.
- Policy must be fixed: Policy evaluation assumes the policy does NOT change during the evaluation. If you change the policy mid-evaluation, the values become meaningless.
- Terminal states are always 0: Do not update terminal states — their value is defined to be 0.
- Uses expected update, NOT max: In policy evaluation, you average over actions per (using ), not take the max. Using max would be value iteration, not policy evaluation.
- Convergence is guaranteed: Under standard conditions ( or eventual termination), iterative policy evaluation converges to .
6.6 Policy Improvement
6.6.1 Greedy Policy Improvement
After evaluating a policy (finding for each state), the next question is: can we improve the policy by acting greedily on the evaluated values?
The policy improvement theorem states: if for a deterministic policy , we define a new policy that is greedy with respect to , then is guaranteed to be at least as good as . Formally, if
then
with strict improvement at any state where the first inequality is strict.
The greedy policy is defined as:
This is the same formula as policy extraction (Section 6.4), but applied to (the value of the current policy) rather than (the optimal value).
The professor said: "I just want you to go through this theorem offline. I may not even ask you to recite this theorem in the exams, but I want you to go through it."
Starting from the left-biased policy (), policy evaluation gives negative values for all states:
- (2) ≈ −0.80
- (Start) ≈ −0.78
- (4) ≈ −0.28
Now apply greedy policy improvement to each state:
State 2:- Action left (current policy): leads to Bad, expected value = −1
- Action right: leads to Start (value ≈ −0.78), expected value = 0 + 0.9 × (−0.78) = −0.702
- Right is better (−0.702 > −1) → change to right
- Action left: leads to State 2 (value ≈ −0.80), expected value = 0 + 0.9 × (−0.80) = −0.72
- Action right: leads to State 4 (value ≈ −0.28), expected value = 0 + 0.9 × (−0.28) = −0.252
- Right is better (−0.252 > −0.72) → change to right
- Action left: leads to Start (value ≈ −0.78), expected value = 0 + 0.9 × (−0.78) = −0.702
- Action right: leads to Good (value = 1 since terminal), expected value = 1 + 0 = 1
- Right is better (1 > −0.702) → change to right
One can also create a stochastic policy by making the probability proportional to the relative goodness of each action. After improving the policy, you go back and evaluate the new policy, then improve again. This cycle of evaluate → improve → evaluate → improve continues until the policy stops changing.
- Not re-evaluating: After improving the policy, you MUST re-evaluate it (run policy evaluation again) before the next improvement step. The old is no longer valid for the new policy.
- Ties: If two actions have equal value, the argmax can pick either. The resulting policy is still optimal.
- Terminal states: No policy improvement is needed for terminal states — they have no outgoing actions.
6.7 Generalized Policy Iteration (GPI)
6.7.1 The Evaluate-Improve Cycle
The evaluate-improve cycle is called Generalized Policy Iteration (GPI). The big picture: you start with a fixed policy, perform policy evaluation to get the value function, then greedily improve the policy using those values, and repeat.
- Start with an arbitrary policy
- Evaluate: Compute (the value function for the current policy)
- Improve: Make the policy greedy with respect to
- Repeat steps 2–3 until the policy stops changing
When both processes stabilize (the policy is greedy with respect to its own value function), you have found the optimal policy and optimal value function .
Professor's summary: "You start with a fixed policy and you perform policy evaluation. You get the value for the policy. Now take the value and be greedy in the value and update the policy. Keep repeating it. Finally, you will get optimal value and optimal policy."
The professor is drawing a parallel: in SGD, you update parameters after each batch (not after seeing all data). In GPI, you can improve the policy after partial evaluation (not waiting for full convergence). Both work because the iterative process converges regardless of the granularity of updates.
- Policy iteration: Full policy evaluation (to convergence) at each step
- Value iteration: One sweep of policy evaluation per improvement step
- Truncated policy iteration: A few sweeps of policy evaluation per improvement step
- Asynchronous methods: Interleave evaluation and improvement at the finest grain
The key insight: "This actually gives you a way by which you design how you do the learning."
- Thinking GPI is one specific algorithm: GPI is a general framework — many algorithms are instances of GPI.
- Assuming full evaluation is required: You do NOT need to run policy evaluation to convergence before improving. Partial evaluation also converges to optimal.
- Confusing the two processes: Policy evaluation makes match (V → ). Policy improvement makes greedy on (). They pull in opposite directions but converge together.
6.8 Policy Iteration Algorithm
6.8.1 Algorithm Steps
- Initialize: Set an initial policy (random or arbitrary). Initialize V(s) arbitrarily for all states.
- Policy Evaluation: Run iterative policy evaluation (Bellman expected update) until convergence to get for the current policy.
- Policy Improvement: For each state s:
- Check stability: If (policy unchanged), stop — you have and . Otherwise, set and go to step 2.
The stopping condition is policy stability: "You stop when the policy between two iterations doesn't change." Repeat the evaluate-improve cycle until the policy is stable.
Start with an arbitrary policy: = always go left.
Iteration 1:- Evaluate: Run policy evaluation for = always left. Converged values: ≈ −1, ≈ −0.9, ≈ −0.8 (all very negative because going left means hitting Bad).
- Improve: At each state, going right gives better value than going left:
- State 2: left → Bad (−1), right → Start (−0.9). Right is better → (2) = right
- Start: left → State 2 (−1), right → State 4 (−0.8). Right is better → (Start) = right
- State 4: left → Start (−0.9), right → Good (+1). Right is better → (4) = right
- Policy changed ( ≠ ) → continue.
- Evaluate: Run policy evaluation for = always right. Converged values: ≈ +0.7, ≈ +0.8, ≈ +0.9 (positive because going right means reaching Good).
- Improve: At each state, going right still gives the best value.
- Policy unchanged ( = ) → STOP. = always right, = converged values.
- Value iteration: Initialize values, iterate Bellman optimality (max) until V converges, then extract policy. Works with values.
- Policy iteration: Initialize policy, alternate between full evaluation (expected update) and greedy improvement. Works with policies.
- Convergence: Both converge to the same optimal policy, but policy iteration often converges in fewer iterations (though each iteration is more expensive).
- Incomplete evaluation: Policy iteration requires FULL policy evaluation (to convergence) before improvement. Truncating evaluation changes the algorithm to truncated policy iteration or value iteration.
- Cycling: If the policy continually switches between equally good policies, the algorithm may never terminate (Exercise 4.4 in Sutton & Barto addresses this).
- Initialization matters: Starting with a good initial policy (close to optimal) reduces the number of iterations needed.
6.9 Value Iteration vs Policy Iteration: Convergence and Comparison
6.9.1 The Policy-Convergence-Before-Values Observation
Using value iteration on a grid problem, the professor tracked both values and policies across iterations:
Iteration 10:- Policy: arrows indicating best actions have STABLE — no more changes
- Values: still changing (e.g., 0.41 → 0.42, 0.27 → 0.28)
- Policy: same as iteration 10 (unchanged)
- Values: finally converged (changes are negligible)
However, the professor cautioned: "That should not tell you that if I stop at iteration 10, I'm really good. In policy iteration, each iteration runs full policy evaluation, which is time-consuming."
6.9.2 Value Iteration Versus Policy Iteration: Which Is Better?
| Aspect | Value Iteration | Policy Iteration |
|---|---|---|
| Works with | Values (V) | Policies () |
| Update per iteration | One sweep of Bellman optimality | Full policy evaluation (many sweeps) + improvement |
| Cost per iteration | — cheap | O(S²A × #eval_sweeps) — expensive |
| # iterations to converge | Many | Few |
| Stopping condition | δ < θ (values stabilize) | Policy unchanged |
| Practical advantage | Fast iterations, usable policy early | Fewer total iterations |
The professor referenced the Sutton and Barto textbook (Chapter 4 on dynamic programming): "It closes saying that it is very difficult to decide which is a good idea to solve a DP problem — policy iteration or value iteration. It's very difficult to quantify for all problems which one is good."
"Practically most problems, value iteration, the way we have done, is actually good, because each iteration goes faster, very quickly you get a usable policy."
The textbook also notes that while in-place updates certainly improve convergence speed, it is very difficult to quantify the improvement mathematically.
- Assuming fewer iterations = faster: Policy iteration converges in fewer iterations, but each iteration is much more expensive (full policy evaluation). Total computation may be higher.
- Ignoring the cost of policy evaluation: Policy iteration's "few iterations" advantage is offset by the cost of running full evaluation each time.
- Thinking one is always better: Neither algorithm dominates across all problems. The choice depends on the specific problem structure.
6.10 Computational Complexity of Value Iteration
6.10.1 Why Per Iteration
Value iteration has per-iteration cost , where S is the number of states and A is the number of actions. This per-iteration cost is significant for large state spaces.
Key points:- Per-iteration cost is — big O of S squared times A
- Policy extraction cost is also per iteration
Formally: the inner computation for one state s is:
- Outer loop: S states
- For each state: A actions evaluated
- For each action: S terms summed
- Total: S × A × S = S²A
Professor's explanation with help from a student: "Assume you are taking a particular state s and an action a. The outcomes can be any state s1, s2, s3, ... — all the states. For each state, for each action state-action pair, the outcome could be any or all of the states in the state space. So S × S × A."
| Problem | States (S) | Actions (A) | S²A per iteration |
|---|---|---|---|
| Race car (this lecture) | 3 | 2 | 3² × 2 = 18 |
| 4×4 grid (Sutton & Barto) | 14 | 4 | 14² × 4 = 784 |
| Chess (approximate) | 10⁴⁷ | 30 | 10⁴⁷ × 30 × 10⁴⁷ ≈ 10⁹⁵ |
| Go (approximate) | 10¹⁷⁰ | 250 | ~10³⁴¹ |
For the race car, 18 operations per iteration is trivial. For chess or Go, S²A is astronomically large — DP is completely infeasible. This is why model-free methods (covered later) are needed for such problems.
- The transition function is dense (any state can be reached from any state-action pair)
- If P is sparse (most transitions have probability 0), the actual cost can be much lower
- The cost is PER ITERATION — total cost is O(S²A × #iterations)
- Both value iteration and policy extraction have this same per-iteration cost
- Confusing per-iteration with total cost: is one sweep. Total cost depends on how many iterations until convergence.
- Forgetting the S in the denominator: For sparse MDPs where each action leads to only a few next states, the cost per state-action pair is much less than S.
- Ignoring policy extraction: Even after value iteration converges, extracting the policy costs another .
6.11 Asynchronous Value Iteration
6.11.1 Priority Queue Approach
When the state space is huge (billions of states), iterating through all states in every sweep is impractical. Asynchronous value iteration addresses this by maintaining a priority queue of states that are likely to need updating.
- Maintain a priority queue of states to update
- When you update a state's value, its neighbors (states whose Bellman computation depends on the updated state) become candidates for update
- Place neighbors in the priority queue, ordered by expected change magnitude
- States with large expected changes get higher priority and are updated sooner
- A particular state might be updated many times before other states are touched at all
- Continue until convergence (all changes are small)
Professor's explanation: "As and when you make an update in different states, you keep track of those potential states where there could be more updates. You maintain a priority queue in which these states are put in. Depending on how significant is the change in the neighbor, if the change is very significant, it gets a high priority. The larger the likelihood of change, the higher in the queue."
- Convergence guarantee: Asynchronous VI converges correctly only if every state is updated infinitely often (no state is permanently ignored). The priority queue must ensure this.
- Not a magic bullet: Avoiding sweeps doesn't reduce total computation — it just avoids committing to a full sweep before making progress. The algorithm can focus on the most "active" parts of the state space.
- Priority design matters: The efficiency gain depends on how well the priority function predicts which states actually need updating.
The professor acknowledged the specific expressions are in the course material but deferred detailed treatment: "These exact expressions are in material at this moment. Don't worry about the rest of the details. Follow the level at which I discuss and say what is not necessary."
6.12 Q-Learning in the Model-Based Setting
This section covers Q-learning in the model-based setting, including the expression, a worked example, and the distinction between model-based and model-free Q-learning.
6.12.1 Symbol Registry — Q-Learning
- — optimal action-value function for state s, action a — — scalar
- s — current state — — element of state space S
- a — action taken in state s — — element of action space A
- s' — next state — — element of S
- a' — action taken in next state s' — — element of A
- — transition probability — — scalar in [0,1]
- R — immediate reward — — scalar
- — discount factor — — scalar in [0,1)
6.12.2 Motivation: Why Q Values Instead of V Values?
The second computational problem with value iteration is that extracting the policy from V values is expensive (). If instead we compute values directly — one value for each state-action pair — policy extraction becomes trivial.
- For each action a: compute
- Take argmax over actions
Cost: O(SA) per state × S states =
With Q values: If you already have for every action in state s:- Simply compare:
- Cost: O(A) per state × S states = O(SA)
For a grid problem with 4 actions per cell, you compute 4 Q values per cell, then compare — much simpler than computing 1 V value per cell and then doing the expensive argmax computation.
Professor's summary: "If I compute 4 Q values for each cell in place of computing 1 V value, I can make a comparison among the four and take the best, and I'm done. If I just compute V, for each action I need to look at for each state outcomes — a big job."
6.12.3 The Expression
Bellman Optimality Equation:
The expression is derived from by "flipping" the expression. The Bellman optimality for is:
For , we want the value of taking action a in state s:
The key difference: Instead of inside the expression, we write . This is because the value of the next state s' under the optimal policy equals the maximum Q value over all actions from s'. Symbol breakdown:
- — the optimal value of taking action a in state s (how good this state-action pair is)
- — the best Q-value from the next state s' (replaces )
- — probability of transitioning to s' from s via action a
- — immediate reward
- — discount factor
Professor's verbal description: "You take action a from state s. There could be multiple outcomes. For each outcome, what is the probability multiplied by the immediate reward plus gamma times the value of the next state. But you don't have V, you write it in terms of Q. Value of s' is max over all outgoing actions from s'."
6.12.4 Worked Example: Computation
The four outgoing Q values from s' are:
- = 0.85
- = 0.60
- = 0.40
- = 0.70
1. (action "up")
2.
Sense-check: = 0.765. This makes sense: taking "right" from s leads to s' with reward 0, and from s' the best you can do is = 0.85, discounted by 0.9. The value is 0.9 × 0.85 = 0.765.6.12.5 Model-Based vs Model-Free Q-Learning
The professor emphasized an important distinction: the Q-learning described above is model-based. "What we are actually doing is model-based learning. Aren't we? My computation of values and using values to extract policy all happens only if I have a model. The P function — the transition probability — is at the heart of all those expressions. Without this P, you don't have dynamic programming."
This Q-learning is based on the model and is not the popular form of Q-learning. The expression works when you have the model. The professor noted: "In Reinforcement Learning, you would encounter the term Q-learning in two different places. This is the first place. This way of computing Q is not very popular. We don't really use model-based Q-learning much."
The second, more common form of Q-learning — model-free Q-learning — will be covered later in the course. Model-free Q-learning learns Q-values directly from experience (interacting with the environment) without needing the transition function P.
For now, the professor's advice: "Understand this Q-learning, understand the use of this expression, be able to answer if I give you some values — be able to plug in this expression and find the values. Don't sweat so much."
Key Distinction: Model-Based vs Model-Free Q-Learning
This section covers Q-learning in the model-based setting. The model-based Q-learning expression works when you have the transition model P. The model-free Q-learning approach, which learns from experience without a model, will be covered later in the course.
Key concepts covered in this section:- Q-learning model-based expression
- Worked example computing values with real numbers
- Model-free distinction explained (covered in detail later in course)
6.13 Problems with Dynamic Programming / Value Iteration
6.13.1 Limitations
- Slow algorithm — per iteration. For problems with billions of states or millions of actions, this is infeasible.
- Policy extraction is expensive — . Computing the optimal policy from converged values requires significant additional work.
- Policy converges long before values. This means the stopping criteria might waste computation.
- Requires full knowledge of the model and reward function. "MDP, dynamic programming — if you want to use dynamic programming, you need a model. The model will tell you how the world works. You don't actually have to interact with the environment to learn the policy." This is why DP methods are called planning algorithms — they plan the optimal behavior using the model without actually interacting with the environment.
- Offline optimization, not online. "You are actually doing an offline optimization, not an online optimization."
- Requires discrete, finite actions. "This idea is completely not feasible in larger state spaces."
- Limitations 1–3 (computational) can be partially addressed by asynchronous methods, better hardware, or approximation
- Limitation 4 (model requirement) is the fundamental barrier — in most real-world problems, the model is unknown or imprecise
- Limitation 5 (offline) means DP cannot adapt to a changing environment
- Limitation 6 (discrete actions) requires discretization for continuous action spaces, which introduces approximation error
6.14 Diabetes Treatment as an MDP: Case Study
6.14.1 Case Study Overview & Sequential Decision Problem
This case study is based on the landmark paper by Steimle and Denton (2017): Markov Decision Processes for Screening and Treatment of Chronic Diseases (with related work by Mason et al., 2014). It formulates repeated medication initiation as a finite-horizon Markov Decision Process (MDP).
6.14.2 Detailed MDP Formulation
The chronic disease treatment decision is formalized as a finite-horizon MDP: .
Decision points occur periodically (e.g., annual clinical reviews) over a finite planning horizon , representing the patient's lifetime or long-term management period.
2. State Space ():The state space is partitioned into living states () and absorbing event/terminal states ():
- Detailed Living State (): , where is total cholesterol category, is HDL cholesterol category, is systolic blood pressure category, and records whether medication has already been initiated.
- Compact Explanatory Living State: , with .
- Absorbing Event States (): Includes major event states like CHD event (), stroke event (), and death from other causes (). Once entered, the patient remains in with no further decision-making.
Actions represent medication initiation choices: .
Critical constraint: The action set is state-dependent to prevent unrealistic repeated initiation of a drug already being taken:
| Current Medication Status | Feasible Action Set |
|---|---|
| No medication started | Start none, Start cholesterol med, Start BP med, Start both |
| Cholesterol med already started | Start none, Start BP med |
| BP med already started | Start none, Start cholesterol med |
| Both medication groups started | Start none |
Let be the age/state-dependent stroke probability, the CHD probability, and the probability of death from other causes. The transition kernel is defined piecewise:
5. Reward Function ():
The reward reflects Quality-Adjusted Life Years (QALYs), treatment costs, side effects, and event penalties:
Illustrative numerical breakdown:
- Survive 1 year without major event: +1.0
- Medication cost/burden for Start C: -0.03
- Medication cost/burden for Start B: -0.03
- Medication cost/burden for Start Both: -0.06
- CHD or Stroke event penalty: -5.0
- Death: 0 continuation value
Find optimal policy maximizing long-term expected discounted reward with discount factor (since long-term health outcomes are clinically critical):
6.14.3 Solving the MDP via Dynamic Programming Algorithms
Initialized with terminal value for all states. For , Bellman backups are computed backward in time:
Optimal policy selection: . Output is an age- and state-dependent decision table.
2. Value Iteration View (Stationary Discounted MDP):Repeatedly applies Bellman optimality backup until .
3. Policy Iteration View (Stationary Model):- Step 1 (Initialize): Start with baseline clinical guideline (e.g., no med for low risk, 1 med for medium risk, both for high risk).
- Step 2 (Policy Evaluation): Solve .
- Step 3 (Policy Improvement): Extract .
- Step 4 (Iterate): Repeat until policy stabilizes.
6.14.4 Optimal Policy Output & Interpretation
| Patient State | Optimal Action | Clinical Rationale |
|---|---|---|
| Low risk, no medication | Wait (Start none) | Event risk reduction does not justify immediate medication cost/burden. |
| Medium risk, no medication | Start cholesterol medication | Targeted risk reduction balances treatment burden. |
| High risk, no medication | Start both medications | High immediate cost is offset by major reduction in high event loss (-5.0). |
| High risk, cholesterol med started | Start BP medication | Adds secondary prevention to control remaining elevated risk. |
| Absorbing event state () | No further initiation decision | Terminal state / decision process ends. |
- Transition Probability Estimation: Probabilities are estimated from epidemiological models and clinical trials; they are subject to statistical uncertainty.
- Discretization Loss: Continuous medical parameters (e.g., blood pressure, cholesterol levels) must be discretized, which may lose fine-grained diagnostic information.
- Imperfect Medication Adherence: Real patients may forget or skip doses, degrading real-world effectiveness relative to model assumptions.
- Heterogeneous Patient Preferences & Side Effects: Individual tolerance and quality-of-life impact vary across patients.
- Decision Support, Not Automated Physician Replacement: DP models serve as decision support tools to guide clinicians, not autonomous medical decision makers.
- Identify the state, action, transition probability, and reward components in the Type 2 diabetes treatment MDP.
- Why is chronic disease medication a sequential decision problem rather than a standard one-step classification problem?
- Write the Bellman optimality equation for the finite-horizon chronic treatment problem.
- Explain how an action with a small immediate negative reward (medication cost/side effect) can have a higher long-term expected value.
- Compare value iteration and policy iteration when solving stationary chronic treatment decision models.
6.15 Planning Algorithms and the Model-Based Paradigm
6.15.1 Planning vs Learning: The Model-Based Paradigm
"Even without getting into the real environment and interacting with aspects, on paper I can find out what is the optimal way of working. People would call these planning algorithms."
Learning (Model-Free): If the model is NOT available, you must learn from experience — by interacting with the environment, observing transitions and rewards, and building up value estimates from samples. This is the domain of model-free RL methods (Monte Carlo, TD learning, Q-learning).DP methods = planning (have the map). Model-free methods = learning (no map, must explore).
- Planning requires a model; learning does not
- Planning can be done offline; learning requires interaction
- Planning gives exact answers (given exact model); learning gives approximate answers
- In practice, many systems combine both: use a learned model for planning, or use planning to improve sample efficiency
Exam Guidance Summary
- Value iteration with the race car example is the primary exam problem format. "The problem can come in multiple flavors" — verbatim understanding of the algorithm and the ability to apply it in different ways is necessary.
- In-place vs not-in-place algorithm: "This is very, very important stuff that you must understand. Whenever you solve a problem, if the question asked is in-place update or not-in-place update, I think you should be very careful." For in-place, show that at every step the most recent values are used.
- Policy extraction is a required skill: after computing values, extract the deterministic policy by computing argmax over actions.
- Policy evaluation: Be able to run Bellman expected update for a given fixed policy and show the values converging.
- Policy iteration: Know the algorithm (initialize policy, evaluate, improve, repeat until stable).
- Q-learning expressions: Be able to plug in values and compute . The professor said: "Be able to answer if I give you some values, be able to plug in this expression and find the values."
- Policy improvement theorem: "I may not even ask you to recite this theorem, but I want you to go through it."
- S vs S+ distinction: Write algorithms for S+ (all states including terminal) in exams. Verify that terminal states retain value 0 through iteration.
- Computational complexity: Understand why value iteration is — be able to explain the reasoning.
- Generalized Policy Iteration: Understand the evaluate-improve cycle as a general framework.
- Study advice: "Spend a lot of time on the lecture notes. Lecture notes plus actual lectures should give a lot of insights." Pick 3-4 problems from the textbook, try to solve them, and share scribbles for discussion.
Key Industry Applications
- Diabetes treatment optimization using MDPs and dynamic programming — a research paper modeling Type 2 diabetes medication decisions as an MDP with states representing medical risk and medication history, actions being medication choices, and rewards based on Quality Adjusted Life Years.
- MDP planning algorithms are used in any domain where the environment model is known — robotics (known physics), game playing (known rules), resource allocation (known constraints).
- Transition probabilities from domain expertise: In healthcare and other domains, the model dynamics (P function) come from clinical data and expert knowledge rather than being perfectly known.
References & Further Reading
- Steimle, L. N., and Denton, B. T. (2017). Markov Decision Processes for Screening and Treatment of Chronic Diseases. In Markov Decision Processes in Practice, Springer, pp. 189–222. Paper Link
- Mason, J. E., Denton, B. T., Shah, N. D., and Smith, S. A. (2014). Optimizing the simultaneous management of blood pressure and cholesterol for type 2 diabetes patients. European Journal of Operational Research, 233(3), 727–738.
- Sutton, R. S., and Barto, A. G. (2018). Reinforcement Learning: An Introduction, 2nd edition. MIT Press. Chapter 4: Dynamic Programming.
DRL Lecture 6 Notes · Dynamic Programming — Value Iteration, Policy Iteration, and Q-Learning
Sections Breakdown
Reviews MDP framework and Bellman equations
Algorithm and race car example
Two variants of value iteration
Extracting deterministic policy from \(V^*\)
Computing V^pi for a fixed policy
Greedy policy improvement theorem
Evaluate-improve cycle framework
Full evaluation + improvement loop
Convergence and comparison
O(S^2 A) per iteration
Priority queue approach
\(Q^*(s,a)\) expression and computation
Limitations motivating model-free methods
Finite-horizon MDP formulation, state-dependent action sets, piecewise transitions, QALY rewards, and backward DP/VI/PI algorithms for chronic disease treatment
Model-based paradigm vs learning
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
MDP and Bellman Equations Review
Must-know: Bellman expected update uses to average over policy; Bellman optimality uses to pick the best action. evaluates a policy; finds the optimal value.
⚠️ Top pitfall: Confusing (value under a specific policy) with (value under the optimal policy).
Self-check: What is the only difference between the Bellman expected update equation and the Bellman optimality equation?
Connects to: 6.2, 6.5
Value Iteration — Algorithm and Race Car Example
Must-know: Value iteration: start with V0=0, repeatedly apply until convergence. Terminal states stay at 0.
⚠️ Top pitfall: Using updated values within the same sweep (in-place) vs using previous iteration values (standard).
Self-check: In the race car example, what is V1(cool) after sweep 1 if and all ?
Connects to: 6.1, 6.3, 6.4
In-Place vs Not-In-Place Value Iteration
Must-know: In-place uses most recent values (Gauss-Seidel style); not-in-place uses previous iteration values (Jacobi style). Both converge to same . Exam: explicitly show which version you're using.
⚠️ Top pitfall: Confusing in-place with not-in-place in exams. In-place = use updated values immediately; not-in-place = use only previous iteration values.
Self-check: What is the key difference between in-place and not-in-place value iteration?
Connects to: 6.2
Policy Extraction from Value Iteration
Must-know: Policy extraction: . Result is deterministic , not probabilities.
⚠️ Top pitfall: Confusing argmax (which action achieves max) with max (the max value itself). Writing =probability instead of =a.
Self-check: What is the optimal policy for cool and warm in the race car example with converged values V(cool)=3.35, V(warm)=2.35?
Connects to: 6.2, 6.5
Policy Evaluation
Must-know: Policy evaluation: . Uses expected update (average per policy), NOT max. Same MDP, different policies → different values.
⚠️ Top pitfall: Using max instead of expected update (that's value iteration, not policy evaluation). Forgetting to keep policy fixed during evaluation.
Self-check: In the 5-state grid, why are all values negative under the left-biased policy?
Connects to: 6.1, 6.6
Policy Improvement
Must-know: Policy improvement: . Guaranteed to be at least as good as . Requires re-evaluation before next improvement.
⚠️ Top pitfall: Not re-evaluating the policy after improvement. Old is invalid for the new policy.
Self-check: What does the policy improvement theorem guarantee about the new greedy policy?
Connects to: 6.5, 6.7
Generalized Policy Iteration (GPI)
Must-know: GPI: alternate policy evaluation (V → ) and policy improvement () until stable. Different algorithms vary the granularity of evaluation.
⚠️ Top pitfall: Thinking GPI is one specific algorithm. It's a framework — policy iteration and value iteration are both instances.
Self-check: What is the difference between policy iteration and value iteration in terms of GPI?
Connects to: 6.6, 6.8
Policy Iteration Algorithm
Must-know: Policy iteration: initialize , evaluate fully, improve greedily, repeat until stable. Converges in fewer iterations than value iteration but each iteration is more expensive.
⚠️ Top pitfall: Truncating policy evaluation (that's no longer policy iteration). Not checking policy stability as stopping condition.
Self-check: What is the stopping condition for policy iteration?
Connects to: 6.7, 6.9
Value Iteration vs Policy Iteration Comparison
Must-know: Policy converges before values in value iteration. Value iteration = cheap iterations, many of them. Policy iteration = expensive iterations, few of them. Professor prefers value iteration for practical speed.
⚠️ Top pitfall: Assuming fewer iterations (policy iteration) means faster. Each policy iteration runs full evaluation.
Self-check: Why might value iteration be preferred over policy iteration in practice?
Connects to: 6.2, 6.8, 6.10
Computational Complexity of Value Iteration
Must-know: per iteration: for each state (S), evaluate each action (A), sum over all possible next states (S). Be able to explain this derivation.
⚠️ Top pitfall: Confusing per-iteration cost () with total cost (O(S²A × #iterations)).
Self-check: Why is value iteration per iteration?
Connects to: 6.2, 6.11
Asynchronous Value Iteration
Must-know: Asynchronous VI uses a priority queue to update states with largest expected changes first. Converges if all states are updated infinitely often.
⚠️ Top pitfall: Thinking it reduces total computation — it focuses computation but doesn't reduce the total amount needed.
Self-check: What is the key advantage of asynchronous value iteration over standard value iteration?
Connects to: 6.10, 6.12
Q-Learning in the Model-Based Setting
Must-know: . Plug in values and compute. Model-based (requires P). Model-free form comes later.
⚠️ Top pitfall: Forgetting in the expression (it's 1 in simple examples but must appear in general). Confusing model-based Q-learning with model-free Q-learning.
Self-check: Compute if , , , and .
Connects to: 6.1, 6.13
Problems with DP / Value Iteration
Must-know: 6 limitations: cost, expensive extraction, policy converges before values, requires full model, offline only, discrete actions only. DP = planning algorithms (no environment interaction needed).
⚠️ Top pitfall: Forgetting that DP requires a model. Confusing planning (model-based) with learning (model-free).
Self-check: Why are DP methods called 'planning algorithms'?
Connects to: 6.10, 6.14
Diabetes Treatment as an MDP: Case Study
Must-know: Diabetes MDP: states = medical indicators + medication history, actions = medication choices, rewards = QALY. Transition probabilities from domain expertise, not exact.
⚠️ Top pitfall: Assuming transition probabilities in real-world MDPs are exactly known. They are estimates from clinical data.
Self-check: What is the reward function in the diabetes treatment MDP based on?
Connects to: 6.13, 6.15
Planning Algorithms and the Model-Based Paradigm
Must-know: DP = planning algorithms (require model, no environment interaction). Model-free = learning algorithms (no model, learn from experience). This distinction drives the rest of the course.
⚠️ Top pitfall: Confusing planning (model-based) with learning (model-free). DP requires a model; if you don't have one, you need model-free methods.
Self-check: What distinguishes a planning algorithm from a learning algorithm in RL?
Connects to: 6.13
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.