TAI BUI
Back to curriculum
LearnPython

MDPs, States, Actions & Rewards

A Markov Decision Process is five things: states, actions, transitions, rewards, a discount. Every RL algorithm you'll meet in this phase — Q-learning, PPO, DPO, GRPO — optimizes over this same shape. Learn it once and the rest of reinforcement learning comes for free.

TIME: ~45 minutesPREREQUISITES: Phase 1 · 06 (Probability & Distributions), Phase 2 · 01 (ML Taxonomy)

Learning Objectives

  • Define the five components of a Markov Decision Process (states, actions, transitions, rewards, discount) and state the Markov property that justifies modeling a task as one.
  • Distinguish a policy, a return, a value function V^π(s), and a Q-value Q^π(s,a), and explain how the Bellman equation splits expected return into immediate reward plus discounted future value.
  • Implement a small MDP (a 4x4 GridWorld) in code, roll out a random policy, and compute exact state values with iterative policy evaluation.
  • Diagnose the recurring MDP formulation failures, non-Markovian state, sparse or hacked rewards, and mis-specified discount or reward scale, before they surface as training bugs.

The Problem

You're writing a chess bot. Or an inventory planner. Or a trading agent. Or the PPO loop that trains a reasoning model. Four different domains, and one surprising fact: all four collapse to the same mathematical object.

Supervised learning hands you (x, y) pairs and asks you to fit a function. Reinforcement learning gives you no labels, only a stream of states, the actions you took, and a scalar reward. Did the move win the game? Did the restock decision save money? Did the trade turn a profit? Did the token the LLM just produced earn a higher score from the judge?

You can't learn from that stream until you formalize it. "What I saw," "what I did," "what happened next," and "how good that was" each need to become an object you can reason about. That formalization is a Markov Decision Process. Every RL algorithm in this phase, including the RLHF and GRPO loops at the end, optimizes over this same shape.

Warm-up0/3
1. What is the expected value of one roll of a fair six-sided die?Warm-up
Six boxes for the faces 1 to 6 of a fair die, each labelled with probability 1/6.
2. What does the sum 1 + 1/2 + 1/4 + 1/8 + ... converge to?Warm-up
Eight bars for the first terms of 1 + 1/2 + 1/4 + 1/8 + ..., each half the height of the one before: 1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, followed by an ellipsis.
3. In supervised learning, what does the training data consist of?Warm-up
Three rows, each a chain from an input (an email's text, a house's size, a photo) to a box 'Model, trained on: ?' to an answer (spam or not spam, a price, cat or dog).
Illustrative examples.
Check: The Problem0/2
1. A chess bot, an inventory planner, a trading agent and an LLM training loop can all be reduced to the same formal object. What is it?Define
Four cards: chess bot (sees the board, plays a move, gets win or loss), inventory planner (sees stock and demand, orders a quantity, gets revenue minus cost), trading agent (asks whether the trade turned a profit), LLM training loop (sees context, emits a token, gets a score from a judge), above a box saying all four fit one formal object, name it: ?
2. What makes the input to reinforcement learning different from the input to supervised learning?Explain
Two cards: a spam filter (takes an email, returns spam or not spam) and a chess bot (takes a board position, returns a move, goal: win the game), each with the line trained on: ?.

The Concept

Markov decision process: states, actions, transitions, rewards, discount

