E. MDPs, Reinforcement Learning & Neural Networks

Policies, value functions, Bellman equations, policy gradients, and the neural networks inside them

Before you start

This primer assumes a first course in linear algebra (matrices, linear systems, eigenvalues) and single-variable calculus, plus:

Study route — Learn the decision model before the learning algorithms

No previous RL or neural-network course is needed. First trace one state–action–reward–next-state transition, then compute a short discounted return. Sections 1–4 explain what is being solved; sections 5–6 explain learning methods. Sections 7–9 form a second strand about the networks used as policies or models. You can begin that strand after refreshing matrix multiplication and the chain rule, even while the policy-gradient material is still new.

Begin with the three readiness checks. If a check is difficult, use its review link and worked answer, then try again without looking. After each section, try its Easy problem, use the separate hint if needed, and continue to Medium once you can explain the steps. Hard problems combine ideas or expose a common mistake. Keep the answers closed on your first attempt.

The original cumulative exercises combine sections after this guided practice. Finish a study session by explaining one worked solution in your own words, then changing a number and solving it again.

Readiness checks — a short prerequisite refresher

These checks are diagnostic, with the needed calculation explained in each answer. A gap tells you where to review; it is not a reason to skip this primer.

Exercise E.R1 — Readiness: A random choice has an expected reward

Choose action $a$ with probability $1/4$ and reward $4$, or action $b$ with probability $3/4$ and reward $0$. Find the expected reward. Must any individual run equal it?

Review if needed: weighted expectations.

Show hint
Multiply each reward by the chance of choosing its action.
Show worked solution

The expectation is $(1/4)(4)+(3/4)(0)=1$. An individual run earns either $4$ or $0$, never $1$. The expectation describes the probability-weighted average. A policy is the rule assigning these action probabilities; its expected performance and the outcome of one trajectory must be kept separate.

Exercise E.R2 — Readiness: Why discounting gives a finite sum

An infinite sequence has reward $2$ every step. With discount $1/2$, evaluate $2+1+1/2+1/4+\cdots$.

Review if needed: geometric series.

Show hint
Factor out $2$ and use the geometric series with ratio $1/2$.
Show worked solution

The sum is $2\sum_{t=0}^\infty(1/2)^t=2/(1-1/2)=4$. The partial sum through step $T-1$ is $4(1-2^{-T})$, which approaches $4$. The finite value depends on the ratio being below one; without discounting, the sum of these positive rewards diverges.

Exercise E.R3 — Readiness: Input and parameter derivatives answer different questions

For $f_\theta(x)=\theta x$, compute the derivative with respect to $\theta$ and with respect to $x$, at $\theta=3$, $x=2$.

Review if needed: partial derivatives.

Show hint
Hold the other argument fixed in each partial derivative.
Show worked solution

Holding $x$ fixed gives $\partial f/\partial\theta=x=2$. Holding $\theta$ fixed gives $\partial f/\partial x=\theta=3$. The first describes how a parameter update changes the output at this input; the second describes sensitivity to an input change in this fixed model. Backpropagation can compute both, but they have different uses.

Book contents · Apply this chapter to a real decision · Glossary

Contents
1. Bandits, Regret & Bayesian Optimization 2. Markov Decision Processes, Policies & Returns 3. Value Functions & Bellman Equations 4. Dynamic Programming: Value & Policy Iteration 5. Policy Gradients, Advantages & Trust Regions 6. Q-Learning, Actor-Critic, Entropy Regularisation, Model-Based & Offline RL 7. Neural Networks: Layers, Activations & Backpropagation 8. Convolutions, Residual, Recurrent & Equilibrium Layers 9. Classifiers, Margins & Adversarial Examples Interactive: Value Iteration & a Tiny Network Application lab & chapter review Exercises Further Reading Flashcards

Half of this section is about agents that learn to act (safe RL, safe exploration, constrained policy optimisation), the other half about the networks those agents and controllers are made of (Lipschitz bounds, certified robustness, networks in feedback loops). This primer builds both vocabularies from scratch: first bandits, the one-state version of learning to act; then Markov decision processes, value functions and the Bellman equations; the dynamic-programming algorithms that solve them exactly; the gradient methods that replace them when the problem is large; and finally neural networks as compositions of affine maps and activations, how they are trained, and what it means to certify a classifier.

