Dynamic Programming

Dive into Deep Learning · §14.2

Dynamic Programming
state & action values · Bellman expectation & optimality equations · contraction & certificates · policy iteration · risk-averse control

Why Local Distance Fails on Slippery Ice

Motivation & Mental Model

On calm ice, following the 6-move shortest path always reaches the goal; on slippery ice, that same shortest-path policy succeeds in only 4.5\% of episodes:

  • Coupled multistage decisions: At cell 9, right steps closer to the goal on calm ice, but on slippery ice it lands in hole 5 one time in three.
  • Safety vs. delay: Down never enters hole 5, yet slides sideways into cell 8 or 10 two times in three.
  • Bellman’s core insight: We cannot rank actions by one-step distance; we must score each cell by the total future return still achievable from it.

State-Value and Action-Value Functions

Scoring States and Commands

V^\pi(s_0) = \mathbb{E}_{\pi, P}\Big[\sum_{t=0}^{\infty} \gamma^t r(s_t, a_t)\Big]

  • Interpretation on FrozenLake: V^\pi(s) is the probability of reaching the goal from s, weighted by \gamma^t for arrival step t.
  • Action value Q^\pi(s, a): Commits to action a at step 0, then follows \pi thereafter, satisfying V^\pi(s) = \sum_a \pi(a \mid s) Q^\pi(s, a).

Bellman Expectation Equations and Tensor Backup

Recursive One-Step Lookahead

Splitting a trajectory after its first step and invoking the Markov property turns the infinite-horizon sum into a coupled linear system across neighboring states:

