Reinforcement Learning (RL) is a paradigm where an agent learns to make sequential decisions by interacting with an environment, receiving rewards as feedback, and optimizing its policy to maximize cumulative reward over time [346]. Unlike supervised learning (which requires labeled input-output pairs), RL discovers optimal behavior through trial and error.

Figure 3.1: Reinforcement Learning overview: an agent interacts with an environment, receiving rewards as feedback and u
Figure 3.1:Reinforcement Learning overview: an agent interacts with an environment, receiving rewards as feedback and updating its policy through trial and error. Unlike supervised learning which learns from labeled pairs, RL learns what to do by maximizing reward through experience.

The Markov Decision Process (MDP)

An MDP is a 5-tuple (S,A,P,R,γ):

  • S: State space — all possible configurations of the environment
  • A: Action space — all actions available to the agent
  • P⁡(s′|s,a): Transition function — probability of reaching state s′ from state s after taking action a
  • R⁡(s,a,s′): Reward function — immediate scalar feedback for a transition
  • γ∈[0,1]: Discount factor — how much future rewards are valued relative to immediate ones

The Markov Property: The future depends only on the current state, not the history:

P⁡(st+1|st,at,st−1,at−1,…)=P⁡(st+1|st,at)

This makes the problem tractable.

Core Concepts and Definitions

Policyπ⁡(a|s): A mapping from states to action probabilities. Deterministic: a=π⁡(s). Stochastic: a∼π(⋅|s).

Return (cumulative discounted reward):

Gt=∑k=0∞γk​rt+k=rt+γ​rt+1+γ2​rt+2+⋯(3.1)

Value Function (expected return from state s under policy π):

Vπ​(s)=𝔼π​[Gt∣st=s]=𝔼π​[∑k=0∞γk​rt+k∣st=s](3.2)

Action-Value Function (expected return from state s, taking action a, then following π):

Qπ(s,a)=𝔼π[Gt∣st=s,at=a](3.3)

Advantage Function (how much better action a is compared to average):

Aπ​(s,a)=Qπ​(s,a)−Vπ​(s)(3.4)

Bellman Equations (recursive relationship):

Taxonomy of RL Methods

Reinforcement learning algorithms can be classified along several axes. Understanding this taxonomy helps select the right approach for a given problem.

Temporal Difference (TD) Learning

TD learning [347] bootstraps — it updates value estimates using other value estimates, without waiting for the full episode to end.

Understanding TD Error: “Surprise” as a Learning Signal

TD error measures the discrepancy between an agent’s current estimate of future reward and a newly updated estimate after taking one step. Put simply, it is the difference between what the agent thought would happen and what actually happened plus what it expects next. It represents the agent’s “surprise.”

The TD Error Formula

δt=Rt+1+γ​V​(St+1)−V⁡(St)(3.9)
  • Rt+1: The immediate reward received after taking an action.
  • γ​V​(St+1): The estimated discounted value of the next state (what the agent expects to get from the next state onward, scaled by discount factor γ).
  • V⁡(St): The original estimate of the current state’s value.

The combined term (Rt+1+γ​V​(St+1)) is called the TD Target. Therefore:

TD Error=TD Target−Old Estimate(3.10)

How the Agent Uses TD Error

The agent adjusts its value function to drive TD error toward zero:

V⁡(St)←V⁡(St)+α⋅δt(3.11)
  • If δt>0: outcome was better than predicted → increase V⁡(St) so the agent seeks this state.
  • If δt<0: outcome was worse than predicted → decrease V⁡(St) so the agent avoids this state.
  • If δt=0: prediction was perfect → no update needed (convergence).

TD Target: yt=rt+γ​V​(st+1) — the “better estimate” we move toward.

Multi-step TD (n-step returns):

Gt(n)=rt+γ​rt+1+⋯+γn−1​rt+n−1+γn​V​(st+n)(3.12)

Q-Learning

Q-Learning [373] is the foundational off-policy, value-based algorithm. It learns the optimal Q∗ directly, regardless of the policy being followed.

Update rule:

Q⁡(st,at)←Q⁡(st,at)+α⁡[rt+γ​maxa′⁡Q⁡(st+1,a′)−Q⁡(st,at)](3.13)

SARSA[311] (on-policy alternative): Uses the action actually taken instead of the max:

Q⁡(st,at)←Q⁡(st,at)+α⁡[rt+γ​Q​(st+1,at+1)−Q⁡(st,at)](3.14)

Deep Q-Networks (DQN)[259]: Replace tabular Q⁡(s,a) with a neural network Qθ​(s,a). Key innovations: experience replay buffer (off-policy data reuse), target network (stability), ϵ-greedy exploration.

DQN Loss Function: The network is trained to minimize the mean squared TD error over mini-batches sampled from the replay buffer:

ℒ⁡(θ)=𝔼(s,a,r,s′)∼ℬ​[(r+γ​maxa′​Qθ¯​(s′,a′)−Qθ​(s,a))2](3.15)

where Qθ¯ is the target network — a frozen copy of Qθ updated only every C steps (e.g., C=10,000). This prevents the moving target problem: without it, both the prediction and the target shift simultaneously, causing divergence.

