◆ SafeZone AI Learn
Learn/ Reinforcement Learning/ Search to Agentic RL · lesson 2 of 8

Deep reinforcement learning

From the MDP formalism through Bellman equations and tabular Q-learning to the DQN family and policy gradients — every derivation done, and every algorithm runnable on your own GPU in the playground.

Search (previous chapter) knew the whole map. Reinforcement learning does not: an agent acts, the environment responds with a new state and a scalar reward, and the agent must improve from that feedback alone — no labels, no gradient of the world, consequences only. This chapter builds the full route from the formalism to the algorithms you can train in the playground: MDPs → Bellman equations → tabular methods (which you’ll watch solve a gridworld live) → deep value-based methods (DQN and its fixes) → policy gradients (REINFORCE to PPO).

The MDP: five objects and a goal

A Markov decision process is (S,A,P,R,γ)(\mathcal S, \mathcal A, P, R, \gamma): states, actions, transition kernel P(s′∣s,a)P(s' \mid s, a), reward function, and a discount γ∈[0,1)\gamma \in [0, 1). The Markov property — the future depends on the past only through the current state — is what makes the mathematics go; “state design” in practice is mostly the art of making it approximately true (Pong’s paddle needs the ball’s velocity in its state, which is why the playground’s Pong observation includes the previous frame).

A policy π(a∣s)\pi(a \mid s) is the agent’s behaviour. The objective is the expected return — discounted cumulative reward:

Gt=∑k=0∞γk rt+k+1,J(π)=Eπ[G0].G_t = \sum_{k=0}^{\infty} \gamma^k\, r_{t+k+1}, \qquad J(\pi) = \mathbb{E}_\pi\big[ G_0 \big] .

Discounting is doing two jobs at once: economically it values sooner over later, and mathematically it makes the infinite sum finite and — as you are about to see — makes the whole theory a contraction. The practical intuition worth keeping: γ\gamma sets an effective horizon of roughly 1/(1−γ)1/(1-\gamma) steps (γ=0.99⇒\gamma = 0.99 \Rightarrow ~100 steps of lookahead).

Value functions and the Bellman equations

Two functions organize everything. The state value and action value under π\pi:

Vπ(s)=Eπ[Gt∣st=s],Qπ(s,a)=Eπ[Gt∣st=s,at=a].V^\pi(s) = \mathbb{E}_\pi\big[ G_t \mid s_t = s \big], \qquad Q^\pi(s, a) = \mathbb{E}_\pi\big[ G_t \mid s_t = s, a_t = a \big].

Peel one step off the return (Gt=rt+1+γGt+1G_t = r_{t+1} + \gamma G_{t+1}) and take expectations — the Bellman expectation equation:

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

For the best possible behaviour, replace the average over actions with a max — the Bellman optimality equation:

V∗(s)=max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γV∗(s′)],π∗(s)=arg⁡max⁡aQ∗(s,a).V^\ast(s) = \max_a \sum_{s'} P(s' \mid s, a) \big[ R(s, a, s') + \gamma V^\ast(s') \big], \qquad \pi^\ast(s) = \arg\max_a Q^\ast(s, a).

Why does iterating this converge? Define the backup operator (TV)(s)=max⁡a∑s′P [R+γV(s′)](\mathcal T V)(s) = \max_a \sum_{s'} P\,[R + \gamma V(s')]. For any two value functions,

∥TV1−TV2∥∞  ≤  γ ∥V1−V2∥∞\lVert \mathcal T V_1 - \mathcal T V_2 \rVert_\infty \;\le\; \gamma\, \lVert V_1 - V_2 \rVert_\infty

— T\mathcal T is a γ\gamma-contraction, so by Banach’s fixed-point theorem it has a unique fixed point (V∗V^\ast) and repeated application converges to it geometrically from any start. This is the optimization module’s linear-convergence story wearing RL clothes, and it is not abstract — the widget below prints the contraction as a shrinking max-delta, sweep by sweep:

Start in Value iteration: press “1 sweep” repeatedly and watch value seep backwards from the +1 goal, the max-|ΔV| readout shrinking geometrically — Banach in action; the arrows are the greedy policy, and notice how it detours around the pit’s neighbourhood more widely as you raise the slip probability (risk shows up in V before it shows up in behaviour). Drop the living reward to −0.5 and the policy starts accepting pit-risk to end episodes sooner — the reward function IS the specification, and you just watched a misspecified one change behaviour. Then switch to Q-learning: same world, but the agent must sample it. Run it: early episodes are drunken walks; the return sparkline climbs as Q estimates sharpen. Set ε = 0 from the start and watch it exploit a mediocre path forever — the exploration–exploitation dilemma in one slider.

