TExcelTAD
Home › Math for Deep Learning & LLMs › Markov Decision Processes and Bellman Equations

Markov Decision Processes and Bellman Equations

Reinforcement learning trains an agent by reward instead of labeled answers. Its mathematical setting is the Markov decision process (MDP), and its central identities are the Bellman equations, which express the value of a state through the values of the states that follow. They are the foundation of game-playing agents and, through policy gradients, of the reinforcement-learning stage of LLM training.

The MDP

An MDP has states ss, actions aa, transition probabilities P(s′∣s,a)P(s' \mid s, a), rewards r(s,a)r(s, a) and a discount factor γ∈[0,1)\gamma \in [0, 1). A policy π(a∣s)\pi(a \mid s) chooses actions. The agent wants to maximize the expected return

Gt=rt+γrt+1+γ2rt+2+⋯=∑k=0∞γkrt+kG_t = r_t + \gamma r_{t+1} + \gamma^2r_{t+2} + \cdots = \sum_{k=0}^{\infty}\gamma^kr_{t+k}

The discount makes the sum finite and prefers sooner rewards. Markov means the future depends on the past only through the current state.

Value functions and the Bellman equations

The state value Vπ(s)=Eπ[Gt∣st=s]V^\pi(s) = \mathbb{E}_\pi[G_t \mid s_t = s] and the action value Qπ(s,a)=Eπ[Gt∣st=s,at=a]Q^\pi(s, a) = \mathbb{E}_\pi[G_t \mid s_t = s, a_t = a]. Splitting the return into the first reward plus the discounted rest gives the Bellman expectation equation:

Vπ(s)=∑aπ(a∣s)[r(s,a)+γ∑s′P(s′∣s,a)Vπ(s′)]V^\pi(s) = \sum_a\pi(a \mid s)\left[r(s, a) + \gamma\sum_{s'}P(s' \mid s, a)V^\pi(s')\right]

For a fixed policy this is a linear system: v=rπ+γPπv\mathbf{v} = \mathbf{r}_\pi + \gamma P_\pi\mathbf{v}, so v=(I−γPπ)−1rπ\mathbf{v} = (I - \gamma P_\pi)^{-1}\mathbf{r}_\pi. The optimal values satisfy the Bellman optimality equation, with a max instead of the average over actions:

V∗(s)=max⁡a[r(s,a)+γ∑s′P(s′∣s,a)V∗(s′)]V^*(s) = \max_a\left[r(s, a) + \gamma\sum_{s'}P(s' \mid s, a)V^*(s')\right]
python · try it yourself
import numpy as np

# A 5-state corridor: actions 0 = left, 1 = right; reaching state 4 gives reward 1 and ends the episode.
nS, gamma = 5, 0.9
P = np.zeros((2, nS, nS)); R = np.zeros((2, nS))
for s in range(nS - 1):
    P[0, s, max(s - 1, 0)] = 1; P[1, s, s + 1] = 1
    R[1, s] = 1.0 if s + 1 == nS - 1 else 0.0
# state 4 is terminal: no transitions, no reward
pi_uniform = np.full((nS, 2), 0.5)
P_pi = np.einsum("sa,ast->st", pi_uniform, P); r_pi = np.einsum("sa,as->s", pi_uniform, R)
v_uniform = np.linalg.solve(np.eye(nS) - gamma * P_pi, r_pi)
print("V of the coin-flip policy (exact linear solve):", np.round(v_uniform, 3))
V = np.zeros(nS)                                   # value iteration for V*
for it in range(100):
    Q = R + gamma * P @ V                          # Q[a, s]
    V_new = Q.max(axis=0)
    if np.max(np.abs(V_new - V)) < 1e-10: break
    V = V_new
print("V* by value iteration:", np.round(V, 3), " after", it, "iterations")
print("greedy policy (1 = right):", Q.argmax(axis=0)[:-1])
V of the coin-flip policy (exact linear solve): [0.275 0.336 0.472 0.712 0.   ]
V* by value iteration: [0.729 0.81  0.9   1.    0.   ]  after 4 iterations
greedy policy (1 = right): [1 1 1 1]

The optimal values are γk\gamma^{k} for a state k+1k + 1 steps from the goal: 1,0.9,0.81,0.7291, 0.9, 0.81, 0.729.

Value iteration converges

The Bellman optimality operator is a contraction in the max norm with factor γ\gamma: applying it to two value estimates shrinks their maximum difference by at least γ\gamma. By the Banach fixed-point theorem, value iteration converges to the unique V∗V^* from any start, with error shrinking like γk\gamma^k.

When the model is unknown

Without PP and RR, the agent learns from experience. Temporal-difference learning nudges V(s)V(s) toward the one-sample target r+γV(s′)r + \gamma V(s'); Q-learning uses r+γmax⁡a′Q(s′,a′)r + \gamma\max_{a'}Q(s', a'); deep Q-networks approximate QQ with a network. Policy-gradient methods skip values and adjust the policy directly (Policy Gradients and RLHF).

In software

  • Gymnasium (formerly OpenAI Gym) defines environments with reset and step(action) -> (obs, reward, terminated, truncated, info).
  • Stable-Baselines3 implements DQN, PPO and other algorithms on top.
  • In RLHF the "environment" is a prompt, the "action" a generated response and the reward a learned reward model's score.

Exercises

Exercise 1: Discounted return

Rewards 1,0,0,51, 0, 0, 5 with γ=0.9\gamma = 0.9. What is G0G_0?

Answer

4.6454.645.

Solution

1+0.93⋅5=1+0.729⋅5=4.6451 + 0.9^3 \cdot 5 = 1 + 0.729 \cdot 5 = 4.645.

Exercise 2: A constant reward stream

What is the value of receiving reward 1 forever with γ=0.95\gamma = 0.95?

Answer
Solution

A geometric series: ∑k0.95k=11−0.95=20\sum_k 0.95^k = \frac{1}{1 - 0.95} = 20. The "effective horizon" of a discount γ\gamma is about 1/(1−γ)1/(1 - \gamma) steps.

Exercise 3: Contraction (code)

Apply the Bellman optimality update to two different value vectors for the corridor and check that their max difference shrinks by at least γ=0.9\gamma = 0.9.

Answer

The ratio is at most 0.9.

Solution
python · try it yourself
import numpy as np
nS, g = 5, 0.9
P = np.zeros((2, nS, nS)); R = np.zeros((2, nS))
for s in range(nS - 1):
    P[0, s, max(s - 1, 0)] = 1; P[1, s, s + 1] = 1; R[1, s] = float(s + 1 == nS - 1)
T = lambda V: (R + g * P @ V).max(axis=0)
rng = np.random.default_rng(0)
U, W = rng.normal(size=nS), rng.normal(size=nS)
print(round(np.max(np.abs(T(U) - T(W))) / np.max(np.abs(U - W)), 4) <= 0.9)
True

Test yourself

The Bellman expectation equation expresses Vπ(s)V^\pi(s) as…

  1. the maximum reward
  2. the expected immediate reward plus the discounted value of the next state
  3. the number of states
  4. the policy entropy

For a fixed policy and known model, VπV^\pi can be found by…

  1. sampling only
  2. solving the linear system (I−γPπ)v=rπ(I - \gamma P_\pi)\mathbf{v} = \mathbf{r}_\pi
  3. gradient ascent on the reward
  4. sorting states

Why does value iteration converge?

  1. Because rewards are positive
  2. The Bellman optimality operator is a γ\gamma-contraction
  3. Because the policy is random
  4. It does not