The five objects.

  • States S. Everything the agent needs to decide. In GridWorld, the cell. In chess, the board. In an LLM, the context window plus any memory.
  • Actions A. The choices. Move up/down/left/right. Play a move. Emit a token.
  • Transitions P(s' | s, a). Given state s and action a, the distribution over next state. Deterministic in chess, stochastic in inventory, almost-deterministic in LLM decoding.
  • Rewards R(s, a, s'). The scalar signal. Win = +1, loss = -1. Revenue minus cost. The log-likelihood ratio term in GRPO.
  • Discount γ ∈ [0, 1). How much future reward counts vs present. γ = 0.99 buys a horizon of ~100 steps; γ = 0.9 buys ~10.

The Markov property P(s_{t+1} | s_t, a_t) = P(s_{t+1} | s_0, a_0, …, s_t, a_t). The future depends only on the present state. If it doesn't, the state representation is incomplete: that's a failure of the state, not of the method.

Policies and returns. A policy π(a | s) maps states to action distributions. The return G_t = r_t + γ r_{t+1} + γ² r_{t+2} + … is the discounted sum of future rewards. The value V^π(s) = E[G_t | s_t = s] is the expected return starting from s under policy π. The Q-value Q^π(s, a) = E[G_t | s_t = s, a_t = a] is the expected return starting with a specific action. Every RL algorithm estimates one of these two, then improves π accordingly.

The Bellman equations. The fixed-point equations that everything in this phase uses:

V^π(s) = Σ_a π(a|s) Σ_{s', r} P(s', r | s, a) [r + γ V^π(s')] Q^π(s, a) = Σ_{s', r} P(s', r | s, a) [r + γ Σ_{a'} π(a'|s') Q^π(s', a')]

These split expected return into "this step's reward" plus "discounted value of where you land." Recursive. Every algorithm in Phase 9 either iterates this equation to convergence (dynamic programming), samples from it (Monte Carlo), or bootstraps it one step (temporal difference).

Check: The Concept0/12
1. What does the state S mean in an MDP?Define
A 4x4 grid of cells labelled (row,column) with the agent outlined at (1,2) and the terminal cell (3,3) outlined in green, beside a card listing agent cell (1, 2), terminal (3, 3) and grid size 4 x 4.
2. What is a policy π(a | s)?Define
A state box s = (1, 2) with four arrows labelled up 0.25, down 0.25, left 0.25 and right 0.25, beside the lesson's uniform_policy code that returns 0.25 for each action.
3. How is the return G_t defined?Define
A table of a six-step episode in the 4x4 GridWorld: states (0,0), (1,0), (2,0), (3,0), (3,1), (3,2), actions down, down, down, right, right, right, and reward -1 at every step, ending in terminal cell (3,3), with gamma 0.99 and G_0 = ?.
4. What does the value V^π(s) measure?Define
A 4x4 grid with the start cell s = (0,0) marked, beside three episodes of the uniform random policy started in s with returns -36, -18, -45 (steps 36, 18, 45), and the text V^π(s) = ?.
Three real rollouts of the lesson's rollout() with random.Random(3).
5. What is the Q-value Q^π(s,a), in contrast to V^π(s)?Define
A state box s = (1, 2) labelled V^π(s) = ? with four arrows to four boxes Q^π(s, up) = ?, Q^π(s, down) = ?, Q^π(s, left) = ? and Q^π(s, right) = ?.
6. What do the Bellman equations for V^π and Q^π decompose expected return into?Define
The Bellman equations for V^π(s) and Q^π(s,a) written out, above a one-step diagram: state s, a policy arrow π(a|s) to action a, then a transition P(s', r | s, a) to a reward r and a next state s'.
7. What does the discount γ control?Define
Five boxes S (16 cells), A (4 moves), P (deterministic), R (-1 per step) and γ (0.99, lesson default) with the γ box outlined, above the signature policy_evaluation(policy, gamma=0.99, tol=1e-6).
8. Which equation states the Markov property?Define
A history of seven boxes: s_0 = (0,0), a_0 = down, s_1 = (1,0), a_1 = right, s_2 = (1,1), a_2 = down, s_3 = ?, with a note that at t = 2 the agent is in s_2 and has just chosen a_2.
9. A task's chosen state fails the Markov property. What is the right conclusion?Explain
Two histories drawn with abstract symbols, A, B, C and X, Y, C, both ending in the same current observation C and the same action a, but followed by different next observations D and E.
Abstract symbols, not a real task.
10. How does a return G_t differ from a value V^π(s)?Explain
A 4x4 grid with the start cell s = (2,2) and the path of one 8-step episode of the uniform random policy drawn in orange, beside a card with reward -1 on every step, gamma 0.99, G_0 = ? and V^π(s) = ?.
A real rollout (seed 11) using the lesson's step() and uniform_policy.
11. With γ = 0.9, an episode earns rewards -1, -1, -1 on three steps. What is the return G_0?Apply
Three boxes t = 0, t = 1, t = 2 each with reward r = -1, with gamma 0.9 and G_0 = ?.
12. In some state, the policy picks one action that gives reward -1 and lands in a state with V = -4. With γ = 0.5, what is this state's value?Apply
A box 'this state, V = ?' with an arrow labelled reward -1 to a box 'next state, V = -4', with gamma 0.5.

Build It

Step 1: a tiny deterministic MDP

A 4×4 GridWorld. Agent starts top-left, terminal at bottom-right, reward of -1 per step, actions {up, down, left, right}. See code/main.py.

python
GRID = 4
TERMINAL = (3, 3)
ACTIONS = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}
 
def step(state, action):
    if state == TERMINAL:
        return state, 0.0, True
    dr, dc = ACTIONS[action]
    r, c = state
    nr = min(max(r + dr, 0), GRID - 1)
    nc = min(max(c + dc, 0), GRID - 1)
    return (nr, nc), -1.0, (nr, nc) == TERMINAL

Five lines. That's the entire environment: deterministic transitions, a constant step penalty, one absorbing terminal state.

Step 2: roll out a policy

A policy is a function from state to action distribution. The simplest: uniform random.

python
def uniform_policy(state):
    return {a: 0.25 for a in ACTIONS}
 
def rollout(policy, max_steps=200):
    s, total, steps = (0, 0), 0.0, 0
    for _ in range(max_steps):
        a = sample(policy(s))
        s, r, done = step(s, a)
        total += r
        steps += 1
        if done:
            break
    return total, steps

Run the random policy 1000 times. Average return is around -60 to -80 for this 4×4 board. The optimal return is -6 (straight-line path down-right). Closing that gap is everything in Phase 9.

Step 3: compute V^π exactly via the Bellman equation

For small MDPs the Bellman equation is a linear system. Enumerate states, apply the expectation, iterate until the values stop changing.

python
def policy_evaluation(policy, gamma=0.99, tol=1e-6):
    V = {s: 0.0 for s in all_states()}
    while True:
        delta = 0.0
        for s in all_states():
            if s == TERMINAL:
                continue
            v = 0.0
            for a, pi_a in policy(s).items():
                s_next, r, _ = step(s, a)
                v += pi_a * (r + gamma * V[s_next])
            delta = max(delta, abs(v - V[s]))
            V[s] = v
        if delta < tol:
            return V

This is iterative policy evaluation, the first algorithm in Sutton & Barto and the theoretical foundation of every RL method that follows.

Step 4: γ is a hyperparameter with physical meaning

Effective horizon is roughly 1 / (1 - γ). γ = 0.9 → 10 steps. γ = 0.99 → 100 steps. γ = 0.999 → 1000 steps.

Too low and the agent acts myopically. Too high and credit assignment becomes noisy, because many early steps share responsibility for far-future reward. LLM RLHF typically uses γ = 1 because episodes are short and bounded. Control tasks use 0.95–0.99. Long-horizon strategy games use 0.999.

Check: Build It0/11
1. Why does policy_evaluation keep sweeping until delta falls below tol?Explain
The loop part of policy_evaluation, and a table of real sweeps for the uniform policy with gamma 0.99: delta shrinks from 1.8930 at sweep 1 to 9.79e-07 at sweep 305, while V at (0,0) moves from -1.000 to -39.412.
In-place sweeps, as in the lesson's policy_evaluation snippet. The main.py version updates all states from the previous sweep, so its sweep counts differ.
2. Why does step return a reward of 0.0 when called on the terminal state?Explain
A 4x4 grid with the terminal cell (3,3) marked, the first lines of the lesson's step function including the check for state == TERMINAL that returns state, 0.0, True, and a terminal call step((3, 3), 'up') that prints ((3, 3), 0.0, True).
Output of the lesson's step().
3. Why does a very high γ such as 0.999 make credit assignment noisy?Explain
A timeline from t = 0 to t = 1000 with a blue dot for the action at each step, a gap marked with an ellipsis, and a reward arriving at the last step, with gamma 0.999 and effective horizon 1000 steps.
Schematic: dots are not drawn to scale.
4. Using the effective horizon of about 1/(1-γ), what horizon does γ = 0.99 buy?Apply
A curve of the weight 0.99^k of a reward k steps ahead for k from 0 to 300, falling smoothly from 1 toward 0.05, with ticks every 50 steps and no marked point.
5. On the 4x4 GridWorld with -1 per step, how does the mean return of the uniform-random policy compare with the optimal return?Apply
Two 4x4 grids with start S at the top left and terminal at the bottom right, one with four short arrows in every cell for the uniform random policy and one with a down arrow and a right arrow in each cell for the down-right policy, each marked reward -1 per step.
6. With GRID = 4 and TERMINAL = (3, 3), what does step((3, 2), 'right') return?Apply
A 4x4 grid of cells labelled (row,column) with the agent outlined at (3,2) next to terminal (3,3), the lesson's step function, and the call step((3, 2), 'right').
7. What does step((0, 0), 'up') return?Apply
A 4x4 grid with the agent at (0,0) and an arrow labelled up pointing out of the top of the grid, the lesson's step function, and the call step((0, 0), 'up').
8. policy_evaluation runs on the uniform policy with gamma = 0. What is the value of each non-terminal state?Apply
A 4x4 grid where the terminal cell shows 0.0 and every other cell shows ?, beside the update lines of policy_evaluation (v += pi_a * (r + gamma * V[s_next])), for the uniform policy with gamma 0.
9. A random-policy rollout with max_steps=200 never reaches the terminal. What total return does it report?Apply
The loop of rollout() with max_steps 200 and a trace of a real random-policy run: steps 1, 2, 3 and 200 each with reward -1.0 and done=False, then 'loop ends: range(200) is used up' and total = ?.
A real run of the lesson's step() with random.Random(0) and uniform_policy, picked because it never reaches the terminal. The loop is shown in simplified form.
10. An agent with γ = 0.9 grabs a small reward now and ignores a much larger payoff 50 steps away. Which ingredient explains this?Analyze
A timeline marked now, +10, +20, +30, +40 and +50 steps with a small reward at now and a much larger reward at +50, with gamma 0.9.
Schematic: reward sizes are not drawn to scale.
11. A teammate says a random-policy mean return of about -70 on the 4x4 GridWorld must be a bug, since the optimal return is -6. What explains the gap?Analyze
A 4x4 grid with start S and terminal T, beside a teammate's message: random policy mean return about -70, optimal return -6, and the claim that -70 must be a bug.

Pitfalls

  • Non-Markovian state. If you need the last three observations to decide, the "state" isn't just the current observation. Fix: stack frames (DQN on Atari stacks 4) or use a recurrent state (LSTM/GRU over observations).
  • Sparse rewards. Win-only rewards make learning nearly impossible in large state spaces. Shape rewards (intermediate signal) or bootstrap with imitation (Phase 9 · 09).
  • Reward hacking. Optimizing a proxy reward often produces pathological behavior. OpenAI's boat-racing agent spun in circles collecting powerups forever instead of finishing the race. Always define reward from the target outcome, not the proxy.
  • Discount mis-spec. γ = 1 on an infinite-horizon task makes every value infinite. Always cap with either a finite horizon or γ < 1.
  • Reward scale. Rewards of {+100, -100} vs {+1, -1} give identical optimal policies but vastly different gradient magnitudes. Normalize to [-1, 1]-ish before plugging into PPO/DQN.
Check: Pitfalls0/7
1. Why must γ = 1 be avoided on an infinite-horizon task unless you add a finite horizon?Explain
Boxes r_0 to r_4, each +1, followed by an ellipsis and an arrow with no end, for a task with no end, with gamma = 1 and the text value = r_0 + r_1 + r_2 + ... = ?.
The +1 per step is illustrative.
2. Why do win-only rewards fail in large state spaces, and what fixes them?Explain
A row of boxes for one game: move 1, move 2 and move 3 each with reward 0, an ellipsis, and the last move with reward ?, for a win-only reward in a large state space.
Schematic, no real game.
3. Rewards of {+100, -100} and {+1, -1} give the same optimal policy. Why normalize anyway?Explain
Two cards for a toy choice between actions A and B: rewards of +100 for a win and -100 for a loss on the left, +1 and -1 on the right.
4. An agent trained to win a boat race instead spins in circles collecting powerups forever. What went wrong in the formulation?Analyze
A schematic oval boat race course with a green finish line at the top and, on the right side, a pair of orange circles marking the agent's path looping around four blue powerup dots.
Schematic, not a recording.
5. A policy needs the last three observations to decide well, but the state is only the current observation. What is the fix?Analyze
Three observation boxes o_(t-2), o_(t-1) and o_t, with an arrow from o_t to a box saying the state s_t is o_t, the current observation only.
6. You reward a cleaning robot per unit of dirt it collects. It learns to dump dirt out and collect it again. Which formulation failure is this?Analyze
Four panels of a cleaning robot: 1 collect (dirt moves from the floor to the bin, reward per unit), 2 dump out (dirt back on the floor, no reward), 3 collect again (reward per unit), 4 dump out, with four illustrative dots of dirt.
Schematic: each panel shows the state after the action. Four dots per panel are illustrative.
7. A never-ending control task needs the agent to plan about 100 steps ahead. Which discount fits?Design
A timeline arrow with no end from now, with a marker at step 100 and an orange bracket labelled that the agent must plan this far ahead.

Use It

The 2026 stack reduces every RL pipeline to an MDP before touching code:

SituationStateActionRewardγ
Control (locomotion, manipulation)Joint angles + velocitiesContinuous torquesTask-specific shaped0.99
Games (chess, Go, poker)Board + historyLegal moveWin=+1 / loss=-11.0 (finite)
Inventory / pricingStock + demandOrder qtyRevenue - cost0.95
RLHF for LLMsContext tokensNext tokenReward-model score at end1.0 (episode ~200 tokens)
GRPO for reasoningPrompt + partial responseNext tokenVerifier 0/1 at end1.0

Write the five tuples before writing any training loop. Most "RL doesn't work" bug reports trace back to an MDP formulation that was broken on paper.

Check: Use It0/2
1. You model GRPO for a reasoning model. Which state and action does the Use It table assign?Apply
A card for a reasoning model mid-answer with a question and the answer written so far, above a box for a verifier that scores the final answer 0 or 1 and a box for GRPO training.
Illustrative response text.
2. You model a warehouse restocking task. Which formulation fits?Design
A warehouse sketch: shelf (items in stock), customers (buy items), supplier (delivers orders) and books (money in and out), above periods 1, 2, 3 and an ellipsis for restocking that repeats.
Schematic.

Ship It

Save as outputs/skill-mdp-modeler.md:

markdown
---
name: mdp-modeler
description: Given a task description, produce a Markov Decision Process spec and flag formulation risks before training.
version: 1.0.0
phase: 9
lesson: 1
tags: [rl, mdp, modeling]
---
 
Given a task (control / game / recommendation / LLM fine-tuning), output:
 
1. State. Exact feature vector or tensor spec. Justify Markov property.
2. Action. Discrete set or continuous range. Dimensionality.
3. Transition. Deterministic, stochastic-with-known-model, or sample-only.
4. Reward. Function and source. Sparse vs shaped. Terminal vs per-step.
5. Discount. Value and horizon justification.
 
Refuse to ship any MDP where the state is non-Markovian without explicit mention of frame-stacking or recurrent state. Refuse any reward that was not defined in terms of the target outcome. Flag any `γ ≥ 1.0` on an infinite-horizon task. Flag any reward range >100x the typical step reward as a likely gradient-explosion source.
Check: Ship It0/1
1. Which draft spec should the mdp-modeler skill refuse or flag?Design
A card listing the five items mdp-modeler outputs (state, action, transition, reward, discount), above a box for a draft spec arriving, an arrow, and a box asking refuse or flag? for the mdp-modeler skill.

Exercises

  1. Easy. Implement the 4×4 GridWorld and random-policy rollout in code/main.py. Run 10,000 episodes. Report mean and std of return. Compare to the optimal return (-6).
  2. Medium. Run policy_evaluation with γ ∈ {0.5, 0.9, 0.99} for the uniform-random policy. Print V as a 4×4 grid for each. Explain why the state values near the terminal grow faster with larger γ.
  3. Hard. Turn the GridWorld stochastic: each action slips to an adjacent direction with probability p = 0.1. Re-evaluate the uniform policy. Does V[start] get better or worse? Why?

Key Terms

TermWhat people sayWhat it actually means
MDP"Reinforcement learning setup"Tuple (S, A, P, R, γ) satisfying the Markov property.
State"What the agent sees"Sufficient statistic for future dynamics under the chosen policy class.
Policy"Agent's behavior"Conditional distribution π(a | s) or deterministic map s → a.
Return"Total reward"Discounted sum Σ γ^t r_t from the current step.
Value"How good a state is"Expected return under π starting from s.
Q-value"How good an action is"Expected return under π starting from s with first action a.
Bellman equation"Dynamic programming recursion"Fixed-point decomposition of value / Q into one-step reward plus discounted successor value.
Discount γ"Future vs present"Geometric weight on far-future reward; effective horizon ~1/(1-γ).

Further Reading

Code

Ships With