Type at least 2 letters. Enter opens the first result, Esc closes.

    Reinforcement Learning · Lesson 1 · MDPs and dynamic programming

    Markov decision processes, returns and the Bellman equations

    Beginner 60 min 4 interactive figures 3 videos Colab notebook

    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 ∞\infty-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 (VπV^\pi), or how good it is under the best policy (V∗V^*). 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 t=0,1,2,…t = 0, 1, 2, \dots. At step tt:

    1. the agent sees the state sts_t;
    2. it picks an action ata_t;
    3. the environment gives a reward rtr_t (a number) and moves to the next state st+1s_{t+1}.

    The rule that picks actions is the policy π\pi. 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.

    Interactive figure: loading…

    Predict, then press Step. Before each step, guess the action (orange), the reward (aqua) and the next state. The table adds up γtrt\gamma^t r_t. One episode gives one random return. Press Average 1000 episodes: the mean of many returns from H is close to the exact value Vπ(H)V^\pi(H) (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 γ∈[0,1)\gamma \in [0, 1) fixes this: a reward kk steps ahead counts γk\gamma^k times as much as a reward now. With reward 1 at every step, the geometric series gives

    1+γ+γ2+⋯=11−γ.1 + \gamma + \gamma^2 + \dots = \frac{1}{1 - \gamma}.

    For γ=0.9\gamma = 0.9 this is 1010 (the answer to predict-first question 1). The number 1/(1−γ)1/(1-\gamma) is the effective horizon: the agent looks about 1/(1−γ)1/(1-\gamma) steps ahead. For γ\gamma close to 1, the weights γk\gamma^k with k<1/(1−γ)k < 1/(1-\gamma) carry about 63% of the total weight, because γ1/(1−γ)≈e−1\gamma^{1/(1-\gamma)} \approx e^{-1} (for γ=0.9\gamma = 0.9 it is 65%).

    Interactive figure: loading…

    Move γ\gamma. The aqua bars are the weights γk\gamma^k. The blue curve adds them up and approaches 1/(1−γ)1/(1-\gamma) (the violet line). The dashed line marks the effective horizon k=1/(1−γ)k = 1/(1-\gamma). Notice that γ=0.99\gamma = 0.99 looks 100 steps ahead, ten times more than γ=0.9\gamma = 0.9.

    Quick check

    An episode gives the rewards r0=1r_0 = 1, r1=0r_1 = 0, r2=2r_2 = 2 and then ends. With γ=0.5\gamma = 0.5, what is the return G0G_0?

    3. Definitions and main results #

    Markov decision processes #

    Definition (finite MDP). A finite Markov decision process is a tuple (S,A,P,R,γ)(\mathcal S, \mathcal A, P, R, \gamma):

    • S\mathcal S is a finite set of states and A\mathcal A a finite set of actions;
    • P(s′∣s,a)P(s' \mid s, a) is the transition probability: the probability that the next state is s′s' when the agent takes action aa in state ss;
    • R(s,a)R(s, a) is the expected reward for taking action aa in state ss;
    • γ∈[0,1]\gamma \in [0, 1] is the discount factor.

    The Markov property says: the next state st+1s_{t+1} and the reward rtr_t depend on the past only through the current pair (st,at)(s_t, a_t). 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 γ<1\gamma < 1. Episodic tasks may use γ=1\gamma = 1.

    Returns #

    Definition (return). The return from step tt is the discounted sum of the future rewards:

    Gt=rt+γrt+1+γ2rt+2+⋯=∑k≥0γkrt+k.G_t = r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} + \dots = \sum_{k \ge 0} \gamma^k r_{t+k}.

    It is also called the reward-to-go. Take out the first term, and the rest is γ\gamma times the return from step t+1t+1:

    Gt=rt+γ(rt+1+γrt+2+…)=rt+γGt+1.G_t = r_t + \gamma \big(r_{t+1} + \gamma r_{t+2} + \dots\big) = r_t + \gamma G_{t+1}.

    This return recursion is the seed of every Bellman equation. It also gives a fast way to compute all returns of an episode r0,…,rT−1r_0, \dots, r_{T-1}: start from GT=0G_T = 0 and go backwards, GT−1=rT−1G_{T-1} = r_{T-1}, GT−2=rT−2+γGT−1G_{T-2} = r_{T-2} + \gamma G_{T-1}, and so on. That is TT steps instead of T2T^2.

    If the rewards are bounded, ∣rt∣≤rmax⁡|r_t| \le r_{\max}, and γ<1\gamma < 1, then ∣Gt∣≤rmax⁡/(1−γ)|G_t| \le r_{\max}/(1 - \gamma): the return is always a finite number.

    Policies and value functions #

    A policy π(a∣s)\pi(a \mid s) gives the probability of action aa in state ss. A deterministic policy picks one action per state; we write it π(s)\pi(s). 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 π\pi:

    Vπ(s)=Eπ[Gt∣st=s],Qπ(s,a)=Eπ[Gt∣st=s,at=a].V^\pi(s) = \mathbb E_\pi[G_t \mid s_t = s], \qquad Q^\pi(s, a) = \mathbb E_\pi[G_t \mid s_t = s, a_t = a].

    The state-value function Vπ(s)V^\pi(s) is the expected return when you start in ss and follow π\pi. The action-value function Qπ(s,a)Q^\pi(s, a) is the expected return when you start in ss, take action aa first (whatever π\pi says), and follow π\pi after that. The expectation is over both sources of randomness: the policy's choices and the environment's transitions.

    The advantage Aπ(s,a)=Qπ(s,a)−Vπ(s)A^\pi(s, a) = Q^\pi(s, a) - V^\pi(s) says how much better action aa is than the policy's average action in ss. Policy-gradient methods use it (lesson 07).

    Two links between VV and QQ.

    Vπ(s)=∑aπ(a∣s) Qπ(s,a)Qπ(s,a)=R(s,a)+γ∑s′P(s′∣s,a) Vπ(s′)\boxed{V^\pi(s) = \sum_a \pi(a \mid s)\, Q^\pi(s, a)} \qquad \boxed{Q^\pi(s, a) = R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V^\pi(s')}

    Proof.

    1. First link. By the law of total expectation, average over the first action: Eπ[Gt∣st=s]=∑aπ(a∣s) Eπ[Gt∣st=s,at=a]\mathbb E_\pi[G_t \mid s_t = s] = \sum_a \pi(a \mid s)\, \mathbb E_\pi[G_t \mid s_t = s, a_t = a]. The inner expectation is Qπ(s,a)Q^\pi(s, a).
    2. Second link. Use Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1} and linearity: Qπ(s,a)=E[rt∣s,a]+γ Eπ[Gt+1∣st=s,at=a]Q^\pi(s, a) = \mathbb E[r_t \mid s, a] + \gamma\, \mathbb E_\pi[G_{t+1} \mid s_t = s, a_t = a]. The first term is R(s,a)R(s, a).
    3. Average the second term over the next state: Eπ[Gt+1∣s,a]=∑s′P(s′∣s,a) Eπ[Gt+1∣st=s,at=a,st+1=s′]\mathbb E_\pi[G_{t+1} \mid s, a] = \sum_{s'} P(s' \mid s, a)\, \mathbb E_\pi[G_{t+1} \mid s_t = s, a_t = a, s_{t+1} = s'].
    4. By the Markov property, once st+1=s′s_{t+1} = s' is known, the future does not depend on sts_t or ata_t. So the last expectation is Eπ[Gt+1∣st+1=s′]=Vπ(s′)\mathbb E_\pi[G_{t+1} \mid s_{t+1} = s'] = V^\pi(s'). ■\blacksquare

    As a consequence, the advantages average to zero under the policy: ∑aπ(a∣s)Aπ(s,a)=Vπ(s)−Vπ(s)=0\sum_a \pi(a \mid s) A^\pi(s, a) = V^\pi(s) - V^\pi(s) = 0.

    Quick check

    You want to compare "clean now, then follow π\pi" with "charge now, then follow π\pi" in state L. Which quantity answers this directly?

    The Bellman expectation equation #

    Put the second link into the first. The result is the Bellman expectation equation:

    Vπ(s)=∑aπ(a∣s)[R(s,a)+γ∑s′P(s′∣s,a) Vπ(s′)]for every s.V^\pi(s) = \sum_a \pi(a \mid s) \Big[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V^\pi(s') \Big] \quad \text{for every } s.

    In words: the value of ss is the average, over the policy's action and the environment's next state, of "reward now plus γ\gamma 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").

    Interactive figure: loading…

    Move the sliders to change the policy. The orange edges are the actions with probabilities π(a∣s)\pi(a \mid s); the aqua labels are the transition probabilities and rewards; the blue numbers are the values. Each QQ is "reward now plus γ\gamma times the average next value", and VπV^\pi is the π\pi-average of the QQ 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:

    rπ(s)=∑aπ(a∣s) R(s,a),Pπ(s,s′)=∑aπ(a∣s) P(s′∣s,a).r_\pi(s) = \sum_a \pi(a \mid s)\, R(s, a), \qquad P_\pi(s, s') = \sum_a \pi(a \mid s)\, P(s' \mid s, a).

    PπP_\pi is the transition matrix of the Markov chain that the policy creates (row ss is the distribution of the next state), and rπr_\pi is the expected reward in each state. With these, the Bellman equation for all states at once is

    Vπ=rπ+γPπVπ  ⟺  (I−γPπ) Vπ=rπ.V^\pi = r_\pi + \gamma P_\pi V^\pi \quad\iff\quad (I - \gamma P_\pi)\, V^\pi = r_\pi .

    This is a linear system with ∣S∣|\mathcal S| equations and ∣S∣|\mathcal S| unknowns. One call to a linear solver gives the values of all states. It costs O(∣S∣3)O(|\mathcal S|^3).

    Theorem (the system has exactly one solution). If 0≤γ<10 \le \gamma < 1, then I−γPπI - \gamma P_\pi is invertible, and

    Vπ=(I−γPπ)−1rπ=∑k≥0γkPπk rπ.V^\pi = (I - \gamma P_\pi)^{-1} r_\pi = \sum_{k \ge 0} \gamma^k P_\pi^k\, r_\pi .

    Proof.

    1. Each row of PπP_\pi has entries ≥0\ge 0 that sum to at most 1. The ∞\infty-norm of a matrix is its largest absolute row sum (linear algebra 11), so ∥Pπ∥∞≤1\|P_\pi\|_\infty \le 1 and ∥(γPπ)k∥∞≤γk\|(\gamma P_\pi)^k\|_\infty \le \gamma^k.
    2. So the partial sums SK=∑k<K(γPπ)kS_K = \sum_{k < K} (\gamma P_\pi)^k converge: the terms are bounded by a geometric series. Call the limit SS.
    3. Multiply out (the middle terms cancel): (I−γPπ)SK=I−(γPπ)K(I - \gamma P_\pi) S_K = I - (\gamma P_\pi)^K.
    4. Let K→∞K \to \infty. The right side tends to II, because ∥(γPπ)K∥∞≤γK→0\|(\gamma P_\pi)^K\|_\infty \le \gamma^K \to 0. So (I−γPπ)S=I(I - \gamma P_\pi) S = I, and SS is the inverse. ■\blacksquare

    The series has a direct meaning. (Pπkrπ)(s)(P_\pi^k r_\pi)(s) is the expected reward at step kk when you start in ss. So ∑kγkPπkrπ\sum_k \gamma^k P_\pi^k r_\pi is the expected discounted sum of rewards: exactly the definition of VπV^\pi.

    The 4×4 gridworld of Sutton and Barto (Example 4.1) shows this. The two aqua corners are terminal. Every step gives reward −1-1, and γ=1\gamma = 1, so −Vπ(s)-V^\pi(s) is the expected number of steps to reach a corner.

    Interactive figure: loading…

    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 Vπ=−14V^\pi = -14: on average a random walk needs 14 steps. The side panel shows the backup of the selected cell: Vπ(s)V^\pi(s) is the π\pi-average of the QQ values. Now make two neighbouring cells point at each other: those two states never end, so their value is −∞-\infty, and so is the value of every state from which the random policy can walk into them.

    Quick check

    In a continuing task with γ=1\gamma = 1, every row of PπP_\pi sums to 1. Why does the linear solve for VπV^\pi fail?

    Optimal values and the Bellman optimality equations #

    Definition (optimal value functions). V∗(s)=max⁡πVπ(s)V^*(s) = \max_\pi V^\pi(s) and Q∗(s,a)=max⁡πQπ(s,a)Q^*(s, a) = \max_\pi Q^\pi(s, a). A policy π∗\pi^* is optimal if Vπ∗(s)=V∗(s)V^{\pi^*}(s) = V^*(s) in every state ss.

    The best first action gives the best value, and after the first step you should act optimally again. This gives the Bellman optimality equations:

    V∗(s)=max⁡a[R(s,a)+γ∑s′P(s′∣s,a) V∗(s′)],V^*(s) = \max_a \Big[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V^*(s') \Big],
    Q∗(s,a)=R(s,a)+γ∑s′P(s′∣s,a) max⁡a′Q∗(s′,a′).Q^*(s, a) = R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, \max_{a'} Q^*(s', a').

    The links are now V∗(s)=max⁡aQ∗(s,a)V^*(s) = \max_a Q^*(s, a) and Q∗(s,a)=R(s,a)+γ∑s′P(s′∣s,a)V∗(s′)Q^*(s, a) = R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V^*(s'). 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 γ<1\gamma < 1 the optimality equation has exactly one solution, and that this solution is V∗V^*. Here we use that fact for the main consequence.

    Theorem (a greedy policy with respect to Q∗Q^* is optimal). Let π(s)∈arg⁡max⁡aQ∗(s,a)\pi(s) \in \arg\max_a Q^*(s, a) in every state. Then Vπ=V∗V^\pi = V^*. So every finite discounted MDP has an optimal policy that is deterministic and stationary, and it is optimal in all states at once.

    Proof.

    1. By the choice of π\pi: V∗(s)=max⁡aQ∗(s,a)=Q∗(s,π(s))=R(s,π(s))+γ∑s′P(s′∣s,π(s))V∗(s′)V^*(s) = \max_a Q^*(s, a) = Q^*(s, \pi(s)) = R(s, \pi(s)) + \gamma \sum_{s'} P(s' \mid s, \pi(s)) V^*(s').
    2. Read this as a statement about the deterministic policy π\pi: the vector V∗V^* solves V=rπ+γPπVV = r_\pi + \gamma P_\pi V, the Bellman expectation equation of π\pi.
    3. That linear system has exactly one solution, VπV^\pi (previous theorem). So Vπ=V∗V^\pi = V^*. ■\blacksquare

    Note what you need for this: Q∗Q^*, or V∗V^* together with the model P,RP, R. With V∗V^* alone you cannot pick the action, because Q∗=R+γPV∗Q^* = R + \gamma P V^* needs the model.

    Quick check

    For the robot vacuum with the random policy (π(clean∣s)=12\pi(\text{clean} \mid s) = \tfrac12 in both states), Vπ(H)=8.55V^\pi(H) = 8.55 and Vπ(L)=7.90V^\pi(L) = 7.90 (γ=0.9\gamma = 0.9). Is the greedy policy with respect to these values optimal?

    Linear versus nonlinear. For a fixed policy, the action probabilities are constants, so VV appears linearly and one solve is enough. In the optimality equation, the max over actions depends on VV 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, γ=0.9\gamma = 0.9, states ordered (H, L).

    (a) Evaluate "always clean" by hand. The policy is π(H)=π(L)=clean\pi(H) = \pi(L) = \text{clean}.

    • In L, cleaning earns 1 and stays in L: V(L)=1+0.9 V(L)V(L) = 1 + 0.9\, V(L), so 0.1 V(L)=10.1\, V(L) = 1 and V(L)=10V(L) = 10.
    • In H, cleaning earns 2 and goes to H or L with probability ½: V(H)=2+0.9 (0.5 V(H)+0.5⋅10)=2+0.45 V(H)+4.5V(H) = 2 + 0.9\,(0.5\, V(H) + 0.5 \cdot 10) = 2 + 0.45\, V(H) + 4.5. So 0.55 V(H)=6.50.55\, V(H) = 6.5 and V(H)=130/11≈11.82V(H) = 130/11 \approx 11.82.

    (b) The same with the linear system.

    Pπ=(0.50.501),rπ=(21),I−γPπ=(0.55−0.4500.1).P_\pi = \begin{pmatrix} 0.5 & 0.5 \\ 0 & 1 \end{pmatrix}, \quad r_\pi = \begin{pmatrix} 2 \\ 1 \end{pmatrix}, \quad I - \gamma P_\pi = \begin{pmatrix} 0.55 & -0.45 \\ 0 & 0.1 \end{pmatrix}.

    The second row gives 0.1 V(L)=10.1\, V(L) = 1, so V(L)=10V(L) = 10. The first row gives 0.55 V(H)−0.45⋅10=20.55\, V(H) - 0.45 \cdot 10 = 2, so V(H)=6.5/0.55=130/11V(H) = 6.5/0.55 = 130/11. The same numbers.

    Quick check

    Under "always clean", Vπ(H)=11.82V^\pi(H) = 11.82 and Vπ(L)=10V^\pi(L) = 10 (γ=0.9\gamma = 0.9). Predict Qπ(L,charge)Q^\pi(L, \text{charge}): charge once in L, then clean as usual.

    (c) QQ from VV: is charging in L better? Use Qπ(s,a)=R(s,a)+γ∑s′P(s′∣s,a)Vπ(s′)Q^\pi(s, a) = R(s, a) + \gamma \sum_{s'} P(s' \mid s, a) V^\pi(s'):

    • Qπ(L,charge)=0+0.9⋅V(H)=0.9⋅11.82=10.64Q^\pi(L, \text{charge}) = 0 + 0.9 \cdot V(H) = 0.9 \cdot 11.82 = 10.64;
    • Qπ(L,clean)=1+0.9⋅10=10=Vπ(L)Q^\pi(L, \text{clean}) = 1 + 0.9 \cdot 10 = 10 = V^\pi(L).

    So Aπ(L,charge)=10.64−10=0.64>0A^\pi(L, \text{charge}) = 10.64 - 10 = 0.64 > 0: charging once in L, then cleaning as usual, beats the policy. In H, Qπ(H,charge)=0.9⋅11.82=10.64<11.82Q^\pi(H, \text{charge}) = 0.9 \cdot 11.82 = 10.64 < 11.82, so cleaning stays better there.

    (d) Evaluate "clean in H, charge in L". Now L charges and moves to H:

    • V(L)=0+0.9 V(H)V(L) = 0 + 0.9\, V(H).
    • V(H)=2+0.9 (0.5 V(H)+0.5 V(L))=2+0.45 V(H)+0.45⋅0.9 V(H)=2+0.855 V(H)V(H) = 2 + 0.9\,(0.5\, V(H) + 0.5\, V(L)) = 2 + 0.45\, V(H) + 0.45 \cdot 0.9\, V(H) = 2 + 0.855\, V(H).
    • So 0.145 V(H)=20.145\, V(H) = 2, V(H)=400/29≈13.79V(H) = 400/29 \approx 13.79, and V(L)=360/29≈12.41V(L) = 360/29 \approx 12.41.

    Both values went up, in both states.

    (e) Check the optimality equation. For V=(13.79,12.41)V = (13.79, 12.41):

    • H: max⁡(2+0.9 (0.5⋅13.79+0.5⋅12.41), 0+0.9⋅13.79)\max\big(2 + 0.9\,(0.5 \cdot 13.79 + 0.5 \cdot 12.41),\ 0 + 0.9 \cdot 13.79\big) =max⁡(13.79, 12.41)=13.79= \max(13.79,\ 12.41) = 13.79 ✓
    • L: max⁡(1+0.9⋅12.41, 0+0.9⋅13.79)\max\big(1 + 0.9 \cdot 12.41,\ 0 + 0.9 \cdot 13.79\big) =max⁡(12.17, 12.41)=12.41= \max(12.17,\ 12.41) = 12.41 ✓

    In exact fractions, 2+0.45⋅76029=400292 + 0.45 \cdot \tfrac{760}{29} = \tfrac{400}{29} and 35329<36029\tfrac{353}{29} < \tfrac{360}{29}. The equation holds in both states, so V∗=(400/29, 360/29)V^* = (400/29,\ 360/29), and the greedy policy "clean in H, charge in L" is optimal.

    Answers to section 1. (1) ∑k0.9k=1/(1−0.9)=10\sum_k 0.9^k = 1/(1 - 0.9) = 10. (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: Q∗(L,charge)=12.41>Q∗(L,clean)=12.17Q^*(L, \text{charge}) = 12.41 > Q^*(L, \text{clean}) = 12.17.

    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 ∑s′P(s′∣s,a)V(s′)\sum_{s'} P(s' \mid s, a) V(s') for every pair (s,a)(s, a) 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 Q∗Q^* from samples of the Bellman optimality equation (lessons 05 and 06).
    • Advantages. Policy-gradient methods push up actions with Aπ(s,a)>0A^\pi(s, a) > 0 (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 γ=1\gamma = 1, 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 V∗V^* the max is over the action, and the next states are still averaged with PP. It is not max⁡s′\max_{s'}.
    • Greedy from VV without a model. arg⁡max⁡aQ(s,a)\arg\max_a Q(s, a) needs QQ. Turning VV into QQ needs PP and RR. This is why model-free methods learn QQ, not VV.
    • Mixing reward conventions. rtr_t here is Rt+1R_{t+1} in Sutton and Barto. Fix one convention in your code.
    • γ=1\gamma = 1 without termination. I−PπI - P_\pi is singular when the policy never ends an episode.
    • One return is not the value. A return GtG_t is one random sample; Vπ(s)V^\pi(s) is its expectation.
    • VπV^\pi versus V∗V^*. The greedy policy with respect to VπV^\pi is not optimal in general; only greedy with respect to V∗V^* (or Q∗Q^*) is.

    8. Check yourself #

    1. Write QπQ^\pi in terms of VπV^\pi, and VπV^\pi in terms of QπQ^\pi.
      AnswerQπ(s,a)=R(s,a)+γ∑s′P(s′∣s,a)Vπ(s′)Q^\pi(s,a) = R(s,a) + \gamma \sum_{s'} P(s' \mid s,a) V^\pi(s') and Vπ(s)=∑aπ(a∣s)Qπ(s,a)V^\pi(s) = \sum_a \pi(a \mid s) Q^\pi(s,a).
    2. A reward of 1 arrives only at step 10 (all other rewards are 0), and γ=0.9\gamma = 0.9. What is G0G_0?
      AnswerG0=0.910⋅1≈0.349G_0 = 0.9^{10} \cdot 1 \approx 0.349. A reward ten steps ahead keeps about a third of its weight.
    3. Why is the expectation equation linear but the optimality equation not?
      AnswerFor a fixed π\pi the action probabilities are constants, so VV appears linearly. In V∗V^* the max over actions depends on VV itself; a max of linear functions is piecewise linear, not linear.
    4. Show that ∑aπ(a∣s)Aπ(s,a)=0\sum_a \pi(a \mid s) A^\pi(s, a) = 0.
      Answer∑aπ(a∣s)(Qπ(s,a)−Vπ(s))=∑aπ(a∣s)Qπ(s,a)−Vπ(s)∑aπ(a∣s)=Vπ(s)−Vπ(s)=0\sum_a \pi(a \mid s)(Q^\pi(s,a) - V^\pi(s)) = \sum_a \pi(a \mid s) Q^\pi(s,a) - V^\pi(s) \sum_a \pi(a \mid s) = V^\pi(s) - V^\pi(s) = 0, by the first link and because the probabilities sum to 1.
    5. Why does a finite discounted MDP always have a deterministic optimal policy?
      AnswerThe policy that is greedy with respect to Q∗Q^* is optimal in every state, and picking one maximising action per state gives a deterministic policy.
    6. In the 4×4 gridworld with γ=1\gamma = 1, the random policy has Vπ=−14V^\pi = -14 next to a terminal corner. What does −14-14 mean?
      AnswerEach step gives −1-1 and there is no discount, so −Vπ(s)-V^\pi(s) is the expected number of steps until the random walk reaches a terminal corner: 14 steps on average.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Name the five parts of a finite MDP.

    2. Write the return recursion.

    3. Define Vπ(s)V^\pi(s).

    4. Write Qπ(s,a)Q^\pi(s, a) in terms of VπV^\pi.

    5. Write Vπ(s)V^\pi(s) in terms of QπQ^\pi.

    6. Give the matrix form of the Bellman expectation equation and its solution.

    7. Why is I−γPπI - \gamma P_\pi invertible for γ<1\gamma < 1?

    8. Write the Bellman optimality equation for Q∗Q^*.

    9. What is the effective horizon for γ=0.99\gamma = 0.99?

    10. Compute G0G_0 for the rewards (2,2,2)(2, 2, 2) with γ=0.5\gamma = 0.5.

    Open the review →

    9. Interview angle #

    • "What is the Bellman equation, and why does it have a unique solution?" The value is the reward now plus γ\gamma times the expected value of the next state: Vπ=rπ+γPπVπV^\pi = r_\pi + \gamma P_\pi V^\pi. For γ<1\gamma < 1, I−γPπI - \gamma P_\pi is invertible (Neumann series), so there is exactly one solution.
    • "What is the difference between VV and QQ? Why do model-free methods prefer QQ?" QQ fixes the first action. To act greedily from VV you need the model to compute Q=R+γPVQ = R + \gamma P V; from QQ you only need an argmax.
    • "Why discount?" It makes infinite sums finite, sets an effective horizon 1/(1−γ)1/(1-\gamma), 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 PπP_\pi and rπr_\pi, and solve (I−γPπ)V=rπ(I - \gamma P_\pi) V = r_\pi: O(∣S∣3)O(|\mathcal S|^3). 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:

    1. discounted_return and returns_to_go: one backward pass with Gt=rt+γGt+1G_t = r_t + \gamma G_{t+1}.
    2. induced_chain: build PπP_\pi and rπr_\pi from the arrays P[s, a, s'], R[s, a], pi[s, a].
    3. policy_evaluation_linear: solve (I−γPπ)V=rπ(I - \gamma P_\pi) V = r_\pi and check Vπ(H)=130/11V^\pi(H) = 130/11.
    4. Monte Carlo check: simulate many episodes of the robot vacuum and compare the mean return with VπV^\pi.
    5. q_from_v and v_from_q: the two links, and a round trip on the 4×4 gridworld.

    11. Watch and read #

    The classic lecture on Markov processes, returns, value functions and both Bellman equations, with backup diagrams.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A short visual overview of MDPs, returns and value functions, following Sutton and Barto.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A more recent lecture; the first half covers MDPs and the Bellman equations, the second half is lesson 02.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play