Skip to main content
© 2026 ePowerAI — free, open courseware. No login required.
CoursesContact
ePOWERAI
CoursesContact
Week 1: Reinforcement Learning Problem Formulation
Reinforcement Learning

Guided Path · Beginner

  1. 01Reinforcement Learning: Agents, Rewards, and MDPs
  2. 02Bandits: Exploration, Exploitation, and Regret
  3. 03Returns, Value, and the Bellman Equation
  4. 04Bandits: UCB1 and Thompson Sampling
  1. 05Week 1: Reinforcement Learning Problem Formulation
  2. 06Week 2: Multi-Armed Bandits
  3. 07Week 3: Dynamic Programming for Finite MDPs
  4. 08Week 4: Monte Carlo and Temporal-Difference Learning
  5. 09Week 5: Function Approximation in Reinforcement Learning
  6. 10Week 6: Deep Q-Learning and Variants
  7. 11Week 7: Policy Gradient and Actor–Critic Methods
  8. 12Week 8: Modern Deep Reinforcement Learning Algorithms
  9. 13Week 9: Exploration, Partial Observability, and Multi-Agent Reinforcement Learning
  10. 14Week 10: Model-Based Reinforcement Learning and Planning
  11. 15Week 11: Offline Reinforcement Learning
  12. 16Week 12: Reinforcement Learning from Human Feedback
  13. 17Week 13: Direct Preference Optimization and GRPO
  14. 18Week 14: Agentic Systems and Course Capstone
Week 01· Reinforcement Learning29 min read

Week 1: Reinforcement Learning Problem Formulation

Learning Outcomes
  • Formulate sequential decision problems as Markov Decision Processes (MDPs)
  • Define and compute returns with discount factors
  • Explain the reward hypothesis and its implications for goal-directed behavior
  • Derive Bellman expectation and optimality equations
  • Distinguish between episodic and continuing tasks
Prerequisites

Background knowledge assumed:

  • Basic probability theory (probability distributions, expectation), covered in Probability & Statistics
  • Linear algebra (vectors, matrices, matrix operations), covered in Linear Algebra
  • Python programming fundamentals

Recommended: Review the Course Index for an overview of this course. The catalog learning path places RL after Linear Algebra and Optimization.

Reinforcement learning studies sequential decision making under uncertainty. Unlike supervised learning, where data is static, an RLReinforcement Learning agent's actions actively influence future states and rewards, creating a closed feedback loop.

Note
“

How do we formalize goal-directed behavior? We build toward this by asking what kind of signal the agent should maximize, and how that signal relates to the underlying environment dynamics.

Purpose of this lecture#

The core question in reinforcement learning is how to express goal-directed behavior with a single mathematical objective.

Reinforcement learning formalizes this by maximizing expected cumulative reward. Translating this objective into practical algorithms introduces three core problems:

  1. Reward specification. Specifying reward functions precisely is difficult. A misspecified reward leads an agent to optimize the literal reward signal while violating the intended goal.

  2. Uncertainty over time. Environments are stochastic and often partially observable. The agent must evaluate actions whose delayed consequences unfold over time.

  3. Computational tractability. Maximizing an infinite sum of future rewards directly is intractable. Computing solutions requires recursive structure.

This lecture addresses these problems with the MDPMarkov Decision Process formalism, value functions, and the Bellman equations. These concepts provide the mathematical encoding of sequential decision making. Later algorithms, including tabular methods, deep RLReinforcement Learning, RLHFReinforcement Learning from Human Feedback, and GRPOGroup Relative Policy Optimisation, build directly on this theory.

This lecture derives the Bellman equations from first principles, examines where the Markov assumption fails in practice, and presents the engineering techniques used to address partial observability.


Sequential decision making#

In reinforcement learning, an agent interacts with an environment over discrete time steps. This interaction forms a closed feedback loop:

  • At time step ttt, the agent observes a state sts_tst​
  • It selects an action ata_tat​
  • The environment transitions to a new state st+1s_{t+1}st+1​
  • The agent receives a scalar reward rt+1r_{t+1}rt+1​

The agent's objective is not to maximize immediate reward, but to act so as to maximize cumulative reward over time.

Intuition: Why not optimize immediate reward?

Consider a chess player who evaluates only the immediate next move, ignoring downstream consequences. That player would capture any undefended piece, even at the cost of checkmate on the following turn. Greedily maximizing immediate reward produces analogous failures in agents. For example, an agent rewarded for cleaning a room might disable its dirt sensor, accumulating reward by blinding itself to unfinished tasks. The temporal coupling of actions and delayed consequences defines the problem.

This temporal coupling distinguishes reinforcement learning from:

  • Supervised learning, where data is fixed and independent of the learner's actions
  • Standard optimization, where decisions are made once rather than sequentially

The notation rt+1r_{t+1}rt+1​ for the reward received after taking action ata_tat​ follows the Sutton and Barto convention: reward is indexed by the time step at which the agent receives it, rather than when the action occurred. This notation is standard across RL literature.

Formalizing "maximize cumulative reward over time" requires two components: an environment model (an MDPMarkov Decision Process) and an accumulation criterion (the return). We begin with the reward hypothesis, which formalizes the scalar objective.


The reward hypothesis#

A foundational premise in reinforcement learning is the Reward Hypothesis:

“

All goals and purposes can be well thought of as the maximization of the expected value of the cumulative sum of a received scalar signal (reward).

This hypothesis asserts that complex behaviors, such as playing games or robotic locomotion, can be framed as maximizing expected cumulative reward. It is a working hypothesis rather than a mathematical theorem, and much of modern reinforcement learning explores its practical limits.

A concrete starting point#

