Markov decision processes, returns and the Bellman equations
Before this lesson: reading sums and indices (foundations 02); probability and expectation (foundations 08, probability 02); conditional expectation and the law of total expectation (probability 04); the matrix inverse (linear algebra 03); the -norm, only for one proof (linear algebra 11). Time: about 60 minutes, plus the notebook.
Why this matters #
Every RL method estimates one of two things: how good a state is under a given policy (), or how good it is under the best policy (). The Bellman equations define these two objects as one-step recursions. Later methods are sample-based versions of the same equations: TD learning and Q-learning (lessons 04 and 05), DQN (lesson 06), the critic in actor-critic methods (lesson 08), and the value model in PPO for language models (lesson 09). If you know the exact version, you can see what each approximation gives up.
1. Predict first #
2. The picture #
The agent–environment loop #
Time runs in steps . At step :
- the agent sees the state ;
- it picks an action ;
- the environment gives a reward (a number) and moves to the next state .
The rule that picks actions is the policy . One run from a start state to an end is an episode. Four examples:
- A board game. State = the board, action = a move, reward = +1 for a win at the end, 0 otherwise.
- A robot. State = joint angles and speeds, action = motor torques, reward = progress minus energy.
- A recommender. State = the user's history, action = the item to show, reward = a click.
- A language model writing an answer. State = the prompt plus the tokens so far, action = the next token, reward = a score for the finished answer (lesson 09).
A small example: the robot vacuum #
We use one example through lessons 01 and 02. A robot vacuum has a high battery (state H) or a low battery (state L). It has two actions:
- clean: in H it earns 2, then stays in H or drops to L, with probability ½ each. In L it earns 1 and stays in L.
- charge: it earns 0 and moves to H.
Should the robot clean in L (earn 1 now) or charge (earn 0 now, but more later)? To answer, we need the value of a whole future, not of one step.
Predict, then press Step. Before each step, guess the action (orange), the reward (aqua) and the next state. The table adds up . One episode gives one random return. Press Average 1000 episodes: the mean of many returns from H is close to the exact value (blue), which comes from a linear solve (section 3). Switch the policy to "clean in H, charge in L" and compare the values.
Discounting: why the future counts less #
The robot runs forever, so the plain sum of rewards is infinite. The discount factor fixes this: a reward steps ahead counts times as much as a reward now. With reward 1 at every step, the geometric series gives
For this is (the answer to predict-first question 1). The number is the effective horizon: the agent looks about steps ahead. For close to 1, the weights with carry about 63% of the total weight, because (for it is 65%).
Move . The aqua bars are the weights . The blue curve adds them up and approaches (the violet line). The dashed line marks the effective horizon . Notice that looks 100 steps ahead, ten times more than .
An episode gives the rewards , , and then ends. With , what is the return ?
. The answer forgets the discount. The answer uses instead of for the reward two steps ahead.
3. Definitions and main results #
Markov decision processes #
Definition (finite MDP). A finite Markov decision process is a tuple :
- is a finite set of states and a finite set of actions;
- is the transition probability: the probability that the next state is when the agent takes action in state ;
- is the expected reward for taking action in state ;
- is the discount factor.
The Markov property says: the next state and the reward depend on the past only through the current pair . In plain words, the state contains everything about the past that matters for the future. If it does not (for example, a single camera frame without the speed of a ball), you must put more into the state (for example, the last four frames).
Episodic and continuing tasks. In an episodic task, every episode ends in a terminal state. After a terminal state there are no more rewards, so its value is 0. A game is episodic. In a continuing task, the interaction goes on forever, like the robot vacuum. Continuing tasks need . Episodic tasks may use .
Returns #
Definition (return). The return from step is the discounted sum of the future rewards:
It is also called the reward-to-go. Take out the first term, and the rest is times the return from step :
This return recursion is the seed of every Bellman equation. It also gives a fast way to compute all returns of an episode : start from and go backwards, , , and so on. That is steps instead of .
If the rewards are bounded, , and , then : the return is always a finite number.
Policies and value functions #
A policy gives the probability of action in state . A deterministic policy picks one action per state; we write it . In this lesson policies are stationary: they depend on the current state only, not on the time or the past.
Definition (value functions). For a policy :
The state-value function is the expected return when you start in and follow . The action-value function is the expected return when you start in , take action first (whatever says), and follow after that. The expectation is over both sources of randomness: the policy's choices and the environment's transitions.
The advantage says how much better action is than the policy's average action in . Policy-gradient methods use it (lesson 07).
Two links between and .
Proof.
- First link. By the law of total expectation, average over the first action: . The inner expectation is .
- Second link. Use and linearity: . The first term is .
- Average the second term over the next state: .
- By the Markov property, once is known, the future does not depend on or . So the last expectation is .
As a consequence, the advantages average to zero under the policy: .
You want to compare "clean now, then follow " with "charge now, then follow " in state L. Which quantity answers this directly?
fixes the first action and then follows . averages over the actions of , so it cannot compare them. The reward alone ignores the future: charging earns 0 now but gives a full battery.
The Bellman expectation equation #
Put the second link into the first. The result is the Bellman expectation equation:
In words: the value of is the average, over the policy's action and the environment's next state, of "reward now plus times the value of the next state". A backup diagram draws this: the state at the top, the actions below it, the next states at the bottom. The value flows up from the bottom ("is backed up").
Move the sliders to change the policy. The orange edges are the actions with probabilities ; the aqua labels are the transition probabilities and rewards; the blue numbers are the values. Each is "reward now plus times the average next value", and is the -average of the values. Then switch to max to see the optimality equation: the average over actions becomes a max (the arc).
Matrix form. Average the reward and the transitions over the policy:
is the transition matrix of the Markov chain that the policy creates (row is the distribution of the next state), and is the expected reward in each state. With these, the Bellman equation for all states at once is
This is a linear system with equations and unknowns. One call to a linear solver gives the values of all states. It costs .
Theorem (the system has exactly one solution). If , then is invertible, and
Proof.
- Each row of has entries that sum to at most 1. The -norm of a matrix is its largest absolute row sum (linear algebra 11), so and .
- So the partial sums converge: the terms are bounded by a geometric series. Call the limit .
- Multiply out (the middle terms cancel): .
- Let . The right side tends to , because . So , and is the inverse.
The series has a direct meaning. is the expected reward at step when you start in . So is the expected discounted sum of rewards: exactly the definition of .
The 4×4 gridworld of Sutton and Barto (Example 4.1) shows this. The two aqua corners are terminal. Every step gives reward , and , so is the expected number of steps to reach a corner.
Click a cell to change its action (random, then ↑, →, ↓, ←, then random again). The values are recomputed by one linear solve; darker blue means a higher value. For the random policy, the cell next to a corner has : on average a random walk needs 14 steps. The side panel shows the backup of the selected cell: is the -average of the values. Now make two neighbouring cells point at each other: those two states never end, so their value is , and so is the value of every state from which the random policy can walk into them.
In a continuing task with , every row of sums to 1. Why does the linear solve for fail?
Rows that sum to 1 mean , so is in the null space of . The returns are sums of infinitely many undiscounted rewards, so they are infinite or undefined. Whether itself is invertible does not matter. The Neumann series needs , which fails for .
Optimal values and the Bellman optimality equations #
Definition (optimal value functions). and . A policy is optimal if in every state .
The best first action gives the best value, and after the first step you should act optimally again. This gives the Bellman optimality equations:
The links are now and . The max sits inside: it is over the action in the current state, and the average over next states stays an average. The environment is not on your side or against you; only your own choice is maximised.
Lesson 02 proves that for the optimality equation has exactly one solution, and that this solution is . Here we use that fact for the main consequence.
Theorem (a greedy policy with respect to is optimal). Let in every state. Then . So every finite discounted MDP has an optimal policy that is deterministic and stationary, and it is optimal in all states at once.
Proof.
- By the choice of : .
- Read this as a statement about the deterministic policy : the vector solves , the Bellman expectation equation of .
- That linear system has exactly one solution, (previous theorem). So .
Note what you need for this: , or together with the model . With alone you cannot pick the action, because needs the model.
For the robot vacuum with the random policy ( in both states), and (). Is the greedy policy with respect to these values optimal?
Compute . In L: clean gives and charge gives , so the greedy action is clean. In H: clean gives and charge . Only greedy with respect to (or ) is guaranteed optimal. Greedy with respect to is at least as good as (lesson 02) but may need more improvement steps.
Linear versus nonlinear. For a fixed policy, the action probabilities are constants, so appears linearly and one solve is enough. In the optimality equation, the max over actions depends on itself. A max of linear functions is piecewise linear, not linear, so there is no single linear solve. Lesson 02 solves it with value iteration, policy iteration or a linear program.
4. Worked example #
The robot vacuum, , states ordered (H, L).
(a) Evaluate "always clean" by hand. The policy is .
- In L, cleaning earns 1 and stays in L: , so and .
- In H, cleaning earns 2 and goes to H or L with probability ½: . So and .
(b) The same with the linear system.
The second row gives , so . The first row gives , so . The same numbers.
Under "always clean", and (). Predict : charge once in L, then clean as usual.
Charging earns 0 and moves to H for sure, so . The answer uses , the wrong next state. The answer forgets the discount. The answer is itself, the value of cleaning.
(c) from : is charging in L better? Use :
- ;
- .
So : charging once in L, then cleaning as usual, beats the policy. In H, , so cleaning stays better there.
(d) Evaluate "clean in H, charge in L". Now L charges and moves to H:
- .
- .
- So , , and .
Both values went up, in both states.
(e) Check the optimality equation. For :
- H: ✓
- L: ✓
In exact fractions, and . The equation holds in both states, so , and the greedy policy "clean in H, charge in L" is optimal.
Answers to section 1. (1) . (2) For a fixed policy, the Bellman equation is linear: one solve. For the best policy, the max over actions makes it nonlinear (piecewise linear); lesson 02 solves it. (3) Charge: .
5. In code #
NumPy checks the worked example. The notebook has these cells and the exercises.
import numpy as np
gamma = 0.9
# P[s, a, s'] and R[s, a]; states (H, L), actions (clean, charge)
P = np.zeros((2, 2, 2))
P[0, 0] = [0.5, 0.5]; P[0, 1] = [1, 0]
P[1, 0] = [0, 1]; P[1, 1] = [1, 0]
R = np.array([[2.0, 0.0], [1.0, 0.0]])
def evaluate(pi): # pi[s, a]
P_pi = np.einsum("sa,sat->st", pi, P) # Markov chain of the policy
r_pi = (pi * R).sum(axis=1)
return np.linalg.solve(np.eye(2) - gamma * P_pi, r_pi)
always_clean = np.array([[1.0, 0.0], [1.0, 0.0]])
V = evaluate(always_clean)
print(V, 130 / 11) # [11.818 10. ] 11.818
Q = R + gamma * P @ V # Q[s, a] = R + gamma * sum_s' P V
print(Q) # [[11.818 10.636] [10. 10.636]]
smart = np.array([[1.0, 0.0], [0.0, 1.0]]) # clean in H, charge in L
V_star = evaluate(smart)
print(V_star, 400 / 29, 360 / 29) # [13.793 12.414] 13.793 12.414
print((R + gamma * P @ V_star).max(axis=1)) # [13.793 12.414]: the optimality equation holds
P @ V multiplies the last axis of P (the next state) with V, so it is
for every pair at once.
6. Where it shows up #
- Critics and value models. The critic in actor-critic methods, the value head in PPO and the value model in PPO-based RLHF are trained to satisfy the Bellman expectation equation from samples (lessons 08 and 09).
- Q-learning and DQN learn from samples of the Bellman optimality equation (lessons 05 and 06).
- Advantages. Policy-gradient methods push up actions with (lesson 07).
- Language models. Generating an answer is an episodic MDP: tokens are actions, and the reward comes at the end. Post-training usually uses , which is fine because every answer has a finite length.
- Science and engineering. Optimal stopping, inventory control, energy storage and control of physical systems (for example the magnetic control of a tokamak plasma with deep RL, Degrave et al., Nature 2022) are MDPs. Small ones with a known model are solved exactly by the methods of lesson 02.
7. Common mistakes #
- The max in the wrong place. In the max is over the action, and the next states are still averaged with . It is not .
- Greedy from without a model. needs . Turning into needs and . This is why model-free methods learn , not .
- Mixing reward conventions. here is in Sutton and Barto. Fix one convention in your code.
- without termination. is singular when the policy never ends an episode.
- One return is not the value. A return is one random sample; is its expectation.
- versus . The greedy policy with respect to is not optimal in general; only greedy with respect to (or ) is.
8. Check yourself #
- Write in terms of , and in terms of .
Answer
and . - A reward of 1 arrives only at step 10 (all other rewards are 0), and . What is ?
Answer
. A reward ten steps ahead keeps about a third of its weight. - Why is the expectation equation linear but the optimality equation not?
Answer
For a fixed the action probabilities are constants, so appears linearly. In the max over actions depends on itself; a max of linear functions is piecewise linear, not linear. - Show that .
Answer
, by the first link and because the probabilities sum to 1. - Why does a finite discounted MDP always have a deterministic optimal policy?
Answer
The policy that is greedy with respect to is optimal in every state, and picking one maximising action per state gives a deterministic policy. - In the 4×4 gridworld with , the random policy has next to a terminal corner. What does mean?
Answer
Each step gives and there is no discount, so is the expected number of steps until the random walk reaches a terminal corner: 14 steps on average.
Name the five parts of a finite MDP.
: states, actions, transition probabilities , expected rewards , discount factor .
Write the return recursion.
, with at the end of an episode.
Define .
: the expected discounted return from when you follow .
Write in terms of .
.
Write in terms of .
.
Give the matrix form of the Bellman expectation equation and its solution.
, so .
Why is invertible for ?
The rows of are nonnegative and sum to at most 1, so and the Neumann series converges to the inverse.
Write the Bellman optimality equation for .
.
What is the effective horizon for ?
About steps.
Compute for the rewards with .
.
9. Interview angle #
- "What is the Bellman equation, and why does it have a unique solution?" The value is the reward now plus times the expected value of the next state: . For , is invertible (Neumann series), so there is exactly one solution.
- "What is the difference between and ? Why do model-free methods prefer ?" fixes the first action. To act greedily from you need the model to compute ; from you only need an argmax.
- "Why discount?" It makes infinite sums finite, sets an effective horizon , and (lesson 02) makes the Bellman operator a contraction. It also reduces variance in policy gradients (lesson 08).
- "How do you evaluate a policy in a small known MDP?" Build and , and solve : . Lesson 02 gives the iterative alternative.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
discounted_returnandreturns_to_go: one backward pass with .induced_chain: build and from the arraysP[s, a, s'],R[s, a],pi[s, a].policy_evaluation_linear: solve and check .- Monte Carlo check: simulate many episodes of the robot vacuum and compare the mean return with .
q_from_vandv_from_q: the two links, and a round trip on the 4×4 gridworld.
11. Watch and read #
- Richard Sutton and Andrew Barto, Reinforcement Learning: An Introduction, 2nd ed., free PDF: §3.1–3.6 (MDPs, returns, policies, value functions, Bellman equations). Note the convention.
- OpenAI Spinning Up, Part 1: Key Concepts in RL: a short, precise summary of the same definitions.
- Alekh Agarwal, Nan Jiang, Sham Kakade, Wen Sun, Reinforcement Learning: Theory and Algorithms, free PDF: chapter 1 (MDPs, Bellman equations) for a compact, rigorous version.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.