Skip to content
Reinforcement learning Core 29 min read

MDPs and the Bellman equations

A Markov decision process is the formal statement of "act now, live with the consequences later". Its central result, the Bellman equation, says the value of being somewhere is the reward you get now plus the discounted value of where you land. Every algorithm in reinforcement learning is a way of solving that equation, exactly or approximately.

10,000 ft

Bandits have no memory: your choice today does not change tomorrow's options. Real decisions do. A chess move changes the board, a medical dose changes the patient, a token changes what an LLM writes next. The Markov decision process (MDP) adds exactly that: a state that actions change. Richard Bellman's 1950s insight was that such problems decompose recursively, and the resulting equations are the backbone of the whole field: dynamic programming solves them with a model, Monte Carlo and TD learning and Q-learning solve them from samples, policy gradients climb the value they define, and AlphaZero plans with them. The same formalism is used in operations research, control engineering and economics, and RL fine-tuning of language models (RLHF, RL with verifiable rewards) is an MDP in which the state is the text so far and each action is a token.

2,000 ft

An agent and an environment take turns. The agent sees a state, picks an action; the environment returns a reward and a next state, with probabilities that depend only on the current state and action (the Markov property).

The agent–environment loop
The agent–environment loop. Agent policy π(a | s), Environment dynamics p(s′, r | s, a), action A_t, reward R_The agent–environment loop. Agent policy π(a | s), Environment dynamics p(s′, r | s, a), action A_t, reward R_

  1. The agent's goal is the return: the discounted sum of future rewards, \(G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots\)
  2. A policy \(\pi(a \mid s)\) says what to do in each state.
  3. Its value function \(v_\pi(s)\) is the expected return from \(s\) when following \(\pi\); \(q_\pi(s,a)\) is the same after first taking action \(a\).
  4. Because \(G_t = R_{t+1} + \gamma G_{t+1}\), values satisfy the Bellman expectation equation: \(v_\pi(s) = \mathbb{E}_\pi[R_{t+1} + \gamma v_\pi(S_{t+1}) \mid S_t = s]\), a linear system.
  5. The best achievable values satisfy the Bellman optimality equation, \(v_\ast(s) = \max_a \mathbb{E}[R_{t+1} + \gamma v_\ast(S_{t+1}) \mid s, a]\); acting greedily with respect to \(v_\ast\) or \(q_\ast\) is optimal.

Ground level

The interface: states, actions, rewards

Time runs in discrete steps \(t = 0, 1, 2, \dots\). At each step the agent observes a state \(S_t \in \mathcal{S}\), chooses an action \(A_t \in \mathcal{A}(S_t)\), and one step later receives a reward \(R_{t+1} \in \mathbb{R}\) and finds itself in \(S_{t+1}\). The record of an episode is a trajectory \(S_0, A_0, R_1, S_1, A_1, R_2, S_2, \dots\) (we follow Sutton and Barto's convention that the reward for the action at time \(t\) is indexed \(t+1\), because it arrives with the next state).

The environment is described by its dynamics

\[ p(s', r \mid s, a) = \Pr\{S_{t+1} = s', R_{t+1} = r \mid S_t = s, A_t = a\}, \]

from which you can derive the transition probabilities \(p(s' \mid s, a) = \sum_r p(s', r \mid s, a)\) and the expected reward \(r(s,a) = \sum_{s', r} r\, p(s', r \mid s, a)\). A finite MDP is the tuple \((\mathcal{S}, \mathcal{A}, p, \gamma)\) with finite state and action sets, plus a start-state distribution \(\mu_0\).

The boundary between agent and environment is not the boundary of a body. It is the line between what the agent controls and what it does not. A robot's motors are part of the environment (the agent controls the voltage, not the arm's final position); so is the reward signal, even if it is computed inside the robot, because the agent cannot change it at will.

The Markov property

The defining assumption is that the state carries everything about the past that matters for the future:

\[ \Pr\{S_{t+1}, R_{t+1} \mid S_t, A_t\} = \Pr\{S_{t+1}, R_{t+1} \mid S_0, A_0, R_1, \dots, S_t, A_t\}. \]

This is a property of the state representation, not of the world. A chess position is Markov: the board (plus whose move it is, castling rights and the en-passant square) determines the future. A single Atari frame is not: it shows where the ball is but not which way it is moving, which is why DQN fed the network the last four frames stacked together. An LLM's state, the prompt plus every token generated so far, is Markov by construction, because the next-token distribution is a function of exactly that.

When the agent's observation is not Markov, the problem is a partially observable MDP (POMDP). The fix is always the same in spirit: make a state out of history, either by stacking recent observations, by a recurrent network's hidden state, or by a belief distribution over the hidden state.