Before examining where the hypothesis succeeds and fails, consider the simplest case where it clearly works.

Gridworld navigation. An agent moves through a 4×44 \times 44×4 grid to reach a goal cell in the lower-right corner. The reward function assigns +1+1+1 upon reaching the goal and 000 at every other step. This is unambiguous and easy to specify. An agent maximizing expected cumulative reward will learn to navigate efficiently to the goal. The reward hypothesis applies cleanly.

Atari Pong. Reward is +1+1+1 when the agent scores a point and −1-1−1 when the opponent scores. This objective is also unambiguous. Mnih et al. (2013) demonstrated that DQNDeep Q-Network learned competitive policies directly from pixel inputs and score deltas, providing early empirical support for the hypothesis.

These cases share a key property: the reward function captures the intended goal. The difficulty arises when the written reward diverges from the desired behavior.

Why reward design matters#

The hypothesis does not prescribe how to design reward functions. Reward specification remains a central challenge in RLReinforcement Learning. The same principles apply directly to RLHFReinforcement Learning from Human Feedback, preference optimization (GRPOGroup Relative Policy Optimisation, DPODirect Preference Optimization, PPOProximal Policy Optimisation), and autonomous agents. Three common failure modes arise:

  • Sparse rewards: signal arrives only at task completion, making learning slow
  • Dense rewards: accelerate learning but risk reward hacking
  • Reward misspecification: the gap between the written reward and the actual goal

The tension between what is easy to specify and what is safe to optimize is a recurring theme across RL.

With the reward hypothesis establishing the scalar objective, we next formalize the environment: the mathematical framework defining how actions yield transitions and rewards.


Markov decision processes (MDPs)#

The canonical mathematical model for reinforcement learning is the Markov Decision Process (MDPMarkov Decision Process).

An MDPMarkov Decision Process is defined by the tuple:

(S, A, P, R, γ)(\mathcal{S},\, \mathcal{A},\, P,\, R,\, \gamma)(S,A,P,R,γ)

