E. MDPs, Reinforcement Learning & Neural Networks
Policies, value functions, Bellman equations, policy gradients, and the neural networks inside them
This primer assumes a first course in linear algebra (matrices, linear systems, eigenvalues) and single-variable calculus, plus:
- Geometric series and discounting, $\sum_t\gamma^t=1/(1-\gamma)$ (Primer 0)
- Fixed points and fixed-point iteration (Primer 0)
- Expectation, conditional expectation and the tower rule (Primer C)
- Markov chains and transition matrices (Primer C)
- Entropy and KL divergence (Primer C)
- Gradients and the multivariable chain rule (Primer B)
- Gradient descent and stochastic gradients (Primer B)
- Vector and matrix norms, including $\|\cdot\|_\infty$ and the spectral norm (Primer A)
- Cost-to-go and dynamic programming for deterministic control (Primer D)
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.
- Decision foundations: Bandits, trajectories, Bellman values and iteration. Section practice: 1, 2, 3, 4.
- Learning methods: Policy gradients and modern RL updates. Section practice: 5, 6.
- Network foundations: Layers, architectures and robustness certificates. Section practice: 7, 8, 9.
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
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
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
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
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.
- 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
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)?
- 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^*$.
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$.
- 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$).
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.
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.
- Choose a GP prior (mean and kernel) for $f$; collect initial data if available.
- for $t=1,\dots,T$:
- condition the GP on the data: posterior $\mu_{t-1},\sigma_{t-1}$
- $x_t\in\operatorname*{arg\,max}_{x\in D}\alpha_t(x)$ // inner optimisation: cheap compared with an experiment
- run the experiment, observe $y_t=f(x_t)+\epsilon_t$, add $(x_t,y_t)$ to the data
- recommend $\hat x_T$, e.g. the maximiser of $\mu_T$ or of a lower confidence bound.
- 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$.
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
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.
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).
- Regret, no-regret and GP-UCB: "vanishing average regret" in Module 1; the GP-UCB regret bound in Module 3; simple versus cumulative regret, "a bad experiment only costs regret" in Module 4; dynamic regret for drifting objectives in Module 5; the "regret" readout of the Module 6 explorer is the simple regret of the recommendation.
- Optimism: SNO-MDP and ActSafe plan with upper confidence rewards (Module 6).
- Acquisitions, trust regions, grids and Pareto fronts: Module 4 (local trust regions), Module 4 (constrained EI, EHVI), Module 4 (constrained EI, information-theoretic safe BO), Module 5 (grids beyond $d\approx3$), return–cost fronts in Module 9, clean-versus-certified fronts in Module 15.
- Multiplicative weights and no-regret multipliers: Module 8 and Module 9.
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
Show worked solution
- The per-round regrets are $0$, $0.2$, $0.5$, $0.2$.
- The cumulative regret is $0.9$, and the average is $0.9/4=0.225$.
- 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
Show worked solution
- 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$.
- 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.
- 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
Show worked solution
- The learner earns $1+0=1$. Each fixed arm also earns total reward $1$, so static regret is $1-1=0$.
- The per-round best actions earn $1$ in each round, total $2$. Dynamic regret is $2-1=1$.
- 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
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.
- 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.
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).
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$:
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.
- 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).
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.
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.
- 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.
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
Show worked solution
- $G_0=2+0.5(4)+0.5^2(0)=4$.
- Starting at step $1$ gives $G_1=4+0.5(0)=4$, not $2$; the time origin has changed.
- 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
Show worked solution
- The expected next-state value after $a$ is $0.75(4)+0.25(0)=3$.
- Therefore $Q(s,a)=1+0.5(3)=2.5$. Immediate reward is not discounted; continuation value is.
- 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
Show worked solution
- Policy $A$ has expected count $0.01(100)+0.99(0)=1$. Policy $B$ also has expected count $1$.
- The probability of any violation is $0.01$ under $A$ and $1$ under $B$.
- 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
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.
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):
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
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.
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
- Linear evaluation: $J(\pi)=\frac1{1-\gamma}\sum_{s,a}\rho_\pi(s,a)\,r(s,a)$, and likewise $J_c$.
- 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')$.
- 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$).
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.
- $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.
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
Show worked solution
- The Bellman equation is $V=2+0.5V$.
- Subtracting $0.5V$ gives $0.5V=2$, hence $V=4$.
- 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
Show worked solution
- Substitution gives $V(A)=1+0.25V(A)$, so $V(A)=4/3$ and $V(B)=2/3$.
- The alternative's action-value uses the original policy after its first step: $Q(A,\text{stay})=0+0.5V(A)=2/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
Show worked solution
- The normalised action occupancy is $\rho(a)=p$, $\rho(b)=1-p$, because $(1-\gamma)\sum_t\gamma^t=1$.
- The reward return is $J=2p/0.2=10p$, and the cost return is $J_c=p/0.2=5p$.
- 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
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.
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).
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$
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.
- 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
- 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
- until $\|V_{k+1}-V_k\|_\infty\lt\epsilon(1-\gamma)/(2\gamma)$
- 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
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.
- $\|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.
- Start with any deterministic stationary policy $\pi_0$.
- for $k=0,1,2,\dots$:
- 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')$
- 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
- stop when $\pi_{k+1}=\pi_k$.
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
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.
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).
- 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.
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
Show worked solution
- The first backup is $V_1=2$.
- The next two are $V_2=2+0.5(2)=3$ and $V_3=2+0.5(3)=3.5$.
- 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
Show worked solution
- Let $e=\|V-V^*\|_\infty$. The triangle inequality and contraction give $e\le0.03+0.9e$.
- Thus $0.1e\le0.03$, so $e\le0.3$. A small residual is amplified by $1/(1-\gamma)$.
- 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
Show worked solution
- Model $A$ gives $V=1+V$, which has no finite solution. Starting at zero, value iteration gives $V_k=k$, diverging to infinity.
- 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.
- 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
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$.
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).
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
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)$.
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.
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.
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$.
- 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.
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
Show worked solution
- $J=4p=1$, and $dJ/d\theta=4p(1-p)=4(1/4)(3/4)=3/4$.
- For action $a$, $d\log p/d\theta=(dp/d\theta)/p=1-p=3/4$.
- 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
Show worked solution
- Subtract the value from each action-value: $A(a)=4-1=3$ and $A(b)=0-1=-1$.
- 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$.
- 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
Show worked solution
- $F^{-1}g=(1/2,1)$ and $g^\top F^{-1}g=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)$.
- 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
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.
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.
- 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
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]$.
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.
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.
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 support | the pairs $(s,a)$ that $\pi_\beta$ takes with positive probability; outside it every value is an extrapolation |
| Expectile regression | fit $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 score | a 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 transformer | a 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 policy | a 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).
- 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.
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
Show worked solution
- The target is $1+0.9(2)=2.8$.
- The temporal-difference error is $2.8-0.5=2.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
Show worked solution
- The softmax probabilities are $(1/(1+3),3/(1+3))=(1/4,3/4)$.
- The soft value is $\ln4\approx1.386294$, whereas the largest action-value is $\ln3\approx1.098612$.
- 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
Show worked solution
- 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$.
- Disagreement contributes one part of uncertainty in this model mixture; it is not a bound on true model error.
- 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
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.
Worked example (used throughout Sections 7–9 and in the explorer). The 2-2-1 ReLU network with
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 / GroupSort | sorts pairs (groups) of coordinates, $(u,w)\mapsto(\max\{u,w\},\min\{u,w\})$ | locally a permutation matrix | not 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.
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.
- 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}$:
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.
- 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.
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
Show worked solution
- At $(1,3)$, the pre-activation is $2(1)-3+0.5=-0.5$, so the output is $0$.
- At $(2,1)$, it is $2(2)-1+0.5=3.5$, so the output is $3.5$.
- $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
Show worked solution
- 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$.
- The output derivative is $2$. Therefore $\partial\ell/\partial w=2z=2$ and the derivative through the hidden pre-activation is $2w=6$.
- 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
Show worked solution
- 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$.
- For either sign of $x$, $\operatorname{ReLU}(x)-\operatorname{ReLU}(-x)=x$. Its exact global Lipschitz constant is $1$.
- 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
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.
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.
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.
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
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.
- 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.
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
Show worked solution
- The windows are $(1,2)$, $(2,3)$ and $(3,4)$, giving output $(-1,-1,-1)$.
- 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.
- 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
Show worked solution
- With $g(x)=0.2x$, $F(x)=1.2x$. Its exact constant is $1.2$, matching $1+0.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$.
- 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
Show worked solution
- The fixed point solves $z_*=0.5z_*+2$, so $z_*=4$. Iterates are $z_1=2$, $z_2=3$, $z_3=3.5$.
- At $z_3$, $F(z_3)=3.75$, giving residual $|3.75-3.5|=0.25$.
- 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
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).
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.
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.
- 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.
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.
- 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.
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
Show worked solution
- Class $1$ wins with margin $3-1=2$.
- After the worst allowed changes, the gap to class $2$ is at least $2-0.4-0.4=1.2\gt0$.
- 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
Show worked solution
- The score is $f(1)=3$ and the exact Lipschitz constant is $L=2$, so the radius is $3/2=1.5$.
- The boundary solves $2x+1=0$, so it is at $x=-0.5$, distance $1.5$ from the input.
- 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
Show worked solution
- The radius is $1/(2\sqrt2)\approx0.353553$, with strict class preservation for smaller perturbations.
- The $50$ valid certificates prove robust correctness on those examples, so true robust accuracy is at least $50\%$.
- 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.
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).
- 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.
- Stopping early is not harmless: after $6$ sweeps the greedy policy falls off the cliff with probability $0.21$, after convergence with $0.07$.
- Slip $0$: the optimal path hugs the cliff edge; slip $0.1$: it detours through the upper rows, trading length for safety.
- 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.
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.
- 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).
- The green disk never crosses the black curve, for any network, scale or activation: that is the theorem.
- 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.
- 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.
- 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.
- 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:
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:
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:
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.
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
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.
Further Reading
| Book / tutorial | Authors, publisher, year | Read it for |
|---|---|---|
| Reinforcement Learning: An Introduction | Sutton, 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 Programming | Puterman; Wiley, 1994 | The 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 Algorithms | Agarwal, 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 Algorithms | Lattimore, 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 Optimization | Garnett; 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 Optimization | Frazier; arXiv, 2018 | A short route through GP regression, expected improvement and entropy search. |
| Spinning Up in Deep Reinforcement Learning | Achiam; 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 Problems | Levine, Kumar, Tucker, Fu; arXiv, 2020 | Distribution shift, pessimism and conservative values, model-based offline RL: the background of Module 9's offline part. |
| Deep Learning | Goodfellow, 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 Learning | Zhang, 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. |