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
Plan. List every possible outcome with its probability, then form the probability-weighted sum of the rewards.
Step 1 — list the outcomes. There are exactly two possible choices. Action $a$ happens with probability $1/4$ and pays $4$; action $b$ happens with probability $3/4$ and pays $0$. The probabilities add to $1/4+3/4=1$, so no outcome is missing.
Step 2 — apply the definition of expectation. For a random reward $R$ taking finitely many values, $\mathbb E[R]=\sum(\text{value})\times(\text{probability of that value})$. Here
Step 3 — compare with a single run. One run performs one choice, so its reward is either $4$ (if $a$ was drawn) or $0$ (if $b$ was drawn). Neither of these equals $1$, so no individual run can earn the expected reward.
Check. Over many independent runs, about one quarter earn $4$ and three quarters earn $0$; for $100$ runs that is about $25\cdot4=100$ in total, an average of $100/100=1$ per run. This matches Step 2, and $1$ lies between the smallest and largest possible rewards, as an average must.
Interpretation. The expectation is a probability-weighted average, not a value any single run is promised. 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 reward at time $t$ is $2$ and its discount weight is $(1/2)^t$, so the first terms are $2,1,1/2,1/4,\ldots$. For $T\ge1$, let $S_T=1+1/2+\cdots+(1/2)^{T-1}$. Then $S_T/2=1/2+\cdots+(1/2)^T$. Subtracting cancels the common terms:
Multiplying by the reward $2$ gives the discounted partial return $2S_T=4(1-2^{-T})$. The same formula gives zero for $T=0$, consistent with an empty sum. Since $2^{-T}\to0$, the infinite return is $4$. This also equals $2/(1-1/2)$ by the geometric-series formula.
Without discounting, $T$ rewards of $2$ would sum to $2T$, which grows without bound. The finite infinite-horizon value here depends on the discount ratio being strictly below $1$.
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
For $f_\theta(x)=\theta x$, with $\theta=3$ and $x=2$, the output is $3(2)=6$. A partial derivative changes one argument while holding the other fixed.
Hold the input at $2$ and change the parameter by $\Delta\theta$. Then $f_{3+\Delta\theta}(2)=6+2\Delta\theta$. Dividing its change by $\Delta\theta\ne0$ gives $2$, so $\partial f/\partial\theta=x=2$.
Hold the parameter at $3$ and change the input by $\Delta x$. Then $f_3(2+\Delta x)=6+3\Delta x$. Dividing by $\Delta x\ne0$ gives $3$, so $\partial f/\partial x=\theta=3$.
The first derivative describes how a parameter update changes the output at this input. The second describes sensitivity to an input change for this fixed model. Backpropagation can compute both, but they answer different questions. Because this model is linear in each argument separately, these single-argument changes are exact, rather than merely first-order approximations.
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
Plan. Find the best mean, measure each round's shortfall from it, then add (cumulative), divide by the number of rounds (average), and separately score only the final recommendation (simple regret).
Step 1 — identify the benchmark. Regret compares with the best arm's true mean, $\mu^*=\max\{0.8,0.6,0.3\}=0.8$ (arm $1$). Writing $\mu_k$ for arm $k$'s mean, the regret of pulling arm $k$ once is $\mu^*-\mu_k\ge0$.
Step 2 — per-round regrets. The pulls are arms $1,2,3,2$, so
Step 3 — cumulative and average regret. Cumulative regret after $T=4$ rounds is the sum of the per-round regrets, and average regret divides that sum by $T$:
Step 4 — simple regret. Simple regret looks only at the recommended arm, here arm $3$, and ignores how the learner explored: $\mu^*-\mu_3=0.8-0.3=0.5$.
Check. Every per-round regret is between $0$ and the largest possible gap $0.8-0.3=0.5$, so the average $0.225$ must lie in $[0,0.5]$, which it does. Equivalently, $R_4=4(0.8)-(0.8+0.6+0.3+0.6)=3.2-2.3=0.9$.
Interpretation. A low cumulative average and a good final recommendation are different goals: this learner wasted only $0.225$ per round on average, yet its recommendation is the worst arm. Regret uses the true means; observed noisy payoffs would not replace them 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
Plan. Turn each estimate and radius into an interval $[\text{estimate}-\text{radius},\ \text{estimate}+\text{radius}]$. Use the top of the reward interval for optimism and the bottom of the safety interval for caution.
Step 1 — reward upper confidence bounds. If the confidence statement holds, the true mean reward of action $i$ is at most $\hat r_i+\beta_i$. The optimistic (UCB) value is therefore
Since $0.7\gt0.65$, an unconstrained optimistic rule chooses action $1$, even though its point estimate is lower. Its wide interval leaves room for a higher true reward.
Step 2 — safety lower confidence bounds. Safety requires the true safety value $g_i\ge0$. Under the same confidence statement, $g_i\ge\hat g_i-\beta^g_i$, so
Action $2$ has $g_2\ge0.1\ge0$, so it is certified safe. For action $1$, the interval $[-0.1,0.7]$ contains negative values, so the data cannot rule out a violation.
Step 3 — combine the two rules. A safe optimistic rule maximises the reward UCB only over certified actions. The certified set is $\{2\}$, so it chooses action $2$, with UCB $0.65$.
Check. The two rules use opposite ends of their intervals: optimism adds the radius ($+$), caution subtracts it ($-$). Action $1$'s large radius helps it in Step 1 and hurts it in Step 2, which is why the choices differ.
Interpretation. Action $1$ is uncertified, which does not prove it unsafe; its true safety value could be anywhere in $[-0.1,0.7]$. The whole conclusion is conditional on the reward and safety 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
Plan. Compute the learner's total reward, then the total of each comparator, and take differences: regret $=$ comparator total $-$ learner total.
Step 1 — learner's total. The learner picks $A$ in both rounds, so it collects $A$'s rewards: $1+0=1$.
Step 2 — static comparator (best fixed arm). A fixed arm is one arm used in every round. Its totals are
The best fixed total is $\max\{1,1\}=1$, so static regret is $1-1=0$.
Step 3 — dynamic comparator (best arm each round). Here the comparator may switch. Round $1$'s best reward is $\max\{1,0\}=1$ (arm $A$) and round $2$'s is $\max\{0,1\}=1$ (arm $B$), total $1+1=2$. Dynamic regret is $2-1=1$.
Check. A per-round maximum is at least the reward of any fixed arm in that round, so the dynamic total can never be below the static one; here $2\ge1$, consistent. Both regrets are nonnegative because the learner's choice is one of the options each comparator could have made.
Interpretation. The comparators differ because the best arm changes between rounds, and only the dynamic comparator is allowed to follow that change. A no-regret claim must therefore name its comparator; vanishing average static regret does not ensure tracking of a 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
Plan. Use the definition $G_t=\sum_{k\ge0}\gamma^kr_{t+k}$, where the first reward counted gets weight $\gamma^0=1$, and stop at termination.
Step 1 — return from time $0$. The rewards from time $0$ are $2,4,0$ with weights $1,\ 0.5,\ 0.5^2=0.25$:
Step 2 — return from time $1$. Now the clock restarts at step $1$: reward $r_1=4$ gets weight $1$ and $r_2=0$ gets weight $0.5$:
It is not $2$: the reward $4$ is not discounted here, because it is the first reward counted from this new time origin.
Step 3 — verify the recursion. Factor $\gamma$ out of every term of $G_0$ after the first:
This matches Step 1.
Check. All rewards are nonnegative and $\gamma\lt1$, so $G_0$ must lie between $r_0=2$ and the undiscounted sum $2+4+0=6$; indeed $2\le4\le6$.
Interpretation. Splitting a return into "first reward plus discounted rest" is exactly the step that produces Bellman equations once conditional expectations are taken.
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
Plan. Average over the random next state to get $Q(s,a)$; then average over the random action to get $V(s)$.
Step 1 — expected next-state value after $a$. After $a$, the next state has value $4$ with probability $0.75$ and value $0$ with probability $0.25$ (these sum to $1$). Its expectation is
Step 2 — action-value of $a$. The Bellman equation for $Q$ adds the immediate reward to the discounted expected continuation:
The immediate reward is received now and is not discounted; only the continuation, which starts one step later, is multiplied by $\gamma$.
Step 3 — state value under the policy. $V(s)$ is the policy-weighted average of the action-values, $V(s)=\sum_a\pi(a\mid s)Q(s,a)$, with $Q(s,b)=1$ given:
Check. An average lies between its extremes: $1.9$ is between $Q(s,b)=1$ and $Q(s,a)=2.5$, and closer to $2.5$ because $a$ has the larger probability $0.6$.
Interpretation. The two averages correspond to two separate random choices: the selected action (from the policy) and the next state (from the environment).
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
Plan. Write the total violation count of each policy as a random variable with its possible values and probabilities, then compute (i) its mean and (ii) the probability that it is at least $1$.
Step 1 — describe policy $A$'s count. Read as stated, policy $A$ has two kinds of trajectory: with probability $0.01$ it violates at every one of the $100$ steps (count $100$), and with probability $0.99$ it never violates (count $0$).
Step 2 — expected total cost. With cost $1$ per violation and no discount, the total cost equals the count. Its expectation is
because policy $B$ has count exactly $1$ with probability $1$.
Step 3 — probability of any violation. "Any violation" is the event $C\ge1$. For $A$ this happens only on the bad trajectory, so $\Pr(C_A\ge1)=0.01$. For $B$ it always happens, so $\Pr(C_B\ge1)=1$.
Check. Markov's inequality, $\Pr(C\ge1)\le\mathbb E[C]/1=1$, is satisfied by both, and it is tight for $B$. If one instead read $A$ as violating independently with probability $0.01$ at each step, the mean is unchanged, $100(0.01)=1$, while $\Pr(C_A\ge1)=1-0.99^{100}\approx0.634$: still a different failure probability from $B$, so the conclusion does not depend on that reading.
Interpretation. The same expected cumulative cost allows very different trajectory-level failure probabilities. An expectation-constrained MDP must say 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
Plan. Write the value as "reward now plus discounted value of where you land", solve that linear equation, then recompute the value directly as a discounted sum.
Step 1 — write the Bellman equation. From the single state, the policy earns $2$ and lands in the same state, whose value is again $V$. The continuation starts one step later, so it is multiplied by $\gamma=0.5$:
Step 2 — solve it. Subtract $0.5V$ from both sides (allowed because $V$ is a finite number here, as Step 3 confirms), then divide by $0.5$:
Step 3 — verify with the geometric series. The return is $2$ at every time $t$ with weight $0.5^t$. Since $|0.5|\lt1$, the geometric series $\sum_{t=0}^\infty q^t=1/(1-q)$ applies with $q=0.5$:
Check. Substitute back: $2+0.5(4)=2+2=4$. The partial sums $2,\ 3,\ 3.5,\ldots$ approach $4$ from below, as they must for positive rewards.
Interpretation. The fixed-point equation and the whole-trajectory sum describe the same quantity, one from a local one-step viewpoint and one from the full trajectory.
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
Write one equation from each starting state. Under the stated policy, leaving $A$ earns $1$ and moves to $B$, while leaving $B$ earns $0$ and moves to $A$. The future return starts one step later, so it receives the factor $\gamma=0.5$:
Substitute the second equation into the first, then solve:
Evaluate the alternative only at the first step. The action-value $Q$ uses the specified alternative now, then returns to the original alternating policy. Its immediate reward is $0$ and its next state is $A$, so $Q(A,\text{stay})=0+\tfrac12V(A)=2/3$. Subtract the original value at the same state:
The negative advantage means that staying once and then resuming the original policy loses $2/3$ of discounted return. It is not the value of staying forever; that different policy would keep receiving zero.
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
Plan. Compute the discounted frequency of each action, express both returns as linear functions of $p$, then solve the one-variable constrained maximisation.
Step 1 — normalised occupancy. The normalised discounted occupancy of action $u$ is $\rho(u)=(1-\gamma)\sum_{t=0}^\infty\gamma^t\Pr(a_t=u)$. There is only one state and the policy is stationary, so $\Pr(a_t=a)=p$ and $\Pr(a_t=b)=1-p$ at every $t$. Using $\sum_t\gamma^t=1/(1-\gamma)$ for $0\le\gamma\lt1$:
They are nonnegative and sum to $1$, as a probability distribution must.
Step 2 — reward and cost returns. The expected reward at each step is $\mathbb E[r_t]=p(2)+(1-p)(0)=2p$, and the expected cost is $\mathbb E[c_t]=p(1)+(1-p)(0)=p$. Summing with weights $0.8^t$ and $\sum_t0.8^t=1/(1-0.8)=5$:
Equivalently, $J=\frac1{1-\gamma}\sum_u\rho(u)r(u)=5\,(2p)=10p$: once the occupancy is known, the return is just a weighted sum.
Step 3 — impose the budget. The constraint $J_c\le2$ is $5p\le2$, i.e. $p\le0.4$. Together with $0\le p\le1$ (it is a probability), the feasible set is $[0,0.4]$.
Step 4 — maximise. $J(p)=10p$ is increasing in $p$ (slope $10\gt0$), so its maximum over $[0,0.4]$ is at the right endpoint $p^*=0.4$:
Check. The budget is met with equality, as expected when the objective increases along the constraint. Limiting cases: $p=0$ gives $J=J_c=0$; $p=1$ would give $J=10$ but $J_c=5\gt2$, infeasible.
Interpretation. The occupancy turns the constrained problem into a linear program in $p$. The optimal policy is randomised: it 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
Both actions return to the same state, so they have exactly the same continuation value. The optimal Bellman backup is therefore
The second expression exceeds the first by $1$ for every $V$, which justifies using the reward-$2$ action in all three backups. Starting at $V_0=0$ gives
The optimal value is the fixed point of this backup. Solving $V_*=2+0.5V_*$ gives $0.5V_*=2$, hence $V_*=4$. The same value follows from earning $2$ forever: $2/(1-0.5)=4$.
The errors at indices $0,1,2,3$ are $4,2,1,0.5$. More generally, subtracting the fixed-point equation gives $V_{k+1}-4=0.5(V_k-4)$, so $|V_k-4|=4(0.5)^k$. Each backup halves the error; the iterate itself and its remaining error are different quantities.
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
Use the residual as one side of a triangle. For a finite discounted MDP, $\mathcal T^*$ is a $0.9$-contraction in the sup norm and $V^*=\mathcal T^*V^*$. Write $e=\|V-V^*\|_\infty$ and insert $\mathcal T^*V$ between the two vectors:
The first inequality is the triangle inequality; the second uses the measured residual and contraction. Subtracting $0.9e$ gives $0.1e\le0.03$, so $e\le0.3$.
Solve for the residual needed by the new target. If the residual is $r$ instead, the same argument gives $e\le r/(1-0.9)=10r$. Therefore $r\le0.01$ is sufficient for $e\le0.1$, since $10(0.01)=0.1$. The factor $1/(1-\gamma)$ explains why a residual of $0.03$ does not mean a value error of $0.03$.
This is a guarantee about the whole value vector under the stated Bellman operator. A guarantee about the return of its greedy policy requires a policy-performance bound as well.
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$: a reward on every visit forever. There is no terminal continuation to remove. Its Bellman equation is $V=1+V$, which would imply $0=1$ if $V$ were finite. Thus there is no finite value solution. Starting from $V_0=0$, the backup is $V_{k+1}=1+V_k$, giving $0,1,2,3,\ldots$ and, by induction, $V_k=k$. These iterates and the infinite undiscounted return diverge to $+\infty$.
Model $B$: reward now, then possibly terminate. The current visit earns $1$ regardless of what happens next. With probability $1/2$ another visit follows and with probability $1/2$ the terminal state's continuation is zero. Therefore
From zero, value iteration gives $V_{k+1}=1+\tfrac12V_k$, so the first values are $0,1,3/2,7/4$. Iterating the recurrence sums a geometric series:
The same sum has a trajectory interpretation. To receive the reward on visit $j+1$, the process must survive $j$ previous transitions, with probability $(1/2)^j$. Summing these expected rewards gives $2$. The probability of surviving forever is zero.
The backup in model $B$ contracts by $1/2$ because only half of the next-state probability remains nonterminal. This factor comes from termination, even though there is no discount. Model $A$ has no such structure. One must check the model's termination or other uniqueness assumptions before using an undiscounted Bellman equation.
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
Plan. Write $J$ as a function of $p$, find $dp/d\theta$ once, and then use the chain rule for $J$ and for each log-probability.
Step 1 — the objective. The expected reward is $J=p(4)+(1-p)(0)=4p$. At $p=1/4$ this is $J=1$.
Step 2 — derivative of the sigmoid. Write $p=\sigma(\theta)=(1+e^{-\theta})^{-1}$. The chain rule (outer function $u^{-1}$, inner $u=1+e^{-\theta}$ with $du/d\theta=-e^{-\theta}$) gives
because $1-p=\dfrac{(1+e^{-\theta})-1}{1+e^{-\theta}}=\dfrac{e^{-\theta}}{1+e^{-\theta}}$. At $p=1/4$: $dp/d\theta=(1/4)(3/4)=3/16$.
Step 3 — gradient of $J$. By the chain rule, $\dfrac{dJ}{d\theta}=\dfrac{dJ}{dp}\dfrac{dp}{d\theta}=4\cdot\dfrac{3}{16}=\dfrac34$.
Step 4 — score of action $a$. Using $\dfrac{d}{d\theta}\log u=\dfrac{u'}{u}$ (valid since $p\gt0$):
Step 5 — score of action $b$. Action $b$ has probability $1-p\gt0$, whose derivative is $-p(1-p)$:
Check. The policy-weighted mean of the scores is $\tfrac14\cdot\tfrac34+\tfrac34\cdot(-\tfrac14)=\tfrac3{16}-\tfrac3{16}=0$, the score identity. The score-function formula also reproduces Step 3: $\tfrac14\cdot4\cdot\tfrac34+\tfrac34\cdot0\cdot(-\tfrac14)=\tfrac34$. (Here $p=1/4$ corresponds to $\theta=\ln(1/3)\approx-1.0986$.)
Interpretation. The parameter $\theta$ is not an action: it shifts probability between the two actions. Raising $\theta$ makes $a$ more likely (positive score) and $b$ less likely (negative score), and the zero-mean score is what later allows a baseline to be subtracted.
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
Plan. Form the advantages $A=Q-V$, then average "advantage $\times$ score" over the two actions with the policy probabilities, and compare with $dJ/d\theta=3/4$ from the previous exercise.
Step 1 — advantages. In a one-step bandit the action-value is the reward: $Q(a)=4$, $Q(b)=0$. The baseline $V=1$ equals $J$, the policy's expected reward. Subtracting it:
As a check, the expected advantage is $\tfrac14(3)+\tfrac34(-1)=0$, which holds because the baseline is exactly the mean reward.
Step 2 — recall the scores. From the previous exercise, at $p=1/4$: score of $a$ is $3/4$ and score of $b$ is $-1/4$.
Step 3 — the baselined gradient estimate's mean. Weight each action's product by its probability:
Step 4 — compare with the direct derivative. The direct derivative was $dJ/d\theta=4p(1-p)=3/4$. They agree.
Check (why they must agree). Since $A=Q-V$ with constant $V$, $\mathbb E[A\,\text{score}]=\mathbb E[Q\,\text{score}]-V\,\mathbb E[\text{score}]$, and $\mathbb E[\text{score}]=0$ (previous exercise). So the baseline term contributes $1\cdot0=0$: here $\mathbb E[Q\,\text{score}]=\tfrac14\cdot4\cdot\tfrac34=\tfrac34$ and the baseline removes nothing from the mean.
Interpretation. Subtracting the baseline changes the individual sample weights (e.g. $b$'s sample now has weight $(-1)(-\tfrac14)=+\tfrac14$ instead of $0$) but not their expected gradient, because the expected score is zero. That argument used that $V$ does not depend on the action; 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
Write the local optimisation in coordinates. Here $g^\top\Delta=2\Delta_1+\Delta_2$ and $\Delta^\top F\Delta=4\Delta_1^2+\Delta_2^2$. Introduce $v=(2\Delta_1,\Delta_2)$. The constraint becomes $\|v\|_2^2\le0.1$ and the objective becomes $v_1+v_2=(1,1)^\top v$.
By Cauchy–Schwarz, $(1,1)^\top v\le\sqrt2\,\|v\|_2\le\sqrt{0.2}$. Equality requires $v$ to be a positive multiple of $(1,1)$ and to use the full allowed norm. Thus $v_1=v_2=\sqrt{0.05}$, which gives the maximising step
Check it in the original coordinates. The natural direction is $F^{-1}g=(2/4,1)=(1/2,1)$ and $g^\top F^{-1}g=2(1/2)+1=2$. Writing $c=\sqrt{0.05}$, we have
The step saturates the quadratic constraint and attains the proved upper bound on linear gain. This is the predicted improvement in the local model. The true reward objective and KL are nonlinear in policy parameters; a finite deployment step may therefore require a line search and a check of the actual KL.
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
Plan. Apply the three parts of the Q-learning rule in order: target, temporal-difference (TD) error, step of size $\alpha$ along that error.
Step 1 — target. Q-learning's target is the sampled reward plus the discounted best next action-value, $y=r+\gamma\max_{a'}Q(s',a')$. The next state is nonterminal, so the continuation is kept:
Step 2 — TD error. The TD error is target minus current estimate:
Step 3 — update. The rule moves the estimate a fraction $\alpha=0.2$ of the way along the error:
Check. The same update is the weighted average $(1-\alpha)Q+\alpha y=0.8(0.5)+0.2(2.8)=0.4+0.56=0.96$, so the new value lies between the old estimate $0.5$ and the target $2.8$, moving $20\%$ of the distance $2.3$.
Interpretation. The estimate is not replaced by $2.8$, because the learning rate is below one: a single noisy sample only nudges it. For a terminal transition the continuation term would be zero and the target would be just $r=1$.
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
Plan. Exponentiate the action-values (divided by $\alpha=1$), normalise to get the softmax policy, take the log of the normaliser for the soft value, and verify it equals expected value plus entropy.
Step 1 — exponentiate. The entropy-regularised optimal policy is $\pi(i)\propto e^{Q_i/\alpha}$. With $\alpha=1$: $e^{Q_1}=e^0=1$ and $e^{Q_2}=e^{\ln3}=3$, because $e^{\ln u}=u$.
Step 2 — normalise. The sum is $1+3=4$, so
Step 3 — soft value. The soft value is the log of the same normaliser:
Their difference is $\ln4-\ln3=\ln(4/3)\approx0.287682$.
Step 4 — where the extra comes from. The soft value is the regularised objective $\mathbb E_\pi[Q]+\alpha H(\pi)$ at the optimal $\pi$. The expected action-value is $\tfrac14(0)+\tfrac34\ln3$. The entropy is
Adding: $\tfrac34\ln3+\ln4-\tfrac34\ln3=\ln4$, exactly the soft value.
Check. Log-sum-exp always satisfies $\max_iQ_i\le\ln\sum_ie^{Q_i}\le\max_iQ_i+\ln n$ with $n=2$ actions: $\ln3\le\ln4\le\ln6$. Also the ratio $\pi_2/\pi_1=3=e^{Q_2-Q_1}$, as softmax requires.
Interpretation. The softmax is a distribution over actions; the log-sum-exp is a value that includes an entropy bonus. That is why it exceeds the ordinary maximum by $\ln(4/3)$, and why it is not the unregularised expected reward $\tfrac34\ln3\approx0.824$ 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
Plan. Treat the ensemble as a random choice of model $M$ (each with probability $1/2$) followed by a draw from that model; use the law of total expectation and the law of total variance. Then examine what the offline data can and cannot distinguish.
Step 1 — mixture mean. By the law of total expectation, $\mathbb E[X]=\mathbb E\big[\mathbb E[X\mid M]\big]$:
Step 2 — mixture variance. The law of total variance splits the variance into "average within-model variance" plus "variance of the model means":
Cross-check from second moments: $\mathbb E[X^2\mid M]=\operatorname{Var}+\text{mean}^2$ is $1$ and $5$, so $\mathbb E[X^2]=3$ and $\operatorname{Var}(X)=3-1^2=2$.
Step 3 — what disagreement measures. The second term ($1$) is the ensemble's disagreement. It describes spread between these models; it is not a bound on how far the truth is from all of them.
Step 4 — the offline question. The data contain only action $a$, with reward $1$. Consider two environments that both give $a$ reward $1$, but give $b$ reward $+100$ in one and $-100$ in the other. Every observation in the data set has the same probability under both, so no fitting procedure can tell them apart, and every model trained on these data can predict $100$ while the truth is $-100$.
Check. If both models were identical (means $0$ and $0$), the disagreement term would be $0$ while total variance stays $1$; and in Step 4 the ensemble's disagreement on $b$ is $0$ although the error can be $200$. Zero disagreement therefore implies nothing about correctness.
Interpretation. Agreement does not prove $b$ is good. Additional data support for $b$, structural assumptions linking $b$ to $a$, or a justified conservative (pessimistic) method are needed before drawing 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
Plan. For each input, compute the affine pre-activation $v=Wx+b$ as a row-times-column product plus bias, then apply $\max(0,\cdot)$. Read the dimensions off the shape of $W$.
Step 1 — input $(1,3)$. The row $(2,-1)$ times the column $(1,3)^\top$ is $2\cdot1+(-1)\cdot3=2-3=-1$. Adding the bias:
The pre-activation is negative, so the ReLU is inactive and outputs $0$.
Step 2 — input $(2,1)$. $2\cdot2+(-1)\cdot1=4-1=3$, so
The pre-activation is positive, so the ReLU passes it through unchanged.
Step 3 — dimensions. $W$ has $1$ row and $2$ columns ($1\times2$). The product $Wx$ is defined only for $x$ with $2$ entries and produces $1$ entry. So the input dimension is $2$ and the output dimension is $1$; the bias $b$ must also have $1$ entry. ReLU acts entrywise and does not change the dimension.
Check. Both outputs are $\ge0$, as every ReLU output must be, and the active case returns exactly its pre-activation.
Interpretation. The weights and bias set where the neuron switches on (the line $2x_1-x_2+0.5=0$), and the activation clips everything on the negative side. 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
Plan. Do a forward pass, storing every intermediate ($v$, $z$, $f$, $\ell$); then a backward pass that multiplies local derivatives from the loss back to each variable (the chain rule).
Step 1 — forward pass.
Step 2 — derivative at the output. Differentiating $\tfrac12(f-y)^2$ in $f$ (chain rule on the square) gives $\partial\ell/\partial f=f-y=3-1=2$.
Step 3 — through the output weight. Since $f=wz$, $\partial f/\partial w=z$ and $\partial f/\partial z=w$. Hence
Step 4 — through the ReLU. For $v\gt0$, $\max(0,v)=v$ near $v$, so its derivative is $1$. Here $v=1\gt0$, which is why this formula is allowed (at $v=0$ the ReLU has no derivative). Thus $\partial\ell/\partial v=6\cdot1=6$.
Step 5 — through the affine map. Since $v=ax+b$: $\partial v/\partial a=x$, $\partial v/\partial b=1$, $\partial v/\partial x=a$. Therefore
Check. On the active region the network is $f=w(ax+b)$, so $\ell=\tfrac12(w(ax+b)-y)^2$ and, for example, $\partial\ell/\partial x=(f-y)\,wa=2\cdot3\cdot2=12$ and $\partial\ell/\partial w=(f-y)(ax+b)=2\cdot1=2$, matching the backward pass. Numerically, raising $b$ from $-1$ to $-0.99$ gives $f=3.03$ and $\ell=\tfrac12(2.03)^2=2.06045$, a change of about $0.06=6\times0.01$.
Interpretation. Parameter gradients ($w,a,b$) are what training uses; the input gradient ($x$) measures the local sensitivity of this loss to the input, which is what robustness analysis uses.
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
Represent the two hidden activations. With one scalar input, take
There are no biases. The first layer outputs $(\operatorname{ReLU}(x),\operatorname{ReLU}(-x))$, and the second subtracts its second coordinate. A one-column or one-row matrix has spectral norm equal to its Euclidean vector norm, so $\|W_1\|_2=\sqrt{1^2+(-1)^2}=\sqrt2$ and $\|W_2\|_2=\sqrt2$. ReLU is $1$-Lipschitz, giving the product upper bound $\sqrt2\sqrt2=2$.
Use the structure that this bound discards. If $x\ge0$, then $\operatorname{ReLU}(x)=x$ and $\operatorname{ReLU}(-x)=0$, so $f(x)=x$. If $x\lt0$, these activations are $0$ and $-x$, so again $f(x)=0-(-x)=x$. Consequently $|f(x)-f(y)|=|x-y|$ for every pair. A Lipschitz constant of $1$ works, and every pair of distinct inputs forces any valid constant to be at least $1$. The exact global constant is therefore $1$.
Convert the score into a certificate. At $x=2$, $f(2)=2$ and the positive-class margin is $2$. The product bound gives $2/2=1$: every perturbation with $|\delta|\lt1$ preserves the strict positive sign. The exact constant gives $2/1=2$, certifying every $|\delta|\lt2$.
The decision boundary is $f(x)=x=0$, at actual distance $2$. At $\delta=-2$ the score is zero, so a strict-sign certificate includes every smaller radius but not that boundary point. The tighter bound recovers this exact boundary distance; the product bound loses the mutual structure of the two ReLU branches.
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
Plan. Slide the length-$2$ kernel along the input one position at a time, taking a dot product at each position; then write each dot product as one row of a matrix.
Step 1 — count the outputs. With input length $n=4$, kernel length $k=2$, stride $1$ and no padding, the kernel fits at $n-k+1=3$ positions, so there are $3$ outputs.
Step 2 — compute each window. Cross-correlation computes $y_i=1\cdot x_i+(-1)\cdot x_{i+1}$ without flipping the kernel:
So the output is $(-1,-1,-1)$.
Step 3 — build the matrix. Row $i$ must reproduce $y_i$, so it has the kernel entries $1,-1$ in columns $i,i+1$ and zeros elsewhere:
Check. $W$ is $3\times4$: four inputs, three outputs, matching Step 1. Each row of the product, e.g. row $2$: $0\cdot1+1\cdot2-1\cdot3+0\cdot4=-1$, matches Step 2. Sanity: the kernel computes "this entry minus the next", and consecutive inputs differ by $1$, so every output should be $-1$.
Interpretation. The map is a sparse matrix whose rows are shifted copies of the same two numbers: that repetition is parameter sharing. Mathematical convolution would reverse the kernel to $(-1,1)$ and give $(+1,+1,+1)$, so stating the convention matters.
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
Plan. Recall where the bound $1+L_g$ comes from, then compute the exact constant of each combined linear map $F(x)=cx$, which is $|c|$.
Step 1 — the standard bound. For any $x,y$, the triangle inequality gives
Step 2 — exact constant of a scalar linear map. If $F(x)=cx$, then $|F(x)-F(y)|=|c|\,|x-y|$ for every pair, with equality. So $|c|$ works and nothing smaller does: $L_F=|c|$. Likewise $L_g=|{\text{slope of }g}|$.
Step 3 — case $g(x)=0.2x$. $L_g=0.2$ and $F(x)=x+0.2x=1.2x$, so
The bound is exact: the two paths push in the same direction, so the triangle inequality holds with equality.
Step 4 — case $g(x)=-0.8x$. $L_g=|-0.8|=0.8$ and $F(x)=x-0.8x=0.2x$, so
The bound overestimates by a factor $1.8/0.2=9$.
Check. In both cases $L_F\le1+L_g$ ($1.2\le1.2$ and $0.2\le1.8$), so the bound is valid. Equality in Step 1 needs $x-y$ and $g(x)-g(y)$ to have the same sign, which holds for slope $+0.2$ and fails for slope $-0.8$.
Interpretation. The second bound is loose because the skip path and the residual path partially cancel, and the triangle inequality ignores cancellation. A skip connection does not automatically make a block contractive (case one has $L_F=1.2\gt1$); only 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
For this fixed input, write $F(z)=0.5z+2$. Solving $z_*=F(z_*)$ gives $z_*=0.5z_*+2$, hence $0.5z_*=2$ and $z_*=4$. Starting from zero,
Measure the residual at the current iterate. One more evaluation gives $F(z_3)=0.5(3.5)+2=3.75$. Thus $r=|F(z_3)-z_3|=|3.75-3.5|=0.25$. This is the current equation mismatch, not directly the distance to its solution.
The map contracts because $|F(z)-F(w)|=0.5|z-w|$. Let $e=|z_3-z_*|$, use $F(z_*)=z_*$, and insert $F(z_3)$:
Rearranging gives $0.5e\le r$, so $e\le r/(1-0.5)=0.25/0.5=0.5$. Here the actual error is $|3.5-4|=0.5$, so the certificate is exact. The contraction factor is what converts the observed residual into a guaranteed equilibrium error.
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
Plan. Find the winner and its margin; then, for each rival class, push the winner's logit down and the rival's up by the full $0.4$ and show the winner's lead stays positive.
Step 1 — prediction and margin. The largest logit is $3$ (class $1$); the runner-up is $1$ (class $2$). The margin is $3-1=2$.
Step 2 — what the perturbation allows. Write the perturbed logits as $\ell_i'=\ell_i+e_i$ with $|e_i|\le0.4$. Hence $\ell_1'\ge3-0.4=2.6$ and, for every $j$, $\ell_j'\le\ell_j+0.4$.
Step 3 — gap to class $2$. Combining the two inequalities,
Step 4 — gap to class $3$. In the same way,
Class $1$ beats both rivals strictly for every allowed change, so the prediction cannot change.
Check. The worst case is attained by $(2.6,1.4,0.4)$, which still predicts class $1$. In general, a lead over the runner-up is guaranteed to survive every allowed change exactly when margin $\gt2\times0.4=0.8$, because the two logits of a pair can move toward each other by up to $0.4+0.4$ (at margin exactly $0.8$ a tie is possible); here $2\gt0.8$.
Interpretation. The margin is a safety buffer measured in logit units. This argument starts from a proved bound on logit changes; it does not yet say which input perturbations produce that bound, which is what a Lipschitz constant supplies.
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
Plan. Compute the score and the Lipschitz constant, turn them into a lower bound on the perturbed score, and compare the resulting radius with the exact boundary location.
Step 1 — score and Lipschitz constant. $f(1)=2(1)+1=3\gt0$, so the predicted sign is positive. For any $x,y$, $|f(x)-f(y)|=|2x-2y|=2|x-y|$, so $L=2$ works and no smaller constant does: $L=2$ exactly.
Step 2 — lower bound on the perturbed score. By the Lipschitz property, $f(1+\delta)\ge f(1)-L|\delta|=3-2|\delta|$. This is strictly positive when
So the certified radius is $f(1)/L=1.5$.
Step 3 — actual distance to the boundary. The decision boundary is where $f=0$: $2x+1=0\iff x=-0.5$. Its distance from $x=1$ is $|1-(-0.5)|=1.5$.
Step 4 — the boundary radius itself. At $\delta=-1.5$ the input is $x=-0.5$ and $f(-0.5)=2(-0.5)+1=0$, which is not strictly positive. So the guarantee covers $|\delta|\lt1.5$ but not $|\delta|=1.5$.
Check. Because $f$ is affine, the lower bound in Step 2 is attained exactly in the direction $\delta\lt0$ ($f(1+\delta)=3+2\delta=3-2|\delta|$), so the certificate radius and the boundary distance must agree, and they do. At $|\delta|=1$, for instance, $f(0)=1\gt0$ as predicted.
Interpretation. The open ball of radius $1.5$ is certified; the closed ball at the same radius is not a strict-sign guarantee, and whether its edge counts depends on the classifier's tie convention.
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
Plan. For the radius, bound how fast each pairwise logit difference can change and solve "margin minus change $\gt0$". For the accuracy, count examples proved robust (lower bound) and remove those proved non-robust (upper bound).
Step 1 — Lipschitz constant of a logit difference. Let $c$ be the predicted class and $j\ne c$. The difference $h_j(x)=f_c(x)-f_j(x)=(e_c-e_j)^\top f(x)$, where $e_c,e_j$ are standard basis vectors. By Cauchy–Schwarz and the $2$-Lipschitz property,
because $e_c-e_j$ has one entry $1$, one entry $-1$ and zeros elsewhere, so its norm is $\sqrt{1+1}=\sqrt2$.
Step 2 — certified radius. The margin $1$ means $h_j(x)\ge1$ for every $j\ne c$. Then $h_j(x+\delta)\ge1-2\sqrt2\,\|\delta\|_2$, which is strictly positive for all $j$ when
Step 3 — lower bound on robust accuracy. An example is robust-correct if every allowed perturbation, including none, is classified correctly. A valid certificate proves exactly that, so at least $50$ of $100$ are robust-correct: at least $50\%$.
Step 4 — upper bound. The $100-80=20$ clean errors are already wrong at $\delta=0$, which is an allowed perturbation, so they are not robust-correct. Among the $80$ clean-correct examples, $10$ have a concrete adversarial input, so they are not robust-correct either. At most $80-10=70$ remain: at most $70\%$.
Check. The counts are consistent: a valid certificate and a successful attack cannot both hold for one example, so the $50$ certified lie among the $80-10=70$ not yet refuted, and $50\le70$. A naive rule using $1/L=1/2$ would overstate the radius by the factor $\sqrt2$.
Interpretation. True robust accuracy lies in $[50\%,70\%]$. The $20$ clean-correct examples that are neither certified nor broken are unknown: an unsuccessful attack does not certify them, and a missing certificate does not refute 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
Keep the lab's stationary policy family, start state $R$, transition model and discount $0.8$. Its evaluated returns are $C(p)=p/(1+0.2p)$ maintenance units and $J(p)=(2+2p)/(0.2+0.04p)$ items, with $0\le p\le1$.
Solve the new budget. Since $1+0.2p$ is positive throughout the policy interval, multiplying preserves the inequality:
Intersecting with $[0,1]$ leaves the full feasible interval $[0,5/19]$. To find the best member, the quotient rule gives
Production increases with $p$, so the best feasible choice is its largest value, $p_*=5/19\approx0.263158$.
Evaluate the selected policy. Its reward numerator is $2+2(5/19)=48/19$. Its denominator is $1/5+(1/25)(5/19)=1/5+1/95=4/19$. Therefore $J(p_*)=(48/19)/(4/19)=12$ discounted items. The maintenance check is $C(p_*)=(5/19)/(1+1/19)=(5/19)/(20/19)=1/4$ unit.
This is the optimum in the stipulated policy family under the known model. The expected discounted budget can hold while particular trajectories contain repairs; it is not a rule prohibiting each individual maintenance event.
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
Evaluate maintenance with the unknown constant wear rate. In state $R$, fast is chosen with probability $p$ and then causes wear with probability $\rho$. Thus next state is $W$ with probability $\rho p$. Repair costs one now and returns to $R$, so
There is no immediate maintenance cost in $R$. Substitute the first equation into the second:
The denominator is positive for $p\in[0,1]$, $\rho\in[0.2,0.3]$, giving $C(p,\rho)=C_R=0.8\rho p/(0.2+0.16\rho p)$.
Choose the worst allowed model before solving the budget. Put $q=\rho p$. Differentiating $0.8q/(0.2+0.16q)$ gives
For a fixed nonnegative $p$, the greatest cost is therefore at $\rho=0.3$. Its budget condition is
Hence the largest robustly feasible probability is $25/54$, and all probabilities in $[0,25/54]$ satisfy the budget for every allowed constant wear rate.
At $p=0.5$, the worst cost is $0.8(0.3)(0.5)/(0.2+0.16(0.3)(0.5))=0.12/0.224=15/28\approx0.535714\gt0.5$. It fails the robust requirement because this allowed model violates the budget; this does not mean it fails under every smaller wear rate.
The conclusion assumes that the actual wear rate is constant and lies in the stated interval. No confidence level for an estimated interval is supplied here, and the result is still an expected discounted maintenance statement.
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
Compute the nominal score. Normalising $y_0=2.8$ mm/s gives $z_0=(2.8-2)/1=0.8$. Both ReLUs are active there, so
The nominal recommendation is positive. Write the total physical error as the sum of noise $n$ and fixed bias $b$, with $|n|\le0.2$ and $|b|\le0.15$ mm/s. The triangle inequality gives $|n+b|\le0.35$ mm/s. Division by the normalising scale $1$ mm/s gives $|z-z_0|\le0.35$, or $z\in[0.45,1.15]$.
The global Lipschitz bound of $m$ is $1$: each ReLU is $1$-Lipschitz, so their weighted changes are at most $(0.6+0.4)|z-z_0|$. Its resulting lower bound is $m(z)\ge0.3-0.35=-0.05$. A negative lower bound alone is inconclusive about the true score; it shows that this bound does not certify strict positivity.
Check whether failure is actually possible. Choose allowed errors $n=+0.2$, $b=+0.15$ mm/s. Their total places the input at $y=3.15$ mm/s and $z=1.15$. For every $z\ge0.5$, the ReLUs can be removed by their active formulas:
Thus $m(1.15)=1.1-1.15=-0.05$, an actual allowed negative score. The positive nomination is not robustly certified.
Locate the tie in the positive direction. Moving up from $z_0=0.8$ remains in the region $z\ge0.5$, so the first zero is at $z=1.1$. In physical units this is $y=2+(1)(1.1)=3.1$ mm/s, a distance of $3.1-2.8=0.3$ mm/s. At that point the score is zero and the nomination rule selects A, since only a strictly positive score selects B. Any closed uncertainty interval containing it therefore fails strict-positive certification.
Repeated readings do not remove the unknown fixed bias. The given hard bounds also provide no statistical averaging rule that would shrink the total uncertainty automatically.
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
With $p=5/9$, the probability of becoming worn after a ready shift is $q=0.25p=(1/4)(5/9)=5/36$. A worn shift always repairs and returns to ready. In state order $(R,W)$, the transition matrix is therefore
Solve the stationary balance. Let $w$ be the stationary worn probability and $1-w$ the ready probability. A next worn state can come only from a current ready state, so $w=(1-w)(5/36)$. Multiplying by $36$ and collecting terms gives $36w=5-5w$, hence $41w=5$. Thus $w=5/41$ and $1-w=36/41$; these are nonnegative and sum to one.
Repair occurs exactly in $W$ and costs one unit, so the mean stationary repair rate is $5/41\approx0.121951$ maintenance unit per shift. The conditional mean production in $R$ is
Production in $W$ is zero. Averaging across the stationary states gives $(36/41)(28/9)+(5/41)(0)=112/41\approx2.731707$ items per shift.
Count repairs over the specified stationary horizon. If the initial state has this stationary law, every shift has repair probability $5/41$. Let $I_t$ indicate repair. Linearity of expectation gives $\mathbb E[\sum_{t=0}^{19}I_t]=\sum_{t=0}^{19}\mathbb E[I_t]=20(5/41)=100/41\approx2.439024$. The indicators need not be independent for this expectation calculation.
The budget $C(5/9)=0.5$ is instead $\mathbb E[\sum_{t=0}^{\infty}0.8^tI_t]$ starting in $R$, not in stationarity. It uses a different initial distribution, an infinite horizon and geometrically decreasing weights. Twenty unweighted stationary shifts can therefore have an expected count exceeding $0.5$ without contradicting the discounted budget. Neither expectation guarantees a particular number of repairs on each individual trajectory.
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. |