where:

  • S\mathcal{S}S is the state space,
  • A\mathcal{A}A is the action space,
  • P(s′∣s,a)P(s' \mid s, a)P(s′∣s,a) is the transition probability kernel,
  • R(s,a)R(s, a)R(s,a) is the expected reward function,
  • γ∈[0,1)\gamma \in [0,1)γ∈[0,1) is the discount factor.
Agent policy π(a|s) value function Environment dynamics P(s'|s,a) action a reward r, next state s' Standard RL interaction cycle

The standard RLReinforcement Learning interaction cycle. At each step the agent selects an action from its policy, the environment returns a reward and the next state, and the agent updates its policy and value estimates. Every algorithm in this course is a different answer to "how should that update be computed?"

The Markov property#

The defining assumption of an MDPMarkov Decision Process is the Markov property:

P(st+1∣st,at,st−1,at−1,…)=P(st+1∣st,at)P(s_{t+1} \mid s_t, a_t, s_{t-1}, a_{t-1}, \ldots) = P(s_{t+1} \mid s_t, a_t)P(st+1​∣st​,at​,st−1​,at−1​,…)=P(st+1​∣st​,at​)

The future is conditionally independent of the past given the current state and action. The current state sts_tst​ contains all information relevant to predicting what happens next.

Intuition: Why the Markov property matters

The Markov property asserts that the current state encapsulates all information needed to predict future states and rewards. This property makes sequential decision problems computationally tractable. Without it, the value of a state would depend on the unbounded history of prior interactions. In practice, the state representation must be engineered to satisfy this property.

Markovianity is engineered, not given#

In practice, raw sensor observations are rarely Markovian. This distinction is fundamental to reinforcement learning system design.

Consider a robot arm that measures joint angles but not joint velocities. The subsequent state depends directly on momentum, which is absent from position measurements alone. Two robots with identical joint angles but different velocities transition to different subsequent states, making the transition dynamics non-Markovian in the observed state. Similarly, a language model observing only the latest token cannot distinguish between different meanings of polysemous words. In both cases, the current observation fails to capture the true underlying state.

Systems where the agent receives observations oto_tot​ generated by an underlying hidden state xtx_txt​ are modeled as Partially Observable Markov Decision Processes (POMDPs):

ot=O(xt)+noiseo_t = \mathcal{O}(x_t) + \text{noise}ot​=O(xt​)+noise

POMDPs represent the general case; MDPs represent the special case where ot=xto_t = x_tot​=xt​. Most physical systems and real-world problems are POMDPs.

What breaks here

Applying standard MDP algorithms directly to partially observable environments introduces three failure modes:

  • Ill-defined value functions: identical observations yield divergent returns depending on unobserved history.
  • Training instability: value updates oscillate because identical observations correspond to conflicting return distributions.
  • Suboptimal policy execution: actions that are optimal under one unobserved history fail under another.

Effective reinforcement learning systems therefore construct sufficient state representations before optimizing policies.

Three standard engineering techniques address partial observability:

  • State augmentation: incorporate physical derivatives, such as velocities or acceleration signals, directly into the state vector.
  • Observation stacking: concatenate a temporal window of recent observations, as in Atari frame stacking.
  • Recurrent representations: maintain a recurrent state vector via an LSTM or transformer architecture to track belief states over time.
Why not ignore history?

A reactive policy π(a∣ot)\pi(a \mid o_t)π(a∣ot​) can execute actions directly from observations, but value estimation requires state sufficiency. A value function Vπ(s)V^\pi(s)Vπ(s) is well-defined only when state sss uniquely determines the expected future return distribution. Under partial observability, an observation oto_tot​ corresponds to multiple hidden histories with different expected returns. Recurrent or attention-based architectures solve this by constructing a latent representation from sequence history, using that latent state for value estimation.

Language models as MDPs#

To ground this abstraction, consider RLReinforcement Learning applied to large language models, as in RLHFReinforcement Learning from Human Feedback:

MDPMarkov Decision Process componentLLMLarge Language Model interpretation
State sts_tst​Prompt and all generated tokens in the context window
Action ata_tat​Next token selected from vocabulary
Transition PPPAppending selected token to context
Reward rt+1r_{t+1}rt+1​Scalar score from a reward model
Discount γ\gammaγRelative weighting across token positions

Under this formulation, text generation is a sequential decision process, and preference alignment algorithms operate as reinforcement learning methods in this MDP. Because the state includes the prompt and all generated tokens within the context window, the MDP formulation satisfies the Markov property for the sequence.

With the environment formalized as an MDPMarkov Decision Process, the agent's behavior must be specified. A policy defines how the agent maps states to actions, and its properties determine whether the agent can learn effectively.


Policies#

A policy specifies the agent's behavior as a mapping from states to actions:

π(a∣s)=P(at=a∣st=s)\pi(a \mid s) = P(a_t = a \mid s_t = s)π(a∣s)=P(at​=a∣st​=s)

Policies may be:

  • Deterministic: π(s)=a\pi(s) = aπ(s)=a, selecting a single action per state. Common in deployment and in control-theoretic settings.
  • Stochastic: sampling actions from a probability distribution. Essential for exploration during training, and fundamental to policy gradient methods.
Intuition: Why stochasticity matters for learning

A deterministic policy π(s)=a\pi(s) = aπ(s)=a repeatedly visits the same states and actions, yielding no data about alternative trajectories. A stochastic policy π(a∣s)\pi(a \mid s)π(a∣s) explores alternative actions with non-zero probability, collecting transitions to refine value estimates across the state-action space.

In LLMs, the policy is the language model itself: a stochastic policy over the vocabulary at each token position, with temperature controlling the degree of stochasticity.

Given a policy, we evaluate its quality across trajectories using the return.


Returns and discounting#

The agent's objective is formalized via the return, the discounted cumulative reward from time step ttt onward:

Gt=∑k=0∞γkrt+k+1G_t = \sum_{k=0}^{\infty} \gamma^k r_{t+k+1}Gt​=k=0∑∞​γkrt+k+1​

This formulation reflects three distinct mathematical interpretations.

Three interpretations of the discount factor γ\gammaγ#

1. Convergence guarantee. For continuing tasks, the infinite sum ∑k=0∞rt+k+1\sum_{k=0}^\infty r_{t+k+1}∑k=0∞​rt+k+1​ diverges if rewards are bounded away from zero. When γ<1\gamma < 1γ<1, the return is bounded by Gt≤Rmax⁡/(1−γ)G_t \leq R_{\max} / (1 - \gamma)Gt​≤Rmax​/(1−γ). This condition is a mathematical requirement for infinite horizons.

2. Time preference. The discount factor γ\gammaγ balances immediate rewards against delayed rewards. As γ→1\gamma \to 1γ→1, future rewards receive comparable weight to immediate ones. As γ→0\gamma \to 0γ→0, the agent prioritizes immediate reward. The effective planning horizon is approximately 1/(1−γ)1/(1-\gamma)1/(1−γ) steps because ∑k=0∞γk=1/(1−γ)\sum_{k=0}^\infty \gamma^k = 1/(1-\gamma)∑k=0∞​γk=1/(1−γ).

3. Survival probability. The factor γ\gammaγ can represent the probability that an interaction continues at each step. With termination probability 1−γ1 - \gamma1−γ, the expected horizon matches geometric discounting. This perspective unifies episodic and continuing formulations under a single framework.

Why not set $\gamma = 1$?

In continuing tasks with bounded positive rewards, γ=1\gamma = 1γ=1 causes returns to diverge (Gt→∞G_t \to \inftyGt​→∞). Beyond divergence, the Bellman operator T\mathcal{T}T requires γ<1\gamma < 1γ<1 to maintain its contraction property. At γ=1\gamma = 1γ=1, value iteration is not guaranteed to converge, and fixed points may not exist or be unique. Discounting establishes the contraction necessary for dynamic programming.

In episodic tasks with natural termination, setting γ=1\gamma = 1γ=1 remains valid when terminal states are absorbing states that yield zero reward.

A warning on γ\gammaγ and policy gradient bias#

In policy gradient methods, using γ<1\gamma < 1γ<1 introduces an objective discrepancy. The discounted policy gradient does not match the gradient of the undiscounted return. This discrepancy matters in continuing tasks where the ultimate objective is undiscounted cumulative reward. We return to this derivation in later lectures.

Episodic vs continuing tasks#

  • Episodic tasks terminate at a terminal state (games, robotic manipulation episodes, single LLMLarge Language Model responses). The return is a finite sum.
  • Continuing tasks run indefinitely (control systems, long-running agents). The return requires discounting for finiteness.

For episodic tasks, terminal states are often treated as absorbing states with zero reward and self-loops: once reached, the agent stays there and receives zero reward forever. This unifies the episodic and continuing formalisms and is the standard implementation in most RLReinforcement Learning libraries.

The return GtG_tGt​ is a random variable that depends on transition dynamics, policy stochasticity, and trajectory length. We evaluate policies by computing the expected return, which defines the value function.


Value functions#

Value functions quantify expected return from states and actions under policy π\piπ. They are not directly observable; algorithms estimate them from experience or derive them from an environment model.

State-value function#

Vπ(s)=Eπ[Gt∣st=s]=Eπ[∑k=0∞γkrt+k+1  |  st=s]V^\pi(s) = \mathbb{E}_\pi \left[ G_t \mid s_t = s \right] = \mathbb{E}_\pi \left[ \sum_{k=0}^{\infty} \gamma^k r_{t+k+1} \;\middle|\; s_t = s \right]Vπ(s)=Eπ​[Gt​∣st​=s]=Eπ​[k=0∑∞​γkrt+k+1​​st​=s]

This is the expected cumulative discounted reward, starting from state sss and following policy π\piπ thereafter.

Action-value function (Q-function)#

Qπ(s,a)=Eπ[Gt∣st=s,at=a]Q^\pi(s, a) = \mathbb{E}_\pi \left[ G_t \mid s_t = s, a_t = a \right]Qπ(s,a)=Eπ​[Gt​∣st​=s,at​=a]

This conditions on both state and action: the expected return from taking action aaa in state sss, then following π\piπ.

Intuition: State-value versus action-value

State-value Vπ(s)V^\pi(s)Vπ(s) evaluates the expected return from state sss under policy π\piπ. Action-value Qπ(s,a)Q^\pi(s,a)Qπ(s,a) evaluates the expected return of taking action aaa from state sss, then following policy π\piπ. The action-value function directly indicates optimal actions without requiring one-step lookaheads through environment dynamics. The state-value function is the expectation of Qπ(s,a)Q^\pi(s,a)Qπ(s,a) over policy action probabilities.

The relationship between them:

Vπ(s)=∑aπ(a∣s) Qπ(s,a)V^\pi(s) = \sum_a \pi(a \mid s)\, Q^\pi(s, a)Vπ(s)=a∑​π(a∣s)Qπ(s,a)

Value functions turn sequential decision problems into expected return estimation. The optimal value functions V∗V^*V∗ and Q∗Q^*Q∗ determine optimal policies directly: π∗(s)=arg⁡max⁡aQ∗(s,a)\pi^*(s) = \arg\max_a Q^*(s,a)π∗(s)=argmaxa​Q∗(s,a).

Because infinite horizon returns cannot be evaluated by exhaustive summation, reinforcement learning relies on recursive representations. The Bellman equations express the value of each state in terms of expected successor state values.


Bellman equations#

The Bellman equations express value functions recursively, relating the value of the current state to the values of successor states. They define the computational foundation of reinforcement learning.

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]Vπ(s)=a∑​π(a∣s)[R(s,a)+γs′∑​P(s′∣s,a)Vπ(s′)]

This formulation constitutes a system of ∣S∣|\mathcal{S}|∣S∣ linear equations in VπV^\piVπ. Given policy π\piπ, transition model PPP, and reward function RRR, solving for VπV^\piVπ requires solving a linear algebra problem. This process is called policy evaluation.

Intuition: fixed-point iteration

The Bellman expectation equation states that the value of a state equals expected immediate reward plus discounted expected value of the next state. State values depend recursively on one another. The system has a unique solution because γ<1\gamma < 1γ<1 discounts future values geometrically. The equation can be solved directly as a linear system or iterated to convergence via dynamic programming.

Bellman optimality equation#

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]V∗(s)=amax​[R(s,a)+γs′∑​P(s′∣s,a)V∗(s′)]