The running example

Two states and two actions, small enough to solve by hand, rich enough to show every idea on this page:

Fresh or Tired: a two-state MDP (labels show probability and reward)
Fresh or Tired: a two-state MDP (labels show probability and reward). Fresh, Tired, work, rest, 0.7, r = 2, 0.3, r = 2, 1.0, r = 0, 1.0, r = 1, 0.8, r = 0, 0.2, r = 0Fresh or Tired: a two-state MDP (labels show probability and reward). Fresh, Tired, work, rest, 0.7, r = 2, 0.3, r = 2, 1.0, r = 0, 1.0, r = 1, 0.8, r = 0, 0.2, r = 0

Working while fresh earns 2 but risks tiredness (30%). Working while tired earns only 1 and keeps you tired. Resting earns nothing but usually restores you. There are \(2^2 = 4\) deterministic policies. Which is best? It depends on how much you care about the future, and making that precise is the job of the discount factor.

Returns and discounting

The agent maximises the return, the discounted sum of rewards from now on:

\[ G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}, \qquad 0 \le \gamma \le 1 . \]

A worked example: starting Fresh and following "work when fresh, rest when tired", one sampled trajectory gives rewards 2, 2, 0, 2 (work, work, get tired, rest, recover, work). With \(\gamma = 0.9\) the first four terms contribute \(2 + 0.9 \cdot 2 + 0.81 \cdot 0 + 0.729 \cdot 2 = 5.258\).

The single most useful identity in RL is the return's recursion:

\[ G_t = R_{t+1} + \gamma G_{t+1}. \]

Today's return is today's reward plus the discounted return from tomorrow. The Bellman equations are this identity in expectation.

010203040506000.51steps into the future, kweight γᵏγ = 0.5: horizon 1/(1−γ) = 2 stepsγ = 0.9: horizon 1/(1−γ) = 10 stepsγ = 0.99: horizon 1/(1−γ) = 100 steps
How much a reward k steps ahead counts. γ = 0.5 effectively sees two steps, γ = 0.9 ten, γ = 0.99 a hundred. The "effective horizon" 1/(1 − γ) is the sum of all the weights, and also the expected lifetime if you read 1 − γ as a per-step probability that the episode ends.

Three readings of \(\gamma\), all useful:

  • Mathematical: with bounded rewards \(|R| \le R_{\max}\) and \(\gamma < 1\), the return is bounded by \(R_{\max}/(1-\gamma)\), so infinite-horizon sums are finite.
  • Preference: a reward now is worth more than the same reward later, as with an interest rate (in finance, \(\gamma = 1/(1+\text{rate})\)).
  • Survival: \(\gamma\) is the probability that the process continues one more step. Maximising the expected discounted return equals maximising the expected undiscounted return of a process that halts with probability \(1-\gamma\) each step.

Episodic tasks (a game, a maze, an LLM answer) end in a terminal state; there \(\gamma = 1\) is allowed because the sum is finite. Continuing tasks (process control, a recommender serving forever) never end and need \(\gamma < 1\) or an average-reward criterion. Treat a terminal state as an absorbing state with zero reward forever and the two cases share one notation.

Policies and value functions

A policy \(\pi(a \mid s)\) is a probability distribution over actions for every state. Deterministic policies are the special case that puts all mass on one action. Given a policy, two value functions measure how good things are:

\[ 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]. \]

\(v_\pi\) grades states; \(q_\pi\) grades state–action pairs, which is what you need to choose without a model. They are linked both ways:

