Markov Decision Processes

Dive into Deep Learning · §14.1

Markov Decision Processes
states, actions, kernel & reward · discounted return & horizon · termination vs. truncation · state augmentation · potential-based shaping · the verifier task

Acting Under Uncertainty: The Cell 9 Dilemma

Motivation & Mental Model

Before we can optimize decisions over time, we must specify what the agent knows, what it can command, and how stochastic transitions unfold:

  • Slippery 4×4 grid: Starting at cell 0 (S), the agent seeks the goal at cell 15 (G, reward +1) while avoiding four terminal holes (H).
  • Stochastic transitions: Any command moves in the intended direction with probability 1/3 and in each perpendicular direction with probability 1/3.
  • The trade-off at cell 9: Left, right, and up each slip into hole 5 with probability 1/3; only down avoids the hole, at the cost of sliding sideways two times in three.

The Markov Decision Process Tuple

Mathematical Formulation

\textrm{MDP}: \quad (\mathcal{S}, \mathcal{A}, P, r)

  • States \mathcal{S} and actions \mathcal{A}: On FrozenLake, |\mathcal{S}| = 16 cell indices and |\mathcal{A}| = 4 directional commands.
  • Transition kernel P(s' \mid s, a): Conditional landing probabilities satisfying \sum_{s'} P(s' \mid s, a) = 1.
  • Expected reward r(s, a): Immediate reward averaged over landing states, r(s, a) = \sum_{s'} P(s' \mid s, a)\,\rho(s, a, s').

Reading the Transition Kernel from Gymnasium

Simulator Representation

Gymnasium exposes the tabular transition kernel as a nested dictionary env.unwrapped.P[s][a] of (probability, next_state, reward, terminated) tuples:

env = gym.make('FrozenLake-v1', is_slippery=True)
LEFT, DOWN, RIGHT, UP = 0, 1, 2, 3
ARROWS = '<v>^'                        # one glyph per action, for printing
env.unwrapped.P[9][DOWN]
[(0.33333333333333337, 8, 0, False),
 (0.3333333333333333, 13, 0, False),
 (0.33333333333333337, 10, 0, False)]

Commanding down (1) from state 9 branches into three equally likely outcomes (cells 8, 13, and 10), each with probability 1/3 and immediate reward 0.0.

Vectorizing the MDP into Dense Tensors

Array Representation

  • Dense tensor packing: TabularMDP.from_gym packs P[s, a, s'] into shape (16, 4, 16) and r[s, a] into shape (16, 4) for matrix backups.
  • Wall-bounce accumulation: Multiple slips landing on the same boundary cell accumulate via P[s, a, s_next] += p.
gamma = 0.95
mdp = TabularMDP.from_gym(env, gamma)
print(mdp.P[9, DOWN])
[0.         0.         0.         0.         0.         0.
 0.         0.         0.33333333 0.         0.33333333 0.
 0.         0.33333333 0.         0.        ]

Verifying Kernel Normalization and Sparse Rewards

Model Sanity Checks

Two invariants confirm the array construction: every (s, a) slice of P sums to 1, and r[s, a] is nonzero only where a single step can enter the goal cell 15:

largest |row sum - 1|: 0.0e+00
r(s=14, a=v) = 0.333
r(s=14, a=>) = 0.333
r(s=14, a=^) = 0.333
  • Boundary reflection: At corner cells, two perpendicular slips can hit walls and stay put, accumulating 2/3 probability on the current cell.
  • Expected reward at cell 14: Commanding down, right, or up from cell 14 enters goal cell 15 with probability 1/3, giving expected reward r(14, a) = 1/3, while left never reaches the goal.

Trajectories, Policies, and Sampled Rollouts

Agent-Environment Interaction

A stochastic policy \pi(a \mid s) defines action probabilities at each state, generating a random trajectory \tau = (s_0, a_0, r_0, s_1, a_1, r_1, \ldots):

t= 0  s= 0  a=>  s'= 0  r=0
t= 1  s= 0  a=v  s'= 0  r=0
t= 2  s= 0  a=<  s'= 4  r=0
t= 3  s= 4  a=^  s'= 4  r=0
t= 4  s= 4  a=<  s'= 4  r=0
t= 5  s= 4  a=v  s'= 8  r=0
t= 6  s= 8  a=>  s'= 9  r=0
t= 7  s= 9  a=^  s'=10  r=0
t= 8  s=10  a=>  s'=11  r=0
terminated=True, truncated=False, total reward=0
  • Realized vs. expected transitions: At t=0 the command right slips into the top wall and leaves the agent at s'=0; at t=8 the agent enters hole 11 (terminated=True).

Discounted Return and Geometric Tail Bounds

The Optimization Objective

R(\tau) = \sum_{t=0}^{\infty} \gamma^t r_t, \qquad \Big|\sum_{t \geq k} \gamma^t r_t\Big| \leq \frac{\gamma^k\,r_{\max}}{1 - \gamma}

  • Finite objective: Whenever |r_t| \leq r_{\max} and \gamma \in [0, 1), the infinite sum converges and its tail beyond step k shrinks as \gamma^k.
  • Uniformly optimal policy: Every finite MDP with \gamma < 1 admits a deterministic stationary policy \pi^*(s) optimal from all start states.

The Effective Planning Horizon

How Far Ahead Discounting Looks

The discount factor sets an effective horizon of H_{\textrm{eff}} = 1/(1 - \gamma) steps over which rewards carry substantial weight:

  • Exponential decay scale: For \gamma near 1, weights decay by a factor of \gamma^{1/(1-\gamma)} \approx e^{-1} \approx 0.368 per effective horizon.
  • 95% weight window: For a constant reward stream, 95\% of total discounted weight lies within \lceil\ln(0.05)/\ln\gamma\rceil \approx 3\,H_{\textrm{eff}} steps.
  • Chapter benchmark (\gamma = 0.95): Sets a 20-step effective horizon, with 95\% of weight inside 59 steps.

Horizon Decay Across Discount Factors

Numerical Comparison

Comparing four discount factors shows how strongly \gamma prices the 6-move calm-ice shortest path (whose goal reward arrives at index t = 5):

 gamma  horizon 1/(1-gamma)  t: gamma^t < 0.05  gamma^5
   0.5                    2                  5    0.031
   0.9                   10                 29    0.590
  0.95                   20                 59    0.774
  0.99                  100                299    0.951

A short-sighted discount (\gamma = 0.5) values the 6-move goal at only \gamma^5 = 0.031, whereas \gamma = 0.95 values it at 0.774; smaller \gamma trades long-range optimality for lower planning sensitivity.

True Termination vs. Time-Limit Truncation

Systems Pitfall at Episode Boundaries

Gymnasium distinguishes physical episode endings (terminated=True) from artificial clock cutoffs (truncated=True at 100 steps):

  • Terminated (s_8 \in \textrm{Holes}): The environment process has truly ended; future return from s_8 is V(s_8) = 0, so the final target is y_7 = r_7.
  • Truncated (t = 100 cutoff): Recording stopped on safe ice; the unrecorded continuation is worth V(s_{100}) \neq 0, requiring y_{99} = r_{99} + \gamma V(s_{100}).

Absorbing Terminal States and Undiscounted Tasks

Boundary Conventions

Representing terminal states consistently keeps matrix equations and finite-horizon rollouts aligned:

  • Absorbing-state convention: TabularMDP models each hole and the goal as a self-loop (P(s \mid s, a) = 1) with r(s, a) = 0, ensuring every row of P sums to 1 without altering trajectory returns.
  • When \gamma = 1 is well-defined: If every policy terminates in finitely many steps, or if total reward is bounded above (FrozenLake pays at most 1 per episode), undiscounted returns remain finite.
  • When \gamma = 1 diverges: Adding a +0.05 per-step survival bonus makes the cyclic always-up policy collect infinite undiscounted return, forcing continuing tasks to use \gamma < 1.

The Markov Property and State Augmentation

Designing the State Representation

s_{t+1} = f(s_t, a_t, s_{t-1}) \implies \tilde{s}_t = (p_t, v_t)^\top

  • Why position alone fails: For a vehicle driven by acceleration a_t, next position p_{t+1} depends on velocity v_t \propto p_t - p_{t-1}.
  • State augmentation: Enlarging the state to \tilde{s}_t = (p_t, v_t)^\top (or appending remaining time H - t) restores a first-order Markov kernel.

Partial Observability, Belief States, and Memory

When the Full State Is Hidden

  • Exact Bayesian belief state: Tracking \beta_t(s) = \Pr(s_t = s \mid o_{0:t}, a_{0:t-1}) restores a continuous Markov state via Bayes’ rule.
  • Frame stacking in control: Stacking the 4 most recent video frames lets filters infer velocities from finite differences.
  • Recurrent and attention contexts: Modern agents and LLMs attend over the trajectory prefix (o_0, a_0, \ldots, o_t).

Reward Hacking: The Looping Progress Bonus

Reward Design Pitfall

Because FrozenLake’s terminal reward is sparse, suppose we add +0.3 whenever a step reduces the Manhattan distance \ell(s) to the goal:

\tilde{r}(s, a, s') = r(s, a) + 0.3\,\mathbf{1}\big(\ell(s') < \ell(s)\big)

  • One-way incentive flaw: The bonus pays +0.3 for stepping closer (cell 13 \to 14, where \ell drops from 2 to 1) but charges 0 for stepping back (14 \to 13).
  • Cycling beats finishing: On calm ice at \gamma = 0.95, stepping from cell 14 into the goal earns 1 + 0.3 = 1.3 once, whereas shuttling 14 \leftrightarrow 13 forever earns 0.3 every second step: R_{\textrm{loop}} = 0.3\big(\gamma + \gamma^3 + \gamma^5 + \cdots\big) = \frac{0.3\,\gamma}{1 - \gamma^2} \approx 2.92 > 1.30

Potential-Based Reward Shaping Invariance

Safe Dense Rewards

\tilde{r}(s, a, s') = r(s, a) + \gamma\Phi(s') - \Phi(s)

  • Telescoping sum (Ng et al., 1999): With \Phi(s) = -0.3\,\ell(s), moving 13 \to 14 pays +0.315 while retreating 14 \to 13 charges -0.270.
  • Optimal policy preservation: Shuttling forever nets at most -\Phi(14) = +0.3, keeping the goal (1.3) ahead by +1.0.
  • Boundary condition: Enforce \Phi(s_{\textrm{term}}) = 0 at all terminal states.

Language Generation as a Collapsed One-Step MDP

From Token Trees to Contextual Bandits

Autoregressive language generation with a terminal answer checker simplifies the general MDP in two structural ways:

  • Token-level tree MDP: State s_t = (x, y_{<t}) is the prompt plus prefix tokens, action a_t = y_t is the next token, transitions deterministically append y_t, and the verifier scores only the completed response.
  • Collapsing to one step: Because transitions are deterministic, rewards arrive only at termination, and prefixes never repeat, the expected return depends only on the sequence probability \pi_\theta(y \mid x).
  • Contextual bandit equivalence: Prompt x \sim \mu_0 is the start state, the complete response y is a single macro-action, and the verifier score r(x, y) \in \{0, 1\} is the immediate reward.

The Verifier Task: Reference Policy vs. Ceiling

Second Running Benchmark

VerifierTask pairs 4 arithmetic prompts with 9 shared candidate responses (8 numbers plus the hedge “one of 4, 12, 64 or 81”) under a tabular softmax policy \pi(y \mid x) \propto \exp(\theta_{x,y}):

success of a response sampled from the reference: 0.062
  • Why the reference scores 0.062: With \theta_{\textrm{ref}} = 0 on the 8 numbers and -4 on the hedge, the reference assigns \approx 1/8 to the right answer on 2+2 and 3*4, and 0 on unsolvable 8*8 and 9*9 (averaging \approx 1/16 = 0.062 vs. the 0.500 ceiling).

Concept Check: MDP Structure and Reward Design

Check Your Understanding

Test your grasp of MDP modeling, truncation, and reward shaping:

  1. Markov state design: Why is a single video frame of Pong not a Markov state, and what minimal state augmentation restores the Markov property?
  2. Termination vs. truncation: If a 100-step time limit cuts an episode while the agent stands on cell 14, why is setting the continuation value to zero (done = terminated or truncated) a bug?
  3. Potential boundary condition: With \Phi(s) = -0.3\,\ell(s), why must we override \Phi(s) = 0 at the four holes before running episodic simulations?

Answers:

  1. One frame shows ball position but not velocity (direction and speed); stacking 2 consecutive frames provides finite-difference velocity and restores Markovianity.
  2. Cell 14 is adjacent to the goal with positive continuation value V(14) > 0; zeroing it on truncation falsely teaches the learner that cell 14 at step 100 is a worthless dead end.
  3. Without setting \Phi(\textrm{hole}) = 0, stopping at a hole leaves a terminal term \gamma^T\Phi(s_T) = -0.3\gamma^T\ell(s_T) < 0 that varies with hole location and fall time, distorting the optimal policy.

Summary: Markov Decision Processes

Key Takeaways

Concept Mathematical Form Role & Practical Takeaway
MDP tuple (\mathcal{S}, \mathcal{A}, P, r) Encodes state/action sets, transition kernel P(s' \mid s, a), and expected reward r(s, a)
Discounted return R(\tau) = \sum_{t=0}^{\infty} \gamma^t r_t Bounds infinite-horizon returns by r_{\max}/(1-\gamma) and sets horizon 1/(1-\gamma)
Termination vs. cut y_{T-1} = r_{T-1} + \gamma(1 - \textrm{term})V(s_T) Zero continuation only on true physical termination, never on clock truncation
Markov state P(s_{t+1} \mid s_t, a_t, s_{<t}) = P(s_{t+1} \mid s_t, a_t) Enforced by augmenting state with velocities, time remaining, or history context
Potential shaping \tilde{r} = r + \gamma\Phi(s') - \Phi(s), \Phi(\textrm{term}) = 0 Telescopes around cycles so dense progress signals never alter the optimal policy
Verifier task x \sim \mu_0,\; y \sim \pi_\theta(\cdot \mid x),\; r(x, y) Collapses deterministic-transition LLM generation into a one-step contextual bandit