Learning without the model: TD and Q-learning

Value iteration needed PP and RR. Q-learning replaces the expectation with a sampled transition (s,a,r,s′)(s, a, r, s') and a step toward the sampled target — temporal-difference learning:

Q(s,a)  ←  Q(s,a)+α[r+γmax⁡a′Q(s′,a′)⏟TD target−Q(s,a)].Q(s, a) \;\leftarrow\; Q(s, a) + \alpha \Big[ \underbrace{r + \gamma \max_{a'} Q(s', a')}_{\text{TD target}} - Q(s, a) \Big].

Three structural facts, each of which returns at deep scale:

  • It is off-policy: the max in the target evaluates the greedy policy while the agent behaves ε-greedily — learning about the best policy from imperfect behaviour. (SARSA, its on-policy sibling, uses the actually taken next action.)
  • It is bootstrapping: the target contains the current estimate Q(s′,⋅)Q(s', \cdot) — learning a guess from a guess. That is what makes it sample-efficient, and what makes it dangerous later.
  • With decaying α\alpha (the Robbins–Monro conditions — the SGD lesson, again) and sufficient exploration, tabular Q-learning converges to Q∗Q^\ast.

Going deep: DQN and why it needs its tricks

Pac-Man’s state space (a stack of image planes) has no table. Replace Q(s,a)Q(s,a) with a convolutional network QθQ_\theta and minimize the squared TD error:

L(θ)=E(s,a,r,s′)∼D[(r+γmax⁡a′Qθ−(s′,a′)−Qθ(s,a))2].\mathcal{L}(\theta) = \mathbb{E}_{(s,a,r,s') \sim \mathcal{D}} \Big[ \big( r + \gamma \max_{a'} Q_{\theta^-}(s', a') - Q_\theta(s, a) \big)^2 \Big].

Naively this diverges, for reasons the theory names precisely — the deadly triad of function approximation + bootstrapping + off-policy training. DQN (2015) made it work with two stabilizers, both visible in that loss:

  • Experience replay D\mathcal D: store transitions, train on random minibatches. This breaks the temporal correlation of consecutive frames (SGD’s unbiased-sample assumptions — the noise-ball lesson — quietly required i.i.d.-ish batches) and reuses data.
  • Target network θ−\theta^-: the bootstrap target uses a frozen, periodically updated copy. Without it you are regressing toward a target that moves with every gradient step — a feedback loop; with it, the target holds still long enough to be learned.

Two refinements complete the playground’s value-based family:

Double DQN. The same max that selects the target action also evaluates it, and a max over noisy estimates is biased upward: E[max⁡aQ^(a)]≥max⁡aE[Q^(a)]\mathbb{E}[\max_a \hat Q(a)] \ge \max_a \mathbb{E}[\hat Q(a)]. Systematic overestimation compounds through bootstrapping. The fix decouples the two roles — select with the online net, evaluate with the target net:

y=r+γ Qθ−(s′, arg⁡max⁡a′Qθ(s′,a′)).y = r + \gamma\, Q_{\theta^-}\big(s',\, \arg\max_{a'} Q_\theta(s', a')\big).

Dueling architecture. Decompose Q(s,a)=V(s)+A(s,a)Q(s,a) = V(s) + A(s,a) with two heads sharing the conv trunk (centering AA to make the split identifiable). In states where actions barely matter — most of Pac-Man’s corridor frames — the VV head learns the state’s worth once, instead of separately per action; the advantage head spends its capacity only where actions differ.

The other family: policy gradients

Value-based methods derive the policy from QQ. The policy-gradient family parameterizes the policy πθ\pi_\theta directly and ascends J(θ)J(\theta) — necessary when actions are continuous, and often better-behaved when the optimal policy is stochastic. The engine is the policy gradient theorem, whose derivation is one identity — the score/likelihood-ratio trick ∇θπθ=πθ∇θlog⁡πθ\nabla_\theta \pi_\theta = \pi_\theta \nabla_\theta \log \pi_\theta — applied to the trajectory distribution:

∇θJ=Eτ∼πθ[∑t∇θlog⁡πθ(at∣st)  Gt].\nabla_\theta J = \mathbb{E}_{\tau \sim \pi_\theta} \Big[ \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\; G_t \Big].

Read it as a reweighted classifier gradient: increase the log-probability of every action taken, in proportion to the return that followed. No gradient of the environment appears — the trick’s entire point.

REINFORCE is this, verbatim, with Monte-Carlo returns — unbiased and viciously high-variance (a whole game’s worth of noise credits every action). The variance program has three steps, each a named algorithm:

  1. Baselines. Subtracting any state-dependent b(s)b(s) from GtG_t leaves the gradient unbiased (the subtracted term has expectation zero — exercise 4) but can slash variance. The best simple choice is b(s)=V(s)b(s) = V(s), making the weight the advantage A(s,a)=Q(s,a)−V(s)A(s,a) = Q(s,a) - V(s): “was this action better than typical here?”
  2. Actor–critic (A2C). Learn VϕV_\phi (the critic) alongside πθ\pi_\theta (the actor); estimate advantages by bootstrapped TD instead of full returns. GAE interpolates the spectrum with λ\lambda: one-step TD (biased, low variance) at λ=0\lambda = 0, Monte-Carlo (unbiased, high variance) at λ=1\lambda = 1 — the bias–variance dial of RL.
  3. PPO. Policy gradients are valid only near the sampling policy; a large step can collapse performance unrecoverably (the data you would need to recover comes from the policy you just broke). PPO reuses each batch for several epochs while clipping the incentive to stray, via the ratio ρt=πθ(at∣st)/πθold(at∣st)\rho_t = \pi_\theta(a_t \mid s_t) / \pi_{\theta_{\text{old}}}(a_t \mid s_t):
LCLIP=E[min⁡(ρtAt,    clip⁡(ρt, 1−ϵ, 1+ϵ) At)].\mathcal{L}^{\text{CLIP}} = \mathbb{E}\Big[ \min\big( \rho_t A_t,\;\; \operatorname{clip}(\rho_t,\, 1{-}\epsilon,\, 1{+}\epsilon)\, A_t \big) \Big].

Read the clip: once the ratio moves more than ϵ\epsilon (~0.2) in the profitable direction, the min switches to the clipped branch and the gradient vanishes — no more incentive to push that sample further. It is trust-region thinking implemented with a min and a clamp, and it is the modern default (and, next chapter, the engine under RLHF).

Choosing, and reading the training curves

Value-based (DQN family)Policy-gradient (REINFORCE→PPO)
LearnsQ(s,a)Q(s,a), policy implicitπθ\pi_\theta directly (+ critic)
Dataoff-policy, replayed — sample-efficienton-policy, discarded — sample-hungry
Action spacesdiscretediscrete + continuous
Stability leversreplay, target nets, double-Qclipping, GAE-λ, entropy bonus
In the playgroundPac-Man/Pong learn fastestcorrect but hungrier (higher default episodes)

Both families inherit everything from this track’s earlier modules — Adam’s per-coordinate scaling, the noise-ball’s schedule logic, non-convex landscapes — plus RL’s own pathologies: non-stationarity (the data distribution changes as the policy improves; yesterday’s replay buffer is a slightly foreign country) and reward hacking (the agent optimizes the reward you wrote, not the one you meant — you built the miniature version in the widget when the living-reward slider changed the policy’s risk appetite). When your playground curve is flat: check exploration (ε, entropy) before touching the learning rate. When it collapses mid-training: suspect the step size or, for PPO, too many epochs per batch — the clipped objective only removes the incentive to stray; it does not forbid straying.

Exercises

Work these before the next chapter

  1. Prove the contraction property of the Bellman optimality operator (use ∣max⁡af(a)−max⁡ag(a)∣≤max⁡a∣f(a)−g(a)∣\lvert \max_a f(a) - \max_a g(a) \rvert \le \max_a \lvert f(a) - g(a) \rvert). How many sweeps until ∥V−V∗∥∞\lVert V - V^\ast \rVert_\infty drops by 10× at γ = 0.95? Verify against the widget’s delta readout.
    Solution

    Worked solutions are part of Premium — unlock all of them for £5/month →

  2. 5 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →

References

  • R. Sutton & A. Barto, Reinforcement Learning: An Introduction, 2nd ed., 2018 — chapters 3–6 for everything tabular here (free online).
  • V. Mnih et al., “Human-level control through deep reinforcement learning”, Nature 2015 — DQN, replay, target networks.
  • H. van Hasselt, A. Guez, D. Silver, “Deep RL with Double Q-learning”, AAAI 2016; Z. Wang et al., “Dueling Network Architectures”, ICML 2016.
  • R. Williams, “Simple statistical gradient-following algorithms for connectionist reinforcement learning”, 1992 — REINFORCE.
  • J. Schulman et al., “High-Dimensional Continuous Control Using Generalized Advantage Estimation”, ICLR 2016 — GAE; and “Proximal Policy Optimization Algorithms”, 2017 — PPO.
  • R. Sutton et al., “Policy Gradient Methods for RL with Function Approximation”, NeurIPS 1999 — the theorem.
Train the real thing: DQN through PPO learning Pac-Man and Pong from pixels, on your GPU, with every hyperparameter exposed. Open the playground →