Gradient update: Taking the gradient of the loss w.r.t. θ (note: the target y is treated as a constant — no gradient flows through θ¯):

∇θℒ=−𝔼⁡[(r+γ​maxa′​Qθ¯​(s′,a′)−Qθ​(s,a))⏟TD error ​δ​∇θQθ​(s,a)](3.16)
θ←θ−α⋅δ⋅∇θQθ​(s,a)(3.17)

Learning scheme (per training step):

  1. Act: Select action via ϵ-greedy: with probability ϵ take random action, otherwise a=arg⁡maxa​Qθ​(s,a). Anneal ϵ from 1.0 → 0.01 over first 1M steps.
  2. Store: Save transition (s,a,r,s′,d) in replay buffer ℬ (capacity ∼1M).
  3. Sample: Draw mini-batch of 32 transitions uniformly from ℬ.
  4. Compute target: y=r+γ⁡(1−d)​maxa′​Qθ¯​(s′,a′) (zero future value if terminal).
  5. Update: Gradient descent on (y−Qθ​(s,a))2. Clip gradients to [−1,1] (Huber loss variant).
  6. Sync target: Every C steps, copy θ¯←θ.

Understanding Replay Buffers

A replay buffer[220] (experience replay) is a data storage mechanism that saves past experiences so an agent can relearn from them later. Instead of discarding data immediately after an action, the agent stores transitions in a memory bank and samples random mini-batches for training.

What’s stored: Each transition is a tuple:

et=(st,at,rt,st+1,dt)(3.18)

where dt is a boolean flag indicating if the episode ended.

import random
from collections import deque
 
class ReplayBuffer:
    def __init__(self, capacity):
        self.buffer = deque(maxlen=capacity)  # Bounded queue
 
    def push(self, state, action, reward, next_state, done):
        self.buffer.append((state, action, reward, next_state, done))
 
    def sample(self, batch_size):
        # Break correlation by selecting random experiences
        return random.sample(self.buffer, batch_size)
 
    def __len__(self):
        return len(self.buffer)

Policy Gradient Methods — REINFORCE

Instead of learning a value function and deriving a policy, directly optimize the policy parameters θ to maximize expected return [379].

Objective: J⁡(θ)=𝔼τ∼πθ​[R⁡(τ)]=𝔼πθ​[∑t=0Trt]

Policy Gradient Theorem:

∇θJ​(θ)=𝔼πθ​[∑t=0T∇θ​log​πθ​(at|st)⋅Gt](3.19)

REINFORCE Algorithm[379] (Williams, 1992):

  1. Sample complete trajectory τ=(s0,a0,r0,s1,a1,r1,…) under πθ
  2. Compute return Gt=∑k=0T−tγk​rt+k for each time step
  3. Update: θ←θ+α​∑t∇θ​log​πθ​(at|st)⋅Gt

Variance Reduction with Baseline:

∇θJ​(θ)=𝔼πθ​[∑t=0T∇θ​log​πθ​(at|st)⋅(Gt−b⁡(st))](3.20)

Any baseline b⁡(st) that doesn’t depend on at keeps the gradient unbiased but reduces variance. Best choice: b⁡(st)=Vπ​(st). Then Gt−V⁡(st)≈Aπ​(st,at) = advantage.

Actor-Critic Methods

Combine policy gradient (actor) with learned value function (critic) to reduce variance while maintaining the flexibility of policy optimization.

Architecture:

  • Actorπθ​(a|s): The policy. Proposes actions.
  • CriticVϕ​(s) or Qϕ​(s,a): Evaluates how good a state/action is. Provides low-variance baseline.

Actor update (using advantage from critic):

∇θJ=𝔼⁡[∇θ​log​πθ​(at|st)⋅A^t],A^t=rt+γ​Vϕ​(st+1)−Vϕ​(st)(3.21)

Critic update (minimize TD error):

ℒcritic=𝔼⁡[(rt+γ​Vϕ​(st+1)−Vϕ​(st))2](3.22)

Generalized Advantage Estimation (GAE)

Motivation: The Actor-Critic framework needs a good estimate of the advantage A⁡(s,a)=Q⁡(s,a)−V⁡(s) — how much better was this action than average? But there’s a fundamental tension:

  • 1-step TD advantage (rt+γ​V​(st+1)−V⁡(st)): Low variance (only one random step), but biased — if the value function V is wrong, the advantage estimate is systematically off.
  • Monte Carlo advantage (Gt−V⁡(st)): Unbiased (uses actual returns), but high variance — the sum of many random rewards fluctuates wildly between episodes.

GAE [318] (Schulman et al., 2016) provides a smooth interpolation between these extremes via a single parameter λ∈[0,1]. It takes an exponentially-weighted average of n-step advantage estimates for all n, giving a principled way to trade bias for variance.

Core idea: Compute the 1-step TD error δt at each timestep, then blend them with exponentially decaying weights (γ​λ)l — recent TD errors get full weight, distant ones are down-weighted:

A^tGAE=∑l=0T−t(γ​λ)l​δt+l,δt=rt+γ​V​(st+1)−V⁡(st)(3.23)
Figure 3.2: GAE data flow: each TD residual δt+lV\delta_{t+l}^{V} is weighted by (γ​λ)l(\gamma\lambda)^{l} before summat
Figure 3.2:GAE data flow: each TD residual δt+lV is weighted by (γ​λ)l before summation. Higher λ includes more future residuals (lower bias, higher variance).

Intuitive Mapping of Bias and Variance in GAE

In supervised learning, bias and variance stem from structural model assumptions. In reinforcement learning via GAE, they stem from how much you trust a flawed model versus how much you trust a chaotic environment:

  • Bias (Systemic Misalignment): Arises when the estimator relies on the structural assumptions and imperfect predictions of the value network Vθ. If θ is under-trained or lacks capacity, the baseline guesses are systematically wrong.
  • Variance (Sample Jitteriness): Arises when the estimator relies on long, unconstrained environmental trajectories. Stochastic transitions, random seeds, and policy execution noise accumulate over long horizons, causing empirical sample rewards to swing wildly between rollouts.

The Architectural Spectrum: Boundary Analysis

Figure 3.3: Bias vs. Variance in GAE: λ\lambda controls the trade-off. Small λ\lambda (left) yields high bias / low vari
Figure 3.3:Bias vs. Variance in GAE: λ controls the trade-off. Small λ (left) yields high bias / low variance via bootstrapping; large λ (right) yields low bias / high variance using full Monte Carlo returns. The optimal choice (λ∈[0.9,0.95]) balances stable training with accurate long-horizon credit assignment.

The hyperparameter λ serves as a slide-rule between two fundamental estimation paradigms.

The Trade-off Matrix

By selecting λ∈[0.95,0.99], GAE minimizes the total mean squared error of the advantage estimate:

ConfigurationStatistical PropertiesCore ReliancePractical Risk
λ=0High Bias, Low VarianceModel parameters (θ)Policy traps in sub-optimal local minima
λ∈[0.95,0.99]Balanced (Optimal MSE)Hybrid blendingRequires tuning based on environment stochasticity
λ=1Low Bias, High VarianceEmpirical environment rolloutDestructive gradient updates; training explosion

Table 3.1:Operational comparison of GAE parameter choices.

Diagnostics for Tuning λ\lambda

Monitoring training curves yields direct insight into whether bias or variance dominates:

  1. High Variance Indicators: Policy entropy drops precipitously while explained variance of the value function becomes highly negative or erratic → policy updates are noisy. Remedy: Lower λ to smooth target updates.
  2. High Bias Indicators: Agent achieves early stable training but completely fails to discover complex delayed reward sequences → under-estimating long-horizon dependencies due to bootstrapping. Remedy: Raise λ closer to 1.0 to expose policy to real downstream trajectory signals.

On-Policy vs Off-Policy — Detailed Comparison

On-PolicyOff-PolicyData sourceCurrent policy πθ onlyAny policy (replay buffer)After updateOld data is invalid, must regenerateOld data still usableSample efficiencyLow (data used once)High (data reused many times)StabilityMore stable (consistent distribution)Can diverge (distribution mismatch)ExamplesREINFORCE, PPO, A2C, GRPOQ-Learning, DQN, SAC, DPOFor LLMsPPO, GRPO (generate fresh each step)DPO (static preference dataset)

Model-Based vs Model-Free

Model-FreeModel-BasedWhat’s learnedPolicy π and/or value V/Q directlyEnvironment model P^​(s′|s,a)PlanningNo planning, reactive decisionsCan simulate future trajectoriesSample efficiencyLow (must experience everything)High (can plan in imagination)AccuracyNo model biasModel errors compoundWhen to useComplex/unknown dynamicsSimple dynamics, need efficiencyExamplesPPO, DQN, SAC [129]MuZero [316], Dreamer [130], AlphaGo [331]

Reward Shaping

Reward shaping[265] is a technique where a developer modifies or supplements the environment’s original reward function. Its primary objective is to transform a sparse reward scenario — where the agent receives feedback only upon final task completion — into a dense reward scenario with intermediate feedback signals to accelerate convergence.

The Mathematical Framework

Let the original reward at time step t be Rt​(s,a,s′). The reshaped reward adds an auxiliary shaping function F:

Rt′​(s,a,s′)=Rt​(s,a,s′)+F⁡(s,a,s′)(3.26)

Potential-Based Reward Shaping (PBRS)

To mathematically guarantee that reshaping does not alter the optimal policy, use Potential-Based Reward Shaping. The shaping function F is constrained to the difference in a scalar potential function Φ across states:

F⁡(s,a,s′)=γ​Φ​(s′)−Φ⁡(s)(3.27)

where Φ:𝒮→ℝ is a real-valued potential function evaluating the desirable proximity of a state to the goal, and γ is the discount factor.

The complete PBRS reward:

R′​(s,a,s′)=R⁡(s,a,s′)+γ​Φ​(s′)−Φ⁡(s)(3.28)

Theoretical Guarantees