V^\pi(s) = \sum_{a \in \mathcal{A}} \pi(a \mid s)\Big[r(s, a) + \gamma \sum_{s' \in \mathcal{S}} P(s' \mid s, a)\,V^\pi(s')\Big]

  • The one-step backup bracket: For any value vector \mathbf{V} \in \mathbb{R}^{|\mathcal{S}|}, the bracketed lookahead across all (s, a) pairs is a single matrix-vector product:
def backup(self, V):
    """Q(s, a) = r(s, a) + gamma * sum_{s'} P(s'|s, a) V(s') for every
    state-action pair: the bracket of the Bellman equations."""
    return self.r + self.gamma * self.P @ V

The Bellman Optimality Equations

Characterizing Optimal Play

V^*(s) = \max_{a \in \mathcal{A}} \Big[r(s, a) + \gamma \sum_{s' \in \mathcal{S}} P(s' \mid s, a)\,V^*(s')\Big]

  • Action-value optimality: Q^*(s, a) = r(s, a) + \gamma \sum_{s'} P(s' \mid s, a) \max_{a'} Q^*(s', a').
  • Model-based vs. model-free extraction: Extracting \pi^* from V^* requires a lookahead with P and r, whereas \pi^*(s) = \mathrm{argmax}_a Q^*(s, a) requires no model.

Visualizing Exact and Sampled Bellman Backups

Backup Tree Diagrams

Every Bellman equation assembles the value at a root node from the values one step below it:

  • Expectation vs. optimality (a–c): V^\pi and Q^\pi average over policy actions \pi(a \mid s), whereas the optimality operator replaces the action average with \max_a (drawn as an arc).
  • Sampled backup (d): When P is unknown (§14.3), the learner follows a single realized environment transition (blue) instead of summing over P(s' \mid s, a).

Value Iteration: Sweeping the Bellman Operator

Fixed-Point Iteration

The Bellman optimality operator \mathcal{T} maps any value table V to its best one-step lookahead (\mathcal{T}V)(s) = \max_a \big[r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)V(s')\big]:

def value_iteration(mdp, num_iters):
    """Sweep V <- max_a backup(V); return the whole history of iterates."""
    V, history = np.zeros(mdp.num_states), []
    for _ in range(num_iters):
        V = mdp.backup(V).max(axis=1)
        history.append(V)
    return np.array(history)
  • Fixed-point characterization: The optimal value table V^* satisfies V^* = \mathcal{T}V^*; value iteration starts from V_0 = \mathbf{0} and applies V_{k+1} = \mathcal{T}V_k repeatedly.

Wavefront Propagation on Calm Ice

Deterministic Shortest-Path Limit

When transitions are deterministic, value iteration propagates exact values backward from the goal one ring per sweep:

  • Closed-form calm values: A cell whose shortest path around the holes takes j moves has exact value V^*(s) = \gamma^{j-1}.
  • Finite termination in 6 sweeps: Sweep k finalizes all cells at distance k; the start cell (j = 6) stays at 0 for five sweeps and locks onto \gamma^5 = 0.774 on sweep 6.
  • Why slips require analysis: Stochastic slips create cycles (such as 14 \leftrightarrow 13), coupling all states together across infinitely many sweeps.

Contraction of the Bellman Operator in Sup Norm

Why Value Iteration Always Converges

In the sup norm \|V\|_\infty = \max_s |V(s)|, \mathcal{T} shrinks the gap between any two value tables by at least \gamma:

\|\mathcal{T}V - \mathcal{T}V'\|_\infty \leq \gamma\,\|V - V'\|_\infty

  • Proof in two inequalities: First, averaging over P(\cdot \mid s, a) cannot exceed \max_{s'} |V(s') - V'(s')|; second, |\max_a f(a) - \max_a g(a)| \leq \max_a |f(a) - g(a)|.
  • Geometric nested balls: Starting at distance r_0 = \|V_0 - V^*\|_\infty, sweep k lands inside the sup-norm square of radius \gamma^k r_0 around V^*.

Uniqueness, Convergence Rate, and Certificates

Four Consequences of Contraction

\|V_k - V^*\|_\infty \leq \frac{\gamma}{1 - \gamma}\,\|V_k - V_{k-1}\|_\infty

  1. Unique fixed point: V = \mathcal{T}V and V' = \mathcal{T}V' implies V = V' = V^*.
  2. Geometric decay: Error e_k \leq \gamma^k e_0 shrinks by \gamma per sweep.
  3. Observable stopping certificate: Bound true distance using consecutive iterates and horizon factor \gamma/(1-\gamma).

Calm vs. Slippery Optimal Values and Policies

Solving FrozenLake Exactly

Running value iteration on slippery FrozenLake answers the cell 9 question and reveals how drastically stochastic slips reshape optimal behavior:

  • Safety wins at cell 9: Q^*(9, \textrm{down}) = 0.375 beats Q^*(9, \textrm{right}) = 0.289; avoiding hole 5 is worth sliding sideways two times in three.
  • Lower values everywhere: Slips cut the start-state value V^*(s_0) from 0.774 to 0.180, and even cell 14 adjacent to the goal drops from 1.000 to 0.724.

V*(s0) = 0.1805, V*(13) = 0.5090
state 14: V* = 0.7237;  1/3 + gamma (V*(13) + V*(14)) / 3 = 0.7237
cell 9: Q*(9, a) for a = <, v, >, ^: [0.247 0.375 0.289 0.213]

Empirical Convergence vs. Stopping Rules

Certifying Accuracy

Comparing true distance \|V_k - V^*\|_\infty against the a priori bound \gamma^k e_0 and the observable certificate highlights a common stopping pitfall:

  • Stopping on raw change is premature: Stopping when \|V_k - V_{k-1}\|_\infty \leq 10^{-6} halts at sweep 128, where true error is still 1.1 \times 10^{-5} (11\times above tolerance).
  • Certificate reliability: Waiting for \frac{\gamma}{1-\gamma}\|V_k - V_{k-1}\|_\infty \leq 10^{-6} halts at sweep 164, just 6 sweeps after the true error crosses 10^{-6} at sweep 158.

Policy Evaluation: Sweeps vs. Direct Linear Solve

Scoring a Fixed Policy

  • Linear Bellman system: Under a fixed policy \pi, V^\pi = r_\pi + \gamma P_\pi V^\pi with P_\pi(s' \mid s) = \sum_a \pi(a \mid s)P(s' \mid s, a).
  • Exact matrix solve: For \gamma < 1, V^\pi = (I - \gamma P_\pi)^{-1}r_\pi yields the uniform policy’s start value V(s_0) = 0.0078 in one O(|\mathcal{S}|^3) solve.

Policy Evaluation: Sweeps vs. Direct Linear Solve (Code)

Scoring a Fixed Policy

def policy_value(self, pi):
    """V^pi = (I - gamma P_pi)^{-1} r_pi exactly, for pi[s, a] the
    probability of action a at state s (one-hot rows: deterministic).
    Needs gamma < 1 here: from_gym's terminal states loop on themselves."""
    P_pi = np.einsum('sa,sat->st', pi, self.P)
    r_pi = (pi * self.r).sum(axis=1)
    return np.linalg.solve(np.eye(self.num_states) - self.gamma * P_pi,
                           r_pi)

print(f'V(s0) for the uniformly random policy, solved exactly: '
      f'{mdp.policy_value(uniform)[0]:.4f}')
V(s0) for the uniformly random policy, solved exactly: 0.0078

Policy Improvement and Policy Iteration

Howard’s Monotone Improvement Loop

Acting greedily with respect to V^\pi via \pi'(s) = \mathrm{argmax}_a Q^\pi(s, a) guarantees monotone improvement V^{\pi'}(s) \geq V^\pi(s) at every state:

pi, num_outer = uniform, 0
while True:
    V = mdp.policy_value(pi)                           # evaluate pi exactly
    Q = mdp.backup(V)
    num_outer += 1
    if (Q.max(axis=1) <= V + 1e-12).all():             # greedy gains nothing:
        break                                          # pi is optimal
    pi = np.eye(mdp.num_actions)[Q.argmax(axis=1)]     # improve
assert np.abs(V - V_star).max() < 1e-12
  • Proof via monotonicity: Greediness ensures \mathcal{T}^{\pi'}V^\pi = \mathcal{T}V^\pi \geq \mathcal{T}^\pi V^\pi = V^\pi; applying the monotone operator \mathcal{T}^{\pi'} repeatedly gives V^\pi \leq (\mathcal{T}^{\pi'})^k V^\pi \to V^{\pi'}.
  • Tie-safe termination: Stop when \max_a Q^\pi(s, a) \leq V^\pi(s) + \varepsilon everywhere, rather than checking if argmax indices changed (which can cycle on tied actions like cell 6).

Generalized Policy Iteration (GPI)

Interleaving Evaluation and Improvement

Policy iteration and value iteration are two extremes of Generalized Policy Iteration, which alternates value evaluation steps toward V^\pi with greedy improvement steps toward \textrm{greedy}(V):

  • Policy iteration: Completes exact evaluation (V = V^\pi) before each greedy step; on FrozenLake, the very first greedy step on the uniform policy’s values already yields \pi^* (2 solves total).
  • Value iteration: Takes a single evaluation sweep before improving; while certifying V^* takes 164 sweeps (10{,}496 backups), its greedy policy locks onto \pi^* by sweep 14 (896 backups).

Slip-Aware Optimum Beats Shortest Path 16 to 1

Exact vs. Monte Carlo Success Rates

Evaluating policies over 100 sweeps at \gamma = 1 gives the exact probability of reaching the goal within Gymnasium’s 100-step limit, matching 2,000-episode Monte Carlo rollouts:

     slip-aware optimum: goal within 100 steps 0.730 exactly, 0.736 in 2000 episodes
   shortest-path policy: goal within 100 steps 0.045 exactly, 0.046 in 2000 episodes
uniformly random policy: goal within 100 steps 0.014 exactly, 0.010 in 2000 episodes
  • Dramatic survival gap: The slip-aware optimal policy \pi^* reaches the goal in 73.0\% of episodes, compared with 4.5\% for the calm-ice shortest path and 1.4\% for random play.

Why the Optimal Policy Walks Away from the Goal

Risk Analysis Across Cells

Solving (I - P_\pi^\top)\,\mathbf{v} = \mathbf{e}_{s_0} for expected cell visits before termination reveals exactly where episodes fall into holes:

     pi*: P(falls into a hole) 0.22, from 6: 0.22
shortest: P(falls into a hole) 0.96, from 4: 0.31, 1: 0.31, 8: 0.13, 6: 0.08, 3: 0.06, 10: 0.05
  • Wall-bouncing as a shield: In five cells (0, 1, 3, 4, 14), \pi^* commands into a wall so the intended direction stays put and both perpendicular slips stay away from holes.
  • Pointing away from the goal: In four cells (2, 6, 8, 10), \pi^* points away from the goal, reducing one-step hole risk to 0 everywhere except cell 6 (flanked by holes 5 and 7), where all 22\% of its falls occur.

How Naive Approach Bonuses Corrupt Optimal Play

Reward Shaping Verification

Using value iteration on the shaped MDP \tilde{r}(s, a) = r(s, a) + b \sum_{s'} P(s' \mid s, a)\mathbf{1}(\ell(s') < \ell(s)) proves that naive progress bonuses break \pi^* on slippery ice:

bonus 0.3: at s=14 goes <, shaped V(0) 2.15, V(13) 1.71, V(14) 1.52; true V(0) 0.000
bonus 0.1: at s=14 goes v, shaped V(0) 0.79, V(13) 0.87, V(14) 0.94; true V(0) 0.115
bonus 0.0: at s=14 goes v, shaped V(0) 0.18, V(13) 0.51, V(14) 0.72; true V(0) 0.180
  • Catastrophic looping (b = 0.3): The shaped optimum commands left (<) at cell 14 to shuttle back to cell 13 and farm the bonus, earning shaped value 2.15 but 0.000 true goal value.
  • Potential-based invariance (Ng et al., 1999): Shaping via \tilde{r} = r + \gamma\Phi(s') - \Phi(s) shifts every policy’s value by identical -\Phi(s) (\tilde{V}^\pi = V^\pi - \Phi), leaving \pi^* invariant.

Concept Check: Bellman Equations and Contraction

Check Your Understanding

Work through these three questions on dynamic programming:

  1. Bellman equation at cell 14: Cell 14 lies left of the goal on the bottom wall. If \pi commands down at cell 14, write the Bellman expectation equation for V^\pi(14) in terms of V^\pi(13) and V^\pi(14).
  2. Contraction & certificates: If \gamma = 0.95 and consecutive value-iteration sweeps satisfy \|V_k - V_{k-1}\|_\infty = 10^{-5}, what upper bound does the certificate place on \|V_k - V^*\|_\infty?
  3. Action values vs. state values: Once we have converged to the optimal tables, why can an agent act optimally from Q^* without knowing P(s' \mid s, a), whereas acting from V^* still requires P?

Answers:

  1. Commanding down hits the bottom wall (staying at 14), slips left to 13, or slips right into the goal (reward 1, value 0) with probability 1/3 each: V^\pi(14) = \frac{1}{3} + \frac{\gamma}{3}[V^\pi(13) + V^\pi(14)].
  2. By the certificate inequality, \|V_k - V^*\|_\infty \leq \frac{\gamma}{1-\gamma}\|V_k - V_{k-1}\|_\infty = 19 \times 10^{-5} = 1.9 \times 10^{-4}.
  3. Because Q^*(s, a) already averages over the transition distribution P(\cdot \mid s, a), greedy extraction is just \mathrm{argmax}_a Q^*(s, a), whereas V^* requires computing r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)V^*(s').

Summary: Dynamic Programming Methods

Key Takeaways

Method / Operator Mathematical Update Computational Cost & Guarantee
Bellman expectation \mathcal{T}^\pi (\mathcal{T}^\pi V)(s) = \sum_a \pi(a \mid s)[r + \gamma \sum_{s'} P V(s')] Linear \gamma-contraction; fixed point V^\pi = (I - \gamma P_\pi)^{-1}r_\pi
Bellman optimality \mathcal{T} (\mathcal{T}V)(s) = \max_a [r(s, a) + \gamma \sum_{s'} P(s' \mid s, a)V(s')] Nonlinear \gamma-contraction in \|\cdot\|_\infty; unique fixed point V^*
Value iteration V_{k+1} = \mathcal{T}V_k from V_0 = \mathbf{0} O(|\mathcal{S}|^2|\mathcal{A}|) per sweep; error \leq \frac{\gamma}{1-\gamma}\|V_k - V_{k-1}\|_\infty
Policy iteration Solve V^{\pi_k} = \mathcal{T}^{\pi_k}V^{\pi_k}, set \pi_{k+1} = \mathrm{argmax}_a Q^{\pi_k} O(|\mathcal{S}|^3) per exact solve; converges in 2 outer rounds on Lake
Potential shaping \tilde{r}(s, a, s') = r(s, a) + \gamma\Phi(s') - \Phi(s) Shifts \tilde{Q}^*(s, a) = Q^*(s, a) - \Phi(s), preserving \pi^* exactly