\[ v_\pi(s) = \sum_a \pi(a \mid s)\, q_\pi(s,a), \qquad q_\pi(s,a) = r(s,a) + \gamma \sum_{s'} p(s' \mid s, a)\, v_\pi(s'). \]

The difference \(A_\pi(s,a) = q_\pi(s,a) - v_\pi(s)\) is the advantage: how much better action \(a\) is than the policy's average behaviour in \(s\). It becomes the central quantity of policy-gradient methods and PPO.

Reward is not value

Reward is immediate and given by the environment; value is long-run and must be computed or learned. In the running example, working while tired has the higher immediate reward (1 against 0) and the lower value (12.89 against 13.21 at γ = 0.9). Most of RL's difficulty lives in that gap, and the term for it is credit assignment: which earlier actions deserve credit for a reward that arrives much later?

The Bellman expectation equation

Take the expectation of \(G_t = R_{t+1} + \gamma G_{t+1}\) under \(\pi\), conditioning on \(S_t = s\). The Markov property lets the inner expectation of \(G_{t+1}\) collapse to \(v_\pi(S_{t+1})\):

\[ v_\pi(s) = \sum_a \pi(a \mid s) \sum_{s', r} p(s', r \mid s, a)\,\big[r + \gamma\, v_\pi(s')\big]. \]

Read it as a one-step look-ahead. From \(s\), average over the actions the policy might take, then over where the environment might send you, and score each outcome by its reward plus the discounted value of the landing state. Sutton and Barto draw it as a backup diagram: information flows up the tree from successor states to the root.

Backup diagram for v_π: average over actions (policy), then over outcomes (dynamics)
Backup diagram for v_π: average over actions (policy), then over outcomes (dynamics). s, a₁, a₂, s′, r, π(a₁|s), π(a₂|s), pBackup diagram for v_π: average over actions (policy), then over outcomes (dynamics). s, a₁, a₂, s′, r, π(a₁|s), π(a₂|s), p

For a fixed policy this is a system of \(|\mathcal{S}|\) linear equations in \(|\mathcal{S}|\) unknowns. For the running example with \(\pi\) = (work when Fresh, rest when Tired) and \(\gamma = 0.9\):

\[ \begin{aligned} v(F) &= 2 + 0.9\,[\,0.7\, v(F) + 0.3\, v(T)\,] \\ v(T) &= 0 + 0.9\,[\,0.8\, v(F) + 0.2\, v(T)\,] \end{aligned} \]

The second line gives \(0.82\, v(T) = 0.72\, v(F)\), so \(v(T) = 0.878\, v(F)\). Substituting into the first: \(0.37\, v(F) = 2 + 0.27 \times 0.878\, v(F)\), so \(0.1329\, v(F) = 2\) and

\[ v_\pi(F) = 15.046, \qquad v_\pi(T) = 13.211 . \]

A sanity check: rewards are at most 2, so no value can exceed \(2/(1-0.9) = 20\); and a Monte Carlo average of 20,000 simulated returns from Fresh gives \(15.052 \pm 0.023\) (see Build it). Solving the linear system is exact; sampling returns is how you would estimate the same number without knowing \(p\), the idea behind Monte Carlo methods.

Optimal values and the Bellman optimality equation

Policies are compared state by state: \(\pi \ge \pi'\) if \(v_\pi(s) \ge v_{\pi'}(s)\) for every \(s\). That is only a partial order, so it is remarkable, and true for finite MDPs, that there is always a policy at least as good as every other in every state at once. All such policies share the optimal value functions

\[ v_\ast(s) = \max_\pi v_\pi(s), \qquad q_\ast(s,a) = \max_\pi q_\pi(s,a), \]

which satisfy the Bellman optimality equations, the expectation equations with the policy's average replaced by a max:

\[ v_\ast(s) = \max_a \sum_{s', r} p(s', r \mid s, a)\big[r + \gamma\, v_\ast(s')\big], \qquad q_\ast(s,a) = \sum_{s', r} p(s', r \mid s, a)\big[r + \gamma \max_{a'} q_\ast(s', a')\big]. \]
Backup diagram for v*: take the best action, then average over outcomes
Backup diagram for v*: take the best action, then average over outcomes. s, max over a, a₁, a₂, s′, r, pBackup diagram for v*: take the best action, then average over outcomes. s, max over a, a₁, a₂, s′, r, p

The optimality equation is non-linear (because of the max), so in general it is solved by iteration (dynamic programming), not by one matrix inverse. Once you have \(q_\ast\), acting optimally needs no look-ahead and no model: in each state pick \(\arg\max_a q_\ast(s,a)\). This is why model-free control methods learn \(q\), not \(v\): with only \(v_\ast\) you still need \(p\) to compute which action leads to the best successor.

Solving the running example. With only four deterministic policies we can simply evaluate them all:

Policy (Fresh, Tired) \(v(F)\), γ = 0.9 \(v(T)\), γ = 0.9 \(v(F)\), γ = 0.5 \(v(T)\), γ = 0.5
work, work 12.703 10.000 3.538 2.000
work, rest 15.046 13.211 3.429 1.524
rest, work 0.000 10.000 0.000 2.000
rest, rest 0.000 0.000 0.000 0.000

At \(\gamma = 0.9\) the optimal policy is "work when fresh, rest when tired", and it is best in both states simultaneously, as the theory promises. Check it satisfies the optimality equation through its \(q\)-values:

\[ \begin{aligned} q_\ast(T, \text{rest}) &= 0 + 0.9\,(0.8 \times 15.046 + 0.2 \times 13.211) = 13.211, \\ q_\ast(T, \text{work}) &= 1 + 0.9 \times 13.211 = 12.890 , \end{aligned} \]

so resting is greedy in Tired, and \(v_\ast(T) = \max(12.890, 13.211) = 13.211\) is consistent.

At \(\gamma = 0.5\) the answer flips: "always work" is optimal. A myopic agent will not pay the one-step cost of resting for a recovery whose benefit arrives later and is heavily discounted. The discount factor is not a numerical convenience; it is part of the problem statement, and changing it changes what "optimal" means.

Reward design

Sutton and Barto state the premise of the field as the reward hypothesis:

That all of what we mean by goals and purposes can be well thought of as the maximization of the expected value of the cumulative sum of a received scalar signal (called reward).

The hypothesis is powerful because it makes "goal" something you can optimise. It is dangerous for the same reason: the agent optimises the reward you wrote, not the goal you meant. DeepMind's catalogue of specification gaming (Krakovna et al., 2020) collects dozens of cases. In the boat-racing game CoastRunners, an agent given a shaping reward for hitting targets along the course learned to circle and hit the same targets forever instead of finishing the race. In a simulated LEGO-stacking task, rewarded on the height of the red block's bottom face, the agent flipped the red block over instead of stacking it.

Three practical lessons:

  • Reward the outcome, not the method. Reward "the red block is on the blue one", not "the red block is high". Every intermediate reward you add is a new way to be gamed.
  • Shape safely. Adding a bonus \(F(s, s') = \gamma\Phi(s') - \Phi(s)\) for any function \(\Phi\) of state (a potential) speeds learning without changing which policies are optimal (Ng, Harada and Russell, 1999; proof in the maths). Bonuses not of this form can change the optimal policy, which is exactly what happened to the boat.
  • Sparse rewards are honest but hard. A reward only at success cannot be gamed by intermediate behaviour, but it gives no signal until the agent stumbles on success, which makes exploration (bandits and exploration) the bottleneck.

The same tension drives modern LLM training. A learned reward model in RLHF can be gamed (longer, more flattering answers score higher); a verifiable reward in RLVR, such as "the final answer matches" or "the unit tests pass", is harder to game but sparse, and only exists for checkable tasks.

Variations you will meet

  • POMDPs: the agent sees observations \(o \sim O(\cdot \mid s)\), not states. Optimal behaviour depends on the belief \(b(s) = \Pr(S_t = s \mid \text{history})\), which turns a POMDP into an MDP over beliefs, with a continuous state space.
  • Continuous states and actions: robotics and control. Values and policies become functions to approximate with neural networks; the Bellman equations are unchanged.
  • Average reward: for continuing tasks, maximise \(\lim_{T\to\infty} \frac{1}{T}\mathbb{E}\sum_t R_t\) instead of a discounted sum; values become differential values relative to the average.
  • Markov games: several agents, each with its own reward (Shapley's stochastic games, 1953). Optimal play can require randomisation, as in rock–paper–scissors, unlike single-agent MDPs.
  • Constrained MDPs: maximise reward subject to bounds on expected costs (safety, budget).
  • The LLM as an MDP: state = prompt plus tokens so far, action = next token, transitions deterministic (append the token), reward usually given once at the end of the answer. Because the dynamics are known and trivial, the whole difficulty is credit assignment across hundreds of tokens and the quality of the reward. Many methods treat the entire answer as one action, a contextual bandit at the sequence level (offline RL and RL for language models).

First principles

Why "Markov" is the right assumption. Any decision problem can be made Markov by declaring the whole history to be the state. The assumption is therefore not a restriction on the world but a demand on the representation: find a compact summary of history that predicts the future as well as the full history does. All the efficiency of RL comes from this. Values are attached to states and reused every time a state recurs; without a compact Markov state there is nothing to reuse.

Why a recursive equation must exist. The return obeys \(G_t = R_{t+1} + \gamma G_{t+1}\) for every trajectory. Expectations are linear, and the Markov property says the future after \(S_{t+1}\) does not depend on how you got there. Put those two facts together and the expected future from \(s\) must equal the expected immediate reward plus the discounted expected future from the next state. Nothing more is needed. This is Bellman's principle of optimality in its policy-evaluation form, and the optimality version adds one more observation: an optimal policy, whatever the first action, must act optimally from the state that action leads to.

Why one deterministic policy can be best everywhere. In an MDP the future from a state depends only on that state, so a policy's choices in different states do not interact except through the values they produce. If you could do better from \(s\) by changing what you do in \(s\), that change cannot hurt any other state: other states only see \(s\) through \(v(s)\), which went up. So improvements can be combined state by state, and the improvement process ends at one policy that is best in every state. And because the max of a linear function over a probability simplex is attained at a vertex, randomising never beats the best pure action in any single state. Both arguments fail in games (the opponent reacts to your randomisation) and in POMDPs (one observation can stand for several states that need different actions).

Why discount. Undiscounted infinite sums diverge; discounting makes them converge and turns the Bellman operator into a contraction (below), which is what makes iteration work. But \(\gamma\) also carries meaning: horizon, impatience or survival probability. In deep RL \(\gamma\) is often set below the "true" value of the task (0.99 rather than 1) because longer horizons mean higher-variance returns and slower propagation of credit; that is a trade of bias for variance, and it changes the problem being solved.

The maths

Notation

Finite \(\mathcal{S}\) with \(n = |\mathcal{S}|\), finite \(\mathcal{A}\). For a policy \(\pi\) define the \(n\)-vector \(\mathbf{r}_\pi(s) = \sum_a \pi(a\mid s)\, r(s,a)\) and the \(n \times n\) row-stochastic matrix \(P_\pi(s, s') = \sum_a \pi(a \mid s)\, p(s' \mid s, a)\). Values are vectors \(\mathbf{v} \in \mathbb{R}^n\); \(\|\mathbf{v}\|_\infty = \max_s |v(s)|\).

Derivation: the Bellman expectation equation
\[ \begin{aligned} v_\pi(s) &= \mathbb{E}_\pi[G_t \mid S_t = s] = \mathbb{E}_\pi[R_{t+1} + \gamma G_{t+1} \mid S_t = s] \\ &= \sum_a \pi(a\mid s) \sum_{s', r} p(s', r \mid s, a)\Big[r + \gamma\, \mathbb{E}_\pi[G_{t+1} \mid S_{t+1} = s']\Big] \\ &= \sum_a \pi(a\mid s) \sum_{s', r} p(s', r \mid s, a)\big[r + \gamma\, v_\pi(s')\big]. \end{aligned} \]

The second line uses the law of total expectation over \(A_t\) and \((S_{t+1}, R_{t+1})\); the third uses the Markov property, which makes \(\mathbb{E}_\pi[G_{t+1} \mid S_t, A_t, S_{t+1}=s', R_{t+1}]\) equal to \(\mathbb{E}_\pi[G_{t+1} \mid S_{t+1} = s'] = v_\pi(s')\).

Matrix form and the closed-form solution

Stacking the expectation equation over states:

\[ \mathbf{v}_\pi = \mathbf{r}_\pi + \gamma P_\pi \mathbf{v}_\pi \quad\Longrightarrow\quad \mathbf{v}_\pi = (I - \gamma P_\pi)^{-1}\mathbf{r}_\pi . \]

The inverse exists for \(\gamma < 1\): every eigenvalue of a stochastic matrix has modulus at most 1, so every eigenvalue of \(\gamma P_\pi\) has modulus at most \(\gamma < 1\) and \(I - \gamma P_\pi\) has no zero eigenvalue. The Neumann series gives a meaning to the inverse:

\[ (I - \gamma P_\pi)^{-1} = \sum_{k=0}^\infty \gamma^k P_\pi^k , \]

whose \((s, s')\) entry is the expected discounted number of visits to \(s'\) starting from \(s\), the successor representation. Each row sums to \(1/(1-\gamma)\). For the running example at \(\gamma = 0.9\) it is \(\begin{pmatrix} 7.523 & 2.477 \\ 6.606 & 3.394 \end{pmatrix}\): starting Fresh you spend 7.5 discounted steps Fresh and 2.5 Tired, and the value is \(7.523 \times 2 + 2.477 \times 0 = 15.046\). Cost: \(O(n^3)\), fine for thousands of states, hopeless for \(10^{20}\).

The Bellman operators are γ-contractions

Define, for any \(\mathbf{v}\),

\[ (T^\pi \mathbf{v})(s) = \sum_a \pi(a\mid s)\Big[r(s,a) + \gamma \sum_{s'} p(s'\mid s,a)\, v(s')\Big], \qquad (T^\ast \mathbf{v})(s) = \max_a \Big[r(s,a) + \gamma \sum_{s'} p(s'\mid s,a)\, v(s')\Big]. \]

Claim: \(\|T^\ast \mathbf{u} - T^\ast \mathbf{v}\|_\infty \le \gamma \|\mathbf{u} - \mathbf{v}\|_\infty\), and the same for \(T^\pi\).

Proof. Use \(|\max_a f(a) - \max_a g(a)| \le \max_a |f(a) - g(a)|\). For any \(s\),

\[ |(T^\ast\mathbf{u})(s) - (T^\ast\mathbf{v})(s)| \le \max_a \gamma \Big|\sum_{s'} p(s'\mid s,a)\,(u(s') - v(s'))\Big| \le \gamma \max_a \sum_{s'} p(s'\mid s,a)\,\|\mathbf{u} - \mathbf{v}\|_\infty = \gamma\|\mathbf{u} - \mathbf{v}\|_\infty . \]

Take the max over \(s\). For \(T^\pi\) replace the max over actions by the \(\pi\)-average; the same chain of inequalities holds.

Consequences (Banach fixed-point theorem, since \((\mathbb{R}^n, \|\cdot\|_\infty)\) is complete):

  1. \(T^\ast\) has exactly one fixed point; call it \(\mathbf{v}_\ast\). The Bellman optimality equation has a unique solution.
  2. From any start, \(\mathbf{v}_{k+1} = T^\ast \mathbf{v}_k\) converges to \(\mathbf{v}_\ast\) with \(\|\mathbf{v}_k - \mathbf{v}_\ast\|_\infty \le \gamma^k \|\mathbf{v}_0 - \mathbf{v}_\ast\|_\infty\). That is value iteration (dynamic programming).
  3. A policy greedy with respect to \(\mathbf{v}_\ast\) satisfies \(T^{\pi}\mathbf{v}_\ast = T^\ast\mathbf{v}_\ast = \mathbf{v}_\ast\), so \(\mathbf{v}_\ast\) is also the fixed point of \(T^\pi\), that is \(\mathbf{v}_\pi = \mathbf{v}_\ast\): a deterministic, stationary optimal policy exists.

Linear-programming form and occupancy measures

\(\mathbf{v}_\ast\) is the smallest \(\mathbf{v}\) satisfying \(v(s) \ge r(s,a) + \gamma\sum_{s'} p(s'\mid s,a) v(s')\) for all \((s,a)\), so it solves the linear programme \(\min_{\mathbf{v}} \sum_s \mu_0(s) v(s)\) subject to those \(|\mathcal{S}||\mathcal{A}|\) constraints. The dual variables are the discounted state–action occupancies \(d_\pi(s,a) = \sum_t \gamma^t \Pr_\pi(S_t = s, A_t = a)\), and the dual is \(\max_d \sum_{s,a} d(s,a)\, r(s,a)\) subject to flow conservation \(\sum_a d(s',a) = \mu_0(s') + \gamma\sum_{s,a} p(s'\mid s,a)\, d(s,a)\), \(d \ge 0\). Expected return is linear in the occupancy measure, a fact behind constrained MDPs, imitation learning and many offline-RL methods.

Derivation: potential-based shaping leaves optimal policies unchanged

Let \(r'(s,a,s') = r(s,a,s') + \gamma\Phi(s') - \Phi(s)\). Along any trajectory the shaped return telescopes:

\[ \sum_{k=0}^{\infty} \gamma^k \big(R_{t+k+1} + \gamma\Phi(S_{t+k+1}) - \Phi(S_{t+k})\big) = G_t - \Phi(S_t) \]

(for bounded \(\Phi\) and \(\gamma < 1\)). So \(q'_\pi(s,a) = q_\pi(s,a) - \Phi(s)\) for every policy: all actions in a state are shifted by the same amount, the argmax is unchanged, and so is the set of optimal policies. A good potential is an estimate of \(v_\ast\); with \(\Phi = v_\ast\) the shaped optimal values are all zero and every one-step greedy choice is already correct. Ng, Harada and Russell (1999) also showed that, without further assumptions on the MDP, potential-based shaping is the only form with this guarantee.

History

From Markov chains to the language of RL

Andrey Markov studied chains of dependent random variables in 1906. Richard Bellman at the RAND Corporation developed dynamic programming in the 1950s, wrote the recursive "functional equation" now named after him, introduced the discrete stochastic version of optimal control known as the MDP (1957), and coined the phrase "curse of dimensionality". Lloyd Shapley's Stochastic Games (1953) had already set out the multi-agent version with a value-iteration argument. Ronald Howard's Dynamic Programming and Markov Processes (1960) gave policy iteration. For decades MDPs belonged to operations research and control; according to Sutton and Barto, the full integration of dynamic programming with online learning came with Chris Watkins's 1989 thesis, whose MDP framing of RL was widely adopted. Puterman's Markov Decision Processes (1994) is the standard reference. The reward hypothesis, stated informally for decades, was given a precise set of sufficient conditions by Bowling, Martin, Abel and Dabney in Settling the Reward Hypothesis (2022).

Build it

Exact policy evaluation by solving the linear system, the optimality check through \(q\), and a Monte Carlo estimate of the same value, for the Fresh/Tired MDP (NumPy):

import numpy as np, itertools
S, A = ["Fresh", "Tired"], ["work", "rest"]
P = np.zeros((2, 2, 2)); R = np.zeros((2, 2))      # P[s, a, s'], R[s, a]
P[0, 0], R[0, 0] = [0.7, 0.3], 2.0                  # Fresh, work
P[0, 1], R[0, 1] = [1.0, 0.0], 0.0                  # Fresh, rest
P[1, 0], R[1, 0] = [0.0, 1.0], 1.0                  # Tired, work
P[1, 1], R[1, 1] = [0.8, 0.2], 0.0                  # Tired, rest

def evaluate(pol, g):                              # exact: v = (I - g P_pi)^-1 r_pi
    Ppi = P[[0, 1], pol]; rpi = R[[0, 1], pol]
    return np.linalg.solve(np.eye(2) - g * Ppi, rpi)

for g in (0.9, 0.5):
    vals = {pol: evaluate(list(pol), g) for pol in itertools.product(range(2), repeat=2)}
    for pol, v in vals.items():
        print(f"gamma {g}  Fresh:{A[pol[0]]:4s} Tired:{A[pol[1]]:4s}  v = {v.round(3) + 0.0}")
    best = max(vals, key=lambda p: vals[p].sum())
    v = vals[best]; q = R + g * P @ v                # q[s, a] = r + g * sum_s' p v(s')
    print(f"  best {[A[a] for a in best]}; q* =\n{q.round(3)}; greedy-in-q* = {[A[a] for a in q.argmax(1)]}")

# Monte Carlo check of v_pi(Fresh) for (work, rest) at gamma 0.9
rng, g, pol = np.random.default_rng(0), 0.9, [0, 1]
returns = []
for _ in range(20000):
    s, G, disc = 0, 0.0, 1.0
    for t in range(150):                              # 0.9^150 ~ 1.4e-7: truncation is negligible
        a = pol[s]; G += disc * R[s, a]; disc *= g
        s = int(rng.random() < P[s, a, 1])            # next state: 1 = Tired
    returns.append(G)
r = np.array(returns)
print(f"MC estimate v(Fresh) = {r.mean():.3f} +/- {1.96 * r.std() / np.sqrt(len(r)):.3f}  (exact {evaluate(pol, g)[0]:.3f})")
gamma 0.9  Fresh:work Tired:work  v = [12.703 10.   ]
gamma 0.9  Fresh:work Tired:rest  v = [15.046 13.211]
gamma 0.9  Fresh:rest Tired:work  v = [ 0. 10.]
gamma 0.9  Fresh:rest Tired:rest  v = [0. 0.]
  best ['work', 'rest']; q* =
[[15.046 13.541]
 [12.89  13.211]]; greedy-in-q* = ['work', 'rest']
gamma 0.5  Fresh:work Tired:work  v = [3.538 2.   ]
gamma 0.5  Fresh:work Tired:rest  v = [3.429 1.524]
gamma 0.5  Fresh:rest Tired:work  v = [0. 2.]
gamma 0.5  Fresh:rest Tired:rest  v = [0. 0.]
  best ['work', 'work']; q* =
[[3.538 1.769]
 [2.    1.615]]; greedy-in-q* = ['work', 'work']
MC estimate v(Fresh) = 15.052 +/- 0.023  (exact 15.046)

Picking the best policy by the sum of its values is safe here only because the theory guarantees an optimal policy dominates in every state; the greedy-in-q* line confirms the winner satisfies the Bellman optimality equation (it is greedy with respect to its own \(q\)).

Things to try

  • Sweep \(\gamma\) from 0.5 to 0.9 and find the value at which the optimal action in Tired flips from work to rest. Explain the threshold from the two \(q\)-values.
  • Add a third action, "coffee", in Tired: reward 1.5, but leads to a new state "Crashed" with probability 0.5, where every action gives 0 and you return to Tired with probability 0.5. Is coffee ever optimal?
  • Compute the successor matrix \((I - \gamma P_\pi)^{-1}\) for each policy and check that \(\mathbf{v}_\pi\) equals it times \(\mathbf{r}_\pi\).
  • Add a potential-based shaping term with \(\Phi = (5, 0)\) and verify, by evaluating all four policies, that the ranking does not change while the values shift by exactly \(-\Phi\).

Common misconceptions

  • "The Markov property is a property of the environment." It is a property of the state you give the agent. The same environment is Markov or not depending on what you include.
  • "γ is just a hyperparameter for stability." It defines the objective. The running example has different optimal policies at γ = 0.5 and γ = 0.9.
  • "The optimal policy maximises the next reward." It maximises expected return. Working when tired maximises the next reward and is suboptimal at γ = 0.9.
  • "If my agent maximises reward, it will do what I want." Only if the reward encodes what you want, which is the subject of reward design and much of AI safety.

Check yourself

Why does the Bellman expectation equation for a fixed policy have a unique solution when γ < 1, and how would you compute it for 500 states?

In matrix form \(\mathbf{v} = \mathbf{r}_\pi + \gamma P_\pi\mathbf{v}\). All eigenvalues of \(\gamma P_\pi\) have modulus at most \(\gamma < 1\), so \(I - \gamma P_\pi\) is invertible and \(\mathbf{v}_\pi = (I - \gamma P_\pi)^{-1}\mathbf{r}_\pi\) is the unique solution. For 500 states, a direct linear solve (a 500 × 500 system) takes milliseconds; iterative evaluation also works and scales better to very large sparse problems.

You have q* but no model. How do you act optimally? You have v* but no model. Can you?

With \(q_\ast\), pick \(\arg\max_a q_\ast(s,a)\); no model needed. With only \(v_\ast\) you must compute \(\arg\max_a \sum_{s',r} p(s',r\mid s,a)[r + \gamma v_\ast(s')]\), which needs \(p\). That is why model-free control (SARSA, Q-learning, DQN) learns action values.

In the running example, working when tired gives reward 1 and resting gives 0. Why is resting optimal at γ = 0.9?

Because value, not reward, decides. \(q_\ast(T,\text{rest}) = 0.9(0.8 \times 15.046 + 0.2 \times 13.211) = 13.211\), while \(q_\ast(T,\text{work}) = 1 + 0.9 \times 13.211 = 12.890\). Resting gives up 1 now to get back to Fresh, where each step is worth 2, with high probability. At γ = 0.5 the future is discounted so heavily that the immediate 1 wins.

An Atari agent sees one frame at a time. Is that an MDP? What did DQN do about it, and what is the general fix?

No: one frame does not reveal velocities, so the future is not determined by the current observation. DQN stacked the last four frames as the state, which recovers velocity. The general fix is to build a state from history: frame stacks, a recurrent hidden state, or a belief over hidden states (the POMDP view).

Show that adding a constant c to every reward changes the optimal policy in an episodic task but not in a continuing one with γ < 1.

Continuing task: every policy's return increases by the same \(c/(1-\gamma)\) from every state, so the ranking is unchanged. Episodic task: the added total is \(c\) times the episode's length, which depends on the policy. A positive \(c\) rewards dragging episodes out; a negative \(c\) rewards ending them fast (which is why "−1 per step" rewards produce shortest-path behaviour). The constant is not potential-based when episode length varies.

Prove that the Bellman optimality operator is a γ-contraction in the max norm. Why does this make value iteration converge regardless of initialisation?

For each state, \(|\max_a f(a) - \max_a g(a)| \le \max_a |f(a) - g(a)|\), and each \(f(a) - g(a)\) is γ times an average of \(u(s') - v(s')\), bounded by \(\gamma\|\mathbf{u}-\mathbf{v}\|_\infty\). So \(\|T^\ast\mathbf{u} - T^\ast\mathbf{v}\|_\infty \le \gamma\|\mathbf{u}-\mathbf{v}\|_\infty\). Applying it to \(\mathbf{v}_k\) and the fixed point \(\mathbf{v}_\ast\) gives \(\|\mathbf{v}_k - \mathbf{v}_\ast\|_\infty \le \gamma^k\|\mathbf{v}_0 - \mathbf{v}_\ast\|_\infty \to 0\) from any \(\mathbf{v}_0\).

Hard: in RL fine-tuning of an LLM, what are the state, action, transition and reward? Why do many methods treat the whole response as a single action?

State: prompt plus tokens generated so far; action: the next token (vocabulary of ~10⁵); transition: deterministic append; reward: usually a scalar at the end (reward-model score or a verifier's pass/fail), sometimes with a per-token KL penalty to a reference model. Because the dynamics are trivial and the reward is terminal, the response-level view (a contextual bandit: context = prompt, action = whole response) loses little and avoids learning per-token values. Token-level credit assignment then comes from the policy gradient itself (or from a learned value head, as in PPO-based RLHF).

Go deeper

Papers and primary sources

Videos and lectures

Articles

Courses and books

Where this leads