Notation — this page
  • MDPs. State $s\in\mathcal S$, action $a\in\mathcal A$, transition probabilities $P(s'\mid s,a)$, reward $r(s,a)$, cost $c(s,a)$, initial distribution $\mu$, discount factor $\gamma\in[0,1)$; policy $\pi(a\mid s)$ or $\pi_\theta$; value, action-value and advantage $V^\pi,Q^\pi,A^\pi$ (costs: $V^\pi_c,Q^\pi_c,A^\pi_c$); objective $J(\pi)$, cost objective $J_c(\pi)$; discounted occupancy measure $\rho_\pi$ with state marginal $d^\pi$. This matches the table in Module 1. The control modules write $x,u$ for $s,a$.
  • Bandits and BO. Unknown objective $f$ on a domain $D$, query $x_t$, posterior mean and standard deviation $\mu_{t-1},\sigma_{t-1}$, confidence scaling $\beta_t$. On this page $\gamma$ is always the discount factor, never the information gain $\gamma_t$ of Modules 3–6.
  • Networks. Weights $W_k$, biases $b_k$, scalar activation $\varphi$ applied coordinatewise, pre-activations $v_k$, hidden vectors $z_k$; $f(x)$ is the network output in Sections 7–9 (and the unknown objective in Section 1).

1. Bandits, Regret & Bayesian Optimization

Start here — Score decisions before choosing an algorithm

An arm is an available action; its true mean reward is different from one noisy observation. Regret compares true performance with a specified best-action comparator. For true means $0.8$ and $0.6$, choosing the second arm loses $0.2$ that round, whatever noisy reward is observed.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review expectations and noise.

The simplest sequential decision problem has no state: in every round you choose an action, receive a noisy payoff, and want to do well over many rounds. Tuning a controller by experiments (Modules 4–6) is exactly this: each experiment is a round, the controller parameters are the action, the measured performance is the payoff. Two questions organise everything: how do we score a learner (regret), and how should it trade trying new actions against repeating good ones (exploration versus exploitation)?

Definition — Bandit problem; instantaneous, cumulative and simple regret
A bandit has an action set $\mathcal X$ (the arms: a finite set $\{1,\dots,K\}$, or a domain $D\subset\mathbb R^d$ for a continuous bandit) and an unknown objective $f:\mathcal X\to\mathbb R$. In round $t=1,\dots,T$ the learner picks $x_t$ using only the data of rounds $1,\dots,t-1$ and observes $y_t=f(x_t)+\epsilon_t$ with zero-mean noise $\epsilon_t$. The comparator is a best action $x^*\in\operatorname*{arg\,max}_{x\in\mathcal X}f(x)$.
  • Instantaneous regret $r_t=f(x^*)-f(x_t)\ge0$: what round $t$ lost compared with playing $x^*$.
  • Cumulative regret $R_T=\sum_{t=1}^Tr_t$: the total price of learning; every experiment counts.
  • Simple regret of a final recommendation $\hat x_T$: $f(x^*)-f(\hat x_T)$; only the answer counts (pure exploration; best-arm identification when the goal is to name $x^*$).
  • A learner is no-regret if $R_T/T\to0$: $R_T$ grows sublinearly (for example like $\sqrt{T\log T}$; Primer 0), so the average round becomes as good as $x^*$.
Regret uses the true $f$, which the learner never sees: it is a yardstick for analysis, not something an algorithm can compute. When choices are random, one bounds $\mathbb E[R_T]$ or states a bound that holds with probability at least $1-\delta$.

Example. Let $f(x^*)=1$ and suppose five experiments have true values $f(x_t)=0.2,\,0.5,\,0.9,\,1,\,1$. Then $r_t=0.8,\,0.5,\,0.1,\,0,\,0$, so $R_5=1.4$ and the average regret is $0.28$. If the fourth point is recommended, the simple regret is $0$ although the cumulative regret is not: the two criteria reward different behaviour. Changing objectives. If the objective drifts ($f_t$ in round $t$), static regret compares with the best fixed action in hindsight, $\max_x\sum_tf_t(x)-\sum_tf_t(x_t)$, and dynamic regret with the best action of each round, $\sum_t\big(\max_xf_t(x)-f_t(x_t)\big)$; the latter is harder to keep sublinear and needs a bound on how fast $f_t$ changes. For a fixed $f$ both equal $R_T$.

Intuition — why greedy fails
Two arms pay $1$ or $0$ with success probabilities $0.6$ and $0.5$. The greedy learner pulls each arm once, then always pulls the arm with the higher empirical mean. With probability $0.4\cdot0.5=0.2$ the good arm's first pull fails and the bad arm's succeeds. The good arm's estimate is then $0$ and is never updated, the bad arm's estimate stays positive forever, and greedy pulls the bad arm in every later round: $R_T=0.1\,(T-1)$, linear regret. A learner must keep exploring actions whose value is uncertain, even when exploiting the current best estimate looks better.
Definition — Optimism in the face of uncertainty (UCB rules)
Maintain, for every action, an upper confidence bound $U_t(x)$ computed from the data before round $t$ and valid with high probability, $f(x)\le U_t(x)$; play $x_t\in\operatorname*{arg\,max}_xU_t(x)$. Act as if the world were as good as the data still allow.
  • UCB1 (Auer, Cesa-Bianchi & Fischer, Machine Learning 2002), $K$ arms, rewards in $[0,1]$: after $t$ pulls in total, $U(a)=\hat\mu_a+\sqrt{2\ln t/n_a}$, with $n_a$ the number of pulls of arm $a$ and $\hat\mu_a$ their average. The formula needs $n_a\ge1$: first pull every arm once (equivalently, set $U(a)=\infty$ while $n_a=0$), then use it.
  • GP-UCB (Srinivas, Krause, Kakade & Seeger, ICML 2010): $U_t(x)=\mu_{t-1}(x)+\beta_t\sigma_{t-1}(x)$ with the Gaussian-process posterior mean and standard deviation after $t-1$ observations (Module 3; Srinivas et al. write $\beta_t^{1/2}$ for this $\beta_t$).
The bonus is large for rarely tried actions and shrinks as data accumulate: an action is played either because it looks good or because too little is known about it.

Example (UCB1). After $t=12$ pulls, arm 1 has $n_1=10$, $\hat\mu_1=0.6$ and arm 2 has $n_2=2$, $\hat\mu_2=0.5$. With $\ln12=2.485$: $U(1)=0.6+\sqrt{2\cdot2.485/10}=0.6+0.705=1.305$ and $U(2)=0.5+\sqrt{2\cdot2.485/2}=0.5+1.576=2.076$. UCB1 pulls arm 2: lower mean, but far fewer pulls.

Lemma — An optimistic round costs at most its confidence width
Assumptions. In round $t$ there are functions $l_t\le U_t$ with $l_t(x)\le f(x)\le U_t(x)$ for all $x$ simultaneously, and $U_t(x)-l_t(x)=2w_t(x)$. The learner plays $x_t\in\operatorname*{arg\,max}_xU_t(x)$.
Statement. $r_t\le2w_t(x_t)$; hence $R_T\le2\sum_{t=1}^Tw_t(x_t)$ on the event that all bands hold.
Proof. $f(x^*)\le U_t(x^*)\le U_t(x_t)=l_t(x_t)+2w_t(x_t)\le f(x_t)+2w_t(x_t)$. $\blacksquare$
In words. Either the chosen action is good, or its uncertainty was large and observing it teaches something. Why each assumption matters. If the band fails somewhere (a too-small $\beta_t$, a misspecified model; Module 5), the first inequality breaks and nothing is guaranteed. Whether $\sum_tw_t(x_t)$ is sublinear depends on how fast uncertainty shrinks where the algorithm samples: for GPs this is the maximum information gain of Module 3; for UCB1 the argument gives $R_T=O(\sqrt{KT\log T})$.

Bayesian optimization: a bandit with a Gaussian-process model

For a continuous bandit with expensive, noisy evaluations, Bayesian optimization (BO) fits a probabilistic surrogate of $f$, usually a Gaussian process (GP), and chooses each experiment by maximising a cheap acquisition function built from the posterior mean $\mu_{t-1}(x)$ and standard deviation $\sigma_{t-1}(x)$. GP regression is the subject of Module 3 (its engine, Gaussian conditioning, is in Primer C); here only the loop and the acquisition functions matter.

Algorithm 1: Bayesian optimization
  1. Choose a GP prior (mean and kernel) for $f$; collect initial data if available.
  2. for $t=1,\dots,T$:
  3. condition the GP on the data: posterior $\mu_{t-1},\sigma_{t-1}$
  4. $x_t\in\operatorname*{arg\,max}_{x\in D}\alpha_t(x)$ // inner optimisation: cheap compared with an experiment
  5. run the experiment, observe $y_t=f(x_t)+\epsilon_t$, add $(x_t,y_t)$ to the data
  6. recommend $\hat x_T$, e.g. the maximiser of $\mu_T$ or of a lower confidence bound.
Definition — Acquisition functions (maximisation)
Let $f^+$ be the best value observed so far (the incumbent), $z(x)=(\mu_{t-1}(x)-f^+)/\sigma_{t-1}(x)$ wherever $\sigma_{t-1}(x)\gt0$, and $\varphi,\Phi$ the standard normal density and distribution function (in this section only; later $\varphi$ is an activation).
  • UCB: $\alpha_t(x)=\mu_{t-1}(x)+\beta_t\sigma_{t-1}(x)$.
  • Probability of improvement: $\alpha_t(x)=\Phi(z(x))$.
  • Expected improvement (Jones, Schonlau & Welch, J. Global Optim. 1998): $\alpha_t(x)=\mathbb E\big[\max\{f(x)-f^+,0\}\big]=(\mu_{t-1}(x)-f^+)\,\Phi(z)+\sigma_{t-1}(x)\,\varphi(z)$, the average amount by which $x$ beats the incumbent under the posterior.
  • Entropy search (Hennig & Schuler, JMLR 2012): query where the observation is expected to reduce most the entropy (Primer C) of the posterior distribution of the maximiser location $x^*$. It seeks information about where the optimum is, not improvement at $x$.
PI and EI as written need $\sigma_{t-1}(x)\gt0$. Where $\sigma_{t-1}(x)=0$ (for example at an evaluated point under noiseless observations) the value $f(x)=\mu_{t-1}(x)$ is known, and strict improvement gives $\mathrm{PI}=\mathbf 1\{\mu_{t-1}(x)\gt f^+\}$ and $\mathrm{EI}=\max\{\mu_{t-1}(x)-f^+,0\}$. Constrained EI (Module 4): if the posterior models of the objective and of the constraints are independent (separate GPs), it is EI times the posterior probability that all constraints hold; with correlated models the product is wrong in general, and one evaluates $\mathbb E\big[\max\{f(x)-f^+,0\}\,\mathbf 1\{x\text{ feasible}\}\big]$ under the joint posterior.
Derivation — the closed form of expected improvement

Under the posterior, $f(x)=\mu+\sigma Z$ with $Z\sim\mathcal N(0,1)$ (drop the argument $x$). The improvement $\max\{\mu-f^++\sigma Z,0\}$ is positive exactly when $Z\gt-z$ with $z=(\mu-f^+)/\sigma$, so

$$\mathbb E\big[\max\{\mu-f^++\sigma Z,0\}\big]=\int_{-z}^{\infty}(\mu-f^++\sigma u)\,\varphi(u)\,du=(\mu-f^+)\big(1-\Phi(-z)\big)+\sigma\int_{-z}^{\infty}u\,\varphi(u)\,du .$$

Since $\varphi'(u)=-u\varphi(u)$, the last integral is $\big[-\varphi(u)\big]_{-z}^{\infty}=\varphi(-z)=\varphi(z)$, and $1-\Phi(-z)=\Phi(z)$ by symmetry. Hence $\mathrm{EI}=(\mu-f^+)\Phi(z)+\sigma\varphi(z)$. Both terms are visible: a high mean (exploitation) and a large $\sigma$ (exploration) raise EI.

Example. Incumbent $f^+=1$, $\beta_t=2$. Candidate A has $\mu=0.8$, $\sigma=0.3$; candidate B has $\mu=1.05$, $\sigma=0.05$. UCB: $0.8+0.6=1.40$ for A versus $1.05+0.10=1.15$ for B, so UCB explores A. EI: for A, $z=-0.667$, $\mathrm{EI}=(-0.2)(0.2525)+0.3\,(0.3194)=0.0453$; for B, $z=1$, $\mathrm{EI}=0.05\,(0.8413)+0.05\,(0.2420)=0.0542$, so EI exploits B. Acquisition functions encode different exploration preferences; none of them knows anything about safety.

Local search and trust regions. In high dimensions a single global GP is hard to fit and the acquisition is hard to maximise. Local BO (TuRBO, Eriksson et al., NeurIPS 2019) restricts the queries to a trust region, a box around the best point found so far whose side length is doubled after a run of successes and halved after a run of failures (with a restart when it becomes tiny). This region lives in the parameter space of the objective; the trust regions of Section 5 are instead KL balls around the current policy. Grids and the curse of dimensionality. A candidate grid with $m$ points per axis in $d$ dimensions has $m^d$ points: with $m=100$, $10^6$ points for $d=3$ and $10^{12}$ for $d=6$. Grid-based safe BO and grid-based verification therefore stop at a few dimensions, and a statement proved on grid points says nothing about the continuous domain between them unless a Lipschitz argument fills the gaps.

Definition — Dominance, Pareto front, hypervolume
For objectives $F=(F_1,\dots,F_m)$ to be maximised, an outcome $a$ dominates $b$ if $F_i(a)\ge F_i(b)$ for every $i$ and $F_i(a)\gt F_i(b)$ for at least one $i$. The Pareto front is the set of non-dominated outcomes: along it, improving one objective costs another. For a reward–cost pair, $a$ dominates $b$ if it has at least as much reward and no more cost, with one of the two strict. Fix a reference point $q$ worse than every outcome of interest; the hypervolume of a set of outcomes is the volume (area for $m=2$) of the region they dominate above $q$. Expected hypervolume improvement (EHVI) queries where the random outcome is expected to enlarge that volume most.

Example. Outcomes $A=(3,1)$, $B=(2,2)$, $C=(1,3)$, $D=(1.5,1.5)$, reference $q=(0,0)$. $D$ is dominated by $B$; the front is $\{A,B,C\}$ with hypervolume $3\cdot1+2\cdot(2-1)+1\cdot(3-2)=6$. A new outcome $(2.5,1.5)$ is non-dominated and raises the hypervolume to $6.25$; adding $D$ changes nothing. A front is a set of trade-offs, not a ranking: "method X is better" needs a single criterion, such as the best reward at a fixed cost budget.

Full-information and adversarial variants. In online learning with experts every action reveals its loss $\ell_t(a)\in[0,1]$ after each round (possibly chosen by an adversary), and regret is measured against the best fixed action in hindsight. The multiplicative-weights (Hedge) rule plays $p_{t+1}(a)\propto p_t(a)\,e^{-\eta\ell_t(a)}$; with $\eta=\sqrt{8\ln K/T}$ its regret, in expectation over its own randomisation, is at most $\sqrt{(T/2)\ln K}$. With bandit feedback (only the played action's loss is seen) EXP3 feeds Hedge the importance-weighted estimates $\hat\ell_t(a)=\ell_t(a)\mathbf 1\{a_t=a\}/p_t(a)$ and has regret $O(\sqrt{TK\ln K})$ (Lattimore & Szepesvári, Ch. 11, in the Further Reading). If both players of a zero-sum game (for example a policy player and a Lagrange-multiplier player) run no-regret rules, their time-averaged strategies form an approximate saddle point whose error is the sum of the two average regrets, while the last iterates may keep cycling (Primer B).

Where this is used
Pitfall — no-regret is not safety
A no-regret guarantee is a statement about the average over many rounds. It allows arbitrarily bad individual experiments, especially early, and optimism deliberately tries actions whose outcome is uncertain. On hardware a single bad experiment may destroy the system; this is why safe BO (Modules 4–6) adds a separate safety requirement for every query.

Practice — Score decisions before choosing an algorithm

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S1 — Easy: Cumulative and simple regret

Three arms have true mean rewards $0.8$, $0.6$ and $0.3$. A learner selects arms $1,2,3,2$, then recommends arm $3$. Compute cumulative regret, average regret and simple regret. Ignore observation noise in this calculation.

Review if needed: this section and expectations and noise.

Show hint
Compare each chosen arm with the best true mean $0.8$. Simple regret uses only the recommendation.
Show worked solution
  1. The per-round regrets are $0$, $0.2$, $0.5$, $0.2$.
  2. The cumulative regret is $0.9$, and the average is $0.9/4=0.225$.
  3. The final recommendation has simple regret $0.8-0.3=0.5$. A low cumulative average and a good final recommendation are different goals. Observed noisy payoffs would not replace the true means in this definition.
Exercise E.S2 — Medium: Optimism for reward and caution for safety

Two actions have reward estimates $0.5,0.6$ with confidence radii $0.2,0.05$. Which maximises the reward upper bound? Their safety-function estimates are $0.3,0.2$ with radii $0.4,0.1$, and safety means the true function is nonnegative. Which action is certified safe by its lower bound?

Review if needed: this section and expectations and noise.

Show hint
Reward UCB adds the radius; a conservative safety lower bound subtracts it.
Show worked solution
  1. The reward upper bounds are $0.5+0.2=0.7$ and $0.6+0.05=0.65$. An unconstrained optimistic rule chooses action $1$.
  2. The safety lower bounds are $0.3-0.4=-0.1$ and $0.2-0.1=0.1$. Only action $2$ has a nonnegative lower bound.
  3. A safe optimistic rule chooses the best reward UCB among certified actions, hence action $2$. Action $1$ is uncertified, which does not prove it unsafe. This conclusion is conditional on the confidence intervals being valid together.
Exercise E.S3 — Hard: Static and dynamic comparators

In two rounds, arm $A$ has rewards $(1,0)$ and arm $B$ has rewards $(0,1)$. A learner selects $A$ both times. Compute regret against the best fixed arm and against the best arm in each round. Why do these comparators differ?

Review if needed: this section and expectations and noise.

Show hint
The fixed comparator must choose one arm for both rounds; the dynamic comparator may switch.
Show worked solution
  1. The learner earns $1+0=1$. Each fixed arm also earns total reward $1$, so static regret is $1-1=0$.
  2. The per-round best actions earn $1$ in each round, total $2$. Dynamic regret is $2-1=1$.
  3. The objective changes between rounds, and the dynamic comparator exploits that change. A no-regret claim must identify its comparator; vanishing average static regret does not ensure tracking of the changing optimum.

2. Markov Decision Processes, Policies & Returns

Start here — Follow the state-action-reward timeline

At time $t$, observe state $s_t$, choose action $a_t$ using a policy, receive reward $r_t$, then draw next state $s_{t+1}$ from the environment. A policy maps states to action choices or probabilities; it is not the transition model. Discount $\gamma$ weights how much later rewards contribute.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review weighted conditional expectations.

In a bandit the action does not change the situation. In a Markov decision process it does: the action moves a state, the state decides which rewards are reachable next, and a good decision now may pay off only much later.

Definition — Markov decision process (MDP)
A finite discounted MDP is a tuple $(\mathcal S,\mathcal A,P,r,\mu,\gamma)$: finite sets of states $\mathcal S$ and actions $\mathcal A$ (with $\emptyset\ne\mathcal A(s)\subseteq\mathcal A$ the actions available in $s$ when they depend on the state); transition probabilities $P(s'\mid s,a)\ge0$ with $\sum_{s'}P(s'\mid s,a)=1$ for every pair $(s,a)$; a reward function $r:\mathcal S\times\mathcal A\to\mathbb R$; an initial distribution $\mu$ on $\mathcal S$; a discount factor $\gamma\in[0,1)$. The system starts in $s_0\sim\mu$; at each time $t$ the agent chooses $a_t$, receives $r(s_t,a_t)$, and the next state is drawn from $P(\cdot\mid s_t,a_t)$.
  • Costs. Cost functions $c_i:\mathcal S\times\mathcal A\to\mathbb R$ are further signals of the same type as $r$. An MDP with costs and budgets $d_i$ is a constrained MDP (CMDP, Module 8).
  • Deterministic MDP. Each $P(\cdot\mid s,a)$ puts all its mass on one successor: $s_{t+1}=f(s_t,a_t)$.
  • Markov property. $\mathbb P(s_{t+1}=s'\mid s_0,a_0,\dots,s_t,a_t)=P(s'\mid s_t,a_t)$: the current state and action summarise everything about the past that matters for the future.
Continuous state or action spaces turn sums into integrals; in control notation $x_{t+1}=f(x_t,u_t)+w_t$ with a random disturbance $w_t$ is an MDP (Primer D).

The Markov property is a statement about what we call "state". For a pendulum, the angle alone is not a state (the future depends on how fast it swings); angle and angular velocity together are. A reward that depends on the successor, $r(s,a,s')$ as in Module 1, can be replaced by its conditional mean $r(s,a)=\sum_{s'}P(s'\mid s,a)\,r(s,a,s')$ whenever only expected returns matter (tower rule, Primer C).

1home 2field a (rest): r = 1 b (harvest): r = 2, c = 1 b (go): r = 0 a (return): r = 0
The running example of this page: a deterministic two-state MDP, $\gamma=0.9$, start at home ($\mu=(1,0)$). Harvesting pays most but is the only risky action (cost $c=1$).
Definition — Policies: history-dependent, Markov, stationary, deterministic
Let $h_t=(s_0,a_0,\dots,s_{t-1},a_{t-1},s_t)$ be the history. A policy is a sequence of rules $\pi_t(a\mid h_t)$, each a probability distribution over actions given the history. It is Markov if $\pi_t$ depends on $h_t$ only through $(t,s_t)$, stationary if in addition it does not depend on $t$, written $\pi(a\mid s)$, and deterministic if all its probabilities are $0$ or $1$, written $a=\pi(s)$. A stationary randomised policy picks for each state a point of the probability simplex $$\pi(\cdot\mid s)\in\Delta(\mathcal A):=\Big\{p\in\mathbb R^{|\mathcal A|}:\ p_a\ge0,\ \sum_ap_a=1\Big\}$$ (for two actions a segment, for three a triangle). A parametrised policy $\pi_\theta$ is computed from a parameter vector $\theta$, for example the weights of a network (Section 7).

Softmax policies. A standard way to turn arbitrary scores $\theta_{s,a}$ into a point of the simplex is the softmax with temperature $\alpha\gt0$:

$$\pi_\theta(a\mid s)=\frac{\exp(\theta_{s,a}/\alpha)}{\sum_{b}\exp(\theta_{s,b}/\alpha)} .$$

Every action gets positive probability (full support). For scores $(1,2,4)$: $\alpha=1$ gives $(0.042,0.114,0.844)$, $\alpha=0.5$ gives $(0.002,0.018,0.980)$ and $\alpha=5$ gives $(0.247,0.302,0.451)$. As $\alpha\to0$ the mass concentrates on the largest score (greedy), as $\alpha\to\infty$ it becomes uniform. Section 6 explains where this form comes from (entropy regularisation), Section 7 uses it for classifiers.

Pitfall — randomising every step is not randomising once
The stationary policy "$\pi(b\mid s)=\tfrac12$ in every state" flips a fresh coin at every step. The mixture "flip one coin at $t=0$, then follow policy $\pi_1$ forever on heads and $\pi_2$ on tails" randomises once per episode. Written as a rule $\pi_t(a\mid h_t)$ it is history-dependent: the past actions carry information about the coin, and hence about which policy is running. The mixture's return is the average of the two policies' returns; the per-step policy's return is in general something else (worked out in Section 3). The convexity arguments of Modules 2 and 8 mix policies in the second way, once per episode.
Definition — Trajectories and returns
A trajectory is $\tau=(s_0,a_0,s_1,a_1,\dots)$; "$\tau\sim\pi$" means $s_0\sim\mu$, then alternately $a_t\sim\pi(\cdot\mid s_t)$ and $s_{t+1}\sim P(\cdot\mid s_t,a_t)$. For a stationary policy a finite prefix has probability $$p_\pi(s_0,a_0,\dots,s_H)=\mu(s_0)\prod_{t=0}^{H-1}\pi(a_t\mid s_t)\,P(s_{t+1}\mid s_t,a_t).$$ With $r_t=r(s_t,a_t)$, the common performance criteria are
  • finite horizon $\sum_{t=0}^{T-1}r_t$ (episodes of fixed length);
  • discounted return $G=\sum_{t=0}^{\infty}\gamma^tr_t$, and its normalised version $(1-\gamma)G$, a weighted average of the rewards (the weights $(1-\gamma)\gamma^t$ sum to $1$);
  • average reward $\lim_{T\to\infty}\frac1T\sum_{t\lt T}r_t$; when the limit may not exist one uses $\liminf$, the long-run average in the worst case (Primer 0), and it matters whether the limit is taken along each trajectory or after an expectation;
  • total cost $\sum_{t=0}^{T^\ast-1}c_t$ up to a random termination time $T^\ast$ (transient and absorbing models, Section 4).
The objective is $J(\pi)=\mathbb E_{\tau\sim\pi}\big[\sum_t\gamma^tr(s_t,a_t)\big]$; $J_c(\pi)$ is the same with $c$ in place of $r$.

Example. Under the uniform policy ($\pi(a\mid s)=\pi(b\mid s)=\tfrac12$) the prefix $1\xrightarrow{b}2\xrightarrow{b}2$ has probability $1\cdot\tfrac12\cdot1\cdot\tfrac12\cdot1=\tfrac14$. The policy "always harvest" (go, then harvest forever) earns $0,2,2,\dots$, so $G=\sum_{t\ge1}0.9^t\cdot2=2\cdot0.9/0.1=18$ and $J_c=\sum_{t\ge1}0.9^t=9$; "always rest" earns $G=1/(1-0.9)=10$ at zero cost.

Fact — Bounded rewards give bounded, exchangeable discounted sums
If $|r(s,a)|\le B$ for all $(s,a)$ and $0\le\gamma\lt1$, then for every trajectory $$|G|\le\sum_{t\ge0}\gamma^tB=\frac{B}{1-\gamma},\qquad\Big|\sum_{t\ge T}\gamma^tr_t\Big|\le\frac{\gamma^TB}{1-\gamma}.$$ Consequently $\mathbb E\big[\sum_t\gamma^tr_t\big]=\sum_t\gamma^t\,\mathbb E[r_t]$: the partial sums differ from $G$ by at most $\gamma^TB/(1-\gamma)$ on every trajectory, so their expectations differ from $\mathbb E[G]$ by at most the same amount, which tends to $0$. The bound $V_{\max}=R_{\max}/(1-\gamma)$ on any value is this fact.

Effective horizon and time constant. For $0\lt\epsilon\lt1$, the weight $\gamma^T$ is at most $\epsilon$ exactly when $T\ge\ln(1/\epsilon)/\ln(1/\gamma)$; this needs $0\lt\gamma\lt1$ so that $\ln(1/\gamma)\gt0$. For $\gamma$ near $1$, $\ln(1/\gamma)\approx1-\gamma$, so the discount sees about $\ln(1/\epsilon)$ multiples of $1/(1-\gamma)$ steps. Example: $\gamma=0.99$, $\epsilon=0.01$ gives $T\ge458.2$, i.e. $459$ steps, while $1/(1-\gamma)=100$. In continuous time the weight is $e^{-t/\tau}$ with time constant $\tau$ (decay rate $1/\tau$); sampling at unit steps gives $\gamma=e^{-1/\tau}$, i.e. $\tau=-1/\ln\gamma$, which is $9.49$ steps for $\gamma=0.9$ (compare $1/(1-\gamma)=10$).

Episodes and absorbing states. In episodic tasks each episode (rollout) starts from $s_0\sim\mu$, often a fixed reset state $x_0$, and runs until a terminal state or a horizon; learning is an outer loop over episodes (experiments) around an inner loop over time steps. A terminal state is modelled as absorbing: once entered it is never left and yields reward and cost $0$, which turns an episodic task into an infinite-horizon one.

Deterministic MDPs as graphs. Draw a vertex per state and a directed edge $s\to f(s,a)$ per available action; a policy's run is a path. Which states are reachable is found by breadth-first search; a shortest path for nonnegative edge lengths by Dijkstra's algorithm (only this input–output behaviour is used later). A safety feature $g(s)$ that must stay above a threshold at every visited state is a separate signal from the reward.

Partial observation. If the agent sees only observations $o_t$, the Markov property usually fails for $o_t$; an information state (the whole observation history, or the posterior distribution of $s_t$ given it) restores it.

Where this is used
  • MDPs, costs, trajectories $\tau\sim\pi$ and discounted cost sums with $c_i(s_t,a_t,s_{t+1})$: the CMDP of Module 1 and its definition in Module 8, including history-dependent policies and the "discounted, average, episodic" criteria.
  • Episodes from a fixed reset state $x_0$: GoSafe's experiments in Module 6. Finite deterministic MDPs with state-dependent actions, a safety feature and shortest safe paths: SafeMDP in Module 6.
  • Stochastic policies $\pi(a\mid x)$ and $\gamma=e^{-1/\tau}$: Module 7. The simplex $\pi(\cdot\mid s)\in\Delta$: Module 11. Information states: Module 10.
Pitfall — what an expected discounted cost does not say
$J_c(\pi)\le d$ bounds an average over episodes: single episodes may exceed $d$. And discounting down-weights late events: with $\gamma=0.99$ a crash at $t=459$ counts less than $1\%$ of a crash at $t=0$. When "never fail" is the requirement, a discounted expected cost with a positive budget is the wrong object: it tolerates failures (Modules 7, 8 and 10 return to this). The one exception is budget $0$ on a nonnegative failure indicator, $c_t=\mathbf 1\{\text{failure at time }t\}$: for $0\lt\gamma\lt1$, $J_c(\pi)=0$ forces $\sum_t\gamma^tc_t=0$ almost surely, i.e. no failure at any time, but only under the modelled dynamics and initial distribution, not under model error.

Practice — Follow the state-action-reward timeline

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S4 — Easy: Discount a short return

A trajectory produces rewards $r_0=2$, $r_1=4$, $r_2=0$ and then terminates. For $\gamma=0.5$, compute its return $G_0$ and its return from the second step, $G_1$. Verify $G_0=r_0+\gamma G_1$.

Review if needed: this section and weighted conditional expectations.

Show hint
The reward at the current step receives weight one. Discounting restarts when defining $G_1$.
Show worked solution
  1. $G_0=2+0.5(4)+0.5^2(0)=4$.
  2. Starting at step $1$ gives $G_1=4+0.5(0)=4$, not $2$; the time origin has changed.
  3. Indeed $r_0+\gamma G_1=2+0.5(4)=4$. Splitting a return this way is the step that produces Bellman equations after taking conditional expectations.
Exercise E.S5 — Medium: Average over transitions and then actions

At state $s$, action $a$ gives immediate reward $1$ and transitions to states with values $4$ and $0$ with probabilities $0.75$ and $0.25$. Use $\gamma=0.5$. Another action $b$ has action-value $1$. Under policy probabilities $\pi(a\mid s)=0.6$ and $\pi(b\mid s)=0.4$, compute $Q(s,a)$ and $V(s)$.

Review if needed: this section and weighted conditional expectations.

Show hint
First average the next-state value for a fixed action. Then average action-values under the policy.
Show worked solution
  1. The expected next-state value after $a$ is $0.75(4)+0.25(0)=3$.
  2. Therefore $Q(s,a)=1+0.5(3)=2.5$. Immediate reward is not discounted; continuation value is.
  3. Now average over the policy: $V(s)=0.6(2.5)+0.4(1)=1.9$. The two averages correspond to two separate random choices: the selected action and the next state.
Exercise E.S6 — Hard: Equal expected costs can hide different safety events

Over an undiscounted horizon of $100$ steps, policy $A$ has a $1\%$ chance of violating at every step and otherwise never violates. Policy $B$ violates at exactly one step with certainty. Let total cost count violations. Compare their expected total costs and probabilities of any violation.

Review if needed: this section and weighted conditional expectations.

Show hint
For $A$, the count is $100$ or $0$. For $B$, it is always $1$.
Show worked solution
  1. Policy $A$ has expected count $0.01(100)+0.99(0)=1$. Policy $B$ also has expected count $1$.
  2. The probability of any violation is $0.01$ under $A$ and $1$ under $B$.
  3. The same expected cumulative cost therefore allows very different trajectory-level failure probabilities. An expectation-constrained MDP must specify which cost is constrained; it cannot silently be interpreted as a pathwise guarantee. The finite horizon and absence of discounting are part of this example.

3. Value Functions & Bellman Equations

Start here — Solve a fixed point and interpret its weights

The value $V^\pi(s)$ is an expected return from state $s$ while following policy $\pi$. The action-value $Q^\pi(s,a)$ fixes the first action and follows $\pi$ afterward. Splitting the first reward from the remaining return creates the Bellman equation; it is a consistency equation, not yet a learning algorithm.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review fixed points and linear equations.

How good is a policy from a given starting point? That is a number, and collecting these numbers over all states gives a function. The key discovery of dynamic programming is that this function satisfies a simple equation linking each state to its successors.

Definition — Value, action-value and advantage functions
For a stationary policy $\pi$ and $r_t=r(s_t,a_t)$: $$V^\pi(s)=\mathbb E_\pi\Big[\sum_{t\ge0}\gamma^tr_t\ \Big|\ s_0=s\Big],\qquad Q^\pi(s,a)=\mathbb E_\pi\Big[\sum_{t\ge0}\gamma^tr_t\ \Big|\ s_0=s,\ a_0=a\Big],\qquad A^\pi=Q^\pi-V^\pi .$$ $Q^\pi(s,a)$ takes the specified action $a$ first and follows $\pi$ afterwards; the advantage says how much better $a$ is than the policy's own average behaviour in $s$. The objective is $J(\pi)=\sum_s\mu(s)V^\pi(s)=\mathbb E_{s\sim\mu}V^\pi(s)$. Replacing $r$ by a cost $c$ gives $V_c^\pi,Q_c^\pi,A_c^\pi$ and $J_c(\pi)$. With $|r|\le B$, $|V^\pi|$, $|Q^\pi|$ and $|J(\pi)|$ are at most $B/(1-\gamma)$ and $|A^\pi|\le2B/(1-\gamma)$ (a difference of two such values); the cost versions need their own bound $|c|\le B_c$, with $B_c$ in place of $B$. A learned approximation of $V$ or $Q$ is called a critic (a cost critic approximates $Q_c$).
Key equation — Bellman expectation equations
$$V^\pi(s)=\sum_a\pi(a\mid s)\Big[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)\,V^\pi(s')\Big],$$ $$Q^\pi(s,a)=r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)\,V^\pi(s'),\qquad V^\pi(s)=\sum_a\pi(a\mid s)\,Q^\pi(s,a).$$ In particular $\sum_a\pi(a\mid s)A^\pi(s,a)=V^\pi(s)-V^\pi(s)=0$: an advantage has mean zero under its own policy.
Proof — split the return at the first step

Write $G_0=r_0+\gamma G_1$ with $G_1=\sum_{t\ge1}\gamma^{t-1}r_t$ (allowed: the series converges absolutely for bounded rewards). Conditioning on $s_0=s$, then on $a_0=a$ and $s_1=s'$ (tower rule):

$$\mathbb E[G_0\mid s_0=s]=\sum_a\pi(a\mid s)\Big[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)\,\mathbb E[G_1\mid s_0=s,a_0=a,s_1=s']\Big].$$

Given $s_1=s'$, the future $a_1,s_2,a_2,\dots$ is generated by the same rules as a trajectory started in $s'$: the transitions depend only on the current state and action (Markov property) and the policy does not depend on time (stationarity). So $\mathbb E[G_1\mid s_0=s,a_0=a,s_1=s']=V^\pi(s')$, which is the first equation. Stopping before the average over $a$ gives the equation for $Q^\pi$. $\blacksquare$

Worked example (uniform policy on the running example). With $\pi(a\mid s)=\pi(b\mid s)=\tfrac12$ the expected one-step rewards are $0.5$ at home and $1$ in the field, and from either state the next state is home or field with probability $\tfrac12$ each. Writing $m=\tfrac12(V_1+V_2)$, the Bellman equations read $V_1=0.5+0.9m$ and $V_2=1+0.9m$; averaging them gives $m=0.75+0.9m$, so $m=7.5$ and $V^\pi=(7.25,\,7.75)$. Then

$$\begin{aligned}Q^\pi(1,a)&=1+0.9\cdot7.25=7.525, & Q^\pi(1,b)&=0+0.9\cdot7.75=6.975, & A^\pi(1,\cdot)&=(+0.275,\,-0.275),\\ Q^\pi(2,a)&=0+0.9\cdot7.25=6.525, & Q^\pi(2,b)&=2+0.9\cdot7.75=8.975, & A^\pi(2,\cdot)&=(-1.225,\,+1.225).\end{aligned}$$

Each pair of advantages averages to zero. The same computation with the cost ($0.5$ expected cost per step in the field) gives $V_c^\pi=(2.25,\,2.75)$, $A_c^\pi(1,\cdot)=(-0.225,+0.225)$ and $A_c^\pi(2,\cdot)=(-0.725,+0.725)$: in the field, harvesting beats the average by $1.225$ in reward and loses $0.725$ in cost. This is the trade-off every constrained method negotiates.

Cost-to-go of a deterministic loop. For $x_{t+1}=F_\pi(x_t)$, $x_0=x$, and a stage cost $\ell(x)=r(x,\pi(x))\ge0$ with finite total $J(x)=\sum_t\ell(x_t)$, splitting at the first step gives $J(x)=\ell(x)+J(F_\pi(x))$, so $J(F_\pi(x))-J(x)=-\ell(x)\le0$: the undiscounted cost-to-go decreases along trajectories and is a Lyapunov-function candidate (Module 11). With a discount, $J_\gamma(x)=\ell(x)+\gamma J_\gamma(F_\pi(x))$ gives instead $J_\gamma(F_\pi(x))-J_\gamma(x)=-\ell(x)+(1-\gamma)J_\gamma(F_\pi(x))$, which can be positive. Example: stage costs $0,1,0,0,\dots$ along a trajectory give $J=(1,1,0,\dots)$, never increasing, but $J_\gamma=(\gamma,1,0,\dots)$, which increases at the first step.

Definition — Bellman operators, optimality and the Bellman residual
On value tables $V\in\mathbb R^{|\mathcal S|}$ and $Q\in\mathbb R^{|\mathcal S||\mathcal A|}$ define $$(\mathcal T^\pi V)(s)=\sum_a\pi(a\mid s)\Big[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)V(s')\Big],\qquad(\mathcal T^\pi Q)(s,a)=r(s,a)+\gamma\,\mathbb E_{s'\sim P(\cdot\mid s,a),\,a'\sim\pi(\cdot\mid s')}\big[Q(s',a')\big],$$ $$(\mathcal T^\ast V)(s)=\max_a\Big[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)V(s')\Big],\qquad(\mathcal T^\ast Q)(s,a)=r(s,a)+\gamma\,\mathbb E_{s'}\big[\max_{a'}Q(s',a')\big].$$ $V^\pi$ and $Q^\pi$ are fixed points of $\mathcal T^\pi$. The optimal value $V^\ast(s)=\sup_\pi V^\pi(s)$ (over all policies, even history-dependent ones) and $Q^\ast$ are fixed points of $\mathcal T^\ast$ (the Bellman optimality equations), and $V^\ast(s)=\max_aQ^\ast(s,a)$. For a finite discounted MDP, any deterministic stationary policy with $\pi(s)\in\operatorname*{arg\,max}_aQ^\ast(s,a)$ is optimal from every initial state simultaneously (Puterman, Ch. 6). The Bellman residual of a candidate $Q$ is $\mathcal T^\pi Q-Q$; it vanishes exactly at $Q^\pi$ (uniqueness: Section 4). For costs replace $r$ by $c$: $\mathcal T^\pi Q_c=c+\gamma\,\mathbb E[Q_c]$ at the successor pair.

In the running example $V^\ast=(18,20)$ with $Q^\ast(1,\cdot)=(17.2,\,18)$ and $Q^\ast(2,\cdot)=(16.2,\,20)$: harvesting everywhere is optimal for reward, at cost $J_c=9$. In learning the expectation in $\mathcal T^\pi$ is replaced by a sample: from a transition $(s,a,c,s')$ and $a'\sim\pi(\cdot\mid s')$ the target $y=c+\gamma Q(s',a')$ has conditional mean $(\mathcal T^\pi Q)(s,a)$. Fitting $Q$ to such targets by minimising the squared error $\mathbb E_{\mathcal D}\big[(Q(s,a)-y)^2\big]$ over a dataset $\mathcal D$, with $y$ held fixed during the fit (Section 6), moves $Q$ towards $\mathcal T^\pi Q$. In a table, where the fit can match the target at every pair, repeating it is iteration of the contraction $\mathcal T^\pi$ (Section 4, sampling noise averaged out) and approaches $Q^\pi$. With a function approximator the fit also projects onto the model class, which can destroy the contraction: the repeated fit can diverge even when $Q^\pi$ is representable (the "deadly triad" of Section 6). Module 9 writes this Bellman residual loss as $\mathbb E_{\mathcal D}\big[(Q_c-\mathcal T^\pi Q_c)^2\big]$. Indicator masks. Module 9 uses $(\mathcal T^\pi_PQ_r)(s,a)=r+\gamma\,\mathbb E\big[\mathbf 1(Q_c(s',a')\le l)\,Q_r(s',a')\big]$: the indicator is $1$ when the condition holds and $0$ otherwise, so successor pairs judged unsafe contribute no future reward. The bootstrap term is zeroed there.

The TD residual. For a value table $V$ and one observed transition, $\delta_t=r_t+\gamma V(s_{t+1})-V(s_t)$ is a one-sample Bellman residual: $\mathbb E[\delta_t\mid s_t=s]=(\mathcal T^\pi V)(s)-V(s)$. If $V=V^\pi$, then $\mathbb E[\delta_t\mid s_t,a_t]=Q^\pi(s_t,a_t)-V^\pi(s_t)=A^\pi(s_t,a_t)$: the TD residual is a noisy, unbiased advantage estimate. Advantage estimation (Section 5) and TD learning (Section 6) are built on it.

Discounted occupancy measures

Definition — Discounted occupancy measure and flow equations
$$\rho_\pi(s,a)=(1-\gamma)\sum_{t\ge0}\gamma^t\,\mathbb P_\pi(s_t=s,\ a_t=a),\qquad d^\pi(s)=\sum_a\rho_\pi(s,a)=(1-\gamma)\sum_{t\ge0}\gamma^t\,\mathbb P_\pi(s_t=s),$$ with $s_0\sim\mu$. The factor $1-\gamma$ makes $\rho_\pi$ a probability distribution on state–action pairs (discounted visit frequencies); without it one gets the unnormalised measure, total mass $1/(1-\gamma)$ (expected discounted number of visits). For stationary $\pi$, $\rho_\pi(s,a)=d^\pi(s)\,\pi(a\mid s)$. Three facts:
  1. Linear evaluation: $J(\pi)=\frac1{1-\gamma}\sum_{s,a}\rho_\pi(s,a)\,r(s,a)$, and likewise $J_c$.
  2. Flow equations: $\rho_\pi\ge0$ and for every $s$: $\ \sum_a\rho_\pi(s,a)=(1-\gamma)\mu(s)+\gamma\sum_{s',a'}P(s\mid s',a')\,\rho_\pi(s',a')$.
  3. Converse: every $\rho\ge0$ satisfying the flow equations is the occupancy measure of the stationary policy $\pi_\rho(a\mid s)=\rho(s,a)/\sum_b\rho(s,b)$ (arbitrary where the denominator is $0$).
So the set of occupancy measures is a convex polytope (linear equations plus nonnegativity), and a CMDP becomes a linear program over state–action frequencies satisfying probability-flow equations: maximise $\sum\rho r$ subject to the flow equations, $\rho\ge0$ and $\frac1{1-\gamma}\sum\rho c\le d$ (Module 8).
Proof sketch — facts 1–3

1. Exchange the sum and the expectation (Section 2): $J=\sum_t\gamma^t\,\mathbb E[r(s_t,a_t)]=\sum_t\gamma^t\sum_{s,a}\mathbb P(s_t=s,a_t=a)\,r(s,a)=\frac1{1-\gamma}\sum_{s,a}\rho_\pi(s,a)r(s,a)$. 2. The law of $s_{t+1}$ is $\mathbb P(s_{t+1}=s)=\sum_{s',a'}P(s\mid s',a')\,\mathbb P(s_t=s',a_t=a')$. Multiply by $(1-\gamma)\gamma^{t+1}$, sum over $t\ge0$ and add the $t=0$ term $(1-\gamma)\mu(s)$. 3. Insert $\rho(s',a')=\rho(s')\pi_\rho(a'\mid s')$ into the flow equation: the state marginal solves $\rho^{\top}(I-\gamma P_{\pi_\rho})=(1-\gamma)\mu^{\top}$, a linear system with a unique solution because $I-\gamma P$ is invertible (Section 4). By fact 2 the occupancy of $\pi_\rho$ solves the same system, so the two coincide. $\blacksquare$

Worked example. For the uniform policy, $d^\pi(1)=0.1\,(1+0.5\cdot0.9/0.1)=0.55$ (home at $t=0$, then home or field with probability $\tfrac12$ each) and $d^\pi(2)=0.45$, so $\rho_\pi=(0.275,0.275\,;\,0.225,0.225)$ for $(1,a),(1,b),(2,a),(2,b)$. Fact 1: $J=10\,(0.275\cdot1+0.225\cdot2)=7.25=V^\pi(1)$ and $J_c=10\cdot0.225=2.25$. Flow at home: $0.55=0.1+0.9\,(0.275+0.225)$.

Mixing policies versus mixing occupancies. "Always harvest" has $J=18$, $J_c=9$ and $\rho_H(1,b)=0.1$, $\rho_H(2,b)=0.9$; "always rest" has $J=10$, $J_c=0$, $\rho_R(1,a)=1$. With a budget $d=4.5$, flip one coin per episode between them: the occupancy is $\tfrac12\rho_H+\tfrac12\rho_R$, so by fact 1 the return and cost are the averages, $J=14$ and $J_c=4.5$, feasible and better than resting. By fact 3 the stationary policy $\pi_\rho(b\mid1)=0.05/0.55=1/11$, $\pi_\rho(b\mid2)=1$ achieves exactly the same pair (check: $V_1=\tfrac{10}{11}(1+0.9V_1)+\tfrac1{11}\,0.9\cdot20$ gives $V_1=14$). Averaging the action probabilities state by state instead gives $\pi(b\mid s)=\tfrac12$ everywhere, the uniform policy, with $J=7.25$ and $J_c=2.25$: neither average. The convexity used in Modules 2 and 8 is convexity of occupancy measures, not of action probabilities.

Support. $\operatorname{supp}\rho_\pi=\{(s,a):\rho_\pi(s,a)\gt0\}$ for $0\lt\gamma\lt1$ is the set of pairs the policy visits with positive probability from $\mu$ at some finite time (for $\gamma=0$, only the initial time contributes). Zero occupancy of an unsafe pair means only that it is not visited from $\mu$; it certifies nothing about what $\pi$ does at states outside the support, where a disturbance or a different initial state may put the system.

Where this is used
  • $V^\pi,Q^\pi,A^\pi$ and the cost versions: the notation of Module 1, the CMDP of Module 8, the performance-difference lemma of Module 9 (zero-mean advantages); $V_{\max}=R_{\max}/(1-\gamma)$ in Module 6.
  • Occupancy measures: "occupancy-measure LPs" in Module 1, convexity in Module 2, the LP view in Module 8, the support of $\rho_\pi$ in Module 7.
  • Bellman operators, residual losses and indicator masks: Module 9. The cost-to-go identity $J(x)=r(x,\pi(x))+J(F_\pi(x))$: Module 11.
Pitfall — normalisation conventions change constants
With the normalised $\rho_\pi$ (or $d^\pi$), $J=\frac1{1-\gamma}\sum\rho r$; with the unnormalised measure, $J=\sum\rho r$. Every bound that converts occupancy or policy differences into return differences changes by a factor $1-\gamma$ between the two conventions (Module 2 notes a paper printing $\epsilon/(1-\gamma)$ where its unnormalised values give $\epsilon/(1-\gamma)^2$). Check which convention a paper uses before comparing constants.

Practice — Solve a fixed point and interpret its weights

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S7 — Easy: A one-state Bellman equation

A policy stays in a single state, earns reward $2$ every step and uses discount $\gamma=0.5$. Solve its Bellman equation and verify the answer using a geometric series.

Review if needed: this section and fixed points and linear equations.

Show hint
The continuation value is the same unknown value again.
Show worked solution
  1. The Bellman equation is $V=2+0.5V$.
  2. Subtracting $0.5V$ gives $0.5V=2$, hence $V=4$.
  3. The return is also $2\sum_{t=0}^\infty0.5^t=2/(1-0.5)=4$. The fixed-point and return calculations describe the same quantity from local and whole-trajectory viewpoints.
Exercise E.S8 — Medium: Evaluate a two-state cycle

A deterministic policy alternates between states $A$ and $B$. Leaving $A$ earns reward $1$; leaving $B$ earns $0$. With $\gamma=0.5$, solve for $V(A),V(B)$. At $A$, an alternative action stays in $A$ with reward $0$. Find its advantage under the original policy.

Review if needed: this section and fixed points and linear equations.

Show hint
Use $V(A)=1+0.5V(B)$ and $V(B)=0.5V(A)$ before evaluating the alternative action.
Show worked solution
  1. Substitution gives $V(A)=1+0.25V(A)$, so $V(A)=4/3$ and $V(B)=2/3$.
  2. The alternative's action-value uses the original policy after its first step: $Q(A,\text{stay})=0+0.5V(A)=2/3$.
  3. Its advantage is $Q-V=2/3-4/3=-2/3$. This says that taking it once and then returning to the original policy loses $2/3$ in expected discounted return.
Exercise E.S9 — Hard: Occupancy turns a constraint into arithmetic

A one-state MDP has actions $a,b$, discount $0.8$, rewards $r(a)=2,r(b)=0$ and costs $c(a)=1,c(b)=0$. For a stationary policy choosing $a$ with probability $p$, compute its normalised occupancy, reward return and cost return. Maximise reward subject to cost return at most $2$.

Review if needed: this section and fixed points and linear equations.

Show hint
The normalised state occupancy is one. Divide occupancy-weighted immediate quantities by $1-\gamma$.
Show worked solution
  1. The normalised action occupancy is $\rho(a)=p$, $\rho(b)=1-p$, because $(1-\gamma)\sum_t\gamma^t=1$.
  2. The reward return is $J=2p/0.2=10p$, and the cost return is $J_c=p/0.2=5p$.
  3. The constraint gives $p\le0.4$. Since reward increases with $p$, the optimum is $p=0.4$, giving $J=4$ and $J_c=2$. This randomised policy satisfies an expected cost budget, not a guarantee that every action is cost-free.

4. Dynamic Programming: Value & Policy Iteration

Start here — Distinguish an iterate from its error

Value iteration repeatedly applies the optimal Bellman update to an estimate. In a one-state example, $V_{k+1}=2+0.5V_k$ gives $0,2,3,3.5,\dots$ and approaches $4$. The estimate, its update residual and its distance from the true value are separate quantities.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review geometric convergence.

When the model $(P,r)$ is known and the state and action sets are small enough to store a table with one entry per state (the tabular setting), the Bellman equations can be solved exactly. Everything rests on one property: the Bellman operators shrink distances.

Definition — Sup norm, contraction, monotone operator
For value tables $V\in\mathbb R^{n}$ ($n=|\mathcal S|$) let $\|V\|_\infty=\max_s|V(s)|$, the largest error over all states (Primer A). An operator $\mathcal T:\mathbb R^n\to\mathbb R^n$ is a $\gamma$-contraction if $\|\mathcal TV-\mathcal TW\|_\infty\le\gamma\|V-W\|_\infty$ for all $V,W$, with $\gamma\lt1$. It is monotone if $V\le W$ componentwise implies $\mathcal TV\le\mathcal TW$.
Theorem — Contraction mapping (Banach) theorem, finite-dimensional form
Assumption. $\mathcal T$ is a $\gamma$-contraction on $\mathbb R^n$ for some norm, $0\le\gamma\lt1$.
Statement. (i) $\mathcal T$ has exactly one fixed point $\bar V=\mathcal T\bar V$. (ii) For every start $V_0$ the iterates $V_{k+1}=\mathcal TV_k$ converge to $\bar V$ with $\|V_k-\bar V\|\le\gamma^k\|V_0-\bar V\|$. (iii) A computable stopping bound: $\|V_k-\bar V\|\le\frac{\gamma}{1-\gamma}\|V_k-V_{k-1}\|$.
In words. Iterating a contraction from anywhere converges geometrically to the unique solution, and the size of the last step tells how far you still are. Why the assumption matters. With factor $\gamma=1$ (a merely nonexpansive map) fixed points may be non-unique or absent, and iteration may not converge (Primer 0).
Proof — uniqueness, existence, rates

Uniqueness. If $\mathcal T\bar V=\bar V$ and $\mathcal T\bar W=\bar W$, then $\|\bar V-\bar W\|=\|\mathcal T\bar V-\mathcal T\bar W\|\le\gamma\|\bar V-\bar W\|$, which forces $\|\bar V-\bar W\|=0$. Existence. $\|V_{k+1}-V_k\|\le\gamma^k\|V_1-V_0\|$ by induction, so for $m\gt k$, $\|V_m-V_k\|\le\sum_{j=k}^{m-1}\gamma^j\|V_1-V_0\|\le\frac{\gamma^k}{1-\gamma}\|V_1-V_0\|\to0$: the sequence is Cauchy, hence converges in $\mathbb R^n$ to some $\bar V$. A contraction is continuous, so letting $k\to\infty$ in $V_{k+1}=\mathcal TV_k$ gives $\bar V=\mathcal T\bar V$. (ii) $\|V_k-\bar V\|=\|\mathcal TV_{k-1}-\mathcal T\bar V\|\le\gamma\|V_{k-1}-\bar V\|$; repeat. (iii) $\|V_k-\bar V\|\le\gamma\|V_{k-1}-\bar V\|\le\gamma\big(\|V_{k-1}-V_k\|+\|V_k-\bar V\|\big)$; solve for $\|V_k-\bar V\|$. $\blacksquare$

Lemma — Bellman operators are monotone $\gamma$-contractions in the sup norm
For every stationary $\pi$, $\mathcal T^\pi$ and $\mathcal T^\ast$ (on $V$ or on $Q$) are monotone and satisfy $\|\mathcal TV-\mathcal TW\|_\infty\le\gamma\|V-W\|_\infty$. The same holds when the maximum runs over state-dependent action sets $\mathcal A(s)\ne\emptyset$ (for example only the actions currently certified safe).
Proof. $(\mathcal T^\pi V-\mathcal T^\pi W)(s)=\gamma\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\big(V(s')-W(s')\big)$ is $\gamma$ times a weighted average (nonnegative weights summing to $1$) of numbers bounded by $\|V-W\|_\infty$ in absolute value. For $\mathcal T^\ast$ use $|\max_ag(a)-\max_ah(a)|\le\max_a|g(a)-h(a)|$: if $a_g$ maximises $g$, then $\max g-\max h\le g(a_g)-h(a_g)\le\max_a|g-h|$, and symmetrically. Monotonicity: nonnegative weights and $\max$ both preserve $\le$. $\blacksquare$

Consequences. $V^\pi$ and $V^\ast$ are the unique solutions of their Bellman equations, and iterating the operators from any table converges to them geometrically. Monotonicity adds a comparison principle: if $V\ge\mathcal T^\ast V$, then $V\ge\mathcal T^\ast V\ge(\mathcal T^\ast)^2V\ge\dots\to V^\ast$, so $V\ge V^\ast$. A "super-solution" of a Bellman inequality bounds the true value; Module 8 turns this into an LP, Module 11 into Lyapunov functions.

Algorithm 2: Value iteration with a stopping rule
  1. Input: $P,r$, discount $\gamma\in(0,1)$, tolerance $\epsilon\gt0$; any $V_0$ (e.g. $0$). // for $\gamma=0$ no loop is needed: $V^\ast(s)=\max_ar(s,a)$ after one backup, and any maximiser of $r(s,a)$ is optimal
  2. repeat: $V_{k+1}(s)=\max_{a\in\mathcal A(s)}\big[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)V_k(s')\big]$ for all $s$ // one Bellman backup of every state
  3. until $\|V_{k+1}-V_k\|_\infty\lt\epsilon(1-\gamma)/(2\gamma)$
  4. return the greedy policy $\pi(s)\in\operatorname*{arg\,max}_{a}\big[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)V_{k+1}(s')\big]$ // maximiser of the one-step action value; ties broken arbitrarily
Proof sketch — the returned greedy policy is $\epsilon$-optimal

Let $\pi$ be greedy for $V_{k+1}$, so $\mathcal T^\pi V_{k+1}=\mathcal T^\ast V_{k+1}$ and $\delta=\|V_{k+1}-V_k\|_\infty$. Then $\|V^\pi-V_{k+1}\|\le\|\mathcal T^\pi V^\pi-\mathcal T^\pi V_{k+1}\|+\|\mathcal T^\ast V_{k+1}-\mathcal T^\ast V_k\|\le\gamma\|V^\pi-V_{k+1}\|+\gamma\delta$, so $\|V^\pi-V_{k+1}\|\le\frac{\gamma\delta}{1-\gamma}$. Part (iii) of the theorem gives $\|V_{k+1}-V^\ast\|\le\frac{\gamma\delta}{1-\gamma}$. The triangle inequality yields $\|V^\pi-V^\ast\|_\infty\le\frac{2\gamma\delta}{1-\gamma}\lt\epsilon$ (Puterman, Thm. 6.3.1).

Worked example. Value iteration on the running example from $V_0=0$ ($\gamma=0.9$): $V_1=(\max\{1,0\},\max\{0,2\})=(1,2)$; $V_2=(\max\{1.9,1.8\},\max\{0.9,3.8\})=(1.9,3.8)$; $V_3=(\max\{2.71,3.42\},\max\{1.71,5.42\})=(3.42,5.42)$. The errors $\|V_k-V^\ast\|_\infty=18,\ 16.2,\ 14.58$ for $k=1,2,3$ are exactly $20\cdot0.9^k$, the contraction rate. At home the maximising action is "rest" in the backups that produce $V_1$ and $V_2$ and "go" from the backup producing $V_3$ on: the greedy policy for $V_k$ is optimal for every $k\ge2$, long before the values converge. Policies often converge much faster than values.

Other backups, same argument. Any backup built from averages, maxima, minima and constants, then multiplied by $\gamma$, is a $\gamma$-contraction, because each of those operations changes by at most the sup-norm change of its input. Example: the discounted safety Bellman equation $V(s)=(1-\gamma)\ell(s)+\gamma\min\{\ell(s),\max_aV(s^+_a)\}$ of Fisac et al. (safety margin $\ell$, successor $s^+_a$). Its undiscounted version $V(s)=\min\{\ell(s),\max_aV(s^+_a)\}$ is not a contraction: for one state with a self-loop and $\ell=1$, every $V\le1$ is a fixed point.

Fact — Stochastic matrices and the invertibility of $I-\gamma P$
For a stationary policy, $P_\pi(s,s')=\sum_a\pi(a\mid s)P(s'\mid s,a)$ is row-stochastic: row $s$ is the distribution of the next state, entries are $\ge0$ and $P_\pi\mathbf 1=\mathbf 1$. Distributions are row vectors propagated as $\mu^{\top}P_\pi^t$ (the law of $s_t$). Then:
  • $\|P_\pi\|_\infty=1$ (the $\infty$-norm of a matrix is its largest absolute row sum, Primer A), so every eigenvalue has $|\lambda|\le1$, and $\lambda=1$ with eigenvector $\mathbf 1$: the spectral radius is $1$.
  • For $0\le\gamma\lt1$, $I-\gamma P_\pi$ is invertible with $(I-\gamma P_\pi)^{-1}=\sum_{t\ge0}\gamma^tP_\pi^t$ (Neumann series; the terms have norm $\le\gamma^t$), a nonnegative matrix whose rows sum to $1/(1-\gamma)$.
  • Hence $V^\pi=(I-\gamma P_\pi)^{-1}r_\pi$ with $r_\pi(s)=\sum_a\pi(a\mid s)r(s,a)$ (exact policy evaluation is one linear solve), and the flow equation $d^{\top}(I-\gamma P_\pi)=(1-\gamma)\mu^{\top}$ has exactly one solution. Discounting is what makes the flow solution unique.
Algorithm 3: Policy iteration
  1. Start with any deterministic stationary policy $\pi_0$.
  2. for $k=0,1,2,\dots$:
  3. evaluate: $V^{\pi_k}=(I-\gamma P_{\pi_k})^{-1}r_{\pi_k}$ and $Q^{\pi_k}(s,a)=r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)V^{\pi_k}(s')$
  4. improve: $\pi_{k+1}(s)\in\operatorname*{arg\,max}_aQ^{\pi_k}(s,a)$ for every $s$, keeping $\pi_k(s)$ when it is among the maximisers
  5. stop when $\pi_{k+1}=\pi_k$.
Theorem — Policy improvement
If $\pi'$ is greedy with respect to $Q^\pi$, then $V^{\pi'}(s)\ge V^\pi(s)$ for every state $s$, and if $V^{\pi'}=V^\pi$ then both are optimal. For finite MDPs policy iteration therefore stops after finitely many steps at an optimal policy.
Proof. Greedy means $\mathcal T^{\pi'}V^\pi=\mathcal T^\ast V^\pi\ge\mathcal T^\pi V^\pi=V^\pi$. Applying the monotone $\mathcal T^{\pi'}$ repeatedly, $V^\pi\le\mathcal T^{\pi'}V^\pi\le(\mathcal T^{\pi'})^2V^\pi\le\dots\to V^{\pi'}$. If $V^{\pi'}=V^\pi$, then $V^\pi=\mathcal T^{\pi'}V^{\pi'}=\mathcal T^{\pi'}V^\pi=\mathcal T^\ast V^\pi$, so $V^\pi=V^\ast$. There are finitely many deterministic policies and none repeats before the stop. $\blacksquare$

Worked example. Start with $\pi_0$ = rest everywhere: $V^{\pi_0}=(10,9)$, $Q^{\pi_0}(1,\cdot)=(10,\,8.1)$, $Q^{\pi_0}(2,\cdot)=(9,\,10.1)$, so $\pi_1$ rests at home and harvests in the field, $V^{\pi_1}=(10,20)$. Then $Q^{\pi_1}(1,\cdot)=(10,18)$ gives $\pi_2$ = harvest everywhere, $V^{\pi_2}=(18,20)=V^\ast$, and $\pi_3=\pi_2$. Note $J(\pi_1)=J(\pi_0)=10$ for the start distribution $\mu=(1,0)$ although $\pi_1$ is strictly better in the field and $\pi_0$ is not optimal: equal returns for one initial distribution do not mean equal (or optimal) values at every state. The improvement theorem is statewise.

Undiscounted problems: transient chains and weighted norms

Total-cost problems without discount (Module 11's transient CMDP) need a different reason for uniqueness: termination. Let the states be split into transient states and an absorbing terminal state, and let $P$ now be the transition matrix among transient states only. Its rows sum to at most $1$ (the missing mass is the probability of terminating): $P$ is substochastic. Assume termination happens with probability $1$ from every state. Then $P^t\to0$, and the fundamental matrix

$$N=(I-P)^{-1}=\sum_{t\ge0}P^t,\qquad N(s,s')=\mathbb E\big[\text{number of visits to }s'\mid s_0=s\big],$$

exists; the total cost is $V=Nc$ and the expected time to termination is $w=N\mathbf 1$. The sup-norm argument fails, because a row of $P$ may sum to $1$ (a state that cannot terminate in one step). A weighted norm repairs it.

Lemma — A transient chain contracts in the weighted max-norm
Assumptions. $P\ge0$ is substochastic on the transient states, $N=(I-P)^{-1}$ exists (termination with probability $1$), and $w=N\mathbf 1$. Define $\|V\|_w=\max_s|V(s)|/w(s)$.
Statement. $\|PV\|_w\le\beta\|V\|_w$ with $\beta=1-1/\max_sw(s)\lt1$. Hence the undiscounted evaluation operator $\mathcal T^\pi V=c_\pi+P_\pi V$ is a $\beta$-contraction in $\|\cdot\|_w$, and its fixed point $V_c^\pi=Nc_\pi$ is unique.
Proof. From $N=I+PN$, $w=\mathbf 1+Pw$, so $w\ge\mathbf 1$ and $(Pw)(s)=w(s)-1\le\beta\,w(s)$. Then $|(PV)(s)|\le\sum_{s'}P(s,s')\,w(s')\,\|V\|_w=(Pw)(s)\|V\|_w\le\beta\,w(s)\|V\|_w$. $\blacksquare$
Discounting is a special case. Discounting by $\gamma$ is the same as terminating with probability $1-\gamma$ at every step: the substochastic matrix is $\gamma P$, $w=\mathbf 1/(1-\gamma)$ is constant, the weighted norm is the sup norm up to a factor, and $\beta=\gamma$.

Example. Two transient states: from state 1 stay with probability $0.5$ or move to state 2; from state 2 always terminate. Then $P=\begin{bmatrix}0.5&0.5\\0&0\end{bmatrix}$, $\|P\|_\infty=1$ (no sup-norm contraction), $N=\begin{bmatrix}2&1\\0&1\end{bmatrix}$ (from state 1: two visits to itself, one to state 2 on average), $w=(3,1)$ and $\beta=1-1/3=2/3$; indeed $Pw=(2,0)=w-\mathbf 1$. With unit costs, $V=N\mathbf 1=(3,1)$, the expected numbers of steps. Two related terms appear with average-cost criteria (Module 8): a recurrent class is a set of states that the chain never leaves once inside and in which every state is revisited with probability $1$; an MDP is unichain if every deterministic stationary policy induces a chain with exactly one recurrent class (plus possibly transient states), which makes the long-run average reward of a stationary policy independent of the start state.

From dynamic programming to learning. Dynamic programming needs the model $(P,r)$ and a table over all states and actions. Discretising $[0,1]^d$ with $m$ points per axis gives $m^d$ states (Section 1), so tables stop at a few dimensions. Reinforcement learning replaces the expectations by sampled transitions (Section 6), the tables by function approximators such as networks (Section 7), and the exact greedy step by a small gradient step on the policy (Section 5).

Where this is used
  • Contraction, uniqueness and convergence of Bellman backups: the discounted safety backup in Module 7 and why its undiscounted version "is not a contraction" in Module 10; value iteration with constrained action sets and greedy actions in Module 7.
  • Stochastic matrices, $(I-\gamma P_w)^{-1}$ and "$\mathcal T_\lambda$ is monotone and a $\gamma$-contraction": Module 8. Greedy improvement and the policy improvement theorem: Module 9.
  • Transient undiscounted CMDPs, the operators $T_{\pi,h}$, weighted contractions, super-solutions and $(I-P_{\pi_B})^{-1}$: Module 11.
Pitfall — contraction needs a discount or guaranteed termination
The factor $\gamma\lt1$ (or a probability-one termination with a known weight $w$) carries the whole theory. Without it, as in the undiscounted safety equation or an average-reward problem, fixed points can be non-unique and iteration can stall; each such problem needs its own argument (unichain assumptions, discounted approximations, the weighted norms above).

Practice — Distinguish an iterate from its error

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S10 — Easy: Three value-iteration backups

A one-state MDP has two self-loop actions with rewards $1$ and $2$, and $\gamma=0.5$. Start value iteration at $V_0=0$. Compute $V_1,V_2,V_3$ and the optimal value.

Review if needed: this section and geometric convergence.

Show hint
The larger immediate reward always wins, so each backup is $V_{k+1}=2+0.5V_k$.
Show worked solution
  1. The first backup is $V_1=2$.
  2. The next two are $V_2=2+0.5(2)=3$ and $V_3=2+0.5(3)=3.5$.
  3. The fixed point satisfies $V_*=2+0.5V_*$, giving $V_*=4$. The errors $4,2,1,0.5$ halve at each backup, exactly matching the contraction factor.
Exercise E.S11 — Medium: Turn a Bellman residual into an error bound

For a discounted finite MDP with $\gamma=0.9$, a candidate vector $V$ has Bellman residual $\|\mathcal T^*V-V\|_\infty=0.03$. Bound $\|V-V^*\|_\infty$. What residual would guarantee value error at most $0.1$?

Review if needed: this section and geometric convergence.

Show hint
Insert and subtract $\mathcal T^*V$, then use contraction and $\mathcal T^*V^*=V^*$.
Show worked solution
  1. Let $e=\|V-V^*\|_\infty$. The triangle inequality and contraction give $e\le0.03+0.9e$.
  2. Thus $0.1e\le0.03$, so $e\le0.3$. A small residual is amplified by $1/(1-\gamma)$.
  3. For error at most $0.1$, require residual at most $(1-0.9)(0.1)=0.01$. This certifies the value vector's error; a greedy policy's performance needs its own bound.
Exercise E.S12 — Hard: Undiscounted does not automatically mean divergent

Compare two undiscounted models with one nonterminal state and reward $1$ per visit. In model $A$ the state self-loops forever. In model $B$ each visit is followed by termination with probability $1/2$, otherwise another visit. Write their Bellman equations and value-iteration behaviour.

Review if needed: this section and geometric convergence.

Show hint
A terminal state's continuation value is zero. The surviving probability can supply a contraction even without discounting.
Show worked solution
  1. Model $A$ gives $V=1+V$, which has no finite solution. Starting at zero, value iteration gives $V_k=k$, diverging to infinity.
  2. Model $B$ gives $V=1+0.5V+0.5(0)$, so $V=2$. Its backups are a contraction of factor $0.5$ on the nonterminal value.
  3. The difference is transience: model $B$ has a finite expected number of visits, model $A$ does not. Setting $\gamma=1$ requires checking such structure; the discounted contraction theorem cannot simply be reused unchanged.

5. Policy Gradients, Advantages & Trust Regions

Start here — Differentiate probabilities and respect their geometry

For a discrete action, policy gradients differentiate its probability with respect to policy parameters, not the action label. If the probability is $p=\sigma(\theta)$, then $dp/d\theta=p(1-p)$. The score and baseline exercises make the expectation behind the general theorem explicit.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review the chain rule.

Dynamic programming needs a model and a table. Policy-gradient methods need neither: they give the policy trainable parameters $\theta$ (for example the weights of a network) and climb $J(\theta):=J(\pi_\theta)$ by gradient ascent (Primer B), $\theta_{k+1}=\theta_k+\eta\,\hat g_k$. The exact gradient $\nabla J(\theta_k)$ is unknown; $\hat g_k$ is a sampled estimate computed from rollouts, random, and unbiased when $\mathbb E\,\hat g_k=\nabla J(\theta_k)$. The basic ingredient is the score $\nabla_\theta\log\pi_\theta(a\mid s)$: for the Bernoulli policy $\pi_\theta(1)=\sigma(\theta)$, with the logistic function $\sigma(\theta)=1/(1+e^{-\theta})$ and its derivative $\sigma'=\sigma(1-\sigma)$ (Section 7), it is $1-\sigma(\theta)$ for action $1$ (because $\partial_\theta\log\sigma=\sigma'/\sigma$) and $-\sigma(\theta)$ for action $0$ (because $\partial_\theta\log(1-\sigma)=-\sigma'/(1-\sigma)$); for a Gaussian policy $a\sim\mathcal N(m_\theta(s),\sigma^2)$ with a fixed standard deviation $\sigma$ (a number here, not the logistic function) and a network mean it is $(a-m_\theta(s))\nabla_\theta m_\theta(s)/\sigma^2$.

Assumptions. Finite MDP with nonempty action sets, $|r|\le B$, $0\le\gamma\lt1$, and dynamics, rewards and initial distribution independent of $\theta$; the policies $\pi_\theta(a\mid s)$ are continuously differentiable and strictly positive in a neighbourhood of the parameter under consideration.
Statement. $$\nabla_\theta J(\theta)=\mathbb E_{\tau\sim\pi_\theta}\Big[\sum_{t\ge0}\gamma^t\,Q^{\pi_\theta}(s_t,a_t)\,\nabla_\theta\log\pi_\theta(a_t\mid s_t)\Big]=\frac1{1-\gamma}\,\mathbb E_{s\sim d^{\pi_\theta},\,a\sim\pi_\theta}\big[A^{\pi_\theta}(s,a)\,\nabla_\theta\log\pi_\theta(a\mid s)\big].$$ In words. Raise the log-probability of each action in proportion to how much better than average it is, weighted by how often (with discount) its state is visited. The dynamics never appear: the gradient can be estimated from rollouts alone.
Why each assumption matters. Bounded rewards and $\gamma\lt1$ allow exchanging derivatives, expectations and infinite sums. Differentiability of $\pi_\theta$ is what the score needs: a deterministic policy has no score (use the deterministic policy gradient of Section 6, or randomise the parameters instead of the actions, below).

Worked example (one state, two actions). Let $\pi_\theta(1)=\sigma(\theta)=p$, with reward $1$ for action $1$ and $0$ for action $0$, and one-step episodes. Then $J=p$ and $\nabla J=p(1-p)$. The REINFORCE sample $g=r\,\partial_\theta\log\pi_\theta(a)$ equals $1-p$ with probability $p$ and $0$ otherwise, so $\mathbb Eg=p(1-p)$: unbiased. At $\theta=0$ ($p=\tfrac12$), $g\in\{0.5,0\}$ has variance $0.0625$; with the baseline $b=\tfrac12$, $g=(r-b)\,\partial_\theta\log\pi_\theta(a)$ equals $0.25$ for both actions, variance $0$. At $p=0.8$, no baseline gives variance $0.0064$ while the "natural" baseline $b=\bar r=0.8$ gives $0.0576$, nine times worse. An action-independent baseline preserves the score-gradient expectation, but only a well-chosen one reduces variance (Exercise E.4 finds the best one).

Score-function versus pathwise gradients. There are two ways to differentiate $\mathbb E_{x\sim p_\theta}[h(x)]$. The score-function (likelihood-ratio) estimator $\mathbb E[h(x)\nabla_\theta\log p_\theta(x)]$ needs samples and log-probabilities only, never $\nabla h$: it works when $h$ is a black box such as the real environment.

The pathwise (reparametrisation) estimator writes $x=g_\theta(\varepsilon)$ with noise $\varepsilon$ independent of $\theta$ and differentiates through, $\mathbb E[\nabla h(g_\theta(\varepsilon))\,\nabla_\theta g_\theta(\varepsilon)]$; it needs a differentiable $h$ (for example a learned dynamics model) and usually has lower variance.

Example. $x\sim\mathcal N(\theta,1)$, $h(x)=x^2$, $\mathbb Eh=\theta^2+1$: the score estimator averages $x^2(x-\theta)$, the pathwise one $2(\theta+\varepsilon)$; both have mean $2\theta$.

In code, one minimises the negative surrogate $-\sum_t\gamma^t\log\pi_\theta(a_t\mid s_t)\,\mathrm{sg}(\hat A_t)$ (its gradient is $-\hat g$ for one rollout of Step 6 above), where the stop-gradient $\mathrm{sg}(x)$ returns the value $x$ but has derivative $0$, so the advantage acts as a fixed weight; many implementations drop the factor $\gamma^t$, which generally gives a biased estimator with a different variance.

An entropy bonus $\eta\,\mathcal H[\pi_\theta(\cdot\mid s_t)]$, $\mathcal H[p]=-\sum_ap_a\log p_a$, is added to the maximised objective to keep the policy exploring, so it enters the minimised loss with a minus sign: $-\sum_t\gamma^t\big(\log\pi_\theta(a_t\mid s_t)\,\mathrm{sg}(\hat A_t)+\eta\,\mathcal H[\pi_\theta(\cdot\mid s_t)]\big)$.

Action-based versus parameter-based exploration. Action-based methods sample a new action from $\pi_\theta(\cdot\mid s_t)$ at every step. Parameter-based methods sample the parameters once per rollout, $\theta\sim\nu_\omega$ (for example $\mathcal N(\omega,\sigma^2I)$), run the deterministic policy $\pi_\theta$, and use the score of $\nu_\omega$: $\nabla_\omega\mathbb E[R]=\mathbb E_{\theta\sim\nu_\omega}\big[R(\theta)\nabla_\omega\log\nu_\omega(\theta)\big]$. Such methods, like random search with the finite-difference estimate $\hat g=\frac{\hat J(\theta+\sigma u)-\hat J(\theta-\sigma u)}{2\sigma}\,u$ along a random direction $u$, use only returns: a zeroth-order oracle (values, no gradients).

Lemma — Performance difference (Kakade & Langford, ICML 2002)
For any two stationary policies $\pi,\pi'$ on the same MDP and initial distribution $\mu$, $$J(\pi')-J(\pi)=\frac1{1-\gamma}\,\mathbb E_{s\sim d^{\pi'},\,a\sim\pi'}\big[A^\pi(s,a)\big].$$ The new policy is scored with the old policy's advantages, but on the new policy's state distribution. Corollary (policy improvement). If $\sum_a\pi'(a\mid s)A^\pi(s,a)\ge0$ in every state, then $J(\pi')\ge J(\pi)$ for every $\mu$.
Proof — a telescoping sum

Along any trajectory, $\sum_{t\ge0}\gamma^t\big(\gamma V^\pi(s_{t+1})-V^\pi(s_t)\big)=-V^\pi(s_0)$ (the terms telescope and $\gamma^TV^\pi(s_T)\to0$ because $V^\pi$ is bounded). Hence $\sum_t\gamma^tr_t=V^\pi(s_0)+\sum_t\gamma^t\big(r_t+\gamma V^\pi(s_{t+1})-V^\pi(s_t)\big)$. Take expectations over $\tau\sim\pi'$. Both policies face the same transition law, so $\mathbb E\big[r_t+\gamma V^\pi(s_{t+1})\mid s_t,a_t\big]=Q^\pi(s_t,a_t)$ and each bracket has conditional mean $A^\pi(s_t,a_t)$. So $J(\pi')=J(\pi)+\sum_t\gamma^t\,\mathbb E_{\pi'}[A^\pi(s_t,a_t)]$, and $\sum_t\gamma^t\mathbb P_{\pi'}(s_t=s)=d^{\pi'}(s)/(1-\gamma)$. $\blacksquare$

Example. From the uniform policy $\pi$ to "always harvest" $\pi'$ in the running example: $d^{\pi'}=(0.1,0.9)$ and $\pi'$ plays $b$, so $J(\pi')-J(\pi)=10\,\big(0.1\cdot(-0.275)+0.9\cdot1.225\big)=10.75=18-7.25$, exactly. Replacing the unknown $d^{\pi'}$ by the old $d^\pi$ gives the surrogate

$$L_\pi(\pi')=J(\pi)+\frac1{1-\gamma}\sum_sd^{\pi}(s)\sum_a\pi'(a\mid s)\,A^\pi(s,a)=J(\pi)+\frac1{1-\gamma}\,\mathbb E_{s\sim d^{\pi},\,a\sim\pi}\big[\varrho(s,a)\,A^\pi(s,a)\big],\qquad\varrho(s,a)=\frac{\pi'(a\mid s)}{\pi(a\mid s)}\ \ \text{(importance ratio)},$$

where the second form needs the support condition $\pi(a\mid s)=0\Rightarrow\pi'(a\mid s)=0$ at every state with $d^\pi(s)\gt0$ (otherwise the ratio is undefined, and samples of $\pi$ never show the new actions). Under it the surrogate is computable from data of the old policy, exact at $\pi'=\pi$ and with the same gradient there. Its accuracy degrades as the policy moves: here $L_\pi(\pi')=7.25+10\,(0.55\cdot(-0.275)+0.45\cdot1.225)=11.25$ instead of $18$, and the cost surrogate predicts $2.25+10\,(0.55\cdot0.225+0.45\cdot0.725)=6.75$ instead of the true $J_c(\pi')=9$. With a budget $d=7$, the surrogate says "feasible" for a policy that violates the constraint. The error comes entirely from the changed state distribution, $(0.55,0.45)\to(0.1,0.9)$.

Definition — Trust-region update (TRPO, Schulman et al., ICML 2015)
$$\theta_{k+1}=\operatorname*{arg\,max}_\theta\ L_{\pi_k}(\pi_\theta)\quad\text{s.t.}\quad\bar D_{\rm KL}(\theta):=\mathbb E_{s\sim d^{\pi_k}}\Big[D_{\rm KL}\big(\pi_k(\cdot\mid s)\,\big\|\,\pi_\theta(\cdot\mid s)\big)\Big]\le\delta,$$ with $D_{\rm KL}(p\|q)=\sum_ap_a\log(p_a/q_a)\ge0$, zero only for $p=q$, and not symmetric (Primer C). The theory behind it is a minorise–maximise (MM) step: TRPO's Theorem 1 gives $J(\pi')\ge L_\pi(\pi')-C\max_sD_{\rm KL}(\pi(\cdot\mid s)\|\pi'(\cdot\mid s))$ with $C=4\gamma\max_{s,a}|A^\pi(s,a)|/(1-\gamma)^2$. The right-hand side $M(\pi')$ touches $J$ at $\pi'=\pi$ and lies below it everywhere, so maximising $M$ gives $J(\pi_{k+1})\ge M(\pi_{k+1})\ge M(\pi_k)=J(\pi_k)$: monotone improvement. Practical TRPO replaces the penalty by the average-KL constraint with a tuned $\delta$, so the guarantee becomes approximate. A constraint on a surrogate cost is likewise not the true constraint $J_c\le d$; bounds of the same kind quantify the gap (Module 1, Module 9).
Definition — Fisher information and the natural gradient
$$F(\theta)=\mathbb E_{s\sim d^{\pi_\theta},\,a\sim\pi_\theta}\big[\nabla_\theta\log\pi_\theta(a\mid s)\,\nabla_\theta\log\pi_\theta(a\mid s)^{\top}\big]\succeq0,$$ the expected outer product of scores (positive semidefinite as an average of outer products). For strictly positive, three times continuously differentiable policies, it is the Hessian of the mean KL at the current parameters (with the old state weights held fixed): $\bar D_{\rm KL}(\theta+\Delta)=\tfrac12\Delta^{\top}F(\theta)\Delta+O(\|\Delta\|^3)$, since the KL and its gradient vanish at $\Delta=0$. Maximising the linearised gain $g^{\top}\Delta$ ($g=\nabla J$) over the KL ball $\tfrac12\Delta^{\top}F\Delta\le\delta$ gives, for $F\succ0$, $g\ne0$ and $\delta\gt0$ (when $g=0$, every feasible step is optimal; Lagrange condition $g=\lambda F\Delta$ with the constraint active), $$\Delta^\ast=\sqrt{\frac{2\delta}{g^{\top}F^{-1}g}}\;F^{-1}g .$$ $F^{-1}g$ is the natural gradient (Kakade, NIPS 2001): steepest ascent when distance is measured by how much the action distributions change, not by how much the parameters change.

Example. For the Bernoulli policy, $F=p(1-p)$ and $g=p(1-p)$, so $F^{-1}g=1$ for every $\theta$. At $\theta=-4$ ($p=0.018$) the ordinary gradient is only $0.0177$ (a plateau), while the natural step with $\delta=0.01$ is $\sqrt{2\delta/F}=1.06$ in $\theta$: a fixed change in distribution, however flat the parametrisation. Softmax policies. For tabular softmax $\pi_\theta(a\mid s)\propto e^{\theta_{s,a}}$ one checks $F\,w=\nabla J$ for $w=A^{\pi_\theta}/(1-\gamma)$, so a natural-gradient step of size $\eta$ is the probability-space update $\pi_{k+1}(a\mid s)\propto\pi_k(a\mid s)\exp\big(\eta A^{\pi_k}(s,a)/(1-\gamma)\big)$: multiplicative weights on advantages, state by state (Agarwal, Kakade, Lee & Mahajan, JMLR 2021). Conjugate gradients. $F$ has $n^2$ entries for $n$ parameters and is never formed: TRPO and CPO solve $Fx=g$ by the conjugate-gradient method, which needs only products $v\mapsto Fv$ (two backward passes each) and drives the residual $g-Fx$ down in a handful of iterations.

Definition — PPO clipping, and its pessimistic cost version
With the ratio $\varrho_\theta=\pi_\theta(a\mid s)/\pi_k(a\mid s)$, advantage estimates $\hat A,\hat A_c$ from data of $\pi_k$, and $\mathrm{clip}(z,l,u)=\min\{\max\{z,l\},u\}$ (the projection of $z$ onto $[l,u]$), PPO (Schulman et al., 2017) maximises $$L^{\rm CLIP}(\theta)=\mathbb E\Big[\min\big(\varrho_\theta\hat A,\ \mathrm{clip}(\varrho_\theta,1-\epsilon,1+\epsilon)\,\hat A\big)\Big]$$ with several epochs of minibatch gradient steps. Safe variants keep a clipped cost surrogate small, $\mathbb E\big[\max\big(\varrho_\theta\hat A_c,\ \mathrm{clip}(\varrho_\theta,1-\epsilon,1+\epsilon)\,\hat A_c\big)\big]$. The $\min$ makes the reward surrogate a lower bound of the unclipped one and the $\max$ makes the cost surrogate an upper bound: both are conservative, in opposite directions, because reward is maximised and cost is bounded from above.

Example ($\epsilon=0.2$). Reward, $\hat A=2$, $\varrho=1.5$: $\min(3,\,2.4)=2.4$, the gain from raising the action's probability is capped. $\hat A=-2$, $\varrho=1.5$: $\min(-3,-2.4)=-3$, a harmful move is charged in full. Cost, $\hat A_c=2$, $\varrho=0.5$: $\max(1,\,1.6)=1.6$, the credit for avoiding a costly action is capped; $\hat A_c=-2$, $\varrho=1.5$: $\max(-3,-2.4)=-2.4$, capped again. Clipping removes the incentive to move the ratio outside $[1-\epsilon,1+\epsilon]$, not the possibility; implementations also monitor the KL.

Definition — Generalised advantage estimation (GAE, Schulman et al., ICLR 2016)
With a critic $V\approx V^{\pi}$ and TD residuals $\delta_t=r_t+\gamma V(s_{t+1})-V(s_t)$ (with $V=0$ at a terminal state), $$\hat A_t=\sum_{l\ge0}(\gamma\lambda)^l\,\delta_{t+l},\qquad\text{computed backwards as}\quad\hat A_t=\delta_t+\gamma\lambda\,\hat A_{t+1},\qquad\lambda\in[0,1].$$ $\lambda=0$ gives $\hat A_t=\delta_t$ (low variance, biased when $V$ is wrong); $\lambda=1$ gives $\sum_l\gamma^lr_{t+l}-V(s_t)$, the Monte-Carlo return minus a baseline: high variance, but an unbiased policy-gradient weight for any critic $V$ (the baseline depends on the state only; Step 5 of the derivation above), although it estimates $A^\pi$ itself without bias only when $V=V^\pi$. When a batch ends before the episode does, the sum is truncated and the last residual bootstraps with $V$. Cost advantages $\hat A_c$ use $c$ and a cost critic $V_c$, often with their own $\lambda$.

Example. Rewards $1,0,2$, then termination; $V=(2,\,1.5,\,1)$; $\gamma=0.9$. Residuals: $\delta_0=1+1.35-2=0.35$, $\delta_1=0+0.9-1.5=-0.6$, $\delta_2=2-1=1$. With $\lambda=0.8$ ($\gamma\lambda=0.72$): $\hat A_2=1$, $\hat A_1=-0.6+0.72=0.12$, $\hat A_0=0.35+0.72\cdot0.12=0.436$. With $\lambda=1$: $\hat A_0=0.35-0.54+0.81=0.62=(1+0+0.81\cdot2)-2$; with $\lambda=0$: $\hat A_0=0.35$.

Why step sizes matter for safety
A constraint $J_c(\pi_{k+1})\le d$ is a statement about states the next policy will visit, but every sample comes from $\pi_k$. The surrogate is accurate only for small policy changes (in the example it predicted cost $6.75$ where the truth was $9$). A KL radius $\delta$ bounds the error by $\gamma\epsilon_c\sqrt{2\delta}/(1-\gamma)^2$, where $\epsilon_c=\max_s\big|\sum_a\pi'(a\mid s)A_c^\pi(s,a)\big|$ (the CPO bound quoted in Module 1), and step-size control (trust region, line search, early stopping on the KL) is a safety mechanism, not an optimisation detail. Lagrangian methods take "a few policy-gradient steps on $J_r-\lambda J_c$" per multiplier update for the same reason.
Where this is used
  • Trust regions and KL-limited updates: Module 1; policy-gradient steps inside dual ascent: Module 2; "a parametrised policy and a gradient estimator": Module 8; natural policy gradient steps and multiplicative weights: Module 8.
  • The performance-difference lemma, surrogates and trust-region bounds: Module 9; Fisher matrix, conjugate gradients and GAE in CPO: Module 9; clipped reward and cost surrogates: Module 9; entropy bonuses, REINFORCE weights and stop-gradients: Module 9.
  • Parameter-based exploration: Module 8; "a reinforcement-learning agent hands you a network" (the introduction before Module 14's feedback setup) and zeroth-order oracles in Module 14's synthesis section.
Pitfall — an unbiased gradient is not a safe step
$\mathbb E\,\hat g=\nabla J$ says nothing about a single update: with few rollouts $\hat g$ can point anywhere, and even the exact gradient only describes an infinitesimal step. Improvement and constraint satisfaction after a finite step need a trust region or a line search, and hold only up to estimation error.

Practice — Differentiate probabilities and respect their geometry

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S13 — Easy: A policy parameter is not an action

A one-step bandit chooses action $a$ with probability $p=\sigma(\theta)=1/(1+e^{-\theta})$ and action $b$ otherwise. Rewards are $4$ for $a$ and $0$ for $b$. At $p=1/4$, compute $J$, $dJ/d\theta$ and the log-probability scores for both actions.

Review if needed: this section and the chain rule.

Show hint
Use $dp/d\theta=p(1-p)$. The score is the derivative of the logarithm of the chosen action's probability.
Show worked solution
  1. $J=4p=1$, and $dJ/d\theta=4p(1-p)=4(1/4)(3/4)=3/4$.
  2. For action $a$, $d\log p/d\theta=(dp/d\theta)/p=1-p=3/4$.
  3. For action $b$, $d\log(1-p)/d\theta=-p=-1/4$. Their probability-weighted mean is $(1/4)(3/4)+(3/4)(-1/4)=0$, the score identity used to subtract baselines.
Exercise E.S14 — Medium: Subtract a value baseline without changing the mean gradient

In the previous bandit, use baseline $V=1$. Compute advantages and evaluate $\mathbb E[A(a)\,d\log\pi(a)/d\theta]$ explicitly. Compare with the direct derivative.

Review if needed: this section and the chain rule.

Show hint
The advantages are reward minus the same state baseline, so $A(a)=3$ and $A(b)=-1$.
Show worked solution
  1. Subtract the value from each action-value: $A(a)=4-1=3$ and $A(b)=0-1=-1$.
  2. The expected advantage is $(1/4)(3)+(3/4)(-1)=0$. The gradient average is $(1/4)(3)(3/4)+(3/4)(-1)(-1/4)=9/16+3/16=3/4$.
  3. This matches $dJ/d\theta$. Subtracting the baseline changes sample weights but not their expected gradient because the expected score is zero. An action-dependent baseline would need a separate justification.
Exercise E.S15 — Hard: Compute a natural-gradient trust-region step

Let the local reward gradient be $g=(2,1)$ and the positive definite Fisher matrix be $F=\operatorname{diag}(4,1)$. Maximise $g^\top\Delta$ subject to the quadratic KL approximation $\tfrac12\Delta^\top F\Delta\le0.05$. Find the step and its predicted improvement.

Review if needed: this section and the chain rule.

Show hint
The direction is $F^{-1}g$, and its scale makes the constraint active.
Show worked solution
  1. $F^{-1}g=(1/2,1)$ and $g^\top F^{-1}g=2$.
  2. Write $\Delta=cF^{-1}g$. The active constraint becomes $\tfrac12c^2(2)=0.05$, so $c=\sqrt{0.05}$ and $\Delta\approx(0.111803,0.223607)$.
  3. The predicted improvement is $g^\top\Delta=c(2)\approx0.447214$. These are a linear objective and a quadratic approximation to KL; the actual nonlinear policy change may need a line search and measured KL check.

6. Q-Learning, Actor-Critic, Entropy Regularisation, Model-Based & Offline RL

Start here — Understand the update and its data assumptions

Keep the learned quantities separate: a critic estimates values, an actor selects actions, and a dynamics model predicts transitions. A Q-learning target is a number built from one transition and current estimates. Such an update rule needs data and convergence assumptions before it becomes a performance guarantee.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review conditional means and mixtures.

Section 4 solved Bellman equations with a known model; Section 5 improved policies with sampled gradients. Practical algorithms combine the two: they learn value functions from sampled transitions and use them to improve a policy, sometimes with a learned model, sometimes from a fixed dataset. This section is a map of that landscape with the few formulas the modules use.

Definition — On-policy and off-policy learning
The behaviour policy $\pi_\beta$ generates the data; the target policy $\pi$ is the one being evaluated or improved. On-policy methods use $\pi_\beta=\pi$ and collect fresh data after every update (REINFORCE, TRPO, PPO). Off-policy methods learn about $\pi$ from data of other policies: past policies stored in a replay buffer, demonstrations, or a fixed dataset (Q-learning, DQN, DDPG, SAC). Off-policy evaluation estimates $J(\pi)$ or $Q^\pi$ from $\pi_\beta$-data; it is reliable only where $\pi_\beta$ takes the actions $\pi$ takes, since the importance ratios $\pi/\pi_\beta$ blow up elsewhere.
Definition — TD learning, bootstrapping, $n$-step and $\lambda$-returns
TD(0) updates a value table after each transition: $V(s_t)\leftarrow V(s_t)+\alpha_t\delta_t$ with $\delta_t=r_t+\gamma V(s_{t+1})-V(s_t)$. The target $r_t+\gamma V(s_{t+1})$ uses the current estimate itself: bootstrapping. For a parametrised critic $V_\phi$ the semi-gradient update minimises $\tfrac12\big(y_t-V_\phi(s_t)\big)^2$ with the target $y_t=\mathrm{sg}\big(r_t+\gamma V_\phi(s_{t+1})\big)$ held fixed, $\phi\leftarrow\phi+\alpha\,\delta_t\nabla_\phi V_\phi(s_t)$ (often the target uses a slowly updated copy $\phi^-$, a target network). Longer targets bootstrap later: $$G_t^{(n)}=\sum_{k=0}^{n-1}\gamma^kr_{t+k}+\gamma^nV(s_{t+n}),\qquad G_t^\lambda=(1-\lambda)\sum_{n\ge1}\lambda^{n-1}G_t^{(n)},\qquad G_t^\lambda=r_t+\gamma\big[(1-\lambda)V(s_{t+1})+\lambda G_{t+1}^\lambda\big],$$ with every term beyond a terminal state set to $0$. The mixture form needs $0\le\lambda\lt1$ (at $\lambda=1$ it reads $0\cdot\infty$); the recursion holds for $0\le\lambda\le1$ and defines $G_t^1=\sum_k\gamma^kr_{t+k}$, the Monte-Carlo return. For an episode with $N$ steps left the mixture is the finite sum $(1-\lambda)\sum_{n=1}^{N-1}\lambda^{n-1}G_t^{(n)}+\lambda^{N-1}G_t^{(N)}$, which equals $G_t^{(N)}$, the complete return, at $\lambda=1$. Subtracting $V(s_t)$ from the recursion gives $G_t^\lambda-V(s_t)=\delta_t+\gamma\lambda\big(G_{t+1}^\lambda-V(s_{t+1})\big)$, the GAE recursion: the TD($\lambda$) return minus the baseline is the GAE advantage. In the GAE example of Section 5 ($\lambda=0.8$), $G^\lambda=(2.436,\,1.62,\,2)$ and $G^\lambda-V=(0.436,\,0.12,\,1)$.
Definition and theorem — Q-learning (Watkins & Dayan, Machine Learning 1992)
After observing $(s,a,r,s')$: $\quad Q(s,a)\leftarrow Q(s,a)+\alpha\big[r+\gamma\max_{a'}Q(s',a')-Q(s,a)\big]$, a sampled backup of $\mathcal T^\ast$ at one pair. It is off-policy: the behaviour policy only has to keep trying every action (for example $\epsilon$-greedy: a random action with probability $\epsilon$, the greedy one otherwise).
Convergence (tabular). For a finite MDP with bounded rewards, if transition samples are drawn from the stated MDP, every pair $(s,a)$ is updated infinitely often, and its step sizes $\alpha_n\in(0,1]$ satisfy the Robbins–Monro conditions $\sum_n\alpha_n=\infty$, $\sum_n\alpha_n^2\lt\infty$, then $Q\to Q^\ast$ with probability $1$. In words. Steps must stay large enough to get anywhere ($\sum\alpha=\infty$) yet shrink fast enough to average out the sampling noise ($\sum\alpha^2\lt\infty$), e.g. $\alpha_n=1/(n+1)$ at the $n$-th update of the pair. Why each assumption matters. Pairs never tried are never learned; with function approximation and off-policy bootstrapping (the "deadly triad") the iteration can diverge, and none of this theorem survives.

Example. $Q(s,a)=2$, $r=1$, $\gamma=0.9$, $\max_{a'}Q(s',a')=3$, $\alpha=0.1$: target $1+2.7=3.7$, TD error $1.7$, new value $2.17$. DQN (Mnih et al., Nature 2015) replaces the table by a network $Q_\phi$, samples minibatches from a replay buffer, and minimises $\big(r+\gamma\max_{a'}Q_{\phi^-}(s',a')-Q_\phi(s,a)\big)^2$ with a target network $\phi^-$; the maximum over noisy estimates is biased upwards, which double Q-learning reduces by selecting and evaluating the maximiser with different networks. Safety variants change only the target, e.g. $(1-\gamma)\ell(x)+\gamma\min\{\ell(x),\max_{u'}Q(x^+,u')\}$ for the discounted safety equation of Section 4.

Definition — Actor–critic methods
The actor is the policy $\pi_\theta$; the critic is a learned $V_\phi$ or $Q_\phi$ (plus cost critics $V_{c},Q_{c}$ in safe RL). Each iteration collects transitions, updates the critic by TD with fixed bootstrapped targets, and updates the actor with a policy gradient whose advantage comes from the critic ($\delta_t$ or GAE). The critic usually learns on a faster timescale than the actor (larger steps), so the actor sees a nearly converged critic; in Lagrangian methods the multiplier moves slowest. The analysis behind this (stochastic approximation) uses Robbins–Monro steps: with small steps the noisy iterates track the solution of an ordinary differential equation given by the average update direction, and with separated timescales the slow variable sees the fast one as already at its limit.
  • Deterministic actors (DDPG, TD3): $a=\mu_\theta(s)$, exploration noise only for data collection, and the chain rule through the critic, $\nabla_\theta\,\mathbb E_s\big[Q_\phi(s,\mu_\theta(s))\big]=\mathbb E_s\big[\nabla_aQ_\phi(s,a)\big|_{a=\mu_\theta(s)}\nabla_\theta\mu_\theta(s)\big]$ (deterministic policy gradient).
  • Critic ensembles: several critics from different initialisations; their mean is the estimate, their spread a measure of uncertainty; pessimistic combinations (the minimum of two critics) fight overestimation, an upper confidence bound on a cost critic fights underestimation.
  • Distributional critics predict the whole distribution of the future return or cost (for example its quantiles) instead of its mean. Two actions with expected cost $1$, one always costing $1$ and one costing $0$ with probability $0.9$ and $10$ with probability $0.1$, look identical to a mean critic; their worst-$10\%$ averages (CVaR, Primer C) are $1$ and $10$.
  • Policy distillation: train a network by supervised regression to reproduce the actions of another policy (an MPC law, or per-state LP solutions); see Section 7.

Uncertainty-weighted blending. A hybrid controller can mix a trusted control prior with the RL action, $a^{\rm ref}=(1-\lambda)a^{\rm prior}+\lambda a^{\rm RL}$, with a weight that falls as the critics disagree, e.g. $\lambda=\mathrm{clip}\big((u_{\rm hi}-u)/(u_{\rm hi}-u_{\rm lo}),0,1\big)$ with $u$ the standard deviation of the ensemble's $Q$-estimates. With $u_{\rm lo}=0.1$, $u_{\rm hi}=0.5$: $u=0.2$ gives $\lambda=0.75$, and $u\ge0.5$ gives $\lambda=0$ (pure prior). Clipping keeps $\lambda\in[0,1]$, so $a^{\rm ref}$ is always a convex combination of the two actions.

Entropy regularisation, softmax and soft Bellman equations

Definition and fact — Log-sum-exp, softmax and their variational form
For scores $q\in\mathbb R^m$ and a temperature $\alpha\gt0$: $$\mathrm{LSE}_\alpha(q)=\alpha\log\sum_{i=1}^me^{q_i/\alpha},\qquad\mathrm{softmax}_\alpha(q)_i=\frac{e^{q_i/\alpha}}{\sum_je^{q_j/\alpha}}=e^{(q_i-\mathrm{LSE}_\alpha(q))/\alpha}.$$ Variational identity. For every $p\in\Delta$, with the entropy $\mathcal H(p)=-\sum_ip_i\log p_i$, $$p^{\top}q+\alpha\,\mathcal H(p)=\mathrm{LSE}_\alpha(q)-\alpha\,D_{\rm KL}\big(p\,\big\|\,\mathrm{softmax}_\alpha(q)\big),$$ so $\max_{p\in\Delta}\big[p^{\top}q+\alpha\mathcal H(p)\big]=\mathrm{LSE}_\alpha(q)$, attained only at $p=\mathrm{softmax}_\alpha(q)$. Proof: expand $D_{\rm KL}\big(p\,\|\,\mathrm{softmax}_\alpha(q)\big)=\sum_ip_i\log p_i-\sum_ip_i(q_i-\mathrm{LSE}_\alpha(q))/\alpha$ and multiply by $\alpha$; the KL is $\ge0$ with equality only at $p=\mathrm{softmax}_\alpha(q)$. $\blacksquare$
Temperature. $\max_iq_i\le\mathrm{LSE}_\alpha(q)\le\max_iq_i+\alpha\log m$, so $\mathrm{LSE}_\alpha\to\max$ as $\alpha\to0$ (a "soft maximum") and the softmax tends to the uniform distribution on the maximisers. For $\alpha\gt0$ and finite scores every entry of the softmax is positive: full support.

Example. $q=(1,2,4)$: $\alpha=1$ gives $\mathrm{softmax}=(0.042,0.114,0.844)$ and $\mathrm{LSE}=4.170\in[4,\,5.099]$; $\alpha=0.5$ gives $\mathrm{LSE}=4.010$; $\alpha=5$ gives $(0.247,0.302,0.451)$ and $\mathrm{LSE}=7.986\in[4,\,9.493]$.

Key equation — Entropy-regularised RL and the soft Bellman equations
The entropy-regularised objective collects entropy along the trajectory with the same discount, $$J_\alpha(\pi)=\mathbb E_\pi\Big[\sum_t\gamma^t\big(r(s_t,a_t)+\alpha\,\mathcal H(\pi(\cdot\mid s_t))\big)\Big]=J(\pi)+\alpha\,\mathcal H_\gamma(\pi),\qquad\mathcal H_\gamma(\pi):=\mathbb E_\pi\Big[\sum_t\gamma^t\mathcal H(\pi(\cdot\mid s_t))\Big],$$ a trajectory-weighted (discounted) policy entropy, not the entropy at one state. Its value functions satisfy $Q(s,a)=r(s,a)+\gamma\,\mathbb E_{s'}[V(s')]$ and $V(s)=\mathbb E_{a\sim\pi}\big[Q(s,a)-\alpha\log\pi(a\mid s)\big]$. By the variational identity, the optimal policy is the Boltzmann (softmax) policy $\pi^\ast(\cdot\mid s)=\mathrm{softmax}_\alpha(Q^\ast(s,\cdot))$, with $V^\ast(s)=\mathrm{LSE}_\alpha(Q^\ast(s,\cdot))$: the hard $\max$ of the Bellman optimality equation becomes a soft one. SAC (Haarnoja, Zhou, Abbeel & Levine, ICML 2018) is an off-policy actor–critic that learns soft $Q$-critics from a replay buffer, moves the actor towards the softmax of the critic. The original version keeps $\alpha$ fixed (tuned per task); a follow-up (Haarnoja et al., 2018, Soft Actor-Critic Algorithms and Applications) adapts $\alpha$ automatically, through a constraint that keeps the average policy entropy at least at a target level.

Model-based RL and uncertainty

A learned dynamics model $\hat f_\phi(s,a)\approx\mathbb E[s'\mid s,a]$, or a predictive distribution $\hat p_\phi(s'\mid s,a)$, is fitted by regression on observed transitions and then used to plan (model-predictive control: optimise an action sequence over a horizon on the model, apply the first action, re-plan), to generate imagined transitions for a model-free learner (Dyna), or to differentiate through (pathwise gradients). Errors compound along long model rollouts, and a planner actively seeks the places where the model is wrong in its favour.

Definition — Aleatoric versus epistemic uncertainty; probabilistic ensembles
Aleatoric uncertainty is the irreducible randomness of the system itself (the noise $w_t$ in $s_{t+1}=f(s_t,a_t)+w_t$); more data do not remove it. Epistemic uncertainty is uncertainty about the model caused by limited data; it shrinks where data accumulate. A probabilistic ensemble (PE; Chua et al., NeurIPS 2018; deep ensembles: Lakshminarayanan et al., NIPS 2017) trains $B$ networks, each predicting a Gaussian $\mathcal N(\mu_b(s,a),\Sigma_b(s,a))$. By the law of total variance the ensemble's predictive covariance splits as $$\underbrace{\frac1B\sum_b\Sigma_b}_{\text{aleatoric: within-model noise}}+\underbrace{\frac1B\sum_b(\mu_b-\bar\mu)(\mu_b-\bar\mu)^{\top}}_{\text{epistemic: between-model disagreement}},\qquad\bar\mu=\frac1B\sum_b\mu_b .$$

Example ($B=3$, one dimension). Near the data the members predict means $(1.0,1.2,0.8)$ with variances $(0.04,0.05,0.03)$: aleatoric $0.04$, epistemic $0.027$. Far from the data they predict $(1.0,2.0,-0.5)$: the epistemic part jumps to $1.056$. Optimism in model-based RL plans with an upper confidence reward, or jointly over policies and the most favourable model still consistent with the data (Section 1's principle), and epistemic uncertainty as intrinsic reward sends the agent where the model is unsure: useful for learning, and exactly where it is risky to go. Latent world models (Dreamer, Hafner et al., ICLR 2020) encode observations $o_t$ (e.g. images) into a learned latent state $z_t$, learn latent dynamics $z_{t+1}\sim p(\cdot\mid z_t,a_t)$ with reward and cost heads, and train the policy on imagined latent rollouts; a latent state is a learned representation for prediction and control, not a physical state. Approximate weight posteriors such as SWAG (a Gaussian fitted to the iterates of stochastic gradient descent) are another cheap source of epistemic uncertainty.

Caveat — disagreement is not a certified error bound
Ensemble members trained on the same data with the same architecture can agree and all be wrong, especially far from the data. Ensemble spread is a useful heuristic signal; unlike the GP confidence bounds of Modules 3–5 (valid under stated assumptions) it comes with no guarantee that the true dynamics lie inside it.

Offline RL, reward models and safety filters

Offline RL learns from a fixed dataset $\mathcal D=\{(s,a,r,c,s')\}$ collected by unknown behaviour policies $\pi_\beta$, with no further interaction. The central problem is distribution shift: the learned policy takes actions that are rare or absent in $\mathcal D$, their values are extrapolations of the function approximator, and a maximising policy seeks exactly the actions whose values are overestimated. Because no new data arrive, these errors are never corrected. The remedies are pessimistic: push down values outside the data (conservative Q-learning, Kumar et al., NeurIPS 2020), keep the policy close to $\pi_\beta$, or back up values only through dataset actions. A tutorial overview is Levine et al. (Further Reading).

Term (Module 9)Meaning
Data supportthe pairs $(s,a)$ that $\pi_\beta$ takes with positive probability; outside it every value is an extrapolation
Expectile regressionfit $v$ by minimising $\mathbb E\big[|\tau-\mathbf 1\{y-v\lt0\}|\,(y-v)^2\big]$; $\tau=\tfrac12$ gives the mean, $\tau\to1$ ($\tau\to0$) approaches the largest (smallest) target, so it approximates a max (min) over dataset actions without querying unseen ones
CVAE out-of-distribution scorea conditional variational autoencoder (encoder $q(z\mid s,a)$, prior $\mathcal N(0,I)$, decoder) models the dataset actions; a large $D_{\rm KL}(q(z\mid s,a)\|\mathcal N(0,I))$ flags an unusual pair: a heuristic detector, not a certificate
Decision transformera causal sequence model (Section 8) that reads states, actions and "return tokens" such as the reward-to-go $R_t=\sum_{t'\ge t}r_{t'}$ and cost-to-go $C_t$, and outputs an action distribution; at deployment the user sets the target tokens
Diffusion policya generative model of actions trained by denoising: noise is added to dataset actions over an artificial "denoising time" and a network learns to remove it, conditioned on the state; denoising time has nothing to do with physical time

Reward models and RLHF. From pairwise human preferences between a preferred response $y_w$ and a rejected response $y_l$ to a prompt $x$, the Bradley–Terry model sets $\mathbb P(y_w\succ y_l\mid x)=\sigma\big(R_\phi(y_w,x)-R_\phi(y_l,x)\big)$ with the logistic function $\sigma(z)=1/(1+e^{-z})$ (Section 7), and $\phi$ is fitted by minimising $-\mathbb E\big[\log\sigma(R_\phi(y_w,x)-R_\phi(y_l,x))\big]$ (Christiano et al., NeurIPS 2017, learn rewards from preferences this way for Atari and simulated robots). A score difference of $1$ means probability $\sigma(1)=0.731$ and loss $0.313$; a difference of $-1$ costs $1.313$. The policy (a language model: the prompt plays the state, the response the action) is then fine-tuned with PPO to maximise the learned reward minus a KL penalty to a reference model (Ziegler et al., 2019). Safe RLHF fits a cost model the same way. A learned score is a ranking signal: a cost score of $0.7$ is not a $70\%$ (or any) probability of harm unless it has been calibrated separately.

Safety filters and shields. A filter sits between the learner and the plant: it passes the proposed action if a certificate says it is safe and otherwise replaces it by a certified safe action (a backup controller's action, or the closest safe action from a small optimisation problem). A shield does the same against a finite-state safety specification. The learner can be any of the algorithms above; the guarantee comes from the certificate (Module 10).

Where this is used
  • Optimism in planning, epistemic uncertainty as intrinsic reward, latent dynamics models: Module 6.
  • Q-learning of a Bellman fixed point: Module 7; SAC, Boltzmann policies with full support, soft Bellman equations: Module 7; probabilistic ensembles, critic ensembles and the blended action $a^{\rm ref}_t$: Module 7.
  • Actor–critic training, TD targets, Robbins–Monro steps and timescales, off-policy cost critics: Module 8; discounted policy entropy: Module 8; Bradley–Terry reward and cost models and PPO fine-tuning: Module 8; distributional critics: Module 1.
  • Off-policy evaluation: Module 9; TD($\lambda$) returns, latent world models and imagined rollouts: Module 9; offline RL, distribution shift and its vocabulary: Module 9.
  • RL policies wrapped by filters and shields: Module 10; neural dynamics ensembles and latent encoders in learned filters: Module 10; DQN, DDPG, PPO, value approximation and policy distillation in safe DQN and safe DPI: Module 11.
Pitfall — convergence theorems are tabular
The clean results of this page (value iteration, policy iteration, tabular Q-learning) assume exact tables and, for learning, every pair visited infinitely often. Deep RL uses networks, replay buffers and finite data; there, a Bellman residual is minimised approximately and never exactly zero, and guarantees hold only up to approximation and estimation errors that are rarely quantified.

Practice — Understand the update and its data assumptions

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S16 — Easy: One Q-learning update

For a sampled transition, $Q(s,a)=0.5$, reward is $1$, discount is $0.9$, and the largest next-state action-value estimate is $2$. With learning rate $0.2$, compute the target, temporal-difference error and updated value. Assume the next state is nonterminal.

Review if needed: this section and conditional means and mixtures.

Show hint
The target is $r+\gamma\max_{a'}Q(s',a')$; the update moves only partway toward it.
Show worked solution
  1. The target is $1+0.9(2)=2.8$.
  2. The temporal-difference error is $2.8-0.5=2.3$.
  3. The new estimate is $0.5+0.2(2.3)=0.96$. It is not replaced by $2.8$, because the learning rate is below one. For a terminal transition the continuation term would be zero.
Exercise E.S17 — Medium: Softmax is a distribution, log-sum-exp is a value

At temperature $\alpha=1$, two action-values are $Q_1=0$ and $Q_2=\ln3$. Compute the entropy-regularised optimal action probabilities and the soft value $\ln(e^{Q_1}+e^{Q_2})$. Compare it with $\max_iQ_i$.

Review if needed: this section and conditional means and mixtures.

Show hint
Exponentiating the action-values gives weights $1$ and $3$. Normalise for probabilities; take the log of the sum for value.
Show worked solution
  1. The softmax probabilities are $(1/(1+3),3/(1+3))=(1/4,3/4)$.
  2. The soft value is $\ln4\approx1.386294$, whereas the largest action-value is $\ln3\approx1.098612$.
  3. The soft value includes the entropy reward and exceeds the ordinary maximum by $\ln(4/3)\approx0.287682$. It is not the unregularised expected reward of the softmax policy. The temperature and logarithm convention are part of the objective.
Exercise E.S18 — Hard: An ensemble does not certify an unseen action

Two equally weighted dynamics models predict scalar next-state means $0$ and $2$, each with conditional variance $1$. Find the mixture mean and variance. Separately, an offline data set contains only action $a$ with reward $1$; all models predict reward $100$ for an unobserved action $b$. Does agreement prove $b$ is good?

Review if needed: this section and conditional means and mixtures.

Show hint
Total variance adds average predicted variance to variance of predicted means. Unseen outcomes can differ between environments that generate the same data.
Show worked solution
  1. The mixture mean is $(0+2)/2=1$. Average conditional variance is $1$, and variance of the means is $[(0-1)^2+(2-1)^2]/2=1$. Total variance is $2$.
  2. Disagreement contributes one part of uncertainty in this model mixture; it is not a bound on true model error.
  3. For the offline problem, environments with true reward $100$ or $-100$ for $b$ produce identical data when only $a$ is observed. All models can agree and still be wrong. Additional support, assumptions or a justified conservative method are needed to draw a performance conclusion about $b$.

7. Neural Networks: Layers, Activations & Backpropagation

Start here — Trace a forward pass before differentiating

A layer first forms an affine map $Wx+b$, then applies an activation. For one output with $W=(2,-1)$, the input $(1,3)$ gives dot product $-1$ before adding the bias. Trace the forward computation before applying the chain rule backward.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review gradients and the chain rule.

A neural network is a composition of two kinds of simple maps: affine layers that mix coordinates, and scalar nonlinearities applied to each coordinate separately. Every certificate in Modules 12–15 exploits exactly this structure; every RL agent above uses it to represent policies, critics and models.

Definition — Feedforward network
With input $z_0=x\in\mathbb R^{n_0}$ and hidden layers $k=1,\dots,l$: $$v_k=W_kz_{k-1}+b_k\in\mathbb R^{n_k}\ \ \text{(pre-activation)},\qquad z_k=\varphi(v_k):=\big(\varphi(v_{k,1}),\dots,\varphi(v_{k,n_k})\big)\ \ \text{(hidden vector)},\qquad f(x)=W_{l+1}z_l+b_{l+1}.$$ $W_k\in\mathbb R^{n_k\times n_{k-1}}$ are the weights, $b_k$ the biases, $n_k$ the widths; each coordinate of $z_k$ is a neuron. The scalar activation $\varphi$ is applied coordinatewise; the output layer is affine (linear up to its bias) with no activation. So $f=A_{l+1}\circ\varphi\circ A_l\circ\dots\circ\varphi\circ A_1$ with $A_k(z)=W_kz+b_k$, and $\theta$ collects all weights and biases (the trainable parameters). Notation varies: Module 12 counts weights from $0$ ($v_k=W_{k-1}z_{k-1}+b_{k-1}$), Module 15 calls pre-activations $z^{(k)}$ and activations $a^{(k)}$. Each page's notation box fixes its own.

Worked example (used throughout Sections 7–9 and in the explorer). The 2-2-1 ReLU network with

$$W_1=\begin{bmatrix}1&1\\1&-1\end{bmatrix},\quad b_1=\begin{bmatrix}-1\\0\end{bmatrix},\quad W_2=\begin{bmatrix}1&-2\end{bmatrix},\quad b_2=-1,\qquad f(x)=\mathrm{relu}(x_1+x_2-1)-2\,\mathrm{relu}(x_1-x_2)-1 .$$

At $x=(1,2)$: $v_1=(2,-1)$, $z_1=(2,0)$, $f=2-0-1=1$. The lines $x_1+x_2=1$ and $x_1=x_2$ (where a neuron switches) cut the plane into four regions; on each, $f$ is affine. A ReLU network is continuous and piecewise affine.

Activation$\varphi(v)$Slope $\varphi'(v)$Slope interval
ReLU$\max\{0,v\}$$0$ for $v\lt0$, $1$ for $v\gt0$$[0,1]$
leaky ReLU, $0\lt a\lt1$$\max\{av,v\}$$a$ or $1$$[a,1]$
sigmoid (logistic)$\sigma(v)=\dfrac1{1+e^{-v}}$$\sigma(v)(1-\sigma(v))\in(0,\tfrac14]$$[0,\tfrac14]$
tanh$\tanh v=\dfrac{e^v-e^{-v}}{e^v+e^{-v}}=2\sigma(2v)-1$$1-\tanh^2v\in(0,1]$$[0,1]$
softplus$\log(1+e^v)$ (a smooth ReLU)$\sigma(v)\in(0,1)$$[0,1]$
MaxMin / GroupSortsorts pairs (groups) of coordinates, $(u,w)\mapsto(\max\{u,w\},\min\{u,w\})$locally a permutation matrixnot coordinatewise; 1-Lipschitz

A scalar $\varphi$ is slope-restricted in $[\alpha,\beta]$ if $\alpha\le\frac{\varphi(u)-\varphi(w)}{u-w}\le\beta$ for all $u\ne w$: every chord, not only every derivative, has slope in the interval (Module 12's key assumption; Lipschitz continuity: Primer B). The derivatives in the table follow from the quotient rule: $\sigma'=e^{-v}/(1+e^{-v})^2=\sigma(1-\sigma)$, maximal $\tfrac14$ at $v=0$; $\tanh'=(\cosh^2-\sinh^2)/\cosh^2=1-\tanh^2$ with $\cosh v=(e^v+e^{-v})/2$, $\sinh v=(e^v-e^{-v})/2$; and $\frac{d}{dv}\log\cosh v=\tanh v$. MaxMin ($\mathrm{MaxMin}(3,-1)=\mathrm{MaxMin}(-1,3)=(3,-1)$) is not coordinatewise, so slope restriction does not apply; on each region it permutes its inputs, so it preserves Euclidean norms of gradients, which is why Lipschitz-by-design networks use it (Anil, Lucas & Grosse, ICML 2019). Householder activations generalise it: for a unit vector $u$, $z\mapsto z$ if $u^{\top}z\gt0$ and $z\mapsto(I-2uu^{\top})z$ (a reflection) otherwise; with $u=(1,-1)/\sqrt2$ this is exactly MaxMin.

Definition — Softmax as a vector activation; logits
$\mathrm{softmax}(z)_i=e^{z_i}/\sum_je^{z_j}$ (temperature $1$ of Section 6) is not coordinatewise: each output depends on all inputs. Its Jacobian is $$\frac{\partial\,\mathrm{softmax}(z)_i}{\partial z_j}=p_i(\delta_{ij}-p_j),\qquad J=\mathrm{diag}(p)-pp^{\top},\qquad p=\mathrm{softmax}(z),$$ and it is the gradient of the log-sum-exp: $\nabla_z\log\sum_je^{z_j}=\mathrm{softmax}(z)$. The log-sum-exp is convex because its Hessian $J$ is positive semidefinite: $v^{\top}Jv=\sum_ip_iv_i^2-\big(\sum_ip_iv_i\big)^2$ is the variance of $v$ under $p$. A classifier's last layer outputs logits $z\in\mathbb R^K$, unconstrained class scores; $\mathrm{softmax}(z)$ turns them into class probabilities, and adding the same constant to every logit changes nothing.

Networks inside RL. A policy network maps a state to the parameters of an action distribution: logits followed by a softmax for discrete actions, a mean $m_\theta(s)$ and a log-standard-deviation for Gaussian actions, or directly an action $\mu_\theta(s)$ for a deterministic policy (often squashed by $\tanh$ into the action bounds); $\theta$ collects all its weights. Critics $V_\phi(s)$, $Q_\phi(s,a)$ and dynamics models are networks too. Shared parameters couple states: a gradient step that fixes $V_\phi$ at one state also changes it elsewhere (generalisation, and interference). And since a parametrised family rarely contains $V^\pi$ exactly, the Bellman equation cannot hold everywhere: training minimises a mean squared Bellman residual that stays positive, and the learned "value function" is an approximation, not a solution.

Definition — Empirical risk minimisation and common losses
Given data $(x_i,y_i)_{i=1}^N$ and a loss $\ell$, training minimises the average sample loss (the empirical risk), plus possibly a regulariser: $$\hat R(\theta)=\frac1N\sum_{i=1}^N\ell\big(f_\theta(x_i),y_i\big).$$
  • Regression: $\ell=\tfrac12\|f-y\|^2$. Fitting network outputs to target controls (imitating an MPC law, policy distillation) is a regression, and so is fitting a residual model: Module 10 learns the unknown part of a barrier's rate, $b(x)+a(x)^{\top}u$, from data $(x_i,u_i,\dot h_i)$ by $$\min_{a,b}\ \frac1N\sum_{i=1}^N\Big(\dot h_i-\nabla h(x_i)^{\top}\big(\hat f(x_i)+\hat g(x_i)u_i\big)-b(x_i)-a(x_i)^{\top}u_i\Big)^2,$$ the measured rate minus the nominal model's prediction, fitted by least squares. DAgger-style aggregation (Ross, Gordon & Bagnell, AISTATS 2011): run the learned policy, label the states it visits, add them to the data, refit, repeat.
  • Classification: the cross-entropy of logits $z$ and label $y$, $\ell(z,y)=-\log\mathrm{softmax}(z)_y=\log\sum_je^{z_j}-z_y$, with gradient $\mathrm{softmax}(z)-e_y$ (predicted probabilities minus the one-hot label). For two classes with labels $\pm1$ and a score $s$: $\log(1+e^{-ys})=-\log\sigma(ys)$, the logistic loss.
  • Hinge / positive part: $[r]_+=\max\{0,r\}$ penalises only violations. $[\gamma_{\rm safe}-h_\theta(x_i)]_+$ is zero once $h_\theta(x_i)\ge\gamma_{\rm safe}$ (the margin is met). If every hinge argument is affine in $\theta$ (for instance $h_\theta(x)=\theta^{\top}\psi(x)$ with fixed features $\psi$), the objective is convex, since a maximum of two affine functions is convex and sums preserve convexity; for a network $h_\theta$ it is not.

Penalties versus certificates. Weight decay ($L_2$ regularisation) adds $\lambda\sum_k\|W_k\|_F^2$ and shrinks weights; a gradient penalty adds $\mathbb E\|\nabla_xf_\theta(x)\|^2$ at sampled inputs and flattens the network where it is evaluated. Both make large slopes unlikely but prove nothing about inputs that were not sampled. A hard certificate, such as a proven Lipschitz bound (LipSDP, Module 12) or an architecture that is Lipschitz by construction (Module 13), holds for every input. Margin-based training: Lipschitz-margin training adds $\sqrt2\,c\,L$ to every non-target logit before the cross-entropy; the loss then stays small only if the true logit beats the others by more than $\sqrt2cL$, a margin that Section 9 converts into a certified radius $c$. Raising the non-target logits makes training demand larger margins. Schedules: some losses change during training, e.g. Module 15's interval-bound-propagation (IBP) training (Section 9) minimises $\kappa\,\ell(z_K,y)+(1-\kappa)\,\ell(\hat z_K,y)$ with $z_K$ the logits of the last layer $K$, $\hat z_K$ worst-case logits over the perturbation set, and the weight $\kappa$ annealed (moved gradually) from $1$ to $\tfrac12$.

Gradient descent and backpropagation. Training runs (stochastic) gradient descent on $\hat R$ (Primer B), usually with minibatch gradient estimates; one pass over the data is an epoch. The problem is non-convex, so there is no guarantee of a global minimum. The gradient is computed by backpropagation (Rumelhart, Hinton & Williams, Nature 1986), the multivariable chain rule (Primer B) organised backwards: store all $v_k,z_k$ in a forward pass, then, starting from $\bar f=\partial\ell/\partial f$, apply for $k=l+1,\dots,1$ the weight and bias formulas, and for $k=l+1,\dots,2$ the recursion for $\delta_{k-1}$:

$$\delta_{l+1}=\bar f,\qquad\frac{\partial\ell}{\partial W_k}=\delta_k\,z_{k-1}^{\top},\qquad\frac{\partial\ell}{\partial b_k}=\delta_k\quad(k=l+1,\dots,1),\qquad\delta_{k-1}=\varphi'(v_{k-1})\odot\big(W_k^{\top}\delta_k\big)\quad(k=l+1,\dots,2),$$

where $\delta_k=\partial\ell/\partial v_k$ for the hidden layers $k\le l$ and $\delta_{l+1}=\partial\ell/\partial f$ for the affine output layer (write $v_{l+1}:=f$), and $\odot$ is the coordinatewise product. There is no $v_0$: the input is not passed through an activation, so the recursion stops at $\delta_1$. One more product gives the gradient with respect to the input, $\partial\ell/\partial x=W_1^{\top}\delta_1$, which attacks use (Section 9). The walkthrough runs one pass on the worked example.

Fact — Universal approximation (statement only)
For every continuous $g$ on a compact set $K\subset\mathbb R^n$ and every $\epsilon\gt0$ there is a network with one hidden layer (ReLU, sigmoid or tanh) with $\sup_{x\in K}|f(x)-g(x)|\le\epsilon$ (Goodfellow et al., Sec. 6.4.1, in the Further Reading). Networks are dense in the continuous functions for the sup norm: they approximate arbitrarily well, which is not the same as representing a function exactly, and the statement says nothing about the size needed, about training, or about behaviour outside $K$. For policies, an $\epsilon$-universal class approximates every stationary policy within $\epsilon$ in $\max_s\sum_a|\pi(a\mid s)-\pi_\theta(a\mid s)|$; since each step adds at most $\epsilon$ to the distribution error, returns differ by at most $B\epsilon\sum_t(t+1)\gamma^t=B\epsilon/(1-\gamma)^2$ (Module 2).
Where this is used
  • Layers, weights, activations and slope intervals: Module 2 (a network with weights $W_i$ in the LipSDP walkthrough), Module 2 (activation $\varphi$ slope-restricted in $[\alpha,\beta]$; softmax as the gradient of log-sum-exp), Module 12 (pre-activations, ReLU, cross-entropy, Lipschitz-margin training), Module 13 (compositions of affine maps and activations), Module 14 (networks trained to imitate controllers), Module 15 ($m$-layer networks) and Module 15 (IBP training loss and schedules); GroupSort and MaxMin: Module 1.
  • Policy networks and value approximation: Module 9, Module 7, the 32-unit ReLU policy of Module 11; logistic and hyperbolic functions: Module 9 exercises; softmax probabilities of classes: Module 15.
  • Empirical risk minimisation, residual regression, DAgger-style refitting and hinge losses $[\gamma_{\rm safe}-h_\theta(x_i)]_+$: Module 10.
Pitfall — a training penalty is not a certificate
Weight decay, gradient penalties and adversarial training (Section 9) change what the optimiser prefers; they certify nothing about inputs that were never evaluated. When a module says "certified", look for an inequality that holds for every input (a proven Lipschitz bound, an LMI, a verified bound), not for a term in the loss.

Practice — Trace a forward pass before differentiating

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S19 — Easy: Weights, bias and activation

A layer has weight row $W=(2,-1)$, bias $b=0.5$, and output $f(x)=\max(0,Wx+b)$. Compute the pre-activation and output for inputs $(1,3)$ and $(2,1)$. State the input and output dimensions.

Review if needed: this section and gradients and the chain rule.

Show hint
The dot product produces one scalar, then the bias is added, then ReLU is applied.
Show worked solution
  1. At $(1,3)$, the pre-activation is $2(1)-3+0.5=-0.5$, so the output is $0$.
  2. At $(2,1)$, it is $2(2)-1+0.5=3.5$, so the output is $3.5$.
  3. $W$ is a $1\times2$ matrix: the input dimension is $2$ and the output dimension is $1$. ReLU changes values, not these dimensions. Applying the activation before the affine map would define a different network.
Exercise E.S20 — Medium: Backpropagate through one active neuron

Let $f(x)=w\max(0,ax+b)$ and loss $\ell=\tfrac12(f-y)^2$. At $x=1$, $y=1$, $a=2$, $b=-1$, $w=3$, compute $f$, $\ell$ and derivatives with respect to $w,a,b,x$.

Review if needed: this section and gradients and the chain rule.

Show hint
The pre-activation is positive, so ReLU's derivative is one. Start with $\partial\ell/\partial f=f-y$.
Show worked solution
  1. The pre-activation is $v=2(1)-1=1$, hidden activation is $z=1$, output is $f=3$, and loss is $\ell=(3-1)^2/2=2$.
  2. The output derivative is $2$. Therefore $\partial\ell/\partial w=2z=2$ and the derivative through the hidden pre-activation is $2w=6$.
  3. Since $v=ax+b$, the remaining derivatives are $\partial\ell/\partial a=6x=6$, $\partial\ell/\partial b=6$ and $\partial\ell/\partial x=6a=12$. Parameter gradients train the network; the input gradient measures local sensitivity of this loss.
Exercise E.S21 — Hard: A product bound can miss useful structure

For $f(x)=\operatorname{ReLU}(x)-\operatorname{ReLU}(-x)$, write its two-layer weights without biases. Compute the product of their spectral norms and the exact global Lipschitz constant. For binary classification by the sign of $f$, compare the certified radii at $x=2$.

Review if needed: this section and gradients and the chain rule.

Show hint
Check separately $x\ge0$ and $x\lt0$. The network represents a familiar scalar map.
Show worked solution
  1. The first-layer column is $W_1=(1,-1)^\top$ and the second-layer row is $W_2=(1,-1)$. Each has spectral norm $\sqrt2$, so the product bound is $2$.
  2. For either sign of $x$, $\operatorname{ReLU}(x)-\operatorname{ReLU}(-x)=x$. Its exact global Lipschitz constant is $1$.
  3. At $x=2$, the margin is $2$. The product bound certifies every radius below $2/2=1$, whereas the exact constant certifies every radius below $2$. The boundary is at zero, distance $2$; equality would permit a tie.

8. Convolutions, Residual, Recurrent & Equilibrium Layers

Start here — Recognise compositions, skip paths and recurrence

Architectures change how maps are connected: convolution shares local weights, residual blocks add a skip path, and recurrence reuses a map across steps. An equilibrium layer asks for a fixed point of such a map. The examples below reduce these structures to matrix multiplication and scalar iteration.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review operator norms.

Four structures recur in the certified-network modules. All are still built from affine maps and activations; what changes is the pattern inside the weight matrices, or where a layer's input comes from.

Definition — Convolution layer (channels, kernel, stride, padding, dilation)
A 1-D convolution slides a kernel $w\in\mathbb R^k$ along a signal $x\in\mathbb R^n$: $y[i]=\sum_{j=0}^{k-1}w[j]\,x[si+dj]$ on the padded signal (deep-learning libraries use this "cross-correlation" orientation). The stride $s$ is the step between output positions, the dilation $d$ the spacing of the kernel taps, and padding adds $p$ entries at each end: zeros, or for circular padding the values from the other end. The output length is $\lfloor(n+2p-d(k-1)-1)/s\rfloor+1$. With $C_{\rm in}$ input channels (e.g. the three colours of an image) and $C_{\rm out}$ output channels, $w\in\mathbb R^{C_{\rm out}\times C_{\rm in}\times k}$ and $y_o[i]=\sum_c\sum_jw[o,c,j]\,x_c[si+dj]+b_o$. The same weights are used at every position (weight sharing), so the layer is a linear map $y=Tx+b$ with a structured matrix (Primer A). For one channel and stride $1$, $T$ is Toeplitz (constant along diagonals) with zero padding, and circulant (square, each row a cyclic shift of the previous one) for a circular convolution whose output has the input length. A stride $s\gt1$ keeps every $s$-th row of that matrix, which is in general no longer Toeplitz, and with several channels $T$ is a block matrix with one such block per pair of input and output channel. 2-D convolutions do the same with $k\times k$ kernels over images; flattening reshapes a $C\times n$ array into one vector before a dense layer.

Example. $x=(1,2,3,4)$, $w=(1,-1)$, no padding, stride $1$: $y=(x_1-x_2,\,x_2-x_3,\,x_3-x_4)=(-1,-1,-1)$ (length $\lfloor(4-1-1)/1\rfloor+1=3$), i.e. $y=Tx$ with $T=\begin{bmatrix}1&-1&0&0\\0&1&-1&0\\0&0&1&-1\end{bmatrix}$. To keep the length $4$ circularly, append only $x_1$ on the right (symmetric circular padding $p=1$ would give five outputs): then $y_4=x_4-x_1=3$ and $T$ is a $4\times4$ circulant matrix. Stride $2$ in the unpadded example keeps $y_1,y_3$, i.e. rows $1$ and $3$ of $T$, which are not a Toeplitz matrix. Invertible downsampling ("space-to-depth") moves each $2\times2$ block of an image into $4$ channels: the spatial size halves but nothing is lost. It only rearranges entries, so it is a permutation matrix, orthogonal, norm-preserving and exactly $1$-Lipschitz; Lipschitz-by-design networks use it instead of strided convolutions.

Definition — Residual layer
$x\mapsto x+g(x)$ with a small network $g$ (for example $g(x)=W_2\varphi(W_1x+b)$) whose output has the same dimension as $x$: the skip connection passes the input unchanged (He, Zhang, Ren & Sun, CVPR 2016). The naive bound $\mathrm{Lip}\le1+\mathrm{Lip}(g)$ can be very loose, because the residual branch can cancel expansion: $g(x)=-\tfrac12x$ gives $x+g(x)=\tfrac12x$, Lipschitz constant $\tfrac12$, not $\tfrac32$. Module 13's SLL layer $x-2WT^{-1}\varphi(W^{\top}x+b)$ is designed this way: for a coordinatewise $\varphi$ slope-restricted in $[0,1]$ (ReLU, tanh, sigmoid; Section 7) it is $1$-Lipschitz whenever $T$ is a diagonal matrix with positive entries and $W^{\top}W\preceq T$.
Definition — Recurrent network as a dynamical system
$$h_{t+1}=\varphi(Ah_t+Bu_t+b),\qquad y_t=Ch_t+Du_t,$$ with hidden state $h_t$, input sequence $u_t$, output sequence $y_t$, and the same weights at every time step: a nonlinear discrete-time state-space system (Primer D). A feedforward network maps one input to one output and has no memory; a recurrent network maps sequences to sequences and remembers through $h_t$. Unrolling $T$ steps gives a deep feedforward network with shared weights. With $\varphi$ the identity it is an LTI system; in general it is a linear system in feedback with a static nonlinearity (Module 14). An LSTM is a gated recurrent network; used as a predictor it maps an observation history to a forecast of future states (the gate equations are not needed here).

Uses and variants. System identification fits a dynamic model, such as a recurrent network, to measured input–output data; an observer is a dynamical system that estimates the state from measured outputs; both are natural jobs for recurrent networks. An echo state network keeps random, fixed recurrent weights (a "reservoir") and trains only the linear readout $C$. It needs the echo state property: the state forgets its initial condition. If $\varphi$ is $1$-Lipschitz and $\|A\|\lt1$, two runs with the same inputs satisfy $\|h_{t+1}-h'_{t+1}\|\le\|A\|\,\|h_t-h'_t\|$, a contraction, so the dependence on $h_0$ fades geometrically. (For the scalar reservoir $h_{t+1}=\tanh(0.8h_t+u_t)$ with input $u_t=0$, started at $h_0=\pm2$ (initial gap $4$), the gap after $1,2,3$ steps is $1.84,\,1.26,\,0.93$ and keeps shrinking.) Two further sequence and structure models appear in passing: a causal transformer maps a sequence of tokens (vectors encoding states, actions or return targets) to an output at each position using only earlier positions, through attention (averages of earlier tokens' features with softmax weights); a graph neural network updates each node's feature from its own and its neighbours', $h_i\leftarrow\varphi\big(W_{\rm self}h_i+\sum_{j\in\mathcal N(i)}W_{\rm msg}h_j\big)$, with the same weights at every node.

Definition — Equilibrium (implicit) layer and well-posedness
The layer's hidden vector is defined by an equation, and the output read from it: $$z=\varphi(Wz+Ux+b),\qquad y=Cz+Dx .$$ It is well-posed if the equation has exactly one solution $z(x)$ for every $x$. A sufficient condition: $\varphi$ slope-restricted in $[0,1]$ (hence $1$-Lipschitz) and $\|W\|\lt1$. Then $z\mapsto\varphi(Wz+Ux+b)$ is a contraction, since $\|\varphi(Wz+c)-\varphi(Wz'+c)\|\le\|W(z-z')\|\le\|W\|\,\|z-z'\|$, so the solution is unique and fixed-point iteration $z^{k+1}=\varphi(Wz^k+Ux+b)$ finds it (Section 4; deep equilibrium models: Bai, Kolter & Koltun, NeurIPS 2019).

Example. $z=\tanh(0.5z+1)$: from $z^0=0$ the iterates are $0.7616,\,0.8811,\,0.8938,\,0.8951,\,0.8952$, converging to $z^\ast\approx0.8952$. Every feedforward network is an implicit layer with triangular $W$. Stack the hidden vectors, $z=(z_1,z_2)$ for two hidden layers: then $z=\varphi(Wz+W_0x+\beta)$ with

$$W=\begin{bmatrix}0&0\\W_2&0\end{bmatrix},\qquad W_0=\begin{bmatrix}W_1\\0\end{bmatrix},\qquad\beta=\begin{bmatrix}b_1\\b_2\end{bmatrix},\qquad f(x)=\begin{bmatrix}0&W_3\end{bmatrix}z+b_3 .$$

Because $W$ is strictly block lower triangular (layer $k$ only receives layer $k-1$), the equation is solved by forward substitution in one pass: no iteration and no well-posedness question. A genuine equilibrium layer has a non-triangular $W$ that couples neurons of the same layer; in a recurrent equilibrium network (REN) such an equation is solved within each time step while the recurrence $h_t\to h_{t+1}$ runs across time steps.

Where this is used
  • The stacked implicit form $z=\varphi(Wz+W_0x+\beta)$ of a network: Module 11. Convolutional layers as structured maps and as dynamical systems: Module 12.
  • Circular padding, residual layers with $W^{\top}W\preceq T$ and "equilibrium solve (REN only)": Module 13; invertible downsampling: Module 13; system identification, observers and echo state networks: Module 13.
  • Recurrent networks as dynamical systems: Module 14; recurrent (LSTM) trajectory predictors: Module 15; decision transformers: Module 9; graph-neural certificates: Module 10.
Pitfall — an implicit layer must be proven well-posed
Writing $z=\varphi(Wz+Ux+b)$ does not guarantee that a solution exists or is unique: with $\|W\|\ge1$ there may be several (take the scalar $z=\mathrm{relu}(z)$: every $z\ge0$ solves it) or none, and fixed-point iteration may fail to converge. Well-posedness is a condition on the weights (a contraction, or an LMI in Module 13), and it must hold before the layer's output means anything.

Practice — Recognise compositions, skip paths and recurrence

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S22 — Easy: A convolution as a sparse matrix

Use the common neural-network cross-correlation convention: apply kernel $(1,-1)$ to input $(1,2,3,4)$ with stride $1$, no padding and no bias. Find the output and a matrix implementing this map.

Review if needed: this section and operator norms.

Show hint
Each output is the first entry of a length-two window minus the second.
Show worked solution
  1. The windows are $(1,2)$, $(2,3)$ and $(3,4)$, giving output $(-1,-1,-1)$.
  2. The matrix is $W=\begin{bmatrix}1&-1&0&0\\0&1&-1&0\\0&0&1&-1\end{bmatrix}$. Multiplication by the input gives the same output.
  3. The repeated weights encode parameter sharing. Mathematical convolution reverses a kernel, so stating the convention matters; the dimensions here are three outputs from four inputs.
Exercise E.S23 — Medium: A residual norm bound need not be exact

For a scalar residual block $F(x)=x+g(x)$, compare the standard bound $L_F\le1+L_g$ with the exact Lipschitz constant when $g(x)=0.2x$ and when $g(x)=-0.8x$.

Review if needed: this section and operator norms.

Show hint
For the map $cx$, the exact Lipschitz constant is $|c|$. The norm bound ignores cancellation.
Show worked solution
  1. With $g(x)=0.2x$, $F(x)=1.2x$. Its exact constant is $1.2$, matching $1+0.2$.
  2. With $g(x)=-0.8x$, $F(x)=0.2x$, whose exact constant is $0.2$. The standard bound is instead $1+0.8=1.8$.
  3. Both bounds are valid. The second is loose because the two paths partially cancel. A skip connection does not automatically make a block contractive; the full combined map determines that property.
Exercise E.S24 — Hard: An equilibrium layer and a residual-based stopping rule

For constant input $x=2$, iterate $z_{k+1}=0.5z_k+x$ from $z_0=0$. Find the fixed point and the first three iterates. Use the residual at $z_3$ to certify its distance from the fixed point.

Review if needed: this section and operator norms.

Show hint
For a contraction with factor $q$, $|z-z_*|\le|F(z)-z|/(1-q)$.
Show worked solution
  1. The fixed point solves $z_*=0.5z_*+2$, so $z_*=4$. Iterates are $z_1=2$, $z_2=3$, $z_3=3.5$.
  2. At $z_3$, $F(z_3)=3.75$, giving residual $|3.75-3.5|=0.25$.
  3. The contraction factor is $q=0.5$, so the error is at most $0.25/(1-0.5)=0.5$, equal here to $|3.5-4|$. A small iteration residual needs this contraction argument before it becomes a guaranteed fixed-point error bound.

9. Classifiers, Margins & Adversarial Examples

Start here — Separate a margin, a certificate and an attack

The margin is the winning score's lead over its strongest rival. A Lipschitz certificate converts that lead into a radius in a specified input norm. Finding an adversarial input disproves robustness; failing to find one leaves the question open unless a valid certificate covers it.

When ready, try the Easy, Medium and Hard practice for this section. For a prerequisite gap, review norms and distances.

A classifier can be right on a test image and wrong on the same image with an invisible change of every pixel. Certified robustness asks for a proof that no change within a given size can alter the decision. The two ingredients are how far ahead the winning class is (the margin) and how fast the network can change (a Lipschitz bound).

Definition — Logits, prediction, margin; threat model
A classifier has a logit map $f:\mathbb R^n\to\mathbb R^K$ (one score per class) and predicts $C(x)=\operatorname*{arg\,max}_if_i(x)$. For a class $y$, the margin is $M_y(x)=f_y(x)-\max_{j\ne y}f_j(x)$; the prediction is $y$ (without a tie) exactly when $M_y(x)\gt0$. For the predicted class $c=C(x)$, $M(x):=M_c(x)\ge0$ says how far ahead the winner is. For two classes with one score, $C(x)=\mathrm{sign}f(x)$ and the margin is $|f(x)|$. A threat model fixes the allowed perturbations, typically a norm ball $\{\delta:\|\delta\|_p\le\epsilon\}$: in $\ell_2$ a bound on the total size of the change, in $\ell_\infty$ a bound on every pixel separately (e.g. $8/255$ for pixel values in $[0,1]$). An adversarial example is $x+\delta$ in the ball with $C(x+\delta)\ne C(x)$. Since $\|\delta\|_2\le\sqrt n\,\|\delta\|_\infty$ and $\|\delta\|_\infty\le\|\delta\|_2$, radii convert between the two norms at a dimension-dependent price (Primer A).

Example. Logits $(2.0,\,0.5,\,1.2)$: the prediction is class 1 with margin $2.0-1.2=0.8$; the softmax probabilities are $(0.598,\,0.133,\,0.269)$. A logit is a score, not a probability, and even the softmax output $0.598$ is not "the chance the prediction is right" unless the model has been calibrated.

Theorem — Certified radius from a Lipschitz bound
Binary case. Let $L\gt0$. If $f:\mathbb R^n\to\mathbb R$ satisfies $|f(x)-f(x')|\le L\|x-x'\|_2$ for all $x,x'$ and $f(x)\ne0$, then $\mathrm{sign}f(x+\delta)=\mathrm{sign}f(x)$ for every $\|\delta\|_2\lt|f(x)|/L$.
Proof. $|f(x+\delta)-f(x)|\le L\|\delta\|_2\lt|f(x)|$, so $f(x+\delta)$ cannot reach $0$. $\blacksquare$
Multiclass case. If the logit map is $L$-Lipschitz ($\ell_2$ on both sides), then $C(x+\delta)=C(x)$ for $\|\delta\|_2\lt M(x)/(\sqrt2\,L)$: each logit difference $f_c-f_j=(e_c-e_j)^{\top}f$ is $\sqrt2L$-Lipschitz because $\|e_c-e_j\|_2=\sqrt2$ (proof in Module 12).
If $L=0$, the logit map is constant, so the fixed tie convention gives the same prediction for every input. In words. Certified radius = margin divided by the worst possible slope. Why each assumption matters. $L$ must be a proven upper bound valid everywhere: a slope estimated from sampled gradients is a lower bound and certifies nothing. A bound twice too loose halves every radius. The radius lives in the norm, and the input space, in which $L$ was computed.

Worked example. For the 2-2-1 network of Section 7, ReLU slopes lie in $[0,1]$, so $L\le\|W_2\|\,\|W_1\|=\sqrt5\cdot\sqrt2=\sqrt{10}\approx3.162$ (spectral norms, Primer A). At $x=(2,1)$, $f=-1$: certified radius $1/\sqrt{10}\approx0.316$, and here the true distance to the decision boundary is also $0.316$, because the network's local slope $\|(-1,3)\|=\sqrt{10}$ equals the global bound. At $x=(0.5,2.5)$, $f=+1$: the same certified radius $0.316$, but the true distance is $0.707$, since the local slope is only $\|(1,1)\|=\sqrt2$. A global bound is valid everywhere but loose where the network is flat; a local Lipschitz constant on a ball around $x$ can certify more but must be recomputed for every input (Module 15). The explorer below shows the certified radius and a numerical estimate of the true distance for any point.

Definition — Clean, certified, robust and adversarial accuracy
For a test set $\{(x_i,y_i)\}_{i=1}^N$ and a threat set of radius $\epsilon$:
  • clean accuracy: the fraction with $C(x_i)=y_i$;
  • certified (robust) accuracy (CRA): the fraction for which $C(x_i)=y_i$ and a certificate proves $C(x_i+\delta)=y_i$ for every allowed $\delta$ (e.g. certified radius $\gt\epsilon$);
  • robust accuracy: the fraction for which $C(x_i+\delta)=y_i$ for every allowed $\delta$ is actually true (usually not computable);
  • adversarial accuracy: the fraction that survive a particular attack such as PGD.
For the same model, test points and threat set: certified $\le$ robust $\le$ adversarial $\le$ clean. CRA is a fraction of test examples, not the probability that a certificate is right: each certificate is a deterministic statement about one input.

Example. Five test points at $\epsilon=0.3$: four are classified correctly, with certified radii $0.5,\,0.2,\,0.4,\,0.1$; an attack breaks only the point with radius $0.1$. Clean accuracy $80\%$, certified accuracy $40\%$ (radii $0.5$ and $0.4$ exceed $\epsilon$), adversarial accuracy $60\%$; the true robust accuracy lies in $[40\%,60\%]$, because the point with radius $0.2$ survived the attack but is not certified.

Attacks and adversarial training. PGD (projected gradient ascent) maximises the loss over the ball: $\delta\leftarrow\Pi_{\{\|\delta\|\le\epsilon\}}\big(\delta+\eta\,s\big)$ with the ascent direction $s=\mathrm{sign}\big(\nabla_\delta\ell(f(x+\delta),y)\big)$ for $\ell_\infty$ (the projection clips each coordinate to $[-\epsilon,\epsilon]$) or the normalised gradient for $\ell_2$ (the projection rescales onto the ball). A successful attack is a counterexample; a failed one proves nothing, since a stronger attack may exist. Adversarial training (Madry et al., ICLR 2018) solves $\min_\theta\mathbb E\big[\max_{\|\delta\|\le\epsilon}\ell(f_\theta(x+\delta),y)\big]$ with the inner maximum approximated by PGD: it trains on approximately worst-case perturbations and raises adversarial accuracy, but, like weight penalties $\lambda\sum_k\|W_k\|_F^2$, it proves nothing. Certified training (training against bounds, Module 15) and Lipschitz-by-design architectures (Module 13) produce networks that come with certificates.

Input normalisation. Networks usually see $\tilde x=D^{-1}(x-m)$ with per-channel means $m$ and standard deviations $s$, $D=\mathrm{diag}(s)$ with every $s_c\gt0$. If $g$ is $L$-Lipschitz in normalised space, then $f(x)=g(D^{-1}(x-m))$ is $L\max_c(1/s_c)$-Lipschitz in pixel space, because $\|D^{-1}(x-x')\|\le\max_c(1/s_c)\,\|x-x'\|$. A radius certified in normalised space therefore shrinks by the factor $\min_cs_c$ in pixel space: for CIFAR-10's standard deviations of about $(0.247,0.243,0.261)$ the Lipschitz bound grows by $1/0.243\approx4.1$. Always state the input space of a radius.

Bound propagation (preview of Module 15). Push a whole set of inputs through the layers. Interval bound propagation uses boxes: if $x$ lies in the box with centre $c$ and half-widths $r$, then each coordinate of $Wx+b$ lies in $\big[Wc+b-|W|r,\ Wc+b+|W|r\big]$ ($|W|$ taken entrywise), and a monotone activation maps an interval $[a,b]$ to $[\varphi(a),\varphi(b)]$. If the lower bound of the margin over the input box is positive, every input in the box is classified correctly. For the worked network and the $\ell_\infty$ ball of radius $0.2$ around $(1,2)$: $v_1\in[1.6,2.4]\times[-1.4,-0.6]$, $z_1\in[1.6,2.4]\times\{0\}$ and $f\in[0.6,1.4]\gt0$: certified. The exact image of a box under an affine map is a zonotope $\{c+G\epsilon:\epsilon\in[-1,1]^m\}$ (generator matrix $G$), generally not a box; replacing it by its bounding box is where interval bounds lose tightness. Bounds are sound (never wrong) but may be too loose to certify a point that is in fact robust.

Where this is used
  • Logits, margins and the certified radius $M(x)/(\sqrt2L)$: Module 1 and Module 12; adversarial training: Module 12.
  • Normalisation and pixel-space radii, clean versus certified robust accuracy: Module 13; $\ell_2$ PGD attacks versus weight regularisation: Module 13.
  • PGD adversarial accuracy as an upper bound on certified accuracy, interval bounds and zonotopes: Module 15.
Pitfall — attack-based numbers overestimate robustness
An attack that finds nothing is not a proof. Reporting PGD accuracy as "robust accuracy" confuses an upper bound with the quantity itself; only a certificate (a proven Lipschitz bound, sound bound propagation, an exact verifier) gives a lower bound. Papers list both numbers side by side for this reason.

Practice — Separate a margin, a certificate and an attack

Easy checks the basic operation; Medium connects steps; Hard asks you to justify a conclusion or identify a limitation. Each solution explains why the steps work.

Exercise E.S25 — Easy: Read a multiclass margin

A classifier outputs logits $(3,1,0)$. Which class is predicted and what is its margin over the runner-up? Suppose a perturbation changes every logit by at most $0.4$ in absolute value. Prove that the prediction cannot change.

Review if needed: this section and norms and distances.

Show hint
The winning logit can decrease while a rival increases. Allow both changes in the gap.
Show worked solution
  1. Class $1$ wins with margin $3-1=2$.
  2. After the worst allowed changes, the gap to class $2$ is at least $2-0.4-0.4=1.2\gt0$.
  3. The gap to class $3$ is at least $3-0.8=2.2\gt0$. Thus class $1$ still strictly wins. This argument starts from a proved bound on logit changes; it does not yet say which input perturbations produce that bound.
Exercise E.S26 — Medium: State whether the boundary radius is included

A binary classifier uses the sign of $f(x)=2x+1$. At $x=1$, compute the Lipschitz-certified radius and the actual distance to the decision boundary. Does the certificate guarantee a strict positive score for perturbations of exactly that size?

Review if needed: this section and norms and distances.

Show hint
Use $f(x+\delta)\ge f(x)-L|\delta|$. A zero lower bound allows a tie.
Show worked solution
  1. The score is $f(1)=3$ and the exact Lipschitz constant is $L=2$, so the radius is $3/2=1.5$.
  2. The boundary solves $2x+1=0$, so it is at $x=-0.5$, distance $1.5$ from the input.
  3. For $|\delta|\lt1.5$, the lower score bound $3-2|\delta|$ is strictly positive. At $\delta=-1.5$, the score is zero. The open ball is certified; a closed ball at the same radius depends on the classifier's tie convention and is not a strict-sign guarantee.
Exercise E.S27 — Hard: Use certificates and attacks to bound robust accuracy

A multiclass logit map is globally $2$-Lipschitz in Euclidean norm, and one input has winning margin $1$. Find its standard certified radius. Separately, on a $100$-example test set at a fixed threat radius, $80$ are clean-correct, $50$ have valid correctness certificates, and attacks find adversarial failures on $10$ of the clean-correct examples. Bound the true robust accuracy.

Review if needed: this section and norms and distances.

Show hint
The margin radius is $M/(\sqrt2L)$. Certificates lower-bound robust correctness; found counterexamples upper-bound it.
Show worked solution
  1. The radius is $1/(2\sqrt2)\approx0.353553$, with strict class preservation for smaller perturbations.
  2. The $50$ valid certificates prove robust correctness on those examples, so true robust accuracy is at least $50\%$.
  3. The $20$ clean errors cannot be robust-correct because zero perturbation is allowed. Another $10$ have attack-found failures. Thus at most $70$ can be robust-correct, giving $50\%\le\text{robust accuracy}\le70\%$. An unsuccessful attack on the others does not certify them.

Interactive: Value Iteration & a Tiny Network

Two panels, both computed live. Panel A runs value iteration (Section 4) on a slippery cliff gridworld and reports how safe the greedy policy of the current iterate is. Panel B draws the 2-2-1 network of Section 7, its decision boundary, and the certified radius of Section 9 at a point you choose.

A. Value iteration on a cliff gridworld

Bottom row: start S, the cliff (entering it earns $-1$ and ends the episode) and the goal ($+1$, ends the episode). Every move also earns the step reward. With the slip probability the agent moves in one of the two perpendicular directions instead (half each); moving into a wall leaves it in place. Cells show $V_k$ and the greedy action for $V_k$ (green positive, red negative); the blue line follows the greedy arrows from S, ignoring slips. The fall and goal probabilities are exact absorption probabilities of the greedy policy's Markov chain (a linear system on the states from which the goal or the cliff can still be reached); any remaining probability is the chance of never terminating, for example of ending in a loop of arrows that push into walls.

What to look for (A).

  1. With the defaults, press "One sweep" repeatedly: the true error shrinks at least by the factor $\gamma$ per sweep and stays below both bounds; the arrows settle after about $11$ sweeps, long before the values stop changing.
  2. Stopping early is not harmless: after $6$ sweeps the greedy policy falls off the cliff with probability $0.21$, after convergence with $0.07$.
  3. Slip $0$: the optimal path hugs the cliff edge; slip $0.1$: it detours through the upper rows, trading length for safety.
  4. Step reward $-0.3$ and slip $0.3$: the optimal policy walks into the cliff (falls with probability $0.91$). When every step is expensive, ending the episode early is "optimal": a failure penalty enforces safety only if it is large compared with the rewards at stake, the threshold $p^\star$ of Module 7.
B. A 2-2-1 network: decision boundary, margin and certified radius

The network is $f(x)=W_2\varphi(s(W_1x+b_1))+b_2$ on $[-3,3]^2$. Blue: $f\gt0$, orange: $f\lt0$ (darker means larger $|f|$); black: the decision boundary $f=0$; dashed grey: the neuron lines where a pre-activation is $0$. Green disk: certified radius from the all-pattern bound; dotted green: from the product bound; dashed purple: a ray-search estimate of the distance to the boundary ($720$ directions up to distance $12$, then bisection). Each detected sign change brackets a boundary point. In exact arithmetic, distances to such points are upper bounds on the nearest-boundary distance; this finite ray search can miss thin or remote boundary pieces. The plotted bisection values are numerical estimates subject to rounding, and are not certificates; if no sign change is found, the readout says so. Click the plot to move $x$.

How the bounds are computed (B). The Jacobian of $f$ is $W_2\,\mathrm{diag}(\varphi'(v))\,sW_1$ with slopes $\varphi'\in[0,1]$ for ReLU and tanh. Its norm is a convex function of the slope vector, so over the box $[0,1]^2$ it is largest at a corner: the all-pattern bound $L=\max_{d\in\{0,1\}^2}\|W_2\,\mathrm{diag}(d)\,sW_1\|$, which the mean-value inequality along segments turns into a Lipschitz bound. The product bound $\|W_2\|\,\|sW_1\|$ is never smaller. For ReLU, when the two neuron lines cross, all four patterns occur as regions and the all-pattern bound is the exact Lipschitz constant.

What to look for.

  1. Worked example: at $x=(0.5,2.5)$ the certified radius is $0.316$ but the true distance $0.707$; move to $x=(2,1)$ and the two coincide (Section 9).
  2. The green disk never crosses the black curve, for any network, scale or activation: that is the theorem.
  3. Raising $s$ scales $L$ but also changes the margin $|f(x)|$, so the certified radius can grow, shrink or stay the same: at the default point, $s=1$ gives $0.316$ and $s=2$ gives $0.474$; compare both quantities.
  4. With tanh the boundary bends and the slopes vary continuously in $(0,1]$, but the all-pattern bound stays valid and, for invertible $W_1$, exact: the two pre-activations vary independently, so each corner slope pair is attained or approached (at $s=1$, $x=(0.5,0.5)$ both pre-activations vanish, the gradient is $(-1,3)$ and its norm is $L=\sqrt{10}$). A tanh network can also have no boundary at all: for the worked network with $b_2=3$, $f=3+\tanh v_1-2\tanh v_2\gt0$ for every input, whatever $s$, and the readout says so.
  5. Random networks: for the first ten seeds the product bound is $1$–$64\%$ above the all-pattern bound, the price of multiplying norms of layers that do not align (Module 12).

From the mathematics to a real decision

A learning system can make a plausible recommendation while missing the requirement that matters to an operator. We therefore begin with states, rewards and costs, evaluate a policy, and only then introduce a learned recommendation. The running case is a hypothetical packing machine whose faster mode increases wear. A second case asks whether a learned score remains consistent under sensor error. All probabilities, scores and budgets below are specified models, not empirical performance reports.

What you will learn to do
  • Evaluate delayed rewards and costs by conditioning on the next state.
  • Choose a policy parameter that respects a stated expected budget.
  • Turn physical measurement uncertainty into a bound on a neural decision score.
  • Explain why stable recommendations, accurate predictions and feasible policies are different claims.

Specify what a good policy should accomplish

A shift begins with the machine either ready, state $R$, or worn, state $W$. In $R$, gentle operation produces $2$ items during the shift and leaves the machine ready. Fast operation produces $4$ items, then leaves the machine worn with probability $0.25$ and ready with probability $0.75$. In $W$, the only action is repair: it produces zero items, costs one maintenance unit, and returns the machine to $R$ for the next shift.

Assume this two-state description is Markov: wear history does not change transition probabilities once the current state is known. Assume states are observed exactly and the specified probabilities remain constant. These choices make the calculations possible; a real process with hidden cumulative wear would need a richer state or an uncertainty model.

Consider a stationary randomised policy. Whenever the state is $R$, choose fast with probability $p$ and gentle with probability $1-p$, using a fresh draw. Repair whenever the state is $W$. The parameter $p\in[0,1]$ is a probability, not a speed setting. In $R$, expected immediate reward is $2(1-p)+4p=2+2p$ items, and the probability of next state $W$ is $0.25p$.

Start in $R$ and discount future shifts by $\gamma=0.8$. Let $J(p)$ be expected discounted production and $C(p)$ expected discounted maintenance use. Their units are items and maintenance units, respectively: discounting adds weights, not new physical units. The decision is to maximise $J(p)$ subject to $C(p)\le0.5$. This budget concerns an average over random trajectories and is not a ban on individual repairs.

Worked example 1 — Choose speed while accounting for delayed maintenance

Step 1: evaluate reward from each state. Write $V_R,V_W$ for expected discounted production when starting in each state. Repair gives no current production and returns to $R$, so $V_W=0.8V_R$. From $R$, average over the next state:

$$V_R=2+2p+0.8\big[(1-0.25p)V_R+0.25pV_W\big].$$

Substitute $V_W=0.8V_R$. The coefficient of $V_R$ on the right is $0.8-0.04p$. Moving it left gives $(0.2+0.04p)V_R=2+2p$, hence $J(p)=(2+2p)/(0.2+0.04p)$.

Step 2: evaluate cost separately. Write $C_R,C_W$ for expected discounted maintenance. In $W$, repair costs one now, so $C_W=1+0.8C_R$. In $R$, there is no immediate maintenance cost:

$$C_R=0.8\big[(1-0.25p)C_R+0.25pC_W\big],\qquad C(p)=C_R=\frac{0.2p}{0.2+0.04p}=\frac{p}{1+0.2p}.$$

The numerator $0.2p=0.8(0.25p)$ accounts for a repair occurring next shift after wear. Counting one maintenance unit immediately whenever fast is chosen would describe a different cost timeline.

Step 3: solve the budget inequality. The denominator is positive for $p\in[0,1]$, so multiplication preserves the inequality:

$$\frac{p}{1+0.2p}\le0.5\ \Longleftrightarrow\ p\le0.5+0.1p\ \Longleftrightarrow\ 0.9p\le0.5\ \Longleftrightarrow\ p\le\frac59.$$

Step 4: choose within the feasible range. Differentiating $J$ gives $J'(p)=0.32/(0.2+0.04p)^2\gt0$, so production increases with $p$. The best feasible parameter in this policy family is $p_*=5/9$. It yields $C(p_*)=0.5$ maintenance units and $J(p_*)=14$ items. Gentle operation alone gives $10$ discounted items; always fast gives $50/3\approx16.667$ items but maintenance cost $5/6\approx0.8333$, exceeding the budget.

This is an exact optimisation over the specified one-parameter policy family, with known transitions. Learning would enter if rewards or transitions had to be estimated, or if a larger policy were fitted from experience. The algebra supplies a baseline against which such a learned policy can be checked.

Common wrong approach — Optimise the immediate reward alone

Fast produces more items this shift, so an immediate-reward comparison always chooses it. That misses both the next shift lost to repair and the maintenance budget. Repair the argument by writing one Bellman equation for reward and another for cost, including their different immediate signals. A reward penalty can be a useful algorithmic device, but its coefficient does not replace checking the original budget.

Worked example 2 — Check a learned recommendation under sensor error

Suppose a learned system recommends between two fixed operating policies before an episode begins. Mode A uses $p_A=0.4$ and mode B uses $p_B=0.8$ throughout that episode. The choice is made once; within the selected mode, action draws remain fresh at each ready shift. Assume the transition model above applies to either choice regardless of the initial sensor reading.

A vibration measurement $y$, in millimetres per second, is normalised as $z=(y-2\ \mathrm{mm/s})/(1\ \mathrm{mm/s})$. Define the learned score difference

$$m(z)=1.2-0.6\operatorname{relu}(z+0.5)-0.4\operatorname{relu}(z-0.5),\qquad \operatorname{relu}(r)=\max\{0,r\}.$$

A positive score nominates B; a nonpositive score nominates A. The dimensionless score is a preference, not a failure probability or maintenance estimate.

Step 1: compute the nominal recommendation. At measured vibration $y_0=2$ mm/s, $z_0=0$. The hidden activations are $0.5$ and $0$, giving $m(0)=1.2-0.6(0.5)=0.9$. The learned system nominates B.

Step 2: bound the effect of measurement error. Assume a hard measurement bound $|y-y_0|\le0.2$ mm/s. Normalisation gives $|z-z_0|\le0.2$. ReLU changes by at most its input change, so the triangle inequality gives $|m(z)-m(z_0)|\le(0.6+0.4)|z-z_0|=|z-z_0|$. Thus $m(z)\ge0.9-0.2=0.7\gt0$ throughout the uncertainty interval. Direct evaluation gives the tighter minimum $m(0.2)=0.78$, confirming the bound is conservative.

Step 3: apply the original feasibility requirement. The robust recommendation is still B, but $C(0.8)=0.8/1.16=20/29\approx0.68966\gt0.5$. A gate that checks the original model budget rejects B and selects the feasible fallback A, whose cost is $C(0.4)=0.4/1.08=10/27\approx0.37037$. Its expected production is $J(0.4)=350/27\approx12.96296$ items.

Step 4: name the two conclusions. The score certificate guarantees that this fixed network's nomination stays B within the stated input interval. The cost calculation says A satisfies the model's expected budget. Robustness of the nomination does not make B feasible. If the selected mode changed during the episode, the gate would need to evaluate that switching policy; these two fixed-mode values would no longer be sufficient.

Test whether a changed policy still meets the stated requirement

Exercise E.B1 — Easy: Tighten the maintenance budget

Replace the discounted maintenance budget $0.5$ by $0.25$. Find the best $p$ in the same policy family and its expected discounted production.

Review: reward and cost Bellman equations; the constrained policy calculation.

Show hint

Use the already evaluated $C(p)$, solve the new inequality, and use the fact that $J$ increases with $p$.

Show worked solution

The budget requires $p/(1+0.2p)\le0.25$. Multiplying by the positive denominator gives $p\le0.25+0.05p$, hence $0.95p\le0.25$ and $p\le5/19$. The best feasible choice is $p=5/19\approx0.263158$. Its reward numerator is $2+10/19=48/19$ and denominator is $0.2+0.04(5/19)=4/19$, so $J=12$ items. Substitution gives maintenance cost exactly $0.25$ units.

Exercise E.B2 — Medium: Protect the budget against uncertain wear rates

Replace fast mode's wear probability $0.25$ by an unknown constant $\rho\in[0.2,0.3]$. Derive $C(p,\rho)$ and find the largest $p$ meeting the $0.5$ budget for every allowed $\rho$. Does $p=0.5$ pass?

Review: transition probabilities and policies; delayed maintenance cost.

Show hint

Replace $0.25p$ by $\rho p$ in the cost equations. The worst cost occurs at the largest product $\rho p$.

Show worked solution

Eliminating $C_W=1+0.8C_R$ gives $C(p,\rho)=0.8\rho p/(0.2+0.16\rho p)$. This increases with $\rho p$, because its derivative with respect to that product is $0.16/(0.2+0.16\rho p)^2\gt0$. At $\rho=0.3$, the budget becomes $0.24p\le0.1+0.024p$, so $p\le25/54\approx0.462963$. At $p=0.5$, worst-case cost is $0.12/0.224=15/28\approx0.535714$, so it fails. The conclusion is robust to this fixed interval of model parameters, provided that interval contains the actual wear probability; it says nothing about the statistical confidence of an estimated interval.

Exercise E.B3 — Hard: Include a sensor bias before certifying the nomination

At $y_0=2.8$ mm/s, suppose the total error is a bounded noise of magnitude at most $0.2$ mm/s plus a fixed unknown bias of magnitude at most $0.15$ mm/s. Is a positive nomination certified? If not, find an allowed input where the score is negative and the exact positive-direction distance to a tie.

Review: margins and input perturbations; the physical measurement model.

Show hint

Add the magnitudes to obtain a hard total bound. For $z\ge0.5$, both ReLUs are active, so simplify the score first.

Show worked solution

The nominal normalised input is $0.8$, with score $1.2-0.6(1.3)-0.4(0.3)=0.3$. Total input uncertainty is at most $0.35$ after normalisation, so the Lipschitz lower bound is $0.3-0.35=-0.05$, which is inconclusive for positivity. Here there is an actual flip: choosing both errors positive gives $z=1.15$ and score $-0.05$. For $z\ge0.5$, the score is $1.1-z$, so the tie is at $z=1.1$, or $y=3.1$ mm/s, only $0.3$ mm/s above the nominal reading. A closed uncertainty interval including that point cannot certify strict positivity. Repeated readings do not remove the fixed bias bound.

Exercise E.B4 — Hard: Translate the policy into long-run operating rates

For $p=5/9$ and wear probability $0.25$, find the stationary fraction of repair shifts and mean production per shift in stationarity. Compare the expected repairs in $20$ stationary shifts with the discounted budget $0.5$. Why are these different quantities?

Review: stationary distributions; return conventions; the operating model.

Show hint

Let $w$ be stationary probability of state $W$. Balance the next worn probability: $w=(1-w)(0.25p)$. Multiply per-shift means by $20$ only after specifying stationary initialisation.

Show worked solution

Here $0.25p=5/36$. Stationarity gives $w=(1-w)5/36$, hence $41w=5$ and $w=5/41\approx0.121951$. Repair occurs exactly in state $W$, so the mean repair rate is $5/41$ units per shift. Ready probability is $36/41$, giving production $(36/41)(2+10/9)=112/41\approx2.731707$ items per shift. Twenty stationary shifts have expected repairs $100/41\approx2.439024$. This does not contradict $C=0.5$: the latter starts in $R$ and discounts every future maintenance cost by $0.8^t$. The stationary twenty-shift expectation has a different initial law, horizon and weighting.

Keep the objective, model and certificate aligned

Reconstruct the cost Bellman equation without looking, explaining why repair's immediate cost is one while fast's immediate maintenance cost is zero. Then explain why a positive score is neither a probability nor a budget certificate, and why changing the units of the sensor input changes a physical robustness radius.

Learning changes how a policy or model is obtained. It does not change what must be checked: the stated objective, constraint, transition assumptions and deployment inputs. Continue to constrained MDPs to study policy optimisation with budgets, policy performance differences to evaluate updates, and network verification to replace a simple Lipschitz bound with more detailed input-region reasoning.

Exercises

These cumulative problems connect several ideas. If a step feels too large, return to the section practice route, where each topic has an Easy, Medium and Hard problem with a separate hint, worked solution and prerequisite review link.

Exercise E.1 — Discounted sums, horizons and time constants

Rewards satisfy $|r|\le2$ and $\gamma=0.95$. (a) Bound $|G|$ for every trajectory. (b) After how many steps does the weight $\gamma^T$ drop below $1\%$? (c) The discrete steps are samples every $0.1$ s of a continuous-time problem with weight $e^{-t/\tau}$. Which time constant $\tau$ (in seconds) corresponds to $\gamma=0.95$? (d) Bound the part of the return earned after the $T$ of (b).

Show answer

(a) $|G|\le\sum_t0.95^t\cdot2=2/0.05=40$.

(b) $0.95^T\le0.01\iff T\ge\ln100/\ln(1/0.95)\approx89.8$, so the first integer horizon is $T=90$ (check: $0.95^{89}\approx0.0104$, $0.95^{90}\approx0.0099$). Compare $1/(1-\gamma)=20$: about $4.6$ time constants.

(c) $\gamma=e^{-\Delta t/\tau}$ with $\Delta t=0.1$ s gives $\tau=-\Delta t/\ln\gamma=0.1/\ln(20/19)\approx1.95$ s, i.e. approximately $19.5$ steps, close to $1/(1-\gamma)=20$.

(d) $\big|\sum_{t\ge90}\gamma^tr_t\big|\le\gamma^{90}\cdot2/(1-\gamma)=40\cdot0.95^{90}\approx0.40$: the exact bound is below $0.40$, hence at most $1\%$ of the worst-case total. The displayed approximation is rounded from the exact bound, rather than obtained as an exact product of rounded inputs.

Exercise E.2 — Policy evaluation as a linear solve

For the uniform policy on the running example ($\gamma=0.9$): (a) write $P_\pi$ and $r_\pi$ and compute $N=(I-\gamma P_\pi)^{-1}$; check that its rows sum to $1/(1-\gamma)$. (b) Compute $V^\pi=Nr_\pi$ and the state occupancy $d^{\pi\top}=(1-\gamma)\mu^{\top}N$ for $\mu=(1,0)$. (c) Using the $Q^\pi$ values of Section 3, find the greedy policy $\pi'$ and verify $V^{\pi'}\ge V^\pi$ in both states.

Show answer

(a) $P_\pi=\begin{bmatrix}0.5&0.5\\0.5&0.5\end{bmatrix}$, $r_\pi=(0.5,\,1)$. Then $I-0.9P_\pi=\begin{bmatrix}0.55&-0.45\\-0.45&0.55\end{bmatrix}$ with determinant $0.55^2-0.45^2=0.1$, so $N=\frac1{0.1}\begin{bmatrix}0.55&0.45\\0.45&0.55\end{bmatrix}=\begin{bmatrix}5.5&4.5\\4.5&5.5\end{bmatrix}$. Rows sum to $10=1/(1-\gamma)$: $N(s,s')$ is the expected discounted number of visits to $s'$ from $s$.

(b) $V^\pi=(5.5\cdot0.5+4.5\cdot1,\ 4.5\cdot0.5+5.5\cdot1)=(7.25,\,7.75)$, as in Section 3. $d^\pi=0.1\cdot(5.5,\,4.5)=(0.55,\,0.45)$, the first row of $N$ normalised.

(c) $Q^\pi(1,\cdot)=(7.525,6.975)$ picks $a$; $Q^\pi(2,\cdot)=(6.525,8.975)$ picks $b$. So $\pi'$ rests at home and harvests in the field, $V^{\pi'}=(10,20)\ge(7.25,7.75)$ in both states, as the policy improvement theorem promises. It is not yet optimal ($V^\ast=(18,20)$): one more improvement step is needed (Section 4).

Exercise E.3 — When is it worth leaving home?

In the running example let the harvest reward be $h\gt0$ instead of $2$ (rest still pays $1$), with discount $\gamma\in(0,1)$. (a) Compute the value at home of the four deterministic stationary policies. (b) Show that leaving home is optimal if and only if $\gamma h\ge1$, and strictly better than staying if and only if $\gamma h\gt1$. (c) Interpret the condition. (d) With $h=2$ and the harvest cost $c=1$, for which $\gamma$ is "always harvest" both optimal and feasible for the budget $J_c\le4.5$?

Show answer

(a) Write a policy as (action at home, action in the field). $(a,a)$ and $(a,b)$ rest forever: $V(1)=1/(1-\gamma)$. $(b,b)$ goes and harvests forever: $V(1)=\gamma h/(1-\gamma)$. $(b,a)$ shuttles back and forth with reward $0$: $V(1)=0$.

(b) A finite discounted MDP has an optimal deterministic stationary policy (Section 3), so $V^\ast(1)=\max\{1/(1-\gamma),\,\gamma h/(1-\gamma),\,0\}$, and going is optimal exactly when $\gamma h/(1-\gamma)\ge1/(1-\gamma)$, i.e. $\gamma h\ge1$ (the shuttling policy, with value $0$, never wins). It is strictly better than resting exactly when $\gamma h\gt1$; at $\gamma h=1$ the two values coincide and both are optimal.

(c) Leaving costs one step of reward $1$ now and delivers $h$ per step from the next step on; everything after that is the same stream shifted by one step. The trade is worth it when the one-step-delayed gain $\gamma h$ beats the immediate $1$. For $h=2$ the threshold is $\gamma=0.5$ (a tie): a more myopic agent (effective horizon below $2$ steps) strictly prefers to stay home.

(d) $J_c=\sum_{t\ge1}\gamma^t=\gamma/(1-\gamma)\le4.5\iff\gamma\le4.5/5.5=9/11\approx0.818$. By (b) with $h=2$, harvesting is optimal for $\gamma\ge0.5$ (at $\gamma=0.5$ it ties with resting, and $J_c=1\le4.5$). So for $0.5\le\gamma\le9/11$ harvesting is optimal and feasible; for $\gamma\gt9/11$ the constrained optimum must mix, as in the occupancy example of Section 3 ($\gamma=0.9$, value $14$).

Exercise E.4 — The best baseline

One state, two actions, $\pi_\theta(1)=\sigma(\theta)=p$, reward $1$ for action $1$ and $0$ for action $0$. Consider $g_b=(r-b)\,\partial_\theta\log\pi_\theta(a)$ with $a\sim\pi_\theta$. (a) Show $\mathbb E\,g_b=p(1-p)$ for every $b$. (b) Find the $b$ that minimises $\mathrm{Var}\,g_b$ and the minimal variance. (c) Evaluate the variance at $p=0.8$ for $b=0$, $b=0.8$ and the optimal $b$. (d) Assume $\mathbb E[s]=0$, square integrability of $s$ and $rs$, and $\mathbb E[s^2]>0$. Show that the variance-minimising constant baseline is $b^\ast=\mathbb E[r\,s^2]/\mathbb E[s^2]$ with $s$ the score.

Show answer

(a) The scores are $s(1)=1-p$ and $s(0)=-p$, so $g_b=(1-b)(1-p)$ with probability $p$ and $g_b=bp$ with probability $1-p$. Then $\mathbb Eg_b=p(1-b)(1-p)+(1-p)bp=p(1-p)$: the $b$-terms cancel, as Step 5 of the walkthrough predicts.

(b) Since $\mathbb Eg_b$ does not depend on $b$, minimise $\mathbb Eg_b^2=p(1-b)^2(1-p)^2+(1-p)b^2p^2$. Its derivative is $2p(1-p)\big[-(1-b)(1-p)+bp\big]=2p(1-p)\big[b-(1-p)\big]$, zero at $b^\ast=1-p$. Then $g_{b^\ast}=p(1-p)$ for both actions: variance $0$.

(c) $p=0.8$: $b=0$ gives $g\in\{0.2,0\}$, variance $0.8\cdot0.04-0.16^2=0.0064$; $b=0.8$ gives $g\in\{0.04,0.64\}$, variance $0.8\cdot0.0016+0.2\cdot0.4096-0.0256=0.0576$; $b^\ast=0.2$ gives variance $0$. The average reward $0.8$ is nine times worse than no baseline.

(d) Under those assumptions, $\mathrm{Var}\,g_b=\mathbb E[(r-b)^2s^2]-(\mathbb Eg_b)^2$ and the second term does not depend on $b$; the first is the quadratic $\mathbb E[r^2s^2]-2b\,\mathbb E[rs^2]+b^2\,\mathbb E[s^2]$, minimised at $b^\ast=\mathbb E[rs^2]/\mathbb E[s^2]$. Here $\mathbb E[rs^2]=p(1-p)^2$ and $\mathbb E[s^2]=p(1-p)^2+(1-p)p^2=p(1-p)$, so $b^\ast=1-p$. Rewards are weighted by squared score: the rarely chosen action, whose score is large, dominates the baseline.

Exercise E.5 — The performance-difference lemma and a blind surrogate

Running example, $\gamma=0.9$, $\mu=(1,0)$. Let $\pi$ = rest everywhere and $\pi'$ = go and harvest everywhere. (a) Compute $Q^\pi$ and $A^\pi$. (b) Use the performance-difference lemma to compute $J(\pi')-J(\pi)$ and check it against the direct values. (c) Compute the surrogate $L_\pi(\pi')$, which uses $d^\pi$ instead of $d^{\pi'}$, and explain why it fails so badly here.

Show answer

(a) $V^\pi=(10,9)$ (rest forever; from the field, return once and rest). $Q^\pi(1,a)=1+0.9\cdot10=10$, $Q^\pi(1,b)=0.9\cdot9=8.1$, $Q^\pi(2,a)=0.9\cdot10=9$, $Q^\pi(2,b)=2+0.9\cdot9=10.1$. So $A^\pi(1,\cdot)=(0,-1.9)$ and $A^\pi(2,\cdot)=(0,\,1.1)$.

(b) $d^{\pi'}=(0.1,0.9)$ and $\pi'$ plays $b$: $J(\pi')-J(\pi)=10\,\big(0.1\cdot(-1.9)+0.9\cdot1.1\big)=10\cdot0.8=8=18-10$.

(c) $d^\pi=(1,0)$: the old policy never leaves home. In the sum form with the known advantages of (a), $L_\pi(\pi')=10+10\cdot\big(1\cdot(-1.9)\big)=-9$. The surrogate sees the cost of leaving home but none of the benefit of harvesting, because state 2 is outside the support of $d^\pi$. The importance-ratio form is not even available: $\pi'(b\mid1)=1\gt0=\pi(b\mid1)$ violates the support condition, and data from $\pi$ contain only action $a$ at home, where $A^\pi=0$, so their ratio-weighted average is $10+0=10$, blind to the $-1.9$ as well. No amount of data from $\pi$ can reveal what happens after leaving home. The same support problem makes off-policy evaluation and offline RL fail (Section 6), and it is why trust regions keep the new policy close to the one that generated the data.

Exercise E.6 — Clipped surrogates and GAE by hand

(a) With $\epsilon=0.2$, evaluate the clipped reward term $\min(\varrho\hat A,\mathrm{clip}(\varrho,0.8,1.2)\hat A)$ for $(\varrho,\hat A)=(1.3,1),(0.7,1),(0.7,-1),(1.3,-1)$ and say in which cases its derivative with respect to $\varrho$ is zero. (b) Evaluate the pessimistic cost term $\max(\varrho\hat A_c,\mathrm{clip}(\varrho,0.8,1.2)\hat A_c)$ for $(0.7,1)$ and $(1.3,-1)$. (c) An episode has rewards $0,0,1$ and then terminates; the critic gives $V=(0.5,0.6,0.8)$; $\gamma=0.9$. Compute the GAE advantages for $\lambda=0.5$, the $\lambda=1$ advantage at $t=0$, and the TD($0.5$) return $G_0^\lambda$.

Show answer

(a) $(1.3,1)$: $\min(1.3,1.2)=1.2$, the clipped branch, derivative $0$ (no incentive to raise the ratio further). $(0.7,1)$: $\min(0.7,0.8)=0.7$, the unclipped branch: a good action made less likely is charged in full and the gradient pushes $\varrho$ back up. $(0.7,-1)$: $\min(-0.7,-0.8)=-0.8$, clipped, derivative $0$ (the bad action is already $30\%$ less likely; no reward for going further). $(1.3,-1)$: $\min(-1.3,-1.2)=-1.3$, unclipped: a bad action made more likely is charged in full.

(b) $(0.7,1)$: $\max(0.7,0.8)=0.8$; $(1.3,-1)$: $\max(-1.3,-1.2)=-1.2$. In both cases the credit for a cost reduction is capped, so the cost estimate errs upwards.

(c) $\delta_0=0+0.9\cdot0.6-0.5=0.04$, $\delta_1=0+0.9\cdot0.8-0.6=0.12$, $\delta_2=1+0-0.8=0.2$ ($V=0$ after termination). With $\gamma\lambda=0.45$: $\hat A_2=0.2$, $\hat A_1=0.12+0.45\cdot0.2=0.21$, $\hat A_0=0.04+0.45\cdot0.21=0.1345$. For $\lambda=1$: $\hat A_0=0.04+0.9\cdot0.12+0.81\cdot0.2=0.31=0.81\cdot1-0.5$, the discounted return minus $V(s_0)$. And $G_0^\lambda=\hat A_0+V(s_0)=0.6345$ (Section 6).

Exercise E.7 — Soft values and the zero-temperature limit

Two actions with $Q=(0,1)$ in some state. (a) Compute $\mathrm{softmax}_\alpha(Q)$ and $\mathrm{LSE}_\alpha(Q)$ for $\alpha=0.5$ and $\alpha=1$, and check the bounds $\max Q\le\mathrm{LSE}_\alpha\le\max Q+\alpha\ln2$. (b) For $p=(\tfrac12,\tfrac12)$ and $\alpha=0.5$, verify the variational identity $p^{\top}Q+\alpha\mathcal H(p)=\mathrm{LSE}_\alpha(Q)-\alpha D_{\rm KL}(p\|\mathrm{softmax}_\alpha(Q))$ numerically. (c) What happens as $\alpha\to0$? (d) Why does a softmax policy with $\alpha\gt0$ conflict with hard safety constraints?

Show answer

(a) $\alpha=0.5$: $Q/\alpha=(0,2)$, $\mathrm{softmax}=(1,e^2)/(1+e^2)\approx(0.119,\,0.881)$, and $\mathrm{LSE}=0.5\ln(1+e^2)\approx1.0635$, with exact bounds $1\le\mathrm{LSE}\le1+0.5\ln2\approx1.3466$. $\alpha=1$: $\mathrm{softmax}=(1,e)/(1+e)\approx(0.269,\,0.731)$, and $\mathrm{LSE}=\ln(1+e)\approx1.3133$, with exact bounds $1\le\mathrm{LSE}\le1+\ln2\approx1.6931$.

(b) Left side: $0.5+0.5\ln2\approx0.8466$. Use the exact softmax atoms $p^*_0=1/(1+e^2)$ and $p^*_1=e^2/(1+e^2)$, giving $D_{\rm KL}=0.5\ln(0.5/p^*_0)+0.5\ln(0.5/p^*_1)\approx0.4338$. The exact identity is $0.5+0.5\ln2=0.5\ln(1+e^2)-0.5D_{\rm KL}$; both sides round to $0.8466$. The uniform $p$ falls short of the exact maximum $0.5\ln(1+e^2)\approx1.0635$ by $\alpha$ times its KL distance from the exact softmax law. The displayed rounded atoms and values are approximations, not inputs to the exact identity.

(c) $\mathrm{LSE}_\alpha(Q)\in[1,1+\alpha\ln2]$ tends to $\max Q=1$ and the softmax tends to $(0,1)$, the greedy policy: soft Bellman equations become the ordinary optimality equations. The gap is at most $\alpha\ln|\mathcal A|$.

(d) For every $\alpha\gt0$ each action has positive probability, including an action that leads to an unviable state; an agent that must never take such actions cannot use an unconstrained softmax policy. Module 7 studies how penalties and entropy interact with this.

Exercise E.8 — Global versus local certificates for the tiny network

For the worked 2-2-1 network of Section 7 and the input $x=(-2,0)$: (a) compute $v_1$, $z_1$, $f(x)$ and the certified $\ell_2$ radius from $L=\sqrt{10}$. (b) Show that the true distance to the decision boundary is $2\sqrt2$ (nearest boundary point $(0,2)$) and explain the gap. (c) Use interval bound propagation on the box $[-3,-1]\times[-1,1]$ to certify that every input in it is classified negative. What $\ell_2$ radius does this certify? (d) Suppose the network actually acts on normalised inputs $\tilde x=x/0.5$ (standard deviation $0.5$) and $(-2,0)$ is the normalised input. What pixel-space radius does the global certificate give?

Show answer

(a) $v_1=(-2+0-1,\,-2-0)=(-3,-2)$, $z_1=(0,0)$, $f=-1$: negative class, margin $1$, certified radius $1/\sqrt{10}\approx0.316$.

(b) Positive outputs occur only above the kinked boundary of Section 7. The branch $x_1+x_2=2$ with $x_1\le x_2$ is closest: the foot of the perpendicular from $(-2,0)$ is $(-2,0)+2\,(1,1)=(0,2)$, which lies on the branch, at distance $\sqrt{2^2+2^2}=2\sqrt2\approx2.83$; the other branch is farther. The certificate is about $9$ times too small because $L=\sqrt{10}$ is the slope of the steepest region (where both neurons are active), while around $(-2,0)$ both neurons are off and $f\equiv-1$ is flat.

(c) On the box, $v_{1,1}=x_1+x_2-1\in[-5,-1]$ and $v_{1,2}=x_1-x_2\in[-4,0]$, so both ReLUs output $0$ and $f=-1$ on the entire box: certified. The box is the $\ell_\infty$ ball of radius $1$ around $x$, and it contains the $\ell_2$ ball of radius $1$, so this local computation certifies $\ell_2$ radius $1$, a factor $\sqrt{10}\approx3.16$ above the global certificate.

(d) The map $x\mapsto x/0.5$ multiplies distances by $2$, so the composite is $2\sqrt{10}$-Lipschitz in pixel space and the pixel radius is $\frac{0.5}{\sqrt{10}}\approx0.158$. A radius must always be quoted with its input space.

Further Reading

Book / tutorialAuthors, publisher, yearRead it for
Reinforcement Learning: An IntroductionSutton, Barto; MIT Press, 2nd ed. 2018 (free PDF)The standard first course: bandits, MDPs, dynamic programming, TD learning and Q-learning, TD($\lambda$), policy gradients and actor–critic (Sections 1–6).
Markov Decision Processes: Discrete Stochastic Dynamic ProgrammingPuterman; Wiley, 1994The rigorous reference for Sections 3–4: optimality equations, existence of deterministic stationary optimal policies, value and policy iteration with stopping rules, average-reward criteria.
Reinforcement Learning: Theory and AlgorithmsAgarwal, Brantley, Jiang, Kakade, Sun; online draft monograph (continuously updated)Contraction arguments, occupancy measures, the performance-difference lemma, natural policy gradients and their softmax analysis: the theory behind Section 5 and Module 9.
Bandit AlgorithmsLattimore, Szepesvári; Cambridge University Press, 2020 (free online edition)Regret, the optimism principle and UCB (Ch. 7), EXP3 for adversarial bandits (Ch. 11), best-arm identification (Section 1).
Bayesian OptimizationGarnett; Cambridge University Press, 2023 (free online)GP surrogates, acquisition functions (EI, UCB, entropy search), multi-objective BO: the background of Modules 3–5.
A Tutorial on Bayesian OptimizationFrazier; arXiv, 2018A short route through GP regression, expected improvement and entropy search.
Spinning Up in Deep Reinforcement LearningAchiam; OpenAI, 2018 (online)Practical companion to Sections 5–6: the policy-gradient derivation, reward-to-go and baselines, and pages on VPG, TRPO, PPO, DDPG, TD3 and SAC with code.
Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open ProblemsLevine, Kumar, Tucker, Fu; arXiv, 2020Distribution shift, pessimism and conservative values, model-based offline RL: the background of Module 9's offline part.
Deep LearningGoodfellow, Bengio, Courville; MIT Press, 2016 (free online)Ch. 6 feedforward networks, activations, backpropagation and universal approximation; Ch. 7 regularisation and adversarial training; Ch. 9 convolutions; Ch. 10 recurrent networks (Sections 7–9).
Dive into Deep LearningZhang, Lipton, Li, Smola; Cambridge University Press, 2023 (free online)Runnable code for everything in Sections 7–8: MLPs and backpropagation, convolutions with padding, stride and channels, ResNets, RNNs and LSTMs, attention and transformers.

Flashcards