This formulation is a nonlinear fixed-point equation in V∗V^*V∗. Because the max⁡\maxmax operator is nonlinear, V∗V^*V∗ cannot be solved by matrix inversion. It possesses a unique solution that iterative methods reach geometrically.

Intuition: optimality via max

The optimality equation states that the optimal value at state sss equals the maximum over actions of immediate reward plus expected discounted future value. An optimal policy selects the action achieving this maximum. This property enables polynomial-time value iteration over states, avoiding exhaustive enumeration over ∣A∣∣S∣|\mathcal{A}|^{|\mathcal{S}|}∣A∣∣S∣ deterministic policies.

The contraction mapping property#

Define the Bellman optimality operator T\mathcal{T}T:

(TV)(s)=max⁡a[R(s,a)+γ∑s′P(s′∣s,a) V(s′)](\mathcal{T} V)(s) = \max_a \left[ R(s,a) + \gamma \sum_{s'} P(s' \mid s,a)\, V(s') \right](TV)(s)=amax​[R(s,a)+γs′∑​P(s′∣s,a)V(s′)]

T\mathcal{T}T is a γ\gammaγ-contraction in the ℓ∞\ell_\inftyℓ∞​ norm:

∥TV−TV′∥∞≤γ∥V−V′∥∞\|\mathcal{T} V - \mathcal{T} V'\|_\infty \leq \gamma \|V - V'\|_\infty∥TV−TV′∥∞​≤γ∥V−V′∥∞​

By the Banach fixed-point theorem, repeated application of T\mathcal{T}T converges geometrically to the unique fixed point V∗V^*V∗ at rate γ\gammaγ per iteration. This process constitutes value iteration. The contraction property explains why γ<1\gamma < 1γ<1 is an algorithmic necessity: setting γ=1\gamma = 1γ=1 removes the contraction guarantee.

What breaks here

When γ=1\gamma = 1γ=1:

  • The ℓ∞\ell_\inftyℓ∞​ distance between TV\mathcal{T}VTV and TV′\mathcal{T}V'TV′ is no longer contracted.
  • Value iteration may oscillate or diverge rather than converging to V∗V^*V∗.
  • The optimal value function V∗V^*V∗ may fail to be unique or finite.

Discount factors ensure mathematical tractability in continuing tasks.

Connection to the LQR Riccati equation#

This subsection provides optional background connecting dynamic programming to classical control. Readers familiar with robotics control will recognize the Bellman optimality equation in the following continuous-state form.

Consider linear dynamics st+1=Ast+Bats_{t+1} = As_t + Ba_tst+1​=Ast​+Bat​ with quadratic cost, known as the Linear Quadratic Regulator (LQR). Let AAA represent the state-transition matrix, BBB the input matrix, QcQ_cQc​ the state-cost matrix, and RcR_cRc​ the action-cost matrix. We use subscript ccc to distinguish cost matrices from reward functions. The discrete-time Algebraic Riccati Equation (DARE) is:

P=Qc+A⊤PA−A⊤PB(Rc+B⊤PB)−1B⊤PAP = Q_c + A^\top P A - A^\top P B (R_c + B^\top P B)^{-1} B^\top P AP=Qc​+A⊤PA−A⊤PB(Rc​+B⊤PB)−1B⊤PA

This equation is the Bellman optimality equation specialized to linear quadratic systems, where matrix PPP parameterizes the quadratic value function. LQR solves optimal control in closed form under these linear-quadratic assumptions.

Worked example: Bellman backup on a two-state MDP#

Setup. Consider the following MDPMarkov Decision Process:

  • States: S={s1, s2}\mathcal{S} = \{s_1,\, s_2\}S={s1​,s2​}
  • Actions: A={stay, switch}\mathcal{A} = \{\text{stay},\, \text{switch}\}A={stay,switch}
  • Transitions: deterministic. Action stay keeps the agent in the current state, and action switch moves the agent to the other state.
  • Rewards: R(s1,⋅)=1R(s_1, \cdot) = 1R(s1​,⋅)=1, R(s2,⋅)=0R(s_2, \cdot) = 0R(s2​,⋅)=0 (reward depends only on the state).
  • Discount: γ=0.9\gamma = 0.9γ=0.9.

Policy π1\pi_1π1​ (always stay). The Bellman expectation equations are:

Vπ1(s1)=1+0.9 Vπ1(s1)Vπ1(s2)=0+0.9 Vπ1(s2)V^{\pi_1}(s_1) = 1 + 0.9\, V^{\pi_1}(s_1) \qquad V^{\pi_1}(s_2) = 0 + 0.9\, V^{\pi_1}(s_2)Vπ1​(s1​)=1+0.9Vπ1​(s1​)Vπ1​(s2​)=0+0.9Vπ1​(s2​)

Solving the linear system:

Vπ1(s1)=11−0.9=10Vπ1(s2)=01−0.9=0V^{\pi_1}(s_1) = \frac{1}{1 - 0.9} = 10 \qquad V^{\pi_1}(s_2) = \frac{0}{1 - 0.9} = 0Vπ1​(s1​)=1−0.91​=10Vπ1​(s2​)=1−0.90​=0

Interpretation. Starting in s1s_1s1​, the agent collects +1+1+1 at every step. The geometric series ∑k=0∞0.9k=11−0.9=10\sum_{k=0}^\infty 0.9^k = \frac{1}{1-0.9} = 10∑k=0∞​0.9k=1−0.91​=10 confirms the analytical result. Starting in s2s_2s2​, the agent receives zero reward indefinitely.

Policy π2\pi_2π2​ (always switch). The agent alternates between s1s_1s1​ and s2s_2s2​, receiving rewards 1,0,1,0,…1, 0, 1, 0, \ldots1,0,1,0,…. The Bellman equations couple both states:

Vπ2(s1)=1+0.9 Vπ2(s2)Vπ2(s2)=0+0.9 Vπ2(s1)V^{\pi_2}(s_1) = 1 + 0.9\, V^{\pi_2}(s_2) \qquad V^{\pi_2}(s_2) = 0 + 0.9\, V^{\pi_2}(s_1)Vπ2​(s1​)=1+0.9Vπ2​(s2​)Vπ2​(s2​)=0+0.9Vπ2​(s1​)

Substituting the second equation into the first yields Vπ2(s1)=1+0.81 Vπ2(s1)V^{\pi_2}(s_1) = 1 + 0.81\, V^{\pi_2}(s_1)Vπ2​(s1​)=1+0.81Vπ2​(s1​), which gives Vπ2(s1)=10.19≈5.26V^{\pi_2}(s_1) = \frac{1}{0.19} \approx 5.26Vπ2​(s1​)=0.191​≈5.26.

Conclusion. Policy π1\pi_1π1​ strictly dominates policy π2\pi_2π2​ because Vπ1(s1)=10>5.26=Vπ2(s1)V^{\pi_1}(s_1) = 10 > 5.26 = V^{\pi_2}(s_1)Vπ1​(s1​)=10>5.26=Vπ2​(s1​). The optimal policy stays in s1s_1s1​ to maximize cumulative return, matching the choice selected by the Bellman optimality operator.

Browser lab: iterative policy evaluation#

Implement the policy evaluation above using the iterative (not direct) method, and verify convergence to the analytical solution.

python · runs in browser
import numpy as np

# MDP definition
gamma = 0.9

# States: 0 = s1, 1 = s2. Actions: 0 = stay, 1 = switch.
# P[s, a, s'] = P(s' | s, a)
P = np.array([
    [[1.0, 0.0], [0.0, 1.0]],   # from s1: stay->s1, switch->s2
    [[0.0, 1.0], [1.0, 0.0]],   # from s2: stay->s2, switch->s1
])
R = np.array([1.0, 0.0])        # R(s1) = 1, R(s2) = 0

# Policy pi1: always stay (action 0 in both states)
pi = np.array([0, 0])

# Iterative policy evaluation
# Initial guess of zeros. The contraction property guarantees convergence
# regardless of the starting estimate.
V = np.zeros(2)
for i in range(1000):
    # Bellman expectation backup: R(s) + γ Σ_{s'} P(s'|s,π(s)) V(s')
    # np.dot computes the expected future value over successor states.
    V_new = np.array([
        R[s] + gamma * np.dot(P[s, pi[s]], V)
        for s in range(2)
    ])
    # Convergence check using the infinity norm (max absolute difference).
    # A small value means we've reached the fixed point of the Bellman operator.
    if np.max(np.abs(V_new - V)) < 1e-8:
        print(f"Converged after {i+1} iterations")
        break
    # Synchronous (Jacobi-style) update: all states updated using the old V.
    V = V_new

print(f"V(s1) = {V[0]:.4f}")   # Expected: 10.0
print(f"V(s2) = {V[1]:.4f}")   # Expected: 0.0
# Always-stay: V(s1) = 1/(1-γ) = 10 under perpetual reward 1.
print("Notice: under π=always stay, s2 is never left and has R=0 → V(s2)=0.")

Try it: Change to pi = np.array([1, 1]) (always switch) and re-run. The value converges to V(s1)≈5.26V(s_1) \approx 5.26V(s1​)≈5.26. Policy evaluation computes values for a fixed policy; subsequent weeks explore policy optimization.


Taxonomy of reinforcement learning problems#

Classifying reinforcement learning problems guides algorithm selection and clarifies necessary assumptions.

Bandits vs full MDPs#

  • Multi-armed bandits: no state transitions occur; actions yield immediate rewards. The agent balances exploration of uncertain actions against exploitation of high-value actions.
  • Full MDPs: actions influence subsequent states and long-term returns. Local bandit reasoning applies within each state, but value functions account for delayed transitions.

Bandits appear throughout reinforcement learning applications, including recommendation systems, online experimentation, and pairwise preference models in RLHFReinforcement Learning from Human Feedback.

Online vs offline reinforcement learning#

  • Online RL: the agent collects experience while learning. Transitions originate from current or recent policies. Common algorithms, such as Q-learning, PPOProximal Policy Optimisation, and SACSoft Actor-Critic, operate online.
  • Offline RL: the agent learns from a fixed dataset collected by a behavior policy, without active environment interaction. This paradigm is essential in domains such as robotics and healthcare where exploratory actions carry high cost or risk.

The primary technical challenge in offline reinforcement learning is distributional shift. The learned policy can select state-action pairs rare or missing in the dataset. Without environment interaction, erroneous value estimates remain uncorrected, yielding inflated Q-values. Supervised learning avoids this issue because classifiers do not generate sequential trajectories in low-density data regions.

Why not use supervised learning for offline RL?

Behavioral cloning trains a supervised model to imitate offline actions, matching behavior policy performance without exceeding it. Reinforcement learning aims to discover superior policies by reasoning about counterfactual returns. In regions with sparse data, value estimates become unreliable. Offline reinforcement learning methods, such as CQL, IQL, and AWR, constrain policy updates or penalize out-of-distribution values to maintain stability.

Model-free vs model-based RL#

  • Model-free RL: learns value functions or policies directly from experience without constructing an explicit transition model PPP.
  • Model-based RL: constructs or queries an explicit transition model to plan actions, improving sample efficiency at the risk of model bias.

These paradigms form a continuum. Dyna algorithms combine environment transitions with rollouts simulated from a learned model. Dreamer and MuZero plan inside learned latent-state representations rather than physical observation spaces.


Relationship to supervised learning and control theory#

Supervised learning#

Supervised learning optimizes a fixed loss on static datasets where outputs do not alter subsequent data. Reinforcement learning violates this assumption. The policy selects actions that determine subsequent states and collected transitions, forming a non-stationary feedback loop that requires managing exploration.

Why not treat RL as supervised learning on historical data?

Supervised imitation reproduces the empirical distribution of demonstration datasets. Improving beyond demonstration data requires evaluating hypothetical outcomes under counterfactual actions. The Bellman equation provides this mechanism by evaluating expected returns across alternative policies.

Control theory#

Classical control theory addresses sequential decision making under distinct assumptions:

  • Known dynamics: classical control assumes analytical access to transition dynamics PPP, whereas reinforcement learning generally estimates them from data or operates model-free.
  • Stability guarantees: control theory emphasizes Lyapunov stability and robustness criteria that general reinforcement learning rarely guarantees.
  • Function approximation: classical control focuses on low-dimensional analytical representations, whereas reinforcement learning scales to high-dimensional state spaces using neural network approximations.

These formulations intersect directly. Linear Quadratic Regulation (LQR) solves optimal control in closed form for linear dynamics and quadratic costs. Reinforcement learning generalizes this formulation to unknown dynamics and non-linear function approximators.


Connections to modern methods#

The MDP formalism provides the mathematical foundation for modern reinforcement learning architectures. The following examples illustrate how the formal components map to current methods.

DreamerV3: Bellman backups in latent space#

DreamerV3 (Hafner et al., 2023) learns visual control tasks across domains, including robotics and video games, directly from pixel observations. Its architecture instantiates the MDP tuple:

MDP componentDreamerV3 implementation
State sts_tst​Latent state vector from a recurrent state-space model (RSSM)
Transition PPPLearned latent dynamics model
Reward RRRLearned reward predictor from latent states
Value V∗V^*V∗Neural network updated via Bellman backups over simulated latent rollouts
POMDP beliefRSSM maintains a sequence belief state over raw observations

Once the world model is trained, the agent applies Bellman updates to imagined trajectories without querying the environment. Value iteration operates directly in latent space.

TD-MPC: value-weighted planning#

TD-MPC (Hansen et al., 2022) combines model predictive control with value learning:

  • A learned latent world model provides short-horizon rollouts for local transition dynamics PPP.
  • A learned action-value function Q∗(s,a)Q^*(s, a)Q∗(s,a), updated via Bellman optimality backups, estimates long-term returns beyond the rollout window.
  • Trajectory optimization evaluates action sequences by combining simulated short-term rewards with terminal Q-value estimates.

The Bellman Q-function summarizes delayed returns, allowing the planner to truncate rollouts while retaining long-horizon evaluation.


Common pitfalls in RL problem formulation#

Recognizing common formulation errors prevents systematic failures in implementation:

  1. Non-Markovian state representation. Using raw observations without establishing state sufficiency causes value estimates to oscillate. Verify whether identical observations from different histories transition to different outcomes. Restore Markovianity using state augmentation or observation stacking.

  2. Reward hacking. Optimizing a proxy reward that diverges from true intent produces unintended behaviors that maximize numerical reward. Before training, evaluate potential degenerate policies. For instance, rewarding joint velocities alone causes a walking robot to fall forward.

  3. Setting γ=1\gamma = 1γ=1 in continuing tasks. Infinite-horizon sums diverge and Bellman operators lose their contraction property, producing numerical overflow. Set γ<1\gamma < 1γ<1, or formulate the task as episodic with absorbing terminal states.

  4. Confusing episodic and continuing formulations. Fixed-duration manipulation tasks are episodic, whereas continuous process control is continuing. Select the formulation based on whether natural terminal states exist. Continuing formulations require discounting to preserve finite returns.

  5. Ignoring distributional shift in offline RL. Training on static datasets without penalizing out-of-distribution actions causes overoptimistic value estimates. Unlike supervised learning, bootstrapped value estimation compounds extrapolation errors on unsupported state-action pairs.


Key takeaways#

The concepts introduced here form the foundation for every algorithm in the course. The reward hypothesis formalizes goal-directed behavior as scalar reward maximization. Markov decision processes formalize the sequential interaction between agent and environment. Policies specify actions across states, and value functions evaluate expected long-term return.

The Bellman equations express value functions recursively, yielding a linear system for policy evaluation and a nonlinear fixed-point equation for optimality. The contraction mapping property ensures that iterative dynamic programming converges to the unique optimal value function. The discount factor bounds returns in infinite-horizon tasks and defines the effective planning horizon. Finally, the connection to the Riccati equation demonstrates that reinforcement learning extends classical optimal control to systems with unknown dynamics.


Matrix form of the Bellman expectation equation

For a fixed policy π\piπ over a finite state space, the Bellman expectation equation forms a system of ∣S∣|\mathcal{S}|∣S∣ linear equations. In matrix form:

Vπ=Rπ+γPπVπ⟹(I−γPπ) Vπ=RπV^\pi = R^\pi + \gamma P^\pi V^\pi \quad\Longrightarrow\quad (I - \gamma P^\pi)\, V^\pi = R^\piVπ=Rπ+γPπVπ⟹(I−γPπ)Vπ=Rπ

where Rsπ=∑aπ(a∣s) R(s,a)R^\pi_s = \sum_a \pi(a \mid s)\, R(s,a)Rsπ​=∑a​π(a∣s)R(s,a) and Pss′π=∑aπ(a∣s) P(s′∣s,a)P^\pi_{ss'} = \sum_a \pi(a \mid s)\, P(s' \mid s,a)Pss′π​=∑a​π(a∣s)P(s′∣s,a).

This matches the standard linear system Ax=bAx = bAx=b with A=I−γPπA = I - \gamma P^\piA=I−γPπ, x=Vπx = V^\pix=Vπ, and b=Rπb = R^\pib=Rπ. The matrix AAA is invertible whenever γ<1\gamma < 1γ<1. Because PπP^\piPπ is a stochastic transition matrix, its spectral radius is 1, and each eigenvalue λ\lambdaλ of PπP^\piPπ satisfies ∣λ∣≤1|\lambda| \le 1∣λ∣≤1. Each corresponding eigenvalue 1−γλ1 - \gamma\lambda1−γλ of I−γPπI - \gamma P^\piI−γPπ satisfies ∣1−γλ∣≥1−γ∣λ∣≥1−γ>0|1 - \gamma\lambda| \ge 1 - \gamma|\lambda| \ge 1 - \gamma > 0∣1−γλ∣≥1−γ∣λ∣≥1−γ>0. No eigenvalue equals zero. The unique solution is Vπ=(I−γPπ)−1RπV^\pi = (I - \gamma P^\pi)^{-1} R^\piVπ=(I−γPπ)−1Rπ.

Conceptual questions#

  1. A robot observes only joint positions, not velocities. Explain why this observation model violates the Markov property. Propose two state engineering strategies to restore approximate Markovianity, and specify what each strategy assumes about the system.

  2. Suppose you run value iteration with γ=1.0\gamma = 1.0γ=1.0 on a continuing task with bounded positive rewards. Explain why returns diverge, and describe why the Bellman optimality operator loses its contraction property. What minimal modification restores convergence?

  3. A language model trained with RLHFReinforcement Learning from Human Feedback achieves high preference scores but generates persuasive yet factually incorrect responses. Analyze this outcome using the reward hypothesis and reward misspecification. How should the training objective be adjusted to mitigate this behavior?

  4. Compare the Bellman expectation equation for policy evaluation with the linear system Ax=bAx = bAx=b. Identify AAA, xxx, and bbb, and prove that AAA is invertible for any γ<1\gamma < 1γ<1.

  5. An offline reinforcement learning policy is trained on robot manipulation demonstrations. The policy succeeds on configurations close to the training demonstrations but fails on novel configurations. Contrast this failure mode with compounding imitation error in behavioral cloning.


Solutions
  1. Missing velocities. Without velocity observations, future transitions depend on unobserved momentum rather than the current position alone, violating the Markov condition. (a) Stacking a temporal window of recent positions assumes velocities can be approximated by numerical differentiation. (b) Appending state estimates from a Kalman filter assumes an identifiable dynamics model. Both methods supply the missing phase-space information.

  2. Setting γ=1\gamma = 1γ=1 on a continuing task. Infinite-horizon sums Gt=∑trtG_t = \sum_t r_tGt​=∑t​rt​ diverge for bounded positive rewards. The Bellman optimality operator requires γ<1\gamma < 1γ<1 to maintain contraction modulus γ\gammaγ in the supremum norm. At γ=1\gamma = 1γ=1, contraction fails and fixed points are no longer unique or guaranteed to exist. Convergence is restored by choosing γ<1\gamma < 1γ<1, terminating episodes at absorbing states, or adopting an average-reward formulation.

  3. RLHF persuasion without accuracy. A reward model provides a proxy signal for user preference. When human raters reward rhetorical persuasiveness over factual accuracy, the policy exploits this misspecification, generating confident falsehoods. Mitigating this failure requires grounding rewards in verifiable evidence, penalizing hallucinations in preference data, and constraining policy deviation using a reference KL penalty.

  4. Bellman as Ax=bAx=bAx=b. Rearranging Vπ=Rπ+γPπVπV^\pi = R^\pi + \gamma P^\pi V^\piVπ=Rπ+γPπVπ yields (I−γPπ)Vπ=Rπ(I - \gamma P^\pi)V^\pi = R^\pi(I−γPπ)Vπ=Rπ, identifying A=I−γPπA = I-\gamma P^\piA=I−γPπ, x=Vπx = V^\pix=Vπ, and b=Rπb = R^\pib=Rπ. The stochastic transition matrix PπP^\piPπ has spectral radius 1. When γ<1\gamma < 1γ<1, the matrix γPπ\gamma P^\piγPπ has spectral radius strictly less than 1. All eigenvalues of I−γPπI-\gamma P^\piI−γPπ maintain positive real parts, guaranteeing invertibility with unique solution Vπ=(I−γPπ)−1RπV^\pi = (I - \gamma P^\pi)^{-1} R^\piVπ=(I−γPπ)−1Rπ.

  5. Offline distributional shift. The policy evaluates action values for out-of-distribution actions. In regions lacking data, bootstrapped value estimates become excessively optimistic, leading policy optimization to select invalid actions. In contrast, behavioral cloning fails from compounding imitation error along trajectories without actively maximizing value functions.

Knowledge Check#

Check the MDP building blocks from this week.

Exercise · Fill in the blank

In the standard discounted return, future rewards are scaled by powers of ___, the discount factor in (0, 1].

Exercise · Multiple choice

The Bellman optimality equation for V* uses which operator over actions?

Average (expectation under a fixed policy)
Minimum over actions
Maximum over actions
Sum over actions without probabilities
Question 1 of 3

A finite MDP is fully specified by which core ingredients?

Only a reward function and a discount factor
States, actions, transition kernel, reward, and usually γ
A dataset of expert trajectories only
A neural network policy and a loss

Looking ahead#

The next lecture examines multi-armed bandits, the simplest non-trivial reinforcement learning problem. Bandits isolate the trade-off between exploration and exploitation without state transitions. Regret analysis and bandit algorithms provide tools that generalize to full MDPs and to preference feedback mechanisms in later lectures.

Further reading#

  • Bellman, R. (1957). Dynamic Programming. Princeton University Press. Foundational text introducing the Bellman equation and the principle of optimality.
  • Sutton & Barto (2018). Reinforcement Learning: An Introduction (2nd ed.), Chapter 3: Finite Markov Decision Processes. Standard textbook reference.
  • Puterman, M. L. (1994). Markov Decision Processes: Discrete Stochastic Dynamic Programming. Wiley. Comprehensive mathematical treatment of dynamic programming convergence and contraction proofs.
  • Silver, D. (2015). UCL Course on RL, Lecture 2: Markov Decision Processes. Lecture slides and video covering tabular MDP examples.
  • Bertsekas, D. P. (2019). Reinforcement Learning and Optimal Control. Athena Scientific. Bridges classical optimal control and modern reinforcement learning.

Reading is free. PDF and ePub unlock with the newsletter. Join once and every lesson opens in this browser.

← Previous
Bandits: UCB1 and Thompson Sampling
Next →
Week 2: Multi-Armed Bandits
On this page
  • Purpose of this lecture
  • Sequential decision making
  • The reward hypothesis
  • A concrete starting point
  • Why reward design matters
  • Markov decision processes (MDPs)
  • The Markov property
  • Markovianity is engineered, not given
  • Language models as MDPs
  • Policies
  • Returns and discounting
  • Three interpretations of the discount factor gamma
  • A warning on gamma and policy gradient bias
  • Episodic vs continuing tasks
  • Value functions
  • State-value function
  • Action-value function (Q-function)
  • Bellman equations
  • Bellman expectation equation
  • Bellman optimality equation
  • The contraction mapping property
  • Connection to the LQR Riccati equation
  • Worked example: Bellman backup on a two-state MDP
  • Browser lab: iterative policy evaluation
  • Taxonomy of reinforcement learning problems
  • Bandits vs full MDPs
  • Online vs offline reinforcement learning
  • Model-free vs model-based RL
  • Relationship to supervised learning and control theory
  • Supervised learning
  • Control theory
  • Connections to modern methods
  • DreamerV3: Bellman backups in latent space
  • TD-MPC: value-weighted planning
  • Common pitfalls in RL problem formulation
  • Key takeaways
  • Conceptual questions
  • Knowledge Check
  • Looking ahead
  • Further reading