Part I · Foundations of Sequential Decision-Making
4.Markov Decision Processes: The Formalism
“The Markov property recapitulates the idea of state — a state is a sufficient statistic for predicting the future.”
Chapter 3 removed state to isolate exploration. Now we put it back, and the whole subject changes character. Once an action influences what you face next, the value of an action must account for the future it leads to — and that self-reference, embraced rather than avoided, is the Bellman equation. This chapter derives it in full, proves the fixed-point machinery of Chapter 2 applies to it, and then confesses the thing most textbooks postpone: robots never see the state, so the honest formalism is a POMDP.
Foundation
The finite MDP tuple, returns and discounting, value functions, Bellman expectation and optimality equations derived in full, γ-contraction proofs, and the belief-MDP construction.
Conceptual
Rusty's warehouse as a formal object: click any cell to read its transition distribution, and watch the optimal policy respond to the model rather than to a hyperparameter.
Practical
The rl-core gym — Space, Env and Mdp traits — the abstraction every later chapter builds on, plus exact value solving by linear algebra.
After this chapter you can
- Write down a finite MDP and compute its dynamics, expected rewards, and returns from the four-argument function p(s′,r|s,a)
- Derive the Bellman expectation equations for v_π and q_π line by line, naming every step
- Derive the Bellman optimality equations and explain exactly where linearity dies
- Prove that both Bellman operators are γ-contractions, and cash the Chapter 2 theorem for existence and uniqueness
- Explain what a belief state is and why partial observability is the normal case in robotics, not the exception
- Recognize the same robot task as a different MDP depending on the action-space level you choose
4.1 The finite MDP
A finite Markov decision process is a tuple where and are finite sets of states and actions, is a discount factor, and the dynamics are captured by a single function
satisfying for every . Everything else is derived from it. Marginalizing the reward gives the state-transition probabilities,
and weighting by reward gives the expected immediate reward,
Note the indexing convention, inherited from Chapter 1: the reward arrives after action . It is a consequence, not a property of the state you were in.
Rusty's warehouse, fixed once for the rest of Part I. A grid with shelf blocks removed, leaving about 80 traversable cells. Four actions . Slip probability , split evenly between the two lateral directions. Rewards: for reaching the dock, per step, for bumping a shelf. Discount . Chapters 5, 6 and 7 use these exact numbers, so results are comparable across algorithms.
The warehouse as an MDP
ch04-mdp-editorClick any floor cell to read its dynamics. The heatmap shows v*, the arrows show the greedy policy π*.
Selected state
s = 0
v*(s)
-15.5
optimal value
p(s′, r | s, a = →)
| next s′ | reward r | probability |
|---|---|---|
| 1 | -1 | 0.80 |
| 12 | -1 | 0.10 |
| 0 (blocked) | -10 | 0.10 |
| sums to | 1.00 | |
q*(s, a) — one-step lookahead
The greedy action is the argmax — this is exactly the operation the Bellman optimality equation performs at every state.
4.2 Returns, and why we discount
The agent's goal is not to maximize immediate reward but the return — the accumulated reward from time onward:
For a continuing task this is an infinite sum, and we need it to be finite. If rewards are bounded by , the geometric series gives
which is finite exactly because . Discounting is not a modelling nicety; without it the objective may not be defined.
The single most useful property of the return is its recursion, obtained by factoring out of everything after the first term:
Everything that follows in this book is, in some sense, this one line taken seriously.
4.3 Value functions and the Bellman expectation equations
A policy is a distribution over actions in each state. The state-value function is the expected return from following it:
and the action-value function fixes the first action before following thereafter:
Now the derivation. Every step is either the return recursion, the tower property from Chapter 2, or the definition of expectation.
Theorem 4.1— Bellman expectation equation for v_π
For any policy and all ,
▸Proof
Start from the definition and substitute the return recursion :
Expand the expectation over the immediate randomness — which action chooses, and which the environment returns:
Two justifications are needed for that line. First, conditioning on inside the bracket is the tower property (Theorem 2.2): we average the return-from-next-step over where we land. Second, replacing with uses the Markov property — given , the past is irrelevant.
The inner expectation is by definition, giving the result.
The same argument applied to yields its twin:
This is a linear system. With unknowns and equations, we can write it in matrix form as and solve directly:
with the inverse guaranteed to exist by the Neumann-series argument from §2.6. For Rusty's 80-state warehouse this is a trivial linear solve. For a robot with a continuous state space it is hopeless, which is what drives Part II.
4.4 Optimality, and the moment linearity dies
Define a partial order on policies: if for all states. There always exists an optimal policy that is at least as good as every other, and all optimal policies share the same value functions:
The optimal value function satisfies a self-consistency condition of its own — but now with a maximum where the policy average used to be.
Theorem 4.2— Bellman optimality equations
The argument is that must equal the value of the best action available at , evaluated under optimal behaviour thereafter. If some action had a higher one-step-lookahead value, the policy that took it and then behaved optimally would beat — contradiction.
Two consequences follow immediately, and they are the reason this equation is worth its fame.
Greedy is optimal. Any policy that acts greedily with respect to is optimal. A one-step lookahead using already accounts for all future consequences, because that is what encodes. With it is even easier — no lookahead at all, just . This is why so much of RL is the pursuit of : get it, and the policy is free.
A deterministic optimal policy always exists for a finite MDP: pick any argmax at each state.
4.5 The contraction, at last
Chapter 2 built the fixed-point machinery. Here is what it was for.
Define the Bellman optimality operator on value functions by
and the policy-evaluation operator analogously with in place of the max. The Bellman equations say precisely that and are the fixed points of these operators.
Theorem 4.3— Both Bellman operators are γ-contractions in the sup norm
For any value functions ,
and likewise for .
▸Proof
Fix a state . We use the elementary inequality , which holds because the maximizer of one function is a feasible choice for the other.
using in the last step. The rewards cancel exactly because they do not depend on the value function. Taking the maximum over on the left gives the claim.
Now cash Chapter 2's theorem. The space of bounded value functions with the sup norm is complete, so Banach applies and delivers, at no additional cost:
- exists and is the unique fixed point of ;
- iterating converges to it from any starting point — including the all-zeros initialization every implementation uses;
- convergence is geometric at rate , with a computable error bound that tells you when to stop.
That last item is not decoration: it is the stopping rule for value iteration, and Chapter 5's dashboard displays it live.
4.6 The confession: robots never see the state
Everything above assumes the agent observes . Rusty does not. He has wheel encoders that drift, a lidar that returns noisy ranges, and no oracle telling him which cell he occupies.
The honest formalism is a partially observable MDP — an MDP plus an observation space and an observation model . The agent sees , never .
The standard repair is to maintain a belief , a distribution over states. It updates by Bayes' rule: after taking and observing ,
where the numerator predicts forward and reweights by the observation likelihood, and the denominator normalizes.
The remarkable fact is that the belief is Markov even though the observation is not: depends only on , and . So a POMDP is an MDP over beliefs — all the theory above still applies. The catch is that the belief space is continuous even when is finite, and solving POMDPs exactly is PSPACE-hard.
4.7 The same robot, different MDPs
One more idea before the code, because it reframes everything: the MDP is a modelling choice, not a property of the robot.
Tang and colleagues organize this along three axes. The action-space level may be low (joint torques), mid (task-space velocity commands), or high (temporally extended subroutines). The observation space may be a low-dimensional estimated state vector or raw high-dimensional sensing. The reward may be sparse or dense.
Each combination is a different MDP for the same physical task. Rusty at grid level — this chapter — has 80 states and four actions. Rusty at velocity level has a continuous state and continuous actions. Rusty at torque level, Chapter 13's territory, adds motor dynamics.
Author the warehouse
ch04-warehouse-editorWall off a corridor, move the dock, paint a slippery patch. Value iteration re-solves on every edit.
Click or drag across cells with the shelf tool selected. The orange path is a rollout of the current optimal policy.
Dock reachable
Yes
a path exists
Sweeps to converge
38.0
value iteration, θ = 1e−5
v* at the start
-15.5
expected discounted return
Rollout return
-3.00
21 steps
Free cells
76.0
32 shelves
Slippery cells
0
none painted
Optimal action, cell by cell
The arrows are argmax_a q*(s,a), recomputed from scratch after every edit. Nothing is cached and nothing is interpolated — this is the Bellman optimality equation solved on the warehouse you just drew.
Try this
- Trap the robot. Wall Rusty into a pocket and watch v* collapse to the step-cost floor everywhere inside it.
- Build a shortcut. Clear a shelf block and see how far the value change propagates from that one cell.
- Make a river. Paint a slippery line across the map, then raise the patch slip until the policy prefers the long way round.
/// A set an observation or action can be drawn from.
pub trait Space {
type Item;
fn contains(&self, x: &Self::Item) -> bool;
fn sample<R: rand::Rng>(&self, rng: &mut R) -> Self::Item;
}
pub struct Transition<S> {
pub next_state: S,
pub reward: f64,
pub done: bool,
}
/// The black-box view: you may sample the dynamics, never inspect them.
/// This is all a real robot ever offers.
pub trait Env {
type State: Clone;
type Action: Copy;
fn reset<R: rand::Rng>(&mut self, rng: &mut R) -> Self::State;
fn step<R: rand::Rng>(
&mut self,
state: &Self::State,
action: Self::Action,
rng: &mut R,
) -> Transition<Self::State>;
fn gamma(&self) -> f64;
}
/// The white-box view: the full distribution p(s′, r | s, a) is available.
/// Simulators can offer this; reality cannot.
pub trait Mdp: Env {
fn states(&self) -> &[Self::State];
fn actions(&self, state: &Self::State) -> &[Self::Action];
/// Every (next_state, reward, probability) triple, summing to 1.
fn transitions(
&self,
state: &Self::State,
action: Self::Action,
) -> Vec<(Self::State, f64, f64)>;
}4.8 Chapter bridge
The formalism is complete. An MDP is four objects; the return has a recursion; value functions satisfy Bellman equations; those equations are fixed-point conditions for operators that contract at rate ; and Banach hands us existence, uniqueness, and a convergent algorithm with a stopping rule.
We also admitted that the state is not observable, that solving the honest version is intractable, and that the MDP itself is something an engineer chooses rather than discovers.
Chapter 5 takes the algorithm Banach promised and makes it real. With and known, we can compute by iteration and watch value ripple outward from Rusty's dock — and we will find that evaluation and improvement, alternated, form a pattern so general that every remaining algorithm in this book is a variation on it.
- 01Foundation●●●Derive the marginals
From p(s′,r|s,a), derive expressions for p(s′|s,a), r(s,a), and r(s,a,s′). Then compute all three by hand for a slip cell of Rusty’s warehouse using the constants in §4.1.
- 02Foundation●●●The return bound is tight
Prove |G_t| ≤ R_max/(1−γ) and construct an MDP where the bound is attained exactly. What does that MDP look like physically?
- 03Foundation●●●Bellman for q_π
Carry out the derivation of the Bellman expectation equation for q_π in the same detail as Theorem 4.1, naming where the tower property and the Markov property are each used.
- 04Foundation●●●The max inequality
Prove the lemma used in Theorem 4.3: |max_a f(a) − max_a g(a)| ≤ max_a |f(a) − g(a)|. Where would the contraction proof fail without it?
- 05Conceptual●●●Find the risk-aversion threshold
In the MDP explorer, start at p_slip = 0 and increase it. Find the slip probability at which the optimal policy first stops hugging the shelves. Explain the trade-off in terms of the q-values shown for that cell.
- 06Conceptual●●●Horizon and reach
Set γ to 0.5, 0.9, and 0.99 in the explorer and record how many cells away from the dock the value function remains meaningfully non-zero. Compare against the effective horizon 1/(1−γ).
- 07Practical●●●Exact policy evaluation
Implement solve_v_pi using the matrix form v_π = (I − γP_π)⁻¹ r_π with nalgebra, and verify it satisfies the Bellman equation pointwise to 1e−10 with a property test over random MDPs.
- 08Practical●●●A POMDP wrapper
Write NoisyOdometryEnv: a wrapper that hides the true state and emits a noisy observation. Implement a discrete Bayes filter over cells, and measure how localization entropy evolves after a "kidnapping" that teleports Rusty without telling him.
References
Baseline references
- Sutton, R. S. & Barto, A. G. (2018). Reinforcement Learning: An Introduction. MIT Press, 2nd editionChapter 3 in full: §3.1 the agent–environment interface and the Markov property, §3.3 returns, §3.5 policies and value functions, §3.6 optimal value functions.
- Kober, J., Bagnell, J. A. & Peters, J. (2013). Reinforcement Learning in Robotics: A Survey. International Journal of Robotics Research 32(11)§1.3 and §2 — the state-as-sufficient-statistic framing, and why robotic state is never fully observed.
- Tang, C. et al. (2024). Deep Reinforcement Learning for Robotics: A Survey of Real-World Successes. Annual Review of Control, Robotics, and Autonomous Systems link§3.2 problem formulation — the action-space level, observation space, and reward-density axes used in §4.7.
Further reading & modern sources
- Bellman, R. (1957). Dynamic Programming. Princeton University PressThe origin of the principle of optimality and the equations that carry his name.
- Puterman, M. L. (1994). Markov Decision Processes: Discrete Stochastic Dynamic Programming. WileyThe definitive reference. Existence of optimal stationary deterministic policies, and the contraction analysis, in complete rigour.
- Kaelbling, L. P., Littman, M. L. & Cassandra, A. R. (1998). Planning and acting in partially observable stochastic domains. Artificial Intelligence 101(1–2)The belief-MDP construction of §4.6, and the classical algorithms for exact POMDP solution.
- Papadimitriou, C. H. & Tsitsiklis, J. N. (1987). The Complexity of Markov Decision Processes. Mathematics of Operations Research 12(3)The PSPACE-hardness result that explains why nobody solves POMDPs exactly on hardware.
