B. Calculus, Convexity & Optimization

Gradients, Lipschitz continuity, convex sets and functions, descent methods and constraints

Before you start

This primer assumes:

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

Contents
1. Gradients, Jacobians, Hessians & the Chain Rule Practice: Gradients, chain rules and Taylor models (Easy → Hard) 2. Matrix Calculus You Will Need Practice: Matrix derivatives and sensitivity (Easy → Hard) 3. Lipschitz Continuity, Smoothness & Sensitivity Practice: Lipschitz bounds, grids and model errors (Easy → Hard) 4. Convex Sets, Convex Functions & Conjugates Practice: Convexity, subgradients and conjugates (Easy → Hard) 5. Gradient Descent, Newton's Method & Step Sizes Practice: Steps, curvature and line searches (Easy → Hard) 6. Constraints: Lagrange Multipliers, Projections, Penalties & Barriers Practice: Feasibility, KKT and penalty residuals (Easy → Hard) 7. Linear & Quadratic Programs Practice: Linear programs, quadratic programs and feasibility (Easy → Hard) 8. argmax, Min-Max Problems & Saddle Points Practice: Optimisers, worst cases and saddle points (Easy → Hard) Interactive: Descent, Projection & Barriers in 2-D Application lab & chapter review Exercises Further Reading Flashcards

The modules certify safety with inequalities and compute controllers, multipliers and weights by optimisation. Both rest on one toolbox: multivariable derivatives, bounds on how fast functions change, convexity, and algorithms that turn "find the best feasible point" into iterations. Each concept comes with a definition, a small example, the general statement, and pointers to where the modules use it.

Notation — On this page
  • Vectors are columns; $x^\top y$ is the inner product and $\|x\|$ the Euclidean norm unless subscripted ($\|x\|_1,\|x\|_\infty$). $\nabla f$ is the gradient (a column), $J_f$ the Jacobian, $\nabla^2f$ the Hessian; $C^r$: $r$ times continuously differentiable.
  • $A\succeq0$ ($A\succ0$): symmetric positive semidefinite (definite); $\|A\|$ spectral and $\|A\|_F$ Frobenius norm, $\langle A,B\rangle=\operatorname{tr}(A^\top B)$; $(u)_+=\max(u,0)$, componentwise for vectors; $P_C(y)$: projection onto $C$.
  • Running example of Sections 6–8: minimise $(x-2)^2$ subject to $x\le1$; solution $x^\star=1$, optimal value $p^\star=1$.
A route through this primer

If differentiation feels rusty, begin with the algebra and calculus refresher. Read Sections 1–5 in order before the algorithms. In Section 6, master feasibility, one active constraint and the four KKT checks before the longer constraint-qualification examples. Sections 7–8 then connect those tools to solver problems and worst-case decisions.

Each of the eight sections has an Easy, Medium and Hard practice sequence: 24 local exercises, in addition to the mixed exercises at the end. Try the question, use the independent hint only when stuck, and write a complete attempt before opening the worked solution. Afterwards close it and reproduce the reasoning.

Practice menu: Gradients, chain rules and Taylor models, Matrix derivatives and sensitivity, Lipschitz bounds, grids and model errors, Convexity, subgradients and conjugates, Steps, curvature and line searches, Feasibility, KKT and penalty residuals, Linear programs, quadratic programs and feasibility, Optimisers, worst cases and saddle points.

Use the readiness check to decide what to revisit. Research-module links show where the tools will be used; you do not need to read those modules while learning the definitions.

Background — The probability used in the examples (finite case)

A few examples (expectations in Section 4, SGD in Section 5, mixed strategies in Section 8) use probability, treated fully in Primer C (expectation, conditioning, KL divergence). Here a random variable $Z$ takes finitely many values $z_j$ with probabilities $p_j\ge0$, $\sum_jp_j=1$ ("uniform on $n$ values": $p_j=1/n$). Then $\mathbb P(Z\in A)=\sum_{j:\,z_j\in A}p_j$, and the expectation $\mathbb Eg(Z)=\sum_jp_jg(z_j)$ is a probability-weighted average: for $Z$ uniform on $\{1,2,3,6\}$, $\mathbb EZ=3$. The conditional expectation $\mathbb E[g_k\mid x_k]$ in SGD averages over the fresh sampling randomness of step $k$ with the current iterate $x_k$ held fixed. For distributions $p,q$ on the same finite set, $\mathrm{KL}(p\|q)=\sum_jp_j\log(p_j/q_j)\ge0$ (with $0\log0=0$, and $+\infty$ if some $q_j=0\lt p_j$), zero iff $p=q$, measures their discrepancy (not symmetric).

First-course refresher: algebra and single-variable calculus

Multivariable calculus reuses the rules below, one coordinate or one curve at a time. Rebuild a rule with the tiny example before using its vector notation.

Background — Completing a square and respecting an inequality

Square: $x^2-4x+5=x^2-4x+4+1=(x-2)^2+1$. Since a square is nonnegative, the unique unconstrained minimum is 1 at x=2. If $x\le1$, the closest permitted x to 2 is x=1, with value 2. The same expression is a different optimisation problem when its domain changes.

Inequality signs: $2x\le6$ gives $x\le3$, while $-2x\le6$ gives $x\ge-3$ because division by a negative number reverses the sign. The notation $(z)_+=\max(z,0)$ keeps only a violation: $(x-1)_+$ is 0 for $x\le1$ and x-1 for $x\gt1$.

Fractions and domains: $1/x$ and $\log x$ require different domains (x nonzero and x positive, respectively, for real values). You can multiply an inequality by a denominator without reversing its sign only when you know that denominator is positive.

Background — Slopes, derivative rules and the chain rule

Derivative as slope: $f^\prime(t)=\lim_{h\to0}[f(t+h)-f(t)]/h$. For $f(t)=3t^2$ at t=1, the quotient is $[3(1+h)^2-3]/h=6+3h$, tending to 6. Thus a small change h causes approximately 6h change in f near t=1.

FunctionDerivativeDomain / example
Constant c0A fixed offset has no slope.
$t^p$$pt^{p-1}$For instance $(t^3)\prime=3t^2$; general real powers require an appropriate real domain.
$e^t$$e^t$Every real t.
$\log t$$1/t$$t\gt0$; log means natural logarithm.
$1/t$$-1/t^2$$t\ne0$.

Sum and product: $(af+bg)\prime=af^\prime+bg^\prime$ for constants a,b, and $(fg)\prime=f^\prime g+fg^\prime$. For $t^2e^t$ the derivative is $2te^t+t^2e^t$, equal to 3e at t=1. Both factors change, so both contributions are needed.

Chain rule: $[f(g(t))]\prime=f^\prime(g(t))g^\prime(t)$. For $(2t+1)^2$, the outer square contributes $2(2t+1)$ and the inner function contributes 2, giving $4(2t+1)$. At t=1 the derivative is 12. In a partial derivative, freeze all other coordinates; in a curve derivative, account for every coordinate that changes.

Background — Integrals, stationary points and local approximation

Fundamental theorem: if $F^\prime=f$, then $\int_a^bf(t)dt=F(b)-F(a)$. Example: $\int_0^1 2t\,dt=[t^2]_0^1=1$. This is how a derivative bound becomes a finite-change bound along a segment.

Stationary does not mean minimum: at an interior differentiable local minimum the derivative is zero. But $f(t)=-t^2$ also has derivative zero at t=0, a maximum. Curvature helps: $(t-2)^2+1$ has second derivative 2>0 and its stationary point t=2 is a minimum.

Taylor model: $f(t+h)=f(t)+f^\prime(t)h+\tfrac12f^{\prime^\prime}(t)h^2+$ remainder. For f(t)=t² at t=1 this is exactly $1+2h+h^2$. At h=0.1 the linear model gives 1.2, while the quadratic gives the exact value 1.21. For nonquadratic functions a remainder bound determines how accurate the model is; Primer 0 explains O and little-o notation.

Check before continuing: recover $[(t-1)^2]\prime=2(t-1)$ and $[e^{2t}]\prime=2e^{2t}$, and explain why the constrained minimum of $(t-2)^2$ over $t\le1$ is at the boundary. If one step is unfamiliar, keep its recap open for the first local Easy exercise.

1. Gradients, Jacobians, Hessians & the Chain Rule

Almost every argument in the modules that involves motion (a state along a trajectory, weights during training, an input inside a ball) uses one trick: restrict a function of many variables to a line or a curve, and apply single-variable calculus there.

1.1 Gradients and directional slopes

Definition — Partial derivative, gradient, directional derivative
For $f:\mathbb R^n\to\mathbb R$, $\partial f/\partial x_i$ is the ordinary derivative in $x_i$ with the other coordinates frozen, and the gradient is the column $\nabla f(x)=\big(\tfrac{\partial f}{\partial x_1},\dots,\tfrac{\partial f}{\partial x_n}\big)^{\top}$. The directional derivative along $v$ is the slope on the line through $x$ in direction $v$:
$$D_vf(x)=\lim_{t\to0}\frac{f(x+tv)-f(x)}{t}=\frac{d}{dt}f(x+tv)\Big|_{t=0}.$$
$f$ is differentiable at $x$ if $f(x+\delta)=f(x)+\nabla f(x)^{\top}\delta+e(\delta)$ with $e(\delta)/\|\delta\|\to0$; then $D_vf(x)=\nabla f(x)^{\top}v$. $f\in C^1$ if all partials exist and are continuous (this implies differentiability); $C^r$: all partials up to order $r$ exist and are continuous.

Example. $f(x)=x_1^2+3x_1x_2$ has $\nabla f=(2x_1+3x_2,\ 3x_1)$, so $\nabla f(1,2)=(8,3)$ and along $v=(1,1)/\sqrt2$ the slope is $11/\sqrt2\approx7.78$. By Cauchy–Schwarz $\nabla f^{\top}v\le\|\nabla f\|$ for unit $v$, with equality for $v=\nabla f/\|\nabla f\|$: the steepest slope is $\sqrt{73}\approx8.54$.

Intuition
The gradient points uphill most steeply, and it is perpendicular to the level set through $x$: along a curve $c(t)$ inside $\{f=f(x)\}$, $0=\tfrac{d}{dt}f(c(t))=\nabla f^{\top}\dot c$. For a safe set $C=\{h\ge0\}$, $\nabla h$ (where nonzero) is the boundary normal pointing into $C$. "$0$ is a regular value of $h$" means $\nabla h\ne0$ wherever $h=0$; then the boundary is a smooth surface. For the unit disc $h=1-\|x\|^2$, $\nabla h=-2x\ne0$ on the circle, pointing inwards; for $h(x)=-x^3$, $h'(0)=0$ and the derivative cannot tell the safe side from the unsafe one.
Pitfall
Partials can exist without differentiability: $f=x_1x_2/(x_1^2+x_2^2)$, $f(0)=0$, has zero partials at $0$ but equals $\tfrac12$ on the diagonal; $C^1$ rules this out. "$C^1$ on a closed set $S$" means: the restriction of a $C^1$ function on an open set containing $S$, so gradients exist on the boundary too.

1.2 Jacobians: derivatives of vector outputs

Definition — Jacobian
For $f=(f_1,\dots,f_m):\mathbb R^n\to\mathbb R^m$, $J_f(x)\in\mathbb R^{m\times n}$ has entries $\partial f_i/\partial x_j$; row $i$ is $\nabla f_i^{\top}$. If every $f_i$ is differentiable at $x$ (e.g. $f$ is $C^1$ near $x$), then $f(x+\delta)=f(x)+J_f(x)\delta+e(\delta)$ with $\|e(\delta)\|/\|\delta\|\to0$: the Jacobian is the best local linear map. Existing entries alone do not give this (the Pitfall above has $J_f(0)=0$, yet $f=\tfrac12$ on the diagonal). For scalar $f$, $J_f=\nabla f^{\top}$. An affine map $Wx+b$ has $J=W$; an elementwise activation $\sigma(v)$ has $J=\operatorname{diag}(\sigma'(v_1),\dots,\sigma'(v_n))$. Example: $f=(x_1x_2,\ x_1+x_2^2)$ has $J_f=\begin{bmatrix}x_2 & x_1\\ 1 & 2x_2\end{bmatrix}$, equal to $\begin{bmatrix}2 & 1\\ 1 & 4\end{bmatrix}$ at $(1,2)$.

1.3 Chain rules along curves and networks

Theorem — Chain rule
If $g$ is differentiable at $x$ and $f$ at $g(x)$, then $J_{f\circ g}(x)=J_f(g(x))\,J_g(x)$ (composing the best linear maps). Special cases used constantly:
$$\frac{d}{dt}f(x(t))=\nabla f(x(t))^{\top}\dot x,\qquad \nabla(f\circ g)(x)=J_g(x)^{\top}\nabla f(g(x)),\qquad \frac{d}{dt}\big(a^{\top}b\big)=\dot a^{\top}b+a^{\top}\dot b .$$

Derivatives along trajectories. For $\dot x=f(x)+g(x)u$ and $C^1$ $h$, the first case gives the Lie derivatives ($L_gh$ is a row when $u\in\mathbb R^m$):

$$\dot h=\nabla h(x)^{\top}\dot x=\underbrace{\nabla h(x)^{\top}f(x)}_{L_fh(x)}+\underbrace{\nabla h(x)^{\top}g(x)}_{L_gh(x)}\,u .$$

The product rule gives $\tfrac{d}{dt}(x^{\top}Px)=\dot x^{\top}Px+x^{\top}P\dot x=2x^{\top}P\dot x$ for symmetric $P$, and the chain rule applied to $\nabla f$ (whose Jacobian is the Hessian) gives $\tfrac{d}{dt}\nabla f(x(t))=\nabla^2f(x(t))\,\dot x$. A path $q(s)$, $s\in[0,1]$, run with timing $s(t)$ has $\dot q=q'(s)\dot s$ and $\ddot q=q''(s)\dot s^2+q'(s)\ddot s$; with $\dot s\ge0$ the same points are visited in the same order, so time scaling changes only the timing, never the geometric path ($\dot s=0$ means stopping on it). Example: $\dot x_1=x_2$, $\dot x_2=-x_1+u$ and $h=1-x_1^2-x_2^2$ give $L_fh=-2x_1x_2+2x_2x_1=0$ and $L_gh=-2x_2$; at the boundary point $(0.6,0.8)$, $\dot h=-1.6u$, so exactly the inputs $u\le0$ keep $h$ from decreasing.

Backpropagation is the chain rule in reverse. $f(x)=W_2\sigma(W_1x+b_1)+b_2$ with scalar output has $\nabla f(x)=W_1^{\top}\operatorname{diag}(\sigma'(v))W_2^{\top}$, $v=W_1x+b_1$. Backpropagation evaluates it from the output side ($W_2^{\top}$, then $\operatorname{diag}(\sigma'(v))$, then $W_1^{\top}$) by matrix-vector products, so a gradient costs a few forward passes (finite differences need $n+1$). Take the ReLU $\sigma(z)=\max(z,0)$, applied to each coordinate: neuron $i$ is active when $v_i\gt0$, where $\sigma'(v_i)=1$, and inactive when $v_i\lt0$, where $\sigma'(v_i)=0$. With $W_1=\begin{bmatrix}1 & 2\\ 1 & -2\end{bmatrix}$, $b_1=0$, $W_2=[1\ \ 1]$ and $x=(1,0.25)$: $v=(1.5,0.5)$, both neurons active, $\operatorname{diag}(\sigma'(v))=I$ and $\nabla f=W_1^{\top}(1,1)^{\top}=(2,0)$; indeed $f=2x_1$ near $x$. ReLU networks are not differentiable on finitely many hyperplane pieces (zero volume), where autodiff uses a convention such as $\sigma'(0)=0$; along a segment they stay continuous and piecewise affine. More in Primer E.

1.4 Hessians: curvature in every direction

Definition — Hessian
For $f\in C^2$, $\nabla^2f(x)$ has entries $\partial^2f/\partial x_i\partial x_j$; it is the Jacobian of $\nabla f$ and is symmetric (mixed partials commute). $f=x_1^2+3x_1x_2$ has $\nabla^2f=\begin{bmatrix}2 & 3\\ 3 & 0\end{bmatrix}$ with eigenvalues $1\pm\sqrt{10}\approx4.16,-2.16$: it curves up in one direction and down in another although the diagonal is nonnegative; the mixed partial decides.

1.5 Taylor models and finite-change bounds

Key equation — Taylor expansion with remainder
For $f\in C^2$: $\ f(x+\delta)=f(x)+\nabla f(x)^{\top}\delta+\tfrac12\delta^{\top}\nabla^2f(x)\,\delta+o(\|\delta\|^2)$. If $\|\nabla^2f\|\le M$ on the segment from $x$ to $x+\delta$, then $|f(x+\delta)-f(x)-\nabla f(x)^{\top}\delta|\le\tfrac M2\|\delta\|^2$ (one-variable Taylor with remainder applied to $t\mapsto f(x+t\delta)$, whose second derivative is $\delta^{\top}\nabla^2f\,\delta$).

O-notation (Primer 0). $e(\delta)=O(\|\delta\|^k)$ as $\delta\to0$ means $|e(\delta)|\le C\|\delta\|^k$ for small $\delta$; $o(\|\delta\|^k)$ means $e/\|\delta\|^k\to0$. As $n\to\infty$ the same symbol bounds growth: "$O(n^2)$ operations" means at most $Cn^2$. Same definition, opposite limit: always say which variable goes where. Two $C^2$ functions that agree to first order at $x_0$ (value and gradient) differ by $O(\|\delta\|^2)$: first-order agreement fixes the gradient but says nothing quantitative at a finite step, which needs a second-order bound.

Worked example — Multiplying expansions; linearising with a quadratic remainder

With $e^u=1+u+\tfrac{u^2}2+O(u^3)$, multiply term by term and collect everything of total order $\ge3$ into $O(h^3)$:

$$(2-e^{-ah})\,e^{bh}=\big[1+ah-\tfrac{a^2h^2}{2}\big]\big[1+bh+\tfrac{b^2h^2}{2}\big]+O(h^3)=1+(a+b)h+\big(ab+\tfrac{b^2}{2}-\tfrac{a^2}{2}\big)h^2+O(h^3).$$

For $a=0.6$, $b=1.3$ the error of the quadratic is $7.0\cdot10^{-4}\approx0.70h^3$ at $h=0.1$ and $6.8\cdot10^{-7}$ at $h=0.01$: a factor $1000$ for a factor $10$ in $h$, the signature of $O(h^3)$. Subtracting $1$ and dividing by $h=1/\tau$ gives $p^\star(\tau)=a+b+(ab+\tfrac{b^2}{2}-\tfrac{a^2}{2})/\tau+O(\tau^{-2})$ in Exercise 7.3.

Linearisation. For $C^2$ $F$ with $F(0)=0$, $A=J_F(0)$ and $F(x)=Ax+r(x)$: if $\|\nabla^2F_i\|\le M_i$ on $\|z\|\le\rho$, the Taylor bound per component gives $\|r(x)\|\le k\|x\|^2$ there, with $k=\tfrac12(\sum_iM_i^2)^{1/2}$. Example: $F=(0.5x_1+x_2^2,\ 0.5x_2)$ has $A=0.5I$, $r=(x_2^2,0)$, $M_1=2$, $M_2=0$, $k=1$, and indeed $\|r\|=x_2^2\le\|x\|^2$.

Theorem — Integrating the gradient along a segment (mean value theorem)
If $f$ is $C^1$ near the segment from $x$ to $x+\delta$, then $\varphi(t)=f(x+t\delta)$ has $\varphi'(t)=\nabla f(x+t\delta)^{\top}\delta$, and
$$f(x+\delta)-f(x)=\int_0^1\nabla f(x+t\delta)^{\top}\delta\,dt=\nabla f(x+\xi\delta)^{\top}\delta\quad\text{for some }\xi\in(0,1).$$
For $f:\mathbb R^n\to\mathbb R^m$ integrate each component: $f(x+\delta)-f(x)=\big(\int_0^1J_f(x+t\delta)dt\big)\delta$, so $\|f(x+\delta)-f(x)\|\le\sup_t\|J_f(x+t\delta)\|\,\|\delta\|$. If only $r(t)=f(x+t\delta)$ is continuous and piecewise $C^1$ (a ReLU network along any segment), use $f(x+\delta)-f(x)=\int_0^1r'(t)\,dt$: $r'(t)=J_f(x+t\delta)\delta$ where $f$ is differentiable, and for a ReLU network $r'(t)=J_k\delta$ with $J_k$ the Jacobian of an affine piece containing that stretch, even if the segment runs inside a kink ($f=|x_1|+x_2$ has no gradient on the $x_2$-axis, yet $r(t)=t$ there). Caution: for vector-valued maps there is no single $\xi$: $(\cos t,\sin t)$ returns to its start on $[0,2\pi]$ although its derivative never vanishes.
Fact — An interior minimiser has zero gradient
If $x^\star$ is a local minimiser in the interior of the domain and $f$ is differentiable there, then $\nabla f(x^\star)=0$. Proof. $\varphi(t)=f(x^\star+tv)$ has a local minimum at $0$, so $\nabla f(x^\star)^{\top}v=\varphi'(0)=0$ for every $v$; take $v=\nabla f(x^\star)$. For $f\in C^2$ also $\nabla^2f(x^\star)\succeq0$, and $\nabla f=0$ with $\nabla^2f\succ0$ gives a strict local minimum. On the boundary the gradient need not vanish ($\min x$ over $x\ge0$; Section 6), and a zero gradient can be a saddle ($x_1^2-x_2^2$); for convex $f$ it suffices (Section 4).
Where this is used
  • Lie derivatives, derivatives along trajectories: the CBF condition (Module 1, Module 10), $C^1$ safe value functions (Module 7), $\tfrac{d}{dt}x^{\top}Px$ for controller states (Module 14), $\tfrac{d}{dt}\nabla f=\nabla^2f\,\dot x$ in the multiplier ODE (Module 8), time scaling $q(s(t))$ (Module 10).
  • Jacobians, backpropagation: $\|J_f\|$ and Lipschitz constants (Module 12), $W_k^{\top}$ and $\operatorname{diag}(\sigma')$ in the backward pass (Module 13), integrating a network gradient along a segment (Module 15).
  • Taylor and $O(\cdot)$: Module 7 (Exercise 7.3), first-order agreement of surrogates (Module 9), $\|r(x)\|\le k\|x\|^2$ (Module 11). Stationarity in KKT (Module 2).

Practice: Gradients, chain rules and Taylor models

Work from Easy to Medium before trying Hard. Use the review link for a missing definition, then try again with the explanation closed.

Exercise B.1a — Easy: Differentiate one coordinate at a time

For $f(x_1,x_2)=x_1^2+x_1x_2+2x_2^2$, compute the gradient and Hessian. Evaluate the gradient at $(1,-1)$ and find the directional derivative there along $v=(0,1)$.

Review: Gradients, chain rules and Taylor models

Show hint

When taking a partial derivative, hold the other coordinate fixed. The directional derivative is the dot product with v.

Show worked solution

First derivatives: $\partial f/\partial x_1=2x_1+x_2$ because x2 is constant in that calculation. Similarly $\partial f/\partial x_2=x_1+4x_2$. Thus $\nabla f=(2x_1+x_2,\ x_1+4x_2)^\top$.

Second derivatives: differentiating these entries gives $\nabla^2 f=\begin{bmatrix}2&1\\1&4\end{bmatrix}$. The mixed partials agree, as expected for a polynomial.

At the point: $\nabla f(1,-1)=(1,-3)^\top$. The directional derivative is $(1,-3)^\top(0,1)=-3$. For a small positive vertical displacement t, f therefore changes by $-3t+O(t^2)$; a gradient is a local slope, not a finite-step change.

Exercise B.1b — Medium: Follow a scalar function along a curve

Let $h(x)=1-x_1^2-x_2^2$ and $x(t)=(t,t^2)$. Find $dh(x(t))/dt$ in two ways and evaluate it at $t=1$. Explain the sign.

Review: Gradients, chain rules and Taylor models

Show hint

First substitute t to obtain a one-variable polynomial. Then independently use $\nabla h(x(t))^\top\dot x(t)$.

Show worked solution

Substitution: $h(x(t))=1-t^2-t^4$. Ordinary differentiation gives $dh/dt=-2t-4t^3$, hence the derivative at $t=1$ is $-6$.

Chain rule: $\nabla h(x)=(-2x_1,-2x_2)^\top$, so along the curve it is $(-2t,-2t^2)^\top$. Meanwhile $\dot x=(1,2t)^\top$. Their dot product is $-2t-4t^3$, agreeing with substitution.

Interpret: at $t=1$, h is $-1$ and decreases with time. If safety is $h\ge0$, the point is already outside the safe set and moving towards more negative margin. The derivative reports the immediate change; it does not claim the entire path is safe.

Exercise B.1c — Hard: Quantify a Taylor approximation error

For $f(x,y)=e^x+y^2$, form the second-order Taylor model at $(0,0)$ and use it to approximate $f(0.1,0.2)$. Bound the approximation error with the scalar third-derivative remainder and compare to the actual value.

Review: Gradients, chain rules and Taylor models

Show hint

The $y^2$ part is already exact. Only the expansion $e^x=1+x+x^2/2+R_3$ has a remainder.

Show worked solution

Model: $f(0,0)=1$, $\nabla f(0,0)=(1,0)^\top$, and $\nabla^2f(0,0)=\operatorname{diag}(1,2)$. Therefore $m(x,y)=1+x+x^2/2+y^2$.

Approximation: $m(0.1,0.2)=1+0.1+0.005+0.04=1.145$. The exact value is $e^{0.1}+0.04\approx1.145170918$.

Remainder: the third derivative of $e^x$ is $e^x$ and is at most $e^{0.1}$ on $[0,0.1]$. Taylor's remainder therefore gives $0\le f-m\le e^{0.1}(0.1)^3/6\approx0.000184195$. The nonnegative sign also follows from the scalar Taylor remainder at some point in that interval.

Compare: the actual error is approximately $0.000170918$, below the bound. The second-order model includes a factor $1/2$ in front of the Hessian term; omitting it doubles the quadratic contribution and destroys this calculation.

2. Matrix Calculus You Will Need

All gradients with respect to vectors and matrices follow from one habit: write the first-order change of the function (its differential) and read the gradient off it.

Definition — Differential and the identification rule
For $f:\mathbb R^n\to\mathbb R$, $df=\nabla f(x)^{\top}dx$ is the first-order change caused by $dx$. For $g:\mathbb R^{m\times n}\to\mathbb R$: if $dg=\operatorname{tr}(G^{\top}dW)=\langle G,dW\rangle$ for all $dW$, then $\nabla_Wg=G$ (the matrix of partials $\partial g/\partial W_{ij}$); equivalently $g(W+\varepsilon E)=g(W)+\varepsilon\langle G,E\rangle+o(\varepsilon)$. Rules: $d(AXB)=A\,dX\,B$, $d(XY)=dX\,Y+X\,dY$, $d\operatorname{tr}X=\operatorname{tr}dX$, $\operatorname{tr}(AB)=\operatorname{tr}(BA)$, $\operatorname{tr}(A^{\top})=\operatorname{tr}A$.
FunctionGradient / differentialHow
$a^{\top}x$$a$$d(a^{\top}x)=a^{\top}dx$
$x^{\top}Ax$$(A+A^{\top})x$ ($=2Ax$ if $A=A^{\top}$); Hessian $A+A^{\top}$$dx^{\top}Ax+x^{\top}A\,dx$
$\|Ax-b\|^2$$2A^{\top}(Ax-b)$; Hessian $2A^{\top}A\succeq0$$r=Ax-b$, $d(r^{\top}r)=2r^{\top}A\,dx$
$\operatorname{tr}(AX)$$A^{\top}$$\operatorname{tr}(A\,dX)=\langle A^{\top},dX\rangle$
$\|X\|_F^2$$2X$$2\operatorname{tr}(X^{\top}dX)$
$\log\det X$, $X\succ0$$X^{-1}$; directional derivative $\operatorname{tr}(X^{-1}E)$below
$X^{-1}$$d(X^{-1})=-X^{-1}\,dX\,X^{-1}$differentiate $XX^{-1}=I$

Why $X^{-1}$ for $\log\det$. $\det(X+\varepsilon E)=\det X\det(I+\varepsilon X^{-1}E)$ and $\det(I+\varepsilon M)=\prod_i(1+\varepsilon\mu_i)=1+\varepsilon\operatorname{tr}M+O(\varepsilon^2)$ ($\mu_i$ the eigenvalues of $M$), so $\log\det(X+\varepsilon E)=\log\det X+\varepsilon\operatorname{tr}(X^{-1}E)+O(\varepsilon^2)$. Check with $X=\begin{bmatrix}2 & 1\\ 1 & 2\end{bmatrix}$, $E=\begin{bmatrix}0 & 1\\ 1 & 0\end{bmatrix}$: $\det(X+\varepsilon E)=3-2\varepsilon-\varepsilon^2$ has log-slope $-\tfrac23$ at $0$, and $\operatorname{tr}(X^{-1}E)=\tfrac13(-1-1)=-\tfrac23$. For the inverse, $dX\,X^{-1}+X\,d(X^{-1})=d(I)=0$ (scalar case: $d(1/x)=-dx/x^2$).

Example (least squares). Fitting $y\approx\theta_1+\theta_2t$ to $(0,1),(1,2),(2,2)$: $A=\begin{bmatrix}1 & 0\\ 1 & 1\\ 1 & 2\end{bmatrix}$, $b=(1,2,2)$, and $\nabla\|A\theta-b\|^2=0$ gives the normal equations $\begin{bmatrix}3 & 3\\ 3 & 5\end{bmatrix}\theta=\begin{bmatrix}5\\ 6\end{bmatrix}$, so $\theta=(7/6,1/2)$; the residual $(1/6,-1/3,1/6)$ is orthogonal to both columns. The Hessian $2A^{\top}A\succ0$ makes this the global minimiser (Section 4). The ridge objective $\|y-K\alpha\|^2+\lambda\alpha^{\top}K\alpha$ of GP regression has gradient $-2K(y-(K+\lambda I)\alpha)$, which vanishes at $\alpha=(K+\lambda I)^{-1}y$.

Worked example — The chain rule through a matrix-valued map (a log-det barrier)

For symmetric $N(W)\succ0$, $d\log\det N=\operatorname{tr}(N^{-1}dN)$. The barrier $g(W)=-\log\det(cI-W^{\top}W)$ is defined while $\|W\|^2\lt c$. With $N=cI-W^{\top}W$, $dN=-(dW^{\top}W+W^{\top}dW)$ and

$$dg=\operatorname{tr}\big(N^{-1}(dW^{\top}W+W^{\top}dW)\big)=2\operatorname{tr}(N^{-1}W^{\top}dW)\ \Longrightarrow\ \nabla_Wg=2WN^{-1},$$

using $\operatorname{tr}(N^{-1}dW^{\top}W)=\operatorname{tr}(W^{\top}dW\,N^{-1})=\operatorname{tr}(N^{-1}W^{\top}dW)$ (transpose, $N^{-1}$ symmetric, cyclicity). For $W=\begin{bmatrix}1 & 0.5\\ 0 & 1\end{bmatrix}$, $c=4$: $\nabla_Wg=\begin{bmatrix}0.75 & 0.5\\ 0.125 & 0.75\end{bmatrix}$, confirmed by finite differences.

Inverses, linear solves, optimisers. For $\|E\|\lt1$, $(I+E)^{-1}=I-E+E^2-\cdots$ (Neumann series), so $(X+\varepsilon E)^{-1}=X^{-1}-\varepsilon X^{-1}EX^{-1}+O(\varepsilon^2)$ and, for $\lambda\gt\|K\|$, $(K+\lambda I)^{-1}=\lambda^{-1}I-\lambda^{-2}K+O(\lambda^{-3})$, a matrix of norm at most $C\lambda^{-3}$ (eigenvalue by eigenvalue: $\tfrac1{\lambda+k_i}=\tfrac1\lambda-\tfrac{k_i}{\lambda^2}+O(\lambda^{-3})$). If $A(\theta)x=b(\theta)$, then $A\,dx+dA\,x=db$, so $dx=A^{-1}(db-dA\,x)$. If $x^\star(\theta)$ solves $\nabla_xF(x^\star,\theta)=0$ with $\nabla^2_{xx}F\succ0$, then $\partial x^\star/\partial\theta=-(\nabla^2_{xx}F)^{-1}\nabla^2_{x\theta}F$ (implicit function theorem): this is how sensitivities of an optimisation layer or an MPC problem are computed.

Hessian-vector products. For fixed $v$, $\nabla^2f(x)\,v=\nabla_x\big(\nabla f(x)^{\top}v\big)$, which autodiff computes for about the cost of two gradients without forming the $n\times n$ matrix. Example: $f=x_1^2x_2$ gives $\nabla f^{\top}v=2x_1x_2v_1+x_1^2v_2$, whose gradient $(2x_2v_1+2x_1v_2,\ 2x_1v_1)$ equals $\begin{bmatrix}2x_2 & 2x_1\\ 2x_1 & 0\end{bmatrix}v$. A cheaper approximation is $(\nabla f(x+\varepsilon v)-\nabla f(x))/\varepsilon$. In trust-region RL the matrix is the Hessian of the KL divergence at $\theta_k$ (the Fisher matrix), often damped to $(H+\beta I)v$, and conjugate gradients (Section 5) solve $Hx=g$ with these products alone.

Pitfall
Layouts differ: $\nabla_X\operatorname{tr}(AX)=A^{\top}$, not $A$, and tables listing $2X^{-1}-\operatorname{diag}(X^{-1})$ for $\log\det$ treat $X_{ij}$ and $X_{ji}$ as one variable. Test any formula against $\operatorname{tr}(G^{\top}E)$ for one concrete $E$.
Where this is used
Kernel ridge regression (Module 3) and the inverse expansion of Exercise 3.3 (Module 3); Fisher–vector products and CG in CPO (Module 9); the $\log\det$ directional derivative in barrier training (Module 12); $\beta(WW^{\top}-I)W$ (Exercise B.2) and inverses in Cayley layers (Module 13); NLP sensitivities (Module 11).

Practice: Matrix derivatives and sensitivity

Work from Easy to Medium before trying Hard. Use the review link for a missing definition, then try again with the explanation closed.

Exercise B.2a — Easy: Differentiate a least-squares objective

Let $A=\operatorname{diag}(1,2)$, $b=(1,1)$ and $f(x)=\|Ax-b\|^2$. Compute the gradient at $x=0$, the Hessian and the unique minimiser. Confirm using scalar expansion.

Review: Matrix derivatives and sensitivity

Show hint

Use $\nabla f=2A^\top(Ax-b)$, or expand the two squares.

Show worked solution

Residual gradient: at $x=0$, $Ax-b=(-1,-1)$, so $\nabla f(0)=2\operatorname{diag}(1,2)(-1,-1)^\top=(-2,-4)^\top$.

Hessian: $2A^\top A=\operatorname{diag}(2,8)\succ0$. Solving $Ax=b$ gives $x^\star=(1,1/2)$ with objective zero; a squared norm cannot be negative, so this is a global minimum. Since A is invertible it is unique.

Scalar check: $f=(x_1-1)^2+(2x_2-1)^2$, whose partials are $2(x_1-1)$ and $4(2x_2-1)$. This confirms both the transpose orientation and the factor from differentiating the inner $2x_2$.

Exercise B.2b — Medium: Differentiate log det in a concrete direction

For $X=\operatorname{diag}(2,3)$ and $E=\begin{bmatrix}1&1\\1&0\end{bmatrix}$, compute the derivative at $t=0$ of $\log\det(X+tE)$. Verify it by expanding the determinant. Also compute the derivative of $(X+tE)^{-1}$ at $0$.

Review: Matrix derivatives and sensitivity

Show hint

Use $\operatorname{tr}(X^{-1}E)$ for log det and $-X^{-1}EX^{-1}$ for the inverse.

Show worked solution

Log-det differential: $X^{-1}=\operatorname{diag}(1/2,1/3)$, so $X^{-1}E=\begin{bmatrix}1/2&1/2\\1/3&0\end{bmatrix}$ has trace $1/2$. This is the desired directional derivative.

Direct check: $X+tE=\begin{bmatrix}2+t&t\\t&3\end{bmatrix}$ has determinant $6+3t-t^2$. Differentiating its logarithm at $0$ gives $3/6=1/2$. The matrix remains PD for sufficiently small t, so log det is defined in a neighbourhood of $0$.

Inverse derivative: multiply on both sides by $X^{-1}$, preserving order: $-X^{-1}EX^{-1}=-\begin{bmatrix}1/4&1/6\\1/6&0\end{bmatrix}$. The off-diagonal entries scale by two different diagonal factors. Entrywise reciprocals would give the wrong operation.

Exercise B.2c — Hard: Differentiate a solution without differentiating an inverse

Let $A(\theta)=\operatorname{diag}(1+\theta,2)$, $b=(2,4)$, and $A(\theta)x(\theta)=b$ for $\theta\gt-1$. Derive $x^\prime(0)$ from the equation itself, then verify with the explicit solution. Predict $x(0.01)$ to first order and compute the prediction error.

Review: Matrix derivatives and sensitivity

Show hint

Differentiate $Ax=b$ to get $A^\prime x+Ax^\prime=0$, then solve for $x^\prime$.

Show worked solution

Differentiate the system: at $0$, $A=\operatorname{diag}(1,2)$, $A^\prime=\operatorname{diag}(1,0)$ and $x=(2,2)$. Thus $Ax^\prime=-A^\prime x=(-2,0)$, giving $x^\prime(0)=(-2,0)$.

Explicit check: solving the diagonal equations gives $x(\theta)=(2/(1+\theta),2)$. Differentiating yields $x^\prime(\theta)=(-2/(1+\theta)^2,0)$, agreeing at $0$.

Prediction: $x(0.01)\approx x(0)+0.01x^\prime(0)=(1.98,2)$. The exact first coordinate is $2/1.01\approx1.980198020$, so the Euclidean prediction error is $0.000198020$.

Reason for the order: the exact difference from $2-2\theta$ is $2\theta^2/(1+\theta)$ in the first coordinate, hence it is $O(\theta^2)$ near zero. The sensitivity equation uses a linear solve and extends to large systems where explicitly forming an inverse is undesirable.

3. Lipschitz Continuity, Smoothness & Sensitivity

A Lipschitz constant is a worst-case exchange rate between input change and output change. It turns one measurement at one point into a guarantee on a whole neighbourhood, which is why it appears in nearly every safety certificate of the section.

Definition — Lipschitz continuity, global and local
$f:D\to\mathbb R^m$ is $L$-Lipschitz on $D$ (for a distance $d$, e.g. $d(x,x')=\|x-x'\|$) if
$$\|f(x)-f(x')\|\le L\,d(x,x')\qquad\text{for all }x,x'\in D.$$
The smallest such $L$ is the Lipschitz constant; any larger number is also valid, and "a known Lipschitz constant" in a theorem means a known valid upper bound. $f$ is locally Lipschitz if every point has a neighbourhood where it is Lipschitz (the constant may vary), and non-expansive if $L\le1$.

Intuition and examples. Every chord has slope at most $L$, so around each point the graph stays in the cone $|f(x')-f(x)|\le L|x'-x|$. $|x|$ and $\sin x$ are $1$-Lipschitz on $\mathbb R$. $x^2$ is not Lipschitz on $\mathbb R$ (chord slope $x+x'$) but is $2R$-Lipschitz on $[-R,R]$, hence locally Lipschitz. $\sqrt x$ on $[0,1]$ is continuous but not Lipschitz (infinite slope at $0$), and a step function is not even continuous: Lipschitz $\Rightarrow$ continuous, not conversely.

Key equation — Transfer of a lower bound
$|f(x)-f(x')|\le L\,d(x,x')$ gives $f(x')\ge f(x)-L\,d(x,x')$. If $f(x)\ge\ell$ is known, safety means $f\ge h$, and $L\gt0$, every $x'$ with $d(x,x')\le(\ell-h)/L$ is certified without being evaluated. If $L=0$ and $\ell\ge h$, the function is constant on its domain and the whole domain is certified; use this case without dividing by zero. Example: $f(x_0)\ge0.5$, threshold $0$, $L=2$ certify $|x'-x_0|\le0.25$, and no more: $0.5-2|x'-x_0|$ is $2$-Lipschitz and hits $0$ there. If the true constant exceeds the assumed $L$, the certificate is void, not merely loose.
Theorem — A gradient bound is a Lipschitz constant (dual norms)
Let $f$ be $C^1$ on an open convex $D$ (or continuous and piecewise $C^1$ along segments), with inputs measured by a norm $\|\cdot\|$ whose dual norm is $\|g\|_*=\max_{\|d\|\le1}g^{\top}d$. Then $L=\sup_{x\in D}\|\nabla f(x)\|_*$ is the Lipschitz constant; for $f:\mathbb R^n\to\mathbb R^m$ with Euclidean norms, $L=\sup_x\|J_f(x)\|$. Dual pairs: $\ell_2\leftrightarrow\ell_2$, $\ell_1\leftrightarrow\ell_\infty$ (Hölder: $|g^{\top}d|\le\|g\|_*\|d\|$).
Proof. By Section 1, $|f(y)-f(x)|=\big|\int_0^1\nabla f(x+t(y-x))^{\top}(y-x)dt\big|\le\sup_D\|\nabla f\|_*\|y-x\|$ (piecewise case: the integrand is $r'(t)$, the gradient of the active piece times $y-x$). Conversely $\nabla f(x)^{\top}d$ is a limit of chord slopes, each $\le L\|d\|$.

Example. $f(x)=3x_1-x_2$ has gradient $g=(3,-1)$ everywhere, so $|f(x)-f(y)|$ is at most $3\|x-y\|_1$ ($\|g\|_\infty=3$), $4\|x-y\|_\infty$ ($\|g\|_1=4$) or $\sqrt{10}\|x-y\|_2$, each constant exact: an $\ell_\infty$ gradient bound gives an $\ell_1$ Lipschitz constant. For nonlinear $f$ bound each dual norm over $D$ separately: $(2.1,2.1)$ has a smaller $\ell_2$ but a larger $\ell_1$ norm than $(3,-1)$. With several smooth branches (an input saturation switching on and off) take the largest gradient norm over all branches.

Fact — Calculus of Lipschitz constants
$L(f\circ g)\le L(f)L(g)$; $\ L(f+g)\le L(f)+L(g)$; $\ L(af)=|a|L(f)$; for bounded scalars $L(fg)\le\sup|f|\,L(g)+\sup|g|\,L(f)$; if $|g|\ge c\gt0$, $L(1/g)\le L(g)/c^2$. Proofs: $\|f(g(x))-f(g(y))\|\le L(f)\|g(x)-g(y)\|$; $\ fg(x)-fg(y)=f(x)(g(x)-g(y))+g(y)(f(x)-f(y))$; $\ \tfrac1{g(x)}-\tfrac1{g(y)}=\tfrac{g(y)-g(x)}{g(x)g(y)}$.
Local versions. $C^1$ functions are locally Lipschitz (a continuous gradient is bounded on a closed ball). If $f$ and $g$ are locally Lipschitz and $g(x_0)\ne0$, continuity gives $|g|\ge|g(x_0)|/2$ near $x_0$, so $f/g$ is locally Lipschitz there by the two rules above. Continuity of $g$ alone is not enough: $g=1+\sqrt{|x|}$ has $g(0)=1$, but $1/g$ has infinite slope at $0$. Hence closed-form safety filters dividing by $\|L_gh\|^2$ are locally Lipschitz away from $L_gh=0$ provided $L_fh$, $L_gh$, $\alpha$ and the nominal input are locally Lipschitz (e.g. locally Lipschitz dynamics and $\nabla h$). A network with $1$-Lipschitz activations has $L\le\prod_k\|W_k\|$.
Two arguments. If $|g(a,x)-g(a',x)|\le L_a\|a-a'\|$ for every $x$ and $|g(a,x)-g(a,x')|\le L_x\|x-x'\|$ for every $a$, then inserting $g(a',x)$ gives $|g(a,x)-g(a',x')|\le L_a\|a-a'\|+L_x\|x-x'\|$. The bounds must be uniform in the other argument.

Sensitivity along trajectories. Compositions of non-expansive maps are non-expansive, so trajectories of $x_{t+1}=F(x_t)$ with $L(F)\le1$ never separate; the Euler step $x^+=(1-hk)x$ of $\dot x=-kx$ is non-expansive iff $0\le hk\le2$. For nonempty families of real values $a_t,b_t$ bounded below, with $|a_t-b_t|$ bounded above, $|\inf_ta_t-\inf_tb_t|\le\sup_t|a_t-b_t|$ (compare each family with the other plus the finite uniform difference bound). Thus, with an $L$-Lipschitz $\bar g$ and non-expansive dynamics, the real margin $\inf_t\bar g(x_t)$ is $L$-Lipschitz in $x_0$ provided every trajectory has $\bar g(x_t)$ bounded below; this condition makes each margin finite. For a model $\hat f$ with $\|f^\star-\hat f\|\le e$ and $f^\star$ $L_f$-Lipschitz, prediction errors obey $d_{t+1}\le L_fd_t+e$, so $d_t\le L_f^td_0+e\sum_{j\lt t}L_f^j$. From the same initial state ($d_0=0$) this is $e(L_f^t-1)/(L_f-1)$, or $et$ if $L_f=1$: $e=0.01$, $L_f=1.1$ give $d_{10}\le0.159375$ (the exact bound is $0.15937424601$, rounded upward), and margins grow geometrically when $L_f\gt1$. In continuous time a Lipschitz vector field gives unique solutions with $\|x(t)-x'(t)\|\le e^{Lt}\|x(0)-x'(0)\|$ (Primer D); a merely continuous one need not: $\dot x=\sqrt{|x|}$, $x(0)=0$ is solved by $x\equiv0$ and by $x=t^2/4$.

Definition — Hölder continuity and moduli of continuity
A modulus of continuity is a nondecreasing $\omega:[0,\infty)\to[0,\infty)$, $\omega(0)=0$, continuous at $0$, with $|f(x)-f(x')|\le\omega(d(x,x'))$. Lipschitz: $\omega(r)=Lr$; $\alpha$-Hölder: $\omega(r)=Cr^\alpha$, $0\lt\alpha\le1$ (e.g. $c\sqrt r$). The lower bound transfers as $f(x')\ge f(x)-\omega(d(x,x'))$: with margin $s\ge0$ and $\omega$ strictly increasing, the radius $\omega^{-1}(s)$ is certified. $\omega^{-1}$ exists only on the range of $\omega$; for a bounded modulus such as $1-e^{-r}$ and $s\ge\sup\omega$, every point is certified. Example, $s=0.2$: $\omega=2r$ gives radius $0.1$, $\omega=2\sqrt r$ only $(s/2)^2=0.01$.
Fact — Grids, covering radii and the Lipschitz margin
A finite $G\subset D$ has covering radius $r_c$ (is an $r_c$-net) if every $x\in D$ is within $r_c$ of some $g\in G$. Then $f(x)\ge f(g)-Lr_c$ for the nearest $g$, so the grid test $f(g)\ge Lr_c$ for all $g\in G$ (not $f(g)\ge0$) certifies $f\ge0$ on all of $D$; renaming or enlarging $L$ does not remove this margin. A cubic grid on $[0,1]^d$ with equal spacing $\Delta=1/N$ for a positive integer $N$, including endpoints, has $(N+1)^d=(1/\Delta+1)^d$ points and $\ell_2$ covering radius $\tfrac{\sqrt d}2\Delta$: for $\Delta=0.1$, $11$ points in $d=1$ but $11^6\approx1.8$ million in $d=6$ (the curse of dimensionality). The fewest points of an $\varepsilon$-net is the covering number, of order $(1/\varepsilon)^d$ for a cube. Gradients work the same way: if $\|\nabla^2f\|\le H$, then $\|\nabla f(x)\|\le\|\nabla f(g)\|+Hr_c$ on the cell of $g$.
Definition — $L$-smooth functions and the descent lemma
$f$ is $L$-smooth if $\|\nabla f(x)-\nabla f(y)\|\le L\|x-y\|$ (for $C^2$ on a convex set: $\|\nabla^2f\|\le L$). Then $f(y)\le f(x)+\nabla f(x)^{\top}(y-x)+\tfrac L2\|y-x\|^2$. Proof: the left side minus the first two terms on the right is $\int_0^1(\nabla f(x+t(y-x))-\nabla f(x))^{\top}(y-x)\,dt\le\int_0^1Lt\|y-x\|^2dt$. Example: $\tfrac12x^{\top}Qx$ with $Q\succeq0$ is $\lambda_{\max}(Q)$-smooth. $|x|$ is Lipschitz but not smooth; $x^2$ is smooth but not globally Lipschitz.
Going deeper — Rademacher's theorem and set-valued maps

Rademacher's theorem (statement): a Lipschitz $f:\mathbb R^n\to\mathbb R^m$ is differentiable except on a set of zero volume ("almost everywhere"), and its Lipschitz constant is the supremum of $\|J_f\|$ where the Jacobian exists. A set-valued map $F$ is $L$-Lipschitz if $d_H(F(x),F(x'))\le L\|x-x'\|$, with Hausdorff distance $d_H(A,B)=\max\{\sup_{a\in A}\operatorname{dist}(a,B),\sup_{b\in B}\operatorname{dist}(b,A)\}$.

Pitfall
The largest gradient norm at sampled points is a lower bound on the Lipschitz constant and certifies nothing. A local constant (valid on a ball around $x$) only covers perturbations inside that ball. On a nonconvex domain a gradient bound controls changes along paths inside the domain, not along segments that leave it.
Where this is used
  • Transferring lower bounds: SafeOpt's safe set (Module 4, Module 5), GP bounds (Module 3), parameters and initial states (Module 6). Moduli: LoSBO (Module 5), the square-root modulus of $\sigma_N$ (Module 3).
  • Grids and margins: continuous domains in SafeOpt (Module 4), why grids fail beyond small $d$ (Module 5), $\varepsilon$-nets (Module 10), sampled gradients plus a Hessian correction and $\ell_\infty/\ell_1$ duality (Module 11).
  • Composition, local constants, sensitivity: locally Lipschitz dynamics and filters (Module 10), $L_V,L_f,L_\pi$ (Module 11), local versus global constants (Module 12), model-error propagation (Module 9), non-expansive Euler steps and trajectory infima (Module 6), Lipschitz versus continuous dynamics (Module 7).

Practice: Lipschitz bounds, grids and model errors

Work from Easy to Medium before trying Hard. Use the review link for a missing definition, then try again with the explanation closed.

Exercise B.3a — Easy: Distinguish a function bound from a gradient bound

For $f(x)=x^2$, find the smallest Lipschitz constant on $[-2,2]$. Is f globally Lipschitz on $\mathbb R$? Is its derivative globally Lipschitz, and with what smallest constant?

Review: Lipschitz bounds, grids and model errors

Show hint

Factor $x^2-y^2=(x-y)(x+y)$. Smoothness concerns the derivative, not the function itself.

Show worked solution

On the interval: $|x^2-y^2|=|x-y||x+y|\le4|x-y|$ because $|x|,|y|\le2$. Chord slopes with $x=2$ and $y\uparrow2$ approach $4$, so no smaller constant works.

Globally: the chord slope between $x$ and $0$ is $|x|$, which is unbounded as $|x|\to\infty$. Thus f has no finite global Lipschitz constant.

Derivative: $f^\prime(x)=2x$ and $|f^\prime(x)-f^\prime(y)|=2|x-y|$ on all of $\mathbb R$. Therefore f is globally 2-smooth, even though it is not globally Lipschitz. Bounds on f and on its gradient answer different questions.

Exercise B.3b — Medium: Account for dimension in a grid certificate

On $[0,1]$, a 2-Lipschitz function has lower bound $0.15$ at every grid point of spacing $0.1$, including endpoints. Give a uniform lower bound. Repeat for a cubic grid of spacing $0.1$ on $[0,1]^3$ with Euclidean distance. What spacing would suffice in three dimensions?

Review: Lipschitz bounds, grids and model errors

Show hint

The farthest point in a cell is half its diagonal from a vertex: covering radius $\sqrt d\,\Delta/2$.

Show worked solution

One dimension: the covering radius is $0.05$, so everywhere $f(x)\ge0.15-2(0.05)=0.05$. This certifies a positive margin.

Three dimensions: the covering radius is $\sqrt3(0.1)/2$. The uniform bound becomes $0.15-0.1\sqrt3\approx-0.023205$, so these samples and this constant do not certify nonnegativity on the cube.

Required spacing: impose $2(\sqrt3\Delta/2)\le0.15$, obtaining $\Delta\le0.15/\sqrt3\approx0.086603$. If endpoints must be included with equal steps, $\Delta=1/12\approx0.083333$ works, using $13^3=2197$ grid points. Failure of the coarser certificate is not proof the function is negative.

Exercise B.3c — Hard: Propagate model error into a safety margin

The true dynamics and a predictor start at the same point. Their state error obeys $d_{t+1}\le1.2d_t+0.01$, with $d_0=0$. Bound $d_5$ and $d_6$. If a 2-Lipschitz margin h equals $0.2$ at each corresponding predicted state, what lower bounds follow for the true margin? Explain why the accumulated state-error bound can be tight.

Review: Lipschitz bounds, grids and model errors

Show hint

Unroll the recurrence into a geometric sum, then subtract twice the state-error bound from the predicted margin.

Show worked solution

Unroll: induction gives $d_t\le0.01\sum_{j=0}^{t-1}1.2^j=0.01(1.2^t-1)/0.2=0.05(1.2^t-1)$. The initial-error term is absent because $d_0=0$.

Numbers: $1.2^5=2.48832$ gives $d_5\le0.074416$. Similarly $1.2^6=2.985984$ gives $d_6\le0.0992992$.

Transfer safety: $h(x_t)\ge h(\hat x_t)-2d_t$. Thus the guaranteed margins are $0.2-2(0.074416)=0.051168$ at step 5 and $0.2-2(0.0992992)=0.0014016$ at step 6. Both are nonnegative, with very little spare margin at step 6.

Tight state error: consider scalar true dynamics $x^+=1.2x+0.01$ and predictor $\hat x^+=1.2\hat x$, both starting at $0$. The true state is nonnegative and the predictor stays at $0$, so their error obeys the recurrence with equality. Model error does not generally stay at its one-step size $0.01$.

4. Convex Sets, Convex Functions & Conjugates

Convexity makes local information global: a tangent plane underestimates the whole function, a stationary point is a global minimiser, and a feasible region has no hidden pockets. It separates problems that solvers answer reliably from problems they only attack heuristically.

Notation — Sets, topology and hulls (recap)
  • Sets (Primer 0): $\{x\in D:g(x)\ge0\}$ is "the $x$ in $D$ with $g(x)\ge0$"; $\in$, $\subseteq$, $\forall$ (for all), $\exists$ (there exists), $\cup$, $\cap$, $D\setminus S=\{x\in D:x\notin S\}$; $\bigcap_{i\in I}S_i$ holds the points in every $S_i$, $\bigcup_{i\in I}S_i$ those in at least one. Order matters: $C_t=C_{t-1}\cap Q_t$ can only shrink, and $D\setminus(A\cup B)=(D\setminus A)\cap(D\setminus B)$.
  • Topology (Primer 0): $x$ is interior to $S$ if a small ball around $x$ lies in $S$; $S$ is closed if it contains the limits of its convergent sequences; boundary = closure minus interior; in $\mathbb R^n$, compact = closed and bounded. Weierstrass: a continuous function on a nonempty compact set attains its maximum and minimum.
  • Affine hull, relative interior: $\operatorname{aff}S=\{\sum_i\theta_ix_i:x_i\in S,\ \sum_i\theta_i=1\}$ (weights may be negative) is the smallest shifted subspace containing $S$, and $\operatorname{relint}S$ is the interior relative to it. The segment from $(0,0)$ to $(1,0)$ has empty interior in $\mathbb R^2$ but relative interior the open segment; the simplex $\{p\in\mathbb R^3:p\ge0,\sum_ip_i=1\}$ has relative interior $\{\text{all }p_i\gt0\}$. Slater's condition asks for a strictly feasible point in $\operatorname{relint}\mathcal D$.
Definition — Convex set, convex combination, convex hull
$C$ is convex if $\theta x+(1-\theta)y\in C$ for all $x,y\in C$, $\theta\in[0,1]$: with $y$, the whole segment $y+\theta(x-y)$ lies in $C$. A convex combination is $\sum_i\theta_ix_i$ with $\theta_i\ge0$, $\sum_i\theta_i=1$; the convex hull $\operatorname{conv}S$ is the set of all finite convex combinations of points of $S$, the smallest convex set containing $S$.
Convex setWhy convex / remark
Ball $\{\|x-c\|\le r\}$, any norm$\|\theta x+(1-\theta)y-c\|\le\theta\|x-c\|+(1-\theta)\|y-c\|$
Half-space $\{a^{\top}x\le b\}$, hyperplane $\{a^{\top}x=b\}$normal vector $a$, signed offset $b/\|a\|$
Polyhedron $\{Hx\le h\}=\bigcap_i\{H_ix\le h_i\}$row $H_i$ is the outward normal of facet $i$
Polytope (bounded polyhedron)the convex hull of its finitely many vertices
Ellipsoid $\{(x-c)^{\top}P^{-1}(x-c)\le1\}$, $P\succ0$image of the unit ball under $u\mapsto c+P^{1/2}u$
Zonotope $\{c+G\xi:\|\xi\|_\infty\le1\}$affine image of a box (a parallelotope if $G$ is square and invertible)
PSD cone $\mathbb S^n_+$$x^{\top}(\theta A+(1-\theta)B)x=\theta x^{\top}Ax+(1-\theta)x^{\top}Bx\ge0$
Simplex $\Delta(\mathcal A)=\{p\ge0,\sum_ap_a=1\}$adding $p_a\ge\epsilon_0/|\mathcal A|$ gives the restricted simplex (nonempty iff $\epsilon_0\le1$); a stationary policy lies in the product $\Delta(\mathcal A)^{|\mathcal S|}$

Not convex: $\{\|x\|\ge1\}$, two disjoint intervals, the ReLU graph, $\{0,1\}^n$. Convexity is preserved by arbitrary intersections, Cartesian products, and affine images and preimages; linear maps commute with hulls, $A\operatorname{conv}S=\operatorname{conv}(AS)$, since $A\sum_i\theta_ix_i=\sum_i\theta_iAx_i$. Polytopes as quadratic constraints: for $x\in\{Hx\le h\}$ each product $(h-Hx)_i(h-Hx)_j\ge0$, so $(Hx-h)^{\top}\Gamma(Hx-h)\ge0$ for every $\Gamma$ with nonnegative entries, one quadratic form in $(x,1)$ once the constant coordinate is appended. It is an outer approximation: a point violating two facets also makes their product positive.

Definition — Convex, concave and extended-value functions
$f$ on a convex set is convex if $f(\theta x+(1-\theta)y)\le\theta f(x)+(1-\theta)f(y)$ (chords above the graph; equivalently the epigraph $\{(x,t):t\ge f(x)\}$ is convex), concave if $-f$ is convex; affine functions are both. With the value $+\infty$ allowed, $\operatorname{dom}f=\{f\lt\infty\}$; $f$ is proper if it is never $-\infty$ and not identically $+\infty$, and closed (lower semicontinuous) if all sublevel sets $\{f\le c\}$ are closed. The indicator $\iota_C$ ($0$ on $C$, $+\infty$ off it) turns a constraint into an objective: $\min_Cf=\min(f+\iota_C)$.

Recognising convexity. Convex: norms, $\|Ax+b\|$, $e^x$, $-\log x$, $x\log x$, $\tfrac12x^{\top}Qx$ ($Q\succeq0$), maxima of affine functions such as $\nu\mapsto(z-\nu)_+$, and the KL divergence (jointly). Concave: $\log x$, $\sqrt x$, $\log\det X$ ($X\succ0$), $\lambda_{\min}(X)=\min_{\|v\|=1}v^{\top}Xv$, and every infimum of affine functions, such as a Lagrange dual function. Rules: (i) nonnegative sums and expectations ($\theta\mapsto\mathbb E_zf(\theta,z)$ is convex if each $f(\cdot,z)$ is); (ii) composition with affine maps; (iii) pointwise maxima and suprema; (iv) partial minimisation: $\inf_yF(x,y)$ is convex if $F$ is jointly convex (and the infimum is $\gt-\infty$); (v) perspectives $t\,f(x/t)$, $t\gt0$.

Proof — Partial minimisation and perspectives; separate convexity and symmetry

(iv) For $\varepsilon\gt0$ pick $y_i$ with $F(x_i,y_i)\le h(x_i)+\varepsilon$; then $h(\theta x_1+(1-\theta)x_2)\le F(\theta(x_1,y_1)+(1-\theta)(x_2,y_2))\le\theta h(x_1)+(1-\theta)h(x_2)+\varepsilon$. (v) With $T=\theta t_1+(1-\theta)t_2$ and $\mu=\theta t_1/T$: $\theta t_1f(\tfrac{x_1}{t_1})+(1-\theta)t_2f(\tfrac{x_2}{t_2})=T[\mu f(\tfrac{x_1}{t_1})+(1-\mu)f(\tfrac{x_2}{t_2})]\ge Tf(\tfrac{\theta x_1+(1-\theta)x_2}{T})$. So $x^{\top}Mx/t$ ($M\succeq0$, $t\gt0$), the perspective of $x^{\top}Mx$, is jointly convex, also after restricting $x$ to an affine set.

Separate is not joint: $xy$ is linear in each variable, yet $f(t,-t)=-t^2$. Separate convexity still gives: the maximum over a box is attained at a vertex (a convex function of one variable on an interval peaks at an endpoint; push the coordinates to endpoints one at a time). Symmetry averaging: if $f$ is convex, the feasible set is convex, and a linear involution $S$ ($S(Sx)=x$) maps feasible points to feasible points with $f(Sx)=f(x)$, then $\tfrac12(x+Sx)$ is feasible, $S$-invariant, and $f(\tfrac12(x+Sx))\le\tfrac12f(x)+\tfrac12f(Sx)=f(x)$: if a minimiser exists, a symmetric one does. Convexity of $f$ is essential: $-x^2$ on $[-1,1]$ with $Sx=-x$ is minimised at $\pm1$, not at the symmetric point $0$.

Theorem — First- and second-order conditions, strong convexity
For $f$ differentiable on an open convex set:
  1. $f$ convex $\iff f(y)\ge f(x)+\nabla f(x)^{\top}(y-x)$ for all $x,y$. Hence $\nabla f(x^\star)=0$ gives a global minimum, and over a convex $C$, $x^\star$ is optimal iff $\nabla f(x^\star)^{\top}(y-x^\star)\ge0$ for all $y\in C$.
  2. For $f\in C^2$: convex $\iff\nabla^2f\succeq0$ everywhere.
  3. Convex $\iff\nabla f$ is monotone, $(\nabla f(x)-\nabla f(y))^{\top}(x-y)\ge0$ (in one variable: $f'$ nondecreasing).
  4. $\mu$-strongly convex ($\mu\ge0$): $f-\tfrac\mu2\|x\|^2$ convex $\iff f(y)\ge f(x)+\nabla f(x)^{\top}(y-x)+\tfrac\mu2\|y-x\|^2\iff(\nabla f(x)-\nabla f(y))^{\top}(x-y)\ge\mu\|x-y\|^2\iff\nabla^2f\succeq\mu I$. $\mu=0$ is plain convexity. For $\mu\gt0$ there is at most one minimiser, and on all of $\mathbb R^n$ one exists (the quadratic lower bound makes $f$ coercive); on a smaller open set it may not ($x^2$ on $(0,1)$). With $f^\star=\inf f$ always $f(x)-f^\star\le\tfrac1{2\mu}\|\nabla f(x)\|^2$, and if $x^\star$ exists, $\tfrac\mu2\|x-x^\star\|^2\le f(x)-f^\star$.
Proof of 1. ($\Rightarrow$) $f(x+\theta(y-x))\le f(x)+\theta(f(y)-f(x))$; subtract $f(x)$, divide by $\theta$, let $\theta\to0$. ($\Leftarrow$) Apply the inequality at $z=\theta x+(1-\theta)y$ towards $x$ and $y$, and add with weights $\theta,1-\theta$. Last bound of 4: minimising the right side of the strong-convexity inequality over $y$ gives $f^\star\ge f(x)-\|\nabla f(x)\|^2/(2\mu)$.

Example. $x_1^2+x_2^2+ax_1x_2$ has Hessian eigenvalues $2\pm a$: convex iff $|a|\le2$. For $a=3$ the diagonal is positive, yet $f(t,-t)=-t^2$: nonnegative curvature along the axes does not make a Hessian PSD.

Slopes and potentials: in one variable, for $0\le\mu\le L$, "$\Phi'$ has chord slopes in $[\mu,L]$" is exactly "$\Phi$ is $\mu$-strongly convex and $L$-smooth", so an activation slope-restricted in $[\alpha,\beta]$ with $0\le\alpha\le\beta$ (nondecreasing, as Module 12 assumes) is the derivative of the convex potential $\int_0^u\varphi$ (ReLU is the derivative of $\tfrac12(u)_+^2$). Negative slopes break this: $\varphi(u)=-u$ has the concave potential $-u^2/2$. A set $R$ of pairs is a monotone relation if $(a-a')(b-b')\ge0$ for all $(a,b),(a',b')\in R$; it may be multivalued, like the subdifferential of $|x|$, whose graph contains the vertical segment $\{0\}\times[-1,1]$.

Definition — Subgradients and one-sided derivatives
$g$ is a subgradient of convex $f$ at $x$ if $f(y)\ge f(x)+g^{\top}(y-x)$ for all $y$; $\partial f(x)$, the set of subgradients, is $\{\nabla f(x)\}$ where $f$ is differentiable (for concave $f$, supergradients reverse the inequality). In one variable the one-sided derivatives $f'_\pm(x)=\lim_{t\to0^\pm}\tfrac{f(x+t)-f(x)}{t}$ exist and $\partial f(x)=[f'_-(x),f'_+(x)]$. Optimality: $x^\star$ minimises $f$ iff $0\in\partial f(x^\star)$, in one variable iff $f'_-(x^\star)\le0\le f'_+(x^\star)$. For $\max_i(a_i^{\top}\lambda+b_i)$, the slope $a_j$ of any maximising piece is a subgradient.

Example. $Z$ uniform on $\{0,1,2,3\}$ and $F(\nu)=\nu+2\,\mathbb E(Z-\nu)_+$ (the Rockafellar–Uryasev function at level $\tfrac12$, Primer C), convex by rules (i) and (iii), with $F'_+(\nu)=1-2\,\mathbb P(Z\gt\nu)$, $F'_-(\nu)=1-2\,\mathbb P(Z\ge\nu)$. At $\nu=1$: $[-0.5,0]\ni0$; at $\nu=2$: $[0,0.5]\ni0$; in between $F'=0$. The minimisers form the interval $[1,2]$, and $\min F=2.5$, the mean of the upper half $\{2,3\}$ (the CVaR).

Theorem — Jensen's inequality
For convex $f$ and a random vector $X$ with $\mathbb E\|X\|\lt\infty$, $\mathbb E|f(X)|\lt\infty$: $f(\mathbb EX)\le\mathbb Ef(X)$; reversed for concave $f$. Equal weights: $f(\tfrac1n\sum_ix_i)\le\tfrac1n\sum_if(x_i)$. For strictly convex $f$, equality iff $X$ is constant with probability one. Proof. With a subgradient $g$ at $m=\mathbb EX$, $f(X)\ge f(m)+g^{\top}(X-m)$; take expectations.

Examples. $X$ uniform on $\{1,4,9,16\}$: $\mathbb E\sqrt X=2.5\le\sqrt{\mathbb EX}=\sqrt{7.5}\approx2.74$. Concavity of $\log$: $\sum_{i=1}^d\log(1+\mu_i/\lambda)\le d\log(1+\tfrac1d\sum_i\mu_i/\lambda)$, with equality iff all $\mu_i$ are equal; for $\lambda=1$, $\mu_1+\mu_2=4$: $(3,1)$ gives $\log8\approx2.08$, $(2,2)$ gives $\log9\approx2.20$. Sublevel sets $\{f\le c\}$ of convex $f$ are convex (e.g. the ellipsoid $\{x^{\top}Px\le c\}$, $P\succ0$), and $\{h\ge0\}$ is convex for concave $h$; the converse fails ($\sqrt{|x|}$).

log det and matrix convexity. $\log\det(X+tE)=\log\det X+\sum_i\log(1+t\mu_i)$ with $\mu_i$ the eigenvalues of $X^{-1/2}EX^{-1/2}$: concave in $t$, so $\log\det$ is concave on $X\succ0$ and maximising $\log\det S$ under LMIs is a convex problem (determinant maximisation, not an SDP with linear objective; interior-point solvers handle it). $F$ is matrix-convex if $F(\theta X+(1-\theta)Y)\preceq\theta F(X)+(1-\theta)F(Y)$ in the PSD order; $W\mapsto W^{\top}W$ is, since the difference equals $\theta(1-\theta)(A-B)^{\top}(A-B)\succeq0$. So $\{W:W^{\top}W\preceq M\}$ is convex, while a term such as $-W^{\top}TW$ on the side that must stay small is matrix-concave and destroys convexity. A product $TW$ of two unknowns is bilinear: a BMI, nonconvex jointly and affine once $T$ is fixed.

Definition — Convex conjugate and Fenchel–Young inequality
$f^*(y)=\sup_x(y^{\top}x-f(x))$ is convex even if $f$ is not (a supremum of affine functions of $y$), and $f(x)+f^*(y)\ge x^{\top}y$ with equality iff $y\in\partial f(x)$. Picture: $-f^*(y)$ is the intercept of the highest line of slope $y$ that stays below the graph. Fenchel–Moreau (statement): for a proper function, $f^{**}=f$ iff $f$ is closed and convex. Examples: $(x^2)^*=y^2/4$; $(\tfrac12x^{\top}Qx)^*=\tfrac12y^{\top}Q^{-1}y$ for $Q\succ0$; $f(w)=\tfrac12(w-1)^2$ on $w\ge0$ has $f^*(e)=e+e^2/2$ for $e\ge-1$ and $-\tfrac12$ for $e\lt-1$ (restricting the domain changes the conjugate).
Sign translations. Convex value function $p^\star(u)$, $\lambda\ge0$: $\inf_u(p^\star(u)+\lambda^{\top}u)=-(p^\star)^*(-\lambda)$. Concave value function $P(\xi)$: $\sup_\xi(P(\xi)-\lambda^{\top}\xi)=(-P)^*(-\lambda)$. For $\alpha\gt0$: $\sup_w(we-\alpha f(w))=\alpha f^*(e/\alpha)$.

Bregman divergence. $D_\varphi(x,y)=\varphi(x)-\varphi(y)-\nabla\varphi(y)^{\top}(x-y)\ge0$ for convex $\varphi$ (first-order condition). $\varphi=\tfrac12\|x\|^2$ gives $\tfrac12\|x-y\|^2$; the negative entropy $\sum_ip_i\log p_i$ gives $\mathrm{KL}(x\|y)$ on the simplex. It is not symmetric.

Convex problems (convex $f_0$, convex $f_i\le0$, affine $h_j=0$) have no bad local minima: if $y$ beat a local minimiser $x$, the points $x+\theta(y-x)$ for small $\theta$ would beat it too. A convex feasible region alone is not enough (maximising a nonconcave acquisition over a ball is nonconvex), and convexity depends on the variables: an objective can be convex in an auxiliary $\nu$ or in occupancy measures but not in network weights.

Where this is used

Practice: Convexity, subgradients and conjugates

Work from Easy to Medium before trying Hard. Use the review link for a missing definition, then try again with the explanation closed.

Exercise B.4a — Easy: Test convex sets with a midpoint

Which sets are convex: $C_1=[-1,2]$, $C_2=\{-1,1\}$ and $C_3=\{(x,y):x^2+y^2\le1\}$? Prove the positive cases and provide a failed midpoint for the negative one.

Review: Convexity, subgradients and conjugates

Show hint

A convex combination has nonnegative weights adding to one. A norm ball is convex by the triangle inequality.

Show worked solution

Interval: if $-1\le a,b\le2$ and $0\le\theta\le1$, multiplying these bounds by $\theta$ and $1-\theta$ and adding gives $-1\le\theta a+(1-\theta)b\le2$. Thus C1 is convex.

Two isolated points: the midpoint of $-1$ and $1$ is $0$, absent from C2. One counterexample suffices to show it is not convex.

Disc: for u and v with norms at most $1$, $\|\theta u+(1-\theta)v\|\le\theta\|u\|+(1-\theta)\|v\|\le1$. Hence the combination remains in C3. Checking a few sample midpoints would not prove this; the argument handles every pair and weight.

Exercise B.4b — Medium: Use a Hessian and handle a kink

For $f_a(x,y)=x^2+y^2+axy$, find the values of a making f convex and strongly convex. Separately, find every subgradient of $g(x)=|x|$ at $0$ and explain why $0$ is a minimiser.

Review: Convexity, subgradients and conjugates

Show hint

The Hessian is $\begin{bmatrix}2&a\\a&2\end{bmatrix}$. For the absolute value, apply $|y|\ge sy$ for every y.

Show worked solution

Curvature: the Hessian has eigenvalues $2+a$ and $2-a$. Both are nonnegative exactly when $|a|\le2$, which is the convexity range.

Strict lower curvature: the smallest eigenvalue is $2-|a|$. It is positive exactly when $|a|\lt2$, giving strong convexity constant $\mu=2-|a|$. At $a=\pm2$, f is a square with a flat direction and is not strongly convex.

Subgradients at the kink: s is a subgradient at zero when $|y|\ge sy$ for every y. Positive y requires $s\le1$; negative y requires $s\ge-1$. Therefore $\partial g(0)=[-1,1]$.

Optimality: this interval contains zero, so the subgradient condition certifies a global minimum at $0$. The ordinary derivative does not exist there; absence of a derivative does not prevent a convex function from having an exact optimality test.

Exercise B.4c — Hard: Derive a conjugate with a restricted domain

Let $f(x)=x^2/2$ for $x\ge0$ and $f(x)=+\infty$ for $x\lt0$. Compute $f^*(y)$ for every real y, including a maximising x. Check Fenchel–Young equality for $x=2,y=2$ and for $x=0,y=-1$.

Review: Convexity, subgradients and conjugates

Show hint

The supremum reduces to $\sup_{x\ge0}(yx-x^2/2)$. Compare the unconstrained maximiser x=y with the boundary x=0.

Show worked solution

Complete the square: $yx-x^2/2=y^2/2-(x-y)^2/2$. If $y\ge0$, x=y is permitted and maximises the expression, giving $f^*(y)=y^2/2$.

Negative y: for $x\ge0$ and $y\lt0$, both $yx$ and $-x^2/2$ are nonpositive. Their largest sum is $0$ at x=0. Thus $f^*(y)=0$ for $y\lt0$, or $f^*(y)=\tfrac12\max(y,0)^2$ for all y.

First equality check: at x=2,y=2, $f(x)+f^*(y)=2+2=4=xy$. At x=0,y=-1, both f and its conjugate are zero, again equal to xy.

Boundary meaning: negative slopes can support this extended-value function at x=0 because its domain stops there. Using the unrestricted conjugate $y^2/2$ for negative y would overlook the domain and incorrectly rule out this equality.

5. Gradient Descent, Newton's Method & Step Sizes

Controllers, multipliers and network weights are improved step by step. What matters is the step size, the information each step uses (gradients, noisy gradients, function values, curvature) and how many steps an accuracy costs.

Definition — Gradient descent and ascent
$x_{k+1}=x_k-\eta\nabla f(x_k)$ with step size (learning rate) $\eta\gt0$. To maximise, use gradient ascent $x_{k+1}=x_k+\eta\nabla f(x_k)$, i.e. descent on $-f$.

Step size and conditioning. On $f=\tfrac L2x^2$ with $L\gt0$, the iteration $x_{k+1}=(1-\eta L)x_k$ from a nonzero initial point converges iff $0\lt\eta\lt2/L$ (at $\eta=2/L$ it oscillates forever, $x_{k+1}=-x_k$), and $\eta=1/L$ lands on the minimiser at once; with $L=4$, $\eta=0.4$ multiplies by $-0.6$ (oscillating convergence) and $\eta=0.6$ by $-1.4$ (divergence). On $f=\tfrac12(x_1^2+10x_2^2)$ the curvatures are $\mu=1$ and $L=10$, the condition number is $\kappa=L/\mu=10$, and with $\eta=1/L$ the coordinate $x_2$ is solved in one step while $x_1$ shrinks only by $0.9$ per step: the flattest direction sets the pace, about $\kappa\ln(1/\varepsilon)$ steps (see the explorer).

Theorem — Gradient descent with $\eta=1/L$ on an $L$-smooth $f$
(1) $f\ge f_{\inf}$: $\ \min_{k\lt K}\|\nabla f(x_k)\|^2\le2L(f(x_0)-f_{\inf})/K$ (stationary points only, not global minima). (2) Convex with minimiser $x^\star$: $\ f(x_K)-f^\star\le L\|x_0-x^\star\|^2/(2K)$ (sublinear, $O(1/K)$). (3) $\mu$-strongly convex: $\ f(x_K)-f^\star\le(1-\mu/L)^K(f(x_0)-f^\star)$ (linear, or geometric). The walkthrough derives (1) and (3); (2) needs a longer telescoping argument (Bubeck 2015, Thm. 3.3, proves the same $O(1/K)$ rate with a constant about four times larger).

Rates and budgets (Primer 0). "An $O(1/\sqrt T)$ rate" means error $\le C/\sqrt T$ for large $T$, with $C$ hiding constants such as $L$, $\|x_0-x^\star\|$ or a noise level; $\Omega$ is a lower bound, $\Theta$ both. Solve for the budget: $C/\sqrt T\le\varepsilon$ needs $T\ge C^2/\varepsilon^2$, while $(1-1/\kappa)^T$ needs only $O(\kappa\log(1/\varepsilon))$ steps. Count iterations, work per iteration (a dense $n\times n$ solve $O(n^3)$, a matrix-vector product $O(n^2)$) and measurements per iteration separately.

Definition — Stochastic gradients and SGD
$g_k$ is unbiased if $\mathbb E[g_k\mid x_k]=\nabla f(x_k)$ (the average over the fresh sampling of step $k$, with $x_k$ held fixed), with bounded variance if $\mathbb E[\|g_k-\nabla f(x_k)\|^2\mid x_k]\le\sigma^2$; a minibatch average of $B$ independent samples has variance $\le\sigma^2/B$. SGD: $x_{k+1}=x_k-\eta_kg_k$. With persistent noise a constant step generally ends in a noise ball growing with $\eta\sigma^2$ (with $\sigma=0$ it is plain gradient descent, which does converge); Robbins–Monro steps, $\sum_k\eta_k=\infty$ and $\sum_k\eta_k^2\lt\infty$ (e.g. $c/(k+1)$), converge under standard assumptions. For $L$-smooth $f\ge f_{\inf}$, unbiased $g_k$ with variance $\le\sigma^2$ and a constant $\eta\le1/L$, the descent-lemma argument of the walkthrough above, with the extra term $\tfrac{L\eta^2}2\sigma^2$ per step (from $\mathbb E[\|g_k\|^2\mid x_k]\le\|\nabla f(x_k)\|^2+\sigma^2$), gives
$$\frac1K\sum_{k\lt K}\mathbb E\|\nabla f(x_k)\|^2\le\frac{2\,(f(x_0)-f_{\inf})}{\eta K}+L\eta\sigma^2,$$
so $\eta\propto1/\sqrt K$ gives $\mathbb E\min_{k\lt K}\|\nabla f(x_k)\|^2=O(1/\sqrt K)$. Two-timescale schemes move one variable (say a multiplier) much more slowly than another, which then sees it as frozen.

Example. $f(x)=\tfrac12\mathbb E(x-Z)^2$, $Z$ uniform on $\{1,2,3,6\}$: at $x=0$ the gradient is $-3$; the minibatch $\{1,6\}$ gives $-3.5$, $\{2,3\}$ gives $-2.5$, and the six minibatches of size two average exactly $-3$. Variants: momentum adds $\beta(x_k-x_{k-1})$, and accelerated methods improve $\kappa$ to $\sqrt\kappa$ in iteration counts; Adam rescales each coordinate by running averages of $g$ and $g^2$ (treat it as a black box). Zeroth-order methods see only values: $\hat g_i=(f(x+he_i)-f(x-he_i))/(2h)$ has error $O(h^2)$ but costs $2d$ evaluations, and noise is amplified by $1/h$; random search keeps random perturbations that improve $f$.

Definition — Newton's method, damping and backtracking
Where $\nabla^2f(x_k)\succ0$, minimise the quadratic Taylor model: solve $\nabla^2f(x_k)\Delta=-\nabla f(x_k)$ (never invert), a descent direction when $\nabla f(x_k)\ne0$ because $\nabla f^{\top}\Delta=-\nabla f^{\top}(\nabla^2f)^{-1}\nabla f\lt0$ (a zero gradient instead gives $\Delta=0$), and set $x_{k+1}=x_k+t\Delta$. Without a positive definite Hessian, the model may have no minimiser or may have nonunique minimisers: a negative-curvature direction makes it unbounded below, while a singular PSD Hessian can still attain a minimum (for example, the model $d_1^2$ is minimised by every $(0,d_2)$). A Newton direction from an indefinite Hessian can point uphill ($f=-x^2$ at $x=1$ gives $\Delta=-1$, which raises $f$ from $-1$ to $0$, and no backtracking repairs it): modify the Hessian (e.g. add $\beta I$ until it is positive definite) or use another descent direction. Pure Newton ($t=1$) solves a strictly convex quadratic in one step, and near a minimiser with $\nabla^2f\succ0$ and a locally Lipschitz Hessian the error roughly squares each step. Damped Newton uses backtracking: halve $t$, starting from $1$, until $x_k+t\Delta$ is in the domain and $f(x_k+t\Delta)\le f(x_k)+c\,t\,\nabla f(x_k)^{\top}\Delta$ (Armijo, e.g. $c=0.25$).

Example. $f(x)=x-\log x$ ($x\gt0$, minimiser $1$) gives $x^+=2x-x^2$, i.e. $1-x^+=(1-x)^2$: from $0.5$, the iterates $0.75,\ 0.9375,\ 0.99609,\ 0.9999847$ square the error. From $3$ the full step lands at $-3$, outside the domain; backtracking rejects $t=1$ and $t=\tfrac12$ (which gives $0$) and accepts $t=\tfrac14$: $x=1.5$, with $f(1.5)=1.095\le f(3)-0.25\cdot\tfrac14\cdot4=1.651$. Conjugate gradients solve $Hv=g$ ($H\succ0$) using only products $Hp$: they minimise $\tfrac12v^{\top}Hv-g^{\top}v$ over growing subspaces, finish in at most $n$ steps in exact arithmetic, report accuracy by the residual $\|g-Hv\|$, and need about $\sqrt{\kappa(H)}\log(1/\varepsilon)$ iterations; with Hessian-vector products (Section 2) this gives Newton-type steps for millions of parameters.

Four more ideas. (1) Majorise–minimise: a surrogate $u(\cdot\mid x_k)\ge f$ touching $f$ at $x_k$ gives $f(x_{k+1})\le u(x_{k+1}\mid x_k)\le u(x_k\mid x_k)=f(x_k)$ for its minimiser; gradient descent with $\eta=1/L$ is MM with the upper bound of Section 3, and minorise–maximise is the mirror image. (2) Mirror descent / multiplicative weights on the simplex: $p_{k+1}(a)\propto p_k(a)e^{-\eta g_k(a)}$, a step measured in KL instead of Euclidean distance that never leaves the simplex; $p=(\tfrac12,\tfrac12)$, $g=(1,0)$, $\eta=\ln2$ give $(\tfrac13,\tfrac23)$. (3) Trust regions for black-box search: accept only steps within a radius $\Delta_k$, enlarged after success and shrunk after failure. (4) Multi-start: minimising $x^4-2x^2+0.5x$, gradient descent from $0.5$ stops at the local minimiser $0.930$ ($f=-0.517$), from $-0.5$ at the global one $-1.057$ ($f=-1.515$); restarts help but certify nothing for nonconvex objectives.

Definition — One-dimensional searches: bisection and golden section
Bisection needs a bracket $[a,b]$ on which a continuous $g$ changes sign, or a yes/no test that switches exactly once (monotone feasibility); keep the half that still contains the switch, so after $k$ steps the bracket has width $(b-a)/2^k$. Example: $x^3=2$ on $[1,2]$: $1.5$ gives $+1.375$, keep $[1,1.5]$; $1.25$ gives $-0.047$, keep $[1.25,1.5]$; after $10$ halvings $[1.2598,1.2607]\ni2^{1/3}$. Ternary / golden-section search maximises a unimodal (e.g. concave) $f$: for $m_1\lt m_2$ inside the bracket, $f(m_1)\lt f(m_2)$ excludes $[a,m_1)$; golden-section spacing reuses a point and shrinks the bracket by $0.618$ per evaluation. Without monotonicity or unimodality neither method guarantees anything.
Pitfall
Steps above $2/L$ lose the convergence guarantee and can diverge (every such step diverges on $\tfrac L2x^2$ with $L\gt0$ from a nonzero initial point), persistent gradient noise generally stops constant-step SGD from converging exactly, a zero gradient can be a saddle, and rates hide constants. Bisection on a certified radius finds the largest radius this verifier certifies: with an incomplete verifier, "not certified" is not a counterexample.
Where this is used
Gradient steps, noisy and value-only estimates (Module 4, zeroth-order oracles in Module 14); local trust regions (Module 4); multi-start acquisition optimisation (Module 5); $O(1/\sqrt T)$ rates, smoothness and bounded variance, Robbins–Monro, multiplicative weights (Module 8); SGD, mirror descent, dual updates (Module 9); CG (Module 9); SGD, Newton and backtracking in barrier training (Module 12); SGD and Adam (Module 13); minorisation–maximisation (Module 11); ternary search on a concave $\lambda_{\min}$ (Module 2); bisection (Module 8, Module 15) and golden section (Module 14).

Practice: Steps, curvature and line searches

Work from Easy to Medium before trying Hard. Use the review link for a missing definition, then try again with the explanation closed.

Exercise B.5a — Easy: Compute iterates and detect an oversized step

For $f(x)=2x^2$ and $x_0=2$, compute the first two gradient-descent iterates with step $\eta=0.4$. What happens instead for $\eta=0.25$, $0.5$ and $0.6$?

Review: Steps, curvature and line searches

Show hint

The gradient is $4x$, so each update multiplies x by $1-4\eta$.

Show worked solution

Update rule: $x_{k+1}=x_k-4\eta x_k=(1-4\eta)x_k$. For $\eta=0.4$ this factor is $-0.6$, giving $x_1=-1.2$ and $x_2=0.72$. The signs alternate while the magnitudes decrease.

Other steps: $\eta=0.25$ gives factor zero, reaching the minimiser in one step. At $\eta=0.5$ the factor is $-1$, so the iterates alternate between $2$ and $-2$ forever. At $\eta=0.6$ the factor is $-1.4$, giving $-2.8,3.92,\dots$ with growing magnitude.

Condition: convergence from nonzero x0 requires $|1-4\eta|\lt1$, equivalent to $0\lt\eta\lt1/2=2/L$ with $L=4$. A small gradient-descent step need not decrease the coordinate monotonically; it decreases the objective here because the magnitude shrinks.

Exercise B.5b — Medium: Compare a Newton solve with one gradient step

Let $f(x)=\tfrac12x^\top Hx-c^\top x$, $H=\operatorname{diag}(2,8)$, $c=(2,8)$, and $x_0=(3,0)$. Compute one full Newton step and one gradient step with $\eta=1/8$. Which solves the problem exactly?

Review: Steps, curvature and line searches

Show hint

The gradient is Hx-c. Newton solves $H\Delta=-\nabla f$; gradient descent scales both coordinates by the same step size.

Show worked solution

Gradient: at x0 it is $(6,0)-(2,8)=(4,-8)$. The stationary equation $Hx=c$ gives $x^\star=(1,1)$. Since H is PD, this is the unique global minimiser.

Newton: solve $2\Delta_1=-4$, $8\Delta_2=8$, giving $\Delta=(-2,1)$ and $x_0+\Delta=(1,1)=x^\star$. Newton's quadratic model is exactly f, so a full step solves it.

Gradient descent: $x_1=(3,0)-(1/8)(4,-8)=(2.5,1)$. The steep second coordinate is solved, but the first coordinate still has error $1.5$.

Conditioning: H has eigenvalues $2$ and $8$, so its condition number is $4$. A single scalar step treats both directions alike; the Newton solve divides by their individual curvatures.

Exercise B.5c — Hard: Backtracking must check both the domain and decrease

For $f(x)=x-\log x$ on $x\gt0$, start Newton at $x=4$. Find the Newton direction and run backtracking over $t=1,1/2,1/4,\dots$ with Armijo constant $c=1/4$. Show the first accepted t and check the inequality numerically.

Review: Steps, curvature and line searches

Show hint

Use $f^\prime=1-1/x$, $f^{\prime^\prime}=1/x^2$, and reject any candidate outside the logarithm's domain before evaluating it.

Show worked solution

Direction: $f^\prime(4)=3/4$ and $f^{\prime^\prime}(4)=1/16$, so $\Delta=-f^\prime/f^{\prime^\prime}=-12$. The directional derivative $f^\prime(4)\Delta=-9\lt0$, so it is a descent direction.

Domain checks: t=1 gives $4-12=-8$ and t=1/2 gives $4-6=-2$; both are outside the domain and rejected. At t=1/4 the candidate is $1$, which is permitted.

Armijo: require $f(1)\le f(4)+\tfrac14\cdot\tfrac14\cdot(-9)$. The left side is $1$; the right is $4-\log4-9/16\approx2.051206$. The inequality holds, so the first accepted step is t=1/4.

Interpret: a descent direction controls infinitesimal changes, but a full step can leave the domain. Backtracking explicitly checks finite candidates; here it also lands exactly at the minimiser x=1.

6. Constraints: Lagrange Multipliers, Projections, Penalties & Barriers

Safety enters optimisation as constraints, handled in four ways: attach a price (multiplier), project onto the feasible set, penalise violations, or erect a barrier. The crucial difference is whether the answer is guaranteed to satisfy the constraint.

Definition — Constrained problem, feasibility, optimal value
$$p^\star=\inf_{x\in\mathcal D}\ f_0(x)\quad\text{s.t.}\quad f_i(x)\le0\ \ (i=1,\dots,m),\qquad h_j(x)=0\ \ (j=1,\dots,p).$$
$x$ is the decision variable, $\mathcal D$ the domain, $f_0$ the objective, $f_i\le0$ and $h_j=0$ the constraints. The feasible set $\mathcal F$ holds the points of $\mathcal D$ meeting all constraints; $p^\star=+\infty$ if $\mathcal F=\emptyset$ and $-\infty$ if $f_0$ is unbounded below on $\mathcal F$. A feasible $x^\star$ with $f_0(x^\star)=p^\star$ is a global optimum; a local one is best only among nearby feasible points. Maximising $f$ is minimising $-f$, and $g_i(a)\ge0$ is $-g_i(a)\le0$, so the feasible region $\{a:g_i(a)\ge0\ \forall i\}$ fits the template.

Lagrange multipliers. If $x^\star$ minimises $f$ subject to $h(x)=0$ and $\nabla h(x^\star)\ne0$, then $\nabla f(x^\star)+\nu\nabla h(x^\star)=0$ for some number $\nu$. Geometrically, the level set of $f$ is tangent to the constraint surface; otherwise sliding along the surface would decrease $f$. Example: minimise $x_1+x_2$ on the circle $x_1^2+x_2^2=2$. The conditions $(1,1)+\nu(2x_1,2x_2)=0$ and the constraint give $\nu=\pm\tfrac12$; $\nu=\tfrac12$ yields $x^\star=(-1,-1)$ and $p^\star=-2$. The multiplier is a price: with right-hand side $c$ instead of 2, $p^\star(c)=-\sqrt{2c}$, and $dp^\star/dc=-\tfrac12=-\nu$ at $c=2$.

Inequalities. Take one smooth constraint $f_1\le0$ and a local minimiser $x^\star$ in the interior of $\mathcal D$. Either the constraint is inactive ($f_1(x^\star)\lt0$): then it plays no role locally, $\lambda=0$ and $\nabla f_0(x^\star)=0$. Or it is active ($f_1(x^\star)=0$): then, if $\nabla f_1(x^\star)\ne0$, $\nabla f_0+\lambda\nabla f_1=0$ with $\lambda\ge0$, because the downhill direction must point out of the feasible set. Both cases are summarised by $\lambda\ge0$ and $\lambda f_1(x^\star)=0$ (complementary slackness). The condition $\nabla f_1(x^\star)\ne0$ is a constraint qualification; without one, no multiplier need exist (see below).

Running example ($f_0=(x-2)^2$, $f_1=x-1$): the unconstrained minimum $x=2$ is infeasible, so the constraint is active at $x^\star=1$, and $2(1-2)+\lambda=0$ gives $\lambda^\star=2$. For the looser constraint $x\le3$ the optimum $x=2$ is interior and $\lambda=0$. The general rules for several constraints at once are the KKT conditions below; duality behind them is in Module 2.

Intuition — A multiplier is an adjustable price, not a certificate
For fixed $\lambda\ge0$ the minimiser $x_\lambda$ of $f_0+\lambda f_1$ need not be feasible: in the running example $x_\lambda=2-\lambda/2$, feasible only for $\lambda\ge2$. Dual ascent adjusts the price, $\lambda\leftarrow[\lambda+\eta f_1(x_\lambda)]_+$: up while violated, down (not below $0$) while slack. The sign follows from the concave dual function $d(\lambda)=\inf_x(f_0+\lambda f_1)$, an infimum of affine functions of $\lambda$ with supergradient $f_1(x_\lambda)$: this is projected supergradient ascent. Here $d(\lambda)=\lambda-\lambda^2/4$ peaks at $\lambda=2$ with $d=1=p^\star$. For "maximise $J_r$ s.t. $J_c\le d$" the update is $\lambda\leftarrow[\lambda+\eta(J_c-d)]_+$.

The KKT conditions: several inequality constraints at once

In plain words. Picture a ball rolling downhill inside a fenced field. It comes to rest either in a dip in the middle of the field, where the ground is flat, or pressed against one or more fences. At a fence, gravity pulls the ball outward, into the fence, and the fence pushes back. The Karush–Kuhn–Tucker (KKT) conditions say exactly this. At a constrained minimum, the downhill pull $-\nabla f_0$ is cancelled by pushes from the constraints the point is touching. Each push has a strength $\lambda_i\ge0$, and a fence that is not touched pushes with strength zero.

Symbols in this subsection
Definition — KKT conditions and KKT points
For the problem above with $f_0,f_i,h_j$ differentiable on an open domain $\mathcal D$ (if $\mathcal D$ is not open, for example $x\ge0$, write that restriction as constraints $f_i\le0$), a point $x$ with multipliers $\lambda\in\mathbb R^m$, $\nu\in\mathbb R^p$ satisfies the KKT conditions if
  1. primal feasibility: $f_i(x)\le0$ for all $i$ and $h_j(x)=0$ for all $j$;
  2. dual feasibility: $\lambda_i\ge0$ for all $i$;
  3. complementary slackness: $\lambda_if_i(x)=0$ for all $i$, so an inactive constraint has $\lambda_i=0$;
  4. stationarity: $\nabla f_0(x)+\sum_i\lambda_i\nabla f_i(x)+\sum_j\nu_j\nabla h_j(x)=0$.
The triple $(x,\lambda,\nu)$, or just $x$, is then called a KKT point. Because of complementary slackness, only active constraints enter stationarity: $-\nabla f_0(x)=\sum_{i\in\mathcal A(x)}\lambda_i\nabla f_i(x)+\sum_j\nu_j\nabla h_j(x)$. The downhill direction is a nonnegative combination of the outward normals of the touched fences, plus a component that the equality constraints absorb.
Worked example — one active constraint, checked condition by condition

Minimise $f_0(x)=(x_1-2)^2+(x_2-1)^2$, the squared distance to the point $(2,1)$, subject to $f_1(x)=x_1+x_2-1\le0$.

Step 1: is the constraint active? Without it the minimum is $(2,1)$, but $2+1-1=2\gt0$: infeasible. So the constraint must be active at the solution, $x_1+x_2=1$.

Step 2: stationarity. $\nabla f_0+\lambda\nabla f_1=\big(2(x_1-2),\,2(x_2-1)\big)+\lambda(1,1)=0$ gives $x_1=2-\lambda/2$ and $x_2=1-\lambda/2$.

Step 3: use the active constraint. $x_1+x_2=3-\lambda=1$, so $\lambda=2$ and $x^\star=(1,0)$, with cost $f_0(x^\star)=1+1=2$.

Step 4: check all four conditions. Feasibility: $1+0-1=0\le0$. Dual feasibility: $\lambda=2\ge0$. Complementary slackness: $\lambda f_1(x^\star)=2\cdot0=0$. Stationarity: $(-2,-2)+2\,(1,1)=(0,0)$.

Picture. At $x^\star$ the downhill pull is $-\nabla f_0(x^\star)=(2,2)$. It points along $(1,1)$, the outward normal of the line $x_1+x_2=1$, straight into the fence. The fence cancels it with push strength $\lambda=2$.

The multiplier as a price. Relax the constraint to $x_1+x_2\le b$. The optimal cost is the squared distance from $(2,1)$ to that half-plane, $(3-b)^2/2$ for $b\le3$. Its derivative at $b=1$ is $-(3-1)=-2=-\lambda$: one extra unit of budget saves about $\lambda=2$ units of cost.

Worked example — finding the active set by trying every candidate

Keep the problem above and add a second constraint, $f_2(x)=x_1-0.5\le0$. With two constraints there are four candidate active sets. For each one, solve the equations it implies and check the remaining conditions.

  • None active: the unconstrained minimum $(2,1)$ violates both constraints. Rejected.
  • Only $f_1$ active: this is the previous example, $x=(1,0)$. But $f_2(1,0)=0.5\gt0$. Rejected.
  • Only $f_2$ active: $x_1=0.5$; minimising over $x_2$ gives $x_2=1$. But $f_1(0.5,1)=0.5\gt0$. Rejected.
  • Both active: $x_1=0.5$ and $x_1+x_2=1$ give $x=(0.5,0.5)$. There $\nabla f_0=(2(0.5-2),\,2(0.5-1))=(-3,-1)$, and stationarity reads
    $$(-3,-1)+\lambda_1(1,1)+\lambda_2(1,0)=(0,0).$$
    The second component gives $\lambda_1=1$, and the first gives $-3+1+\lambda_2=0$, so $\lambda_2=2$. Both are $\ge0$: a KKT point.

Here $f_0$ is convex and the constraints are affine, so a KKT point is a global minimum (Module 2 proves why). The minimum is $x^\star=(0.5,0.5)$ with cost $1.5^2+0.5^2=2.5$.

Reading the prices. $\lambda_2=2\gt\lambda_1=1$, so the second constraint is the more expensive one. Relaxing $x_1\le0.5$ by a small $\epsilon$ saves about $2\epsilon$ in cost; relaxing $x_1+x_2\le1$ by $\epsilon$ saves about $\epsilon$.

Worked example — a negative multiplier means the guessed active set is wrong

Take the first example again, now with the extra constraint $f_2(x)=-x_2-1\le0$, that is, $x_2\ge-1$. Suppose you guess that both constraints are active. Then $x_2=-1$ and $x_1=2$, and $\nabla f_0(2,-1)=(0,-4)$. With $\nabla f_1=(1,1)$ and $\nabla f_2=(0,-1)$, stationarity reads

$$(0,-4)+\lambda_1(1,1)+\lambda_2(0,-1)=(0,0)\quad\Longrightarrow\quad \lambda_1=0,\ \ \lambda_2=-4 .$$

A negative multiplier violates dual feasibility. In the picture, the fence $x_2\ge-1$ would have to pull the point toward itself, because moving away from that fence lowers the cost. So that constraint is not really binding: drop it from the guess. With only $f_1$ active you get the first example's $x^\star=(1,0)$ and $\lambda_1=2$. There $f_2(1,0)=-1\lt0$ is inactive, so $\lambda_2=0$, and all four conditions hold.

When must a minimum satisfy KKT? Constraint qualifications

KKT is a test that every well-behaved minimiser passes. Well-behaved is made precise by a constraint qualification (CQ): a condition on the constraints at the point, which guarantees that their gradients describe the feasible set correctly nearby. Without one, a true minimiser can fail the test. Minimise $x$ subject to $x^2\le0$: the only feasible point is $x^\star=0$, so it is the minimiser. But $\nabla(x^2)=2x$ vanishes at $0$, so stationarity, $1+\lambda\cdot0=0$, has no solution. To first order the constraint looks like "$0\le0$", which allows every direction, while in reality no direction is allowed.

Definition — Three constraint qualifications
Let $x$ be feasible, with active set $\mathcal A(x)$.
  • LICQ (linear independence CQ): the gradients $\nabla f_i(x)$, $i\in\mathcal A(x)$, together with all $\nabla h_j(x)$, are linearly independent.
  • MFCQ (Mangasarian–Fromovitz CQ): the $\nabla h_j(x)$ are linearly independent, and there is a direction $d$ with $\nabla h_j(x)^{\top}d=0$ for all $j$ and $\nabla f_i(x)^{\top}d\lt0$ for every active $i$. In words: one direction moves strictly into all active inequality constraints at once while staying on the equality constraints. LICQ implies MFCQ.
  • Slater's condition (convex problems only: $f_0,f_i$ convex, $h_j$ affine): some point $\hat x$ has $f_i(\hat x)\lt0$ for all $i$ and $h_j(\hat x)=0$ for all $j$. It is a property of the whole problem, not of one point.
Theorem — KKT is necessary under a CQ, and sufficient under convexity
Assume $f_0,f_i,h_j$ are continuously differentiable on an open domain $\mathcal D$, as in the definition; for the convex statement $\mathcal D$ is also convex, and Slater's point must lie in $\mathcal D$. Restrictions of the domain itself must be written as constraints, or handled with the normal cone of Module 2; otherwise a minimiser on the boundary of $\mathcal D$ can fail stationarity.
  • If $x^\star$ is a local minimiser and LICQ holds at $x^\star$, there are unique multipliers $(\lambda^\star,\nu^\star)$ that make $(x^\star,\lambda^\star,\nu^\star)$ a KKT point (Nocedal & Wright, Numerical Optimization, Thm 12.1).
  • Under MFCQ, multipliers still exist at a local minimiser, and the set of all of them is bounded (Gauvin, 1977).
  • For a convex problem that satisfies Slater's condition, a feasible $x^\star$ is a global minimiser if and only if some multipliers make it a KKT point (Boyd & Vandenberghe, Sec. 5.5.3; the duality argument is in Module 2).
Worked example — checking the constraint qualifications in the examples above
  • First example, $x^\star=(1,0)$: one active gradient, $(1,1)\ne0$. A single nonzero vector is linearly independent, so LICQ holds, and the multiplier $\lambda=2$ is the only one possible.
  • Second example, $x^\star=(0.5,0.5)$: the active gradients $(1,1)$ and $(1,0)$ are linearly independent (neither is a multiple of the other). LICQ holds, so $(\lambda_1,\lambda_2)=(1,2)$ are the unique multipliers.
  • $\min x$ s.t. $x^2\le0$, $x^\star=0$: the active gradient is the zero vector. Any set containing the zero vector is linearly dependent, so LICQ fails. MFCQ fails too, since it would need $0\cdot d\lt0$. Slater fails as well, because no point has $x^2\lt0$. This is why the theorem gives no multiplier here.
  • Both first two problems are convex with a strictly feasible point (for example $(0,0)$, where $f_1=-1\lt0$ and $f_2=-0.5\lt0$). Slater holds, so in these problems KKT and global optimality are the same thing.

KKT points in non-convex problems. Without convexity, KKT is necessary (under a CQ) but not sufficient: a KKT point can be a local minimum, a saddle point, or even a local maximum. Algorithms for non-convex problems therefore usually promise convergence to a KKT point, or to an approximate one (below), not to a minimum. Examples are the primal–dual policy-gradient methods of Module 8 and the log-barrier method LB-SGD in Module 4.

Worked example — three KKT points, one of them a maximum

Minimise $f_0(x)=-x^2$ subject to $f_1(x)=x-1\le0$ and $f_2(x)=-x-1\le0$, that is, $-1\le x\le1$. Here $f_0'(x)=-2x$.

  • $x=0$: both constraints inactive, so $\lambda_1=\lambda_2=0$, and stationarity $f_0'(0)=0$ holds. A KKT point, but $f_0(0)=0$ is the largest value of $f_0$ on $[-1,1]$: a maximum.
  • $x=1$: $f_1$ active, and $f_0'(1)+\lambda_1\cdot1=-2+\lambda_1=0$ gives $\lambda_1=2\ge0$. A KKT point, and a global minimum with $f_0=-1$.
  • $x=-1$: $f_2$ active, and $f_0'(-1)+\lambda_2\cdot(-1)=2-\lambda_2=0$ gives $\lambda_2=2\ge0$. Also a global minimum.

An algorithm that "converges to a KKT point" may stop at $x=0$. For non-convex problems, a KKT point is a candidate, not a certificate.

Definition — Projection onto a set
$P_C(y)=\operatorname*{arg\,min}_{x\in C}\|x-y\|$. For nonempty closed convex $C$ it exists, is unique, satisfies $(y-P_C(y))^{\top}(x-P_C(y))\le0$ for all $x\in C$ (obtuse angle), and is non-expansive. Closed forms: box $[l,u]$ ($l\le u$): clip, $\min(\max(y_i,l_i),u_i)$ (for $[0,\infty)^n$: $(y)_+$); ball $\{\|x\|\le r\}$, $r\ge0$: $y$ if $\|y\|\le r$, else $ry/\|y\|$ (the compact form $y\min(1,r/\|y\|)$ needs $y\ne0$); half-space $\{a^{\top}x\le b\}$, $a\ne0$: $y-\tfrac{(a^{\top}y-b)_+}{\|a\|^2}a$ (for $a=0$ the set is all of $\mathbb R^n$ if $b\ge0$ and empty otherwise).

Examples. $(1.7,-0.4,0.3)\mapsto(1,0,0.3)$ on $[0,1]^3$; $(3,4)\mapsto(0.6,0.8)$ on the unit ball; $(2,1)\mapsto(1,0)$ on $\{x_1+x_2\le1\}$. Clipping is a two-ReLU network, $\operatorname{clip}_{[l,u]}(x)=u-(u-l-(x-l)_+)_+$: input saturation inside a network model. The interval must be closed and nonempty (on the open $(0,1)$ the point $2$ has no nearest point). Nonconvex sets can have several nearest points: $0$ projects onto $\{|x|\ge1\}$ as the set $\{-1,1\}$ (a tie-break is needed), and the nearest orthogonal matrix to an invertible $W=U\Sigma V^{\top}$ is $UV^{\top}$. The norm matters: projecting transformed coordinates is a different operation.

Definition — Normal and tangent cones; constrained stationarity
For convex $C$ and $x\in C$: $N_C(x)=\{v:v^{\top}(y-x)\le0\ \forall y\in C\}$, the outward directions: $\{0\}$ inside, $\{\lambda a:\lambda\ge0\}$ on the face $a^{\top}x=b$ of a half-space, a quadrant at a box corner. With $v+S=\{v+s:s\in S\}$, optimality of $x^\star$ for convex $f$ over $C$ reads $0\in\nabla f(x^\star)+N_C(x^\star)$. Example: $\min x$ over $[0,\infty)$: $x^\star=0$ and $-1\in N_C(0)=(-\infty,0]$. The tangent cone $T_C(x)$ holds the directions that stay in $C$ to first order; for $C=\{h\ge0\}$ at a boundary point with $\nabla h\ne0$ it is $\{d:\nabla h(x)^{\top}d\ge0\}$.

Projected gradient $x_{k+1}=P_C(x_k-\eta\nabla f(x_k))$ keeps iterates feasible, its fixed points satisfy $-\nabla f\in N_C$, and for $L$-smooth convex $f$ with $\eta=1/L$ it has the rates of Section 5. Projected gradient ascent over a box also serves to falsify a certificate by maximising its violation (a violation found refutes it; none found proves nothing) and to tighten a bound valid for every parameter value (e.g. relaxation slopes in $[0,1]^n$), where soundness never depends on reaching the optimum.

Definition — Penalties, slack variables, augmented Lagrangian
Quadratic penalty: $f_0+\tfrac\rho2\sum_i(f_i)_+^2$. Exact penalty: $f_0+\rho\sum_i(f_i)_+$. Slack: replace $f_i\le0$ by $f_i\le s_i$, $s_i\ge0$, and add $p\sum_is_i$ (or $p\sum_is_i^2$). Augmented Lagrangian ($f_1\le0$): minimise $f_0+\tfrac1{2\rho}[(\lambda+\rho f_1)_+^2-\lambda^2]$ over $x$, then $\lambda\leftarrow(\lambda+\rho f_1(x))_+$.

Running example. The quadratic penalty gives $x_\rho=\tfrac{4+\rho}{2+\rho}$: $1.5,\ 1.1,\ 1.01$ for $\rho=2,18,198$, always infeasible (violation $2/(2+\rho)$). The curvature is $2$ on one side and $2+\rho$ on the other, so large $\rho$ mixes very different scales (ill-conditioning): gradient steps must shrink like $1/\rho$, and errors in an approximate objective are amplified. The exact penalty returns $x=1$ for $\rho\ge2=\lambda^\star$, at the price of a kink; in general $\rho\gt\|\lambda^\star\|_\infty$ makes it exact for a convex problem with an attained optimal multiplier (strong duality), but a nonconvex problem can defeat it: $-x^4+\rho(x^2-1)_+$ is unbounded below for every $\rho$, although the constrained minimisers $\pm1$ of $-x^4$ s.t. $x^2\le1$ have $\lambda^\star=2$. A linear slack penalty has the same threshold: $s=1-p/2$ for $p\lt2$ ($x=1.5$ at $p=1$) and $s=0$ for $p\ge2$. Softening keeps every problem feasible (useful for recursive feasibility in MPC), but the constraint is violated whenever that is cheaper, so feasibility of the softened problem proves nothing about the original: keep safety constraints hard, use slack for soft performance terms. The augmented Lagrangian with $\rho=2$ gives $(x,\lambda)=(1.5,1),(1.25,1.5),(1.125,1.75)\to(1,2)$: the multiplier absorbs the price, so a finite $\rho$ suffices, and its positive part is the "proportional violation correction" $\max\{0,\lambda+c\cdot\text{violation}\}$.

ADMM splits $\min f(x)+g(z)$ s.t. $x=z$: minimise the augmented Lagrangian over $x$, then $z$ (often a projection), then update the multiplier; guaranteed for convex problems, a heuristic for nonconvex training.

Definition — Log barrier, central path and duality gap
$\phi(x)=-\sum_{i=1}^m\log(-f_i(x))$ is defined only at strictly feasible points (all slacks $-f_i\gt0$) and blows up at the boundary. The barrier problem minimises $tf_0+\phi$ (weight $\eta=1/t$ on $\phi$); its minimisers $x^\star(t)$ form the central path. For a convex problem $f_0(x^\star(t))-p^\star\le m/t$, since $\lambda_i=1/(-tf_i(x^\star(t)))$ is dual feasible with dual value $f_0(x^\star(t))-m/t$. Interior-point methods start strictly feasible, centre by damped Newton, increase $t$, repeat. For an LMI $F(x)\succ0$ the barrier is $-\log\det F(x)$. Running example: $x^\star(t)=\tfrac12(3-\sqrt{1+2/t})=0.634,\ 0.952,\ 0.995$ for $t=1,10,100$, with gaps $0.866,\ 0.098,\ 0.010\le1/t$.
Pitfall
A penalised or softened problem is a different problem, and a fixed multiplier is not a feasibility certificate. The $m/t$ bound needs convexity: for a nonconvex problem a stationary point of the barrier objective has no global gap guarantee. Barrier iterates stay strictly feasible (attractive for safe exploration) only if steps are short enough not to jump the boundary, e.g. no constraint may lose more than half its slack per step.

Approximate KKT points

Iterative algorithms stop after finitely many steps, so what they deliver is a point that satisfies the KKT conditions only approximately. Module 4 uses the following version. A feasible $x$ with multipliers $\lambda_i\ge0$ is an $\epsilon$-KKT point if

$$\Big\|\nabla f_0(x)+\sum_i\lambda_i\nabla f_i(x)\Big\|\le\epsilon \quad\text{(approximate stationarity)},\qquad \lambda_i\,\big(-f_i(x)\big)\le\epsilon\ \ \text{for all } i \quad\text{(approximate complementary slackness)}.$$

Papers differ in the details, for example in which residuals they bound and in which norm, so check the definition before comparing rates.

Worked example — a barrier method lands on an approximate KKT point

Return to the running example, $\min(x-2)^2$ subject to $x-1\le0$, whose KKT point is $x^\star=1$ with $\lambda^\star=2$. The log-barrier box above gives the barrier minimiser $x^\star(t)=\tfrac12\big(3-\sqrt{1+2/t}\big)$. At this point the derivative of $t f_0(x)-\log(1-x)$ vanishes:

$$t\cdot2\,(x-2)+\frac{1}{1-x}=0 \qquad\Longleftrightarrow\qquad 2\,(x-2)+\lambda=0 \quad\text{with}\quad \lambda=\frac{1}{t\,(1-x)} .$$

So the barrier minimiser satisfies stationarity exactly with the implied multiplier $\lambda=1/(t(1-x))\ge0$. Its complementary-slackness residual is $\lambda\,(1-x)=1/t$:

$t$$x^\star(t)$implied $\lambda$stationarity residual$\lambda\,(-f_1)$
100.95232.095400.1
1000.99502.010000.01

Each barrier minimiser is an $\epsilon$-KKT point with $\epsilon=1/t$, and as $t$ grows the pair approaches the exact KKT point $(1,2)$. Module 4's lemma for LB-SGD is the same observation: a small barrier gradient gives an approximate KKT point, with multipliers inversely proportional to the slacks.

Where this is used

Practice: Feasibility, KKT and penalty residuals

Work from Easy to Medium before trying Hard. Use the review link for a missing definition, then try again with the explanation closed.

Exercise B.6a — Easy: Check all four KKT conditions

Minimise $(x-3)^2$ subject to $x\le1$. Find the minimiser and its inequality multiplier, then check all four KKT conditions. What changes if the constraint is $x\le4$?

Review: Feasibility, KKT and penalty residuals

Show hint

Use the constraint function $g(x)=x-1\le0$. Stationarity is $2(x-3)+\lambda=0$.

Show worked solution

Candidate: the unconstrained minimum x=3 is forbidden, and f decreases up to x=3. The best feasible point is therefore $x^\star=1$. Stationarity gives $2(1-3)+\lambda=0$, hence $\lambda=4$.

Four checks: primal feasibility: $1-1=0\le0$; dual feasibility: $4\ge0$; complementary slackness: $4(1-1)=0$; stationarity: $-4+4=0$. The objective is convex and the constraint affine, so these checks certify a global optimum.

Looser constraint: with $x\le4$, x=3 is feasible and strictly inside the bound. Complementary slackness forces $\lambda=0$, and the objective derivative at x=3 is zero. A constraint can be present in the problem without influencing the optimum.

Exercise B.6b — Medium: Decide which constraints are active

Minimise $f(x)=\tfrac12\|x-(2,2)\|^2$ subject to $x_1+x_2\le1$ and $x_1\ge0$. Find x and both multipliers. Verify the inactive constraint and explain global optimality.

Review: Feasibility, KKT and penalty residuals

Show hint

First project onto the line $x_1+x_2=1$. Then check whether the resulting first coordinate satisfies the second bound.

Show worked solution

Constraint signs: write $g_1=x_1+x_2-1\le0$ and $g_2=-x_1\le0$. The objective gradient is $x-(2,2)$. The unconstrained point violates g1.

Guess g1 active only: stationarity with $\lambda_2=0$ is $x-(2,2)+\lambda_1(1,1)=0$, so $x=(2-\lambda_1,2-\lambda_1)$. Enforcing the line gives $4-2\lambda_1=1$, hence $\lambda_1=3/2$ and $x=(1/2,1/2)$.

Check the guess: $g_2=-1/2\lt0$, so it really is inactive and $\lambda_2=0$. The first multiplier is nonnegative, both products $\lambda_i g_i$ are zero, and the gradient $(-3/2,-3/2)$ is cancelled by the first constraint normal.

Conclusion: f is strictly convex with Hessian I, and the feasible set is convex, so this KKT point is the unique global minimiser. The minimum is $\tfrac12[(3/2)^2+(3/2)^2]=9/4$. An active-set guess must be checked against all constraints and multiplier signs.

Exercise B.6c — Hard: Compare a penalty solution with an approximate KKT point

For $\min(x-2)^2$ subject to $x\le1$, (a) minimise the quadratic penalty $(x-2)^2+3(x-1)_+^2$ and test feasibility. (b) At the feasible point x=0.9 take multiplier $\lambda=2.2$. Compute the stationarity and complementary-slackness residuals. What is the smallest epsilon for the approximate KKT definition on this page?

Review: Feasibility, KKT and penalty residuals

Show hint

For the penalty consider $x\le1$ and $x\ge1$ separately. Approximate KKT still requires actual feasibility and a nonnegative multiplier.

Show worked solution

Penalty branch $x\le1$: the penalty is zero and $(x-2)^2$ decreases until the branch endpoint x=1, with value 1. Branch $x\ge1$: the derivative is $2(x-2)+6(x-1)=8x-10$, zero at $x=1.25$. Its Hessian is 8>0, and its penalised value is $0.75^2+3(0.25)^2=0.75$, below 1.

Penalty conclusion: its global minimiser is $x=1.25$, violating the original constraint by 0.25. A finite quadratic penalty has traded some constraint violation for a lower objective.

KKT checks at x=0.9: feasibility holds since $g=x-1=-0.1$ and $\lambda=2.2\ge0$. The stationarity residual is $|2(0.9-2)+2.2|=|-2.2+2.2|=0$. The complementary-slackness residual is $\lambda(-g)=2.2(0.1)=0.22$.

Accuracy: the smallest epsilon satisfying both residual bounds is 0.22. The point is an epsilon-KKT point for any $\epsilon\ge0.22$, but it is not an exact KKT point because the inactive constraint has a positive multiplier. A small stationarity residual alone is insufficient.

7. Linear & Quadratic Programs

LPs and QPs are what solvers handle reliably at scale, so the modules reduce to them where possible and treat the solver as a black box. You need the forms, the geometry, and what a solver's answer certifies.

Definition — LP, QP, SOCP
LP: minimise $c^{\top}x$ s.t. $Ax\le b$ (and $Ex=e$); standard form $\min c^{\top}x$ s.t. $Ax=b$, $x\ge0$ via slacks $s=b-Ax\ge0$ and $x=x^+-x^-$. QP: minimise $\tfrac12x^{\top}Qx+c^{\top}x$ under linear constraints; convex when $Q\succeq0$ (and, if the feasible set has nonempty interior, only then); for $Q\succ0$ and a feasible problem the objective is strongly convex and coercive ($\to\infty$ as $\|x\|\to\infty$), so the minimiser exists and is unique. SOCP: linear objective, constraints $\|A_ix+b_i\|\le c_i^{\top}x+d_i$ (the second-order cone $\{\|z\|\le t\}$). LP $\subset$ convex QP $\subset$ SOCP $\subset$ SDP (Module 2). A norm-ball bound $\|u\|\le u_{\max}$ is convex but not linear: with it a QP becomes an SOCP.
Theorem — LP optima sit at vertices when the feasible set is bounded
An LP's feasible set is a polyhedron. If it is a nonempty polytope, the minimum exists and is attained at a vertex: for $x=\sum_i\theta_iv_i$, $c^{\top}x=\sum_i\theta_ic^{\top}v_i\ge\min_ic^{\top}v_i$. On an unbounded polyhedron a recession direction $d$ ($Ad\le0$, so $x+sd$ stays feasible for all $s\ge0$) with $c^{\top}d\lt0$ makes the LP unbounded; checking vertices suffices only when the optimum is finite.

Examples. Maximise $x_1+x_2$ s.t. $x_1+2x_2\le4$, $3x_1+x_2\le6$, $x\ge0$: vertices $(0,0),(2,0),(0,2),(1.6,1.2)$ give $0,2,2,2.8$, so $(1.6,1.2)$ is optimal. Slack allocation: maximise $\sum_s\epsilon_s$ s.t. $w^{\top}\epsilon\le B$, $\epsilon\ge0$, $w\ge0$: each vertex puts the budget on one coordinate (value $B/w_s$), so the smallest $w_s$ wins; $w=(2,1,0.5)$, $B=1$ give $\epsilon=(0,0,2)$, and if some $w_s=0$, $e_s$ is a recession direction and the LP is unbounded. Strict feasibility: $\sigma_i(a_i^{\top}x+b_i)\gt0$ for all $i$ (e.g. "does this ReLU activation pattern occur?") is solvable iff $\max s$ s.t. $\sigma_i(a_i^{\top}x+b_i)\ge s$, $s\le1$ has optimum $s^\star\gt0$; the cap keeps the LP bounded.

Derivation — Projection onto a half-space: the one-constraint QP in closed form

Minimise $\tfrac12\|u-u_{\rm ref}\|^2$ s.t. $a^{\top}u\ge b$, $a\ne0$: the CBF-QP safety filter, with $a=L_gh(x)^{\top}$ and $b=-L_fh(x)-\alpha(h(x))$. Case 1: $a^{\top}u_{\rm ref}\ge b$: $u_{\rm ref}$ is optimal, multiplier $0$. Case 2: otherwise the constraint is active; stationarity of $\tfrac12\|u-u_{\rm ref}\|^2-\lambda(a^{\top}u-b)$ gives $u=u_{\rm ref}+\lambda a$, and $a^{\top}u=b$ gives $\lambda=(b-a^{\top}u_{\rm ref})/\|a\|^2\gt0$. Together:

$$u^\star=u_{\rm ref}+\frac{(b-a^{\top}u_{\rm ref})_+}{\|a\|^2}\,a .$$

Check: for feasible $v$, $(u_{\rm ref}-u^\star)^{\top}(v-u^\star)=-\lambda(a^{\top}v-b)\le0$, the obtuse-angle condition of Section 6. Numbers: $u_{\rm ref}=(2,1)$, $a=(1,2)$, $b=5$: $\lambda=\tfrac15$, $u^\star=(2.2,1.4)$, $a^{\top}u^\star=5$. With an input box $|u_i|\le1.5$ there is no closed form, and here no solution at all: $u_1+2u_2\le4.5\lt5$ on the box (Exercise B.6 solves a feasible version).

Solvers as black boxes. Interior-point (Newton on a barrier), simplex and active-set methods (moving between vertices or active sets) and first-order splitting (ADMM-based, e.g. OSQP, SCS) return an optimal point with multipliers, or a certificate of infeasibility or unboundedness. "Optimal" means residuals below a tolerance (about $10^{-8}$ for interior point, $10^{-3}$ to $10^{-5}$ for first-order methods), so returned points may violate constraints by that much: for a safety certificate, re-check the solution independently with a margin, or in exact or interval arithmetic. Numerical feasibility is not a validated proof.

Hardness and relaxations. LPs and convex QPs are solvable in time polynomial in the bit size of the data. SOCPs and SDPs are solvable to accuracy $\varepsilon$ in time polynomial in the size and $\log(1/\varepsilon)$ only under assumptions on the encoding and conditioning (for instance a known bound $R$ on the size of a solution, entering as $\log R$, and a strictly feasible point), not for every input: in a Khachiyan-type example the LMIs $\begin{bmatrix}x_{i+1} & x_i\\ x_i & 1\end{bmatrix}\succeq0$, i.e. $x_{i+1}\ge x_i^2$, with $x_0=2$ force $x_n\ge2^{2^n}$, a number with exponentially many bits (Pataki & Touzov, arXiv 2021). Nonconvex problems can be NP-hard: at least as hard as every problem in NP (yes/no questions whose "yes" answers can be checked quickly from a certificate, such as an input violating a property), with no known polynomial-time algorithm. NP-complete = NP-hard and in NP; the complementary "no violating input exists" questions of verification form coNP. Hardness is worst case; many instances are easy. Mixed-integer programs add integer variables: $y=\max(0,v)$ with bounds $l\lt0\lt u$ is exactly $y\ge v$, $y\ge0$, $y\le uz$, $y\le v-l(1-z)$, $z\in\{0,1\}$ (big-M); $z\in[0,1]$ gives an LP relaxation (an outer bound), tightened by valid cuts, inequalities satisfied by every integer solution. SDP relaxations: for $x\in\{\pm1\}^n$, $x^{\top}Wx=\operatorname{tr}(WX)$ with $X=xx^{\top}$; replacing $X=xx^{\top}$ by $X\succeq0$, $\operatorname{diag}X=\mathbf 1$ upper-bounds $\max x^{\top}Wx$ (the MAXCUT idea).

Where this is used
The CBF-QP filter (Module 1, Module 10, Module 10); a two-variable QP via KKT (Module 2); half-spaces $w_t^{\top}a\ge b_t$ with an action box (Module 7); the occupancy polytope (Module 8); the slack-allocation LP (Module 11); one LP per activation pattern and NP-hardness (Module 12, Module 12); LPs over polytopes, SOCPs, NP-completeness, big-M and cuts, SDP relaxations (Module 15, Module 15, Module 15); an SOCP for rigorous GP bounds (Module 3).

Practice: Linear programs, quadratic programs and feasibility

Work from Easy to Medium before trying Hard. Use the review link for a missing definition, then try again with the explanation closed.

Exercise B.7a — Easy: Translate a squared-distance objective into QP form

Write $\min_x (x_1-1)^2+2(x_2+1)^2$ subject to $x_1+x_2\le2$ and $x_1\ge0$ in the form $\tfrac12x^\top Qx+c^\top x$ with linear inequalities. State the omitted constant, convexity and the minimiser.

Review: Linear programs, quadratic programs and feasibility

Show hint

Expand the squares. Remember that the QP convention includes a factor 1/2.

Show worked solution

Expansion: the objective is $x_1^2+2x_2^2-2x_1+4x_2+3$. Thus $Q=\operatorname{diag}(2,4)$, $c=(-2,4)$, and the omitted constant is 3. Constants change the optimal value, not the minimiser.

Constraints: $Ax\le b$ with $A=\begin{bmatrix}1&1\\-1&0\end{bmatrix}$ and $b=(2,0)^\top$. The second row correctly translates $x_1\ge0$.

Optimum: Q is PD, so the objective is strictly convex. Its unconstrained minimiser is $(1,-1)$, where both original squares are zero. This point is feasible ($1-1=0\le2$ and $1\ge0$), so it is also the unique constrained minimiser. The original optimal value is 0; the QP without the constant has optimal value -3.

Exercise B.7b — Medium: Solve an LP by its vertices and a bound

Maximise $2x+y$ subject to $x\ge0$, $y\ge0$, $x+y\le3$ and $x\le2$. List the vertices, compute the optimum, and confirm it with an inequality valid on the whole feasible set.

Review: Linear programs, quadratic programs and feasibility

Show hint

The upper-right corner is the intersection of x=2 and x+y=3. Also write $2x+y=x+(x+y)$.

Show worked solution

Vertices: the closed bounded polygon has corners $(0,0)$, $(2,0)$, $(2,1)$ and $(0,3)$. The point $(3,0)$ is not permitted because $x\le2$.

Objective values: the values at these corners are $0,4,5,3$, respectively. A linear objective on a nonempty polytope attains an optimum at a vertex, giving $(2,1)$ with value 5.

Whole-set check: every feasible point satisfies $2x+y=x+(x+y)\le2+3=5$. Both inequalities are equalities at $(2,1)$, proving the claimed optimum without relying only on a picture. Equality requires both x=2 and x+y=3, so the optimum is unique.

Exercise B.7c — Hard: A filter must respect its actuator box

Given $u_{\rm ref}=(0,0)$, minimise $\tfrac12\|u-u_{\rm ref}\|^2$ subject to $u_1+2u_2\ge4$ and $|u_i|\le1.5$. First find the half-space projection without the box. Then solve the full QP and give nonnegative KKT multipliers for its active constraints. What if the required right-hand side is 5?

Review: Linear programs, quadratic programs and feasibility

Show hint

The half-space-only projection points along (1,2). Its second coordinate may violate the actuator bound. With $u_2=1.5$, the safety constraint requires $u_1\ge1$.

Show worked solution

Ignoring the box: the half-space formula gives $u=(4/5)(1,2)=(0.8,1.6)$. It satisfies the safety equality, but violates $u_2\le1.5$, so it is not a permitted filter output.

Full candidate: set $u_2=1.5$ and u1+2u2=4, obtaining $u^\star=(1,1.5)$. This satisfies every box bound and has objective $(1+2.25)/2=1.625$.

KKT certificate: use $g_1=4-u_1-2u_2\le0$ and $g_2=u_2-1.5\le0$ as active constraints. Stationarity is $(1,1.5)+\lambda(-1,-2)+\mu(0,1)=0$. The first coordinate gives $\lambda=1$; the second gives $\mu=0.5$. Both are nonnegative; all other bounds are inactive and have multiplier zero. Feasibility and complementary slackness hold, so convexity certifies the unique global minimum.

Right-hand side 5: on the box, $u_1+2u_2\le1.5+3=4.5\lt5$. The feasible set is empty; a QP solver cannot produce a control satisfying these conflicting constraints. Adding slack would change the problem.

8. argmax, Min-Max Problems & Saddle Points

The modules optimise over infinite sets (inputs, policies, controllers, signals) and nest optimisations. Here is what $\sup$, $\operatorname{arg\,max}$ and $\min\max$ promise, and what they do not.

Definition — Supremum versus maximum; argmax as a set
$\sup_{x\in X}f(x)$ is the least upper bound of the values (Primer 0), possibly $+\infty$; by convention $\sup_\emptyset=-\infty$, $\inf_\emptyset=+\infty$. It is a maximum only if attained. $\operatorname*{arg\,max}_{x\in X}f(x)=\{x\in X:f(x)=\sup_Xf\}$ is a set: empty, one point, or several (ties). The maximum is a value, the argmax a set of decisions; "$x_t\in\operatorname{arg\,max}$" means the algorithm selects one element by a tie-break, and an argmax over pairs $(a,x)$ returns pairs. If $\sup f$ is finite, every $\varepsilon\gt0$ admits an $\varepsilon$-optimal $x$ with $f(x)\ge\sup f-\varepsilon$; without a maximiser, theorems and algorithms use these.

Examples. $\operatorname{arg\,max}_{[-1,1]}x^2=\{-1,1\}$ (tie); $\sup_{(0,1)}x=1$ with empty argmax; $\inf_{x\ge0}e^{-x}=0$ is not attained; $\sup_{u\in\mathbb R}u=+\infty$; the CVaR function of Section 4 has argmin $[1,2]$.

Theorem — When optimisers exist
(i) Weierstrass: continuous $f$ on a nonempty compact $X$ attains its max and min. (ii) Coercivity: continuous $f$ on a nonempty closed $X$ with $f(x)\to+\infty$ as $\|x\|\to\infty$ attains its min: $\{x\in X:f(x)\le f(x_0)\}$ is nonempty, closed and bounded, so (i) applies there, and points outside are worse. Lower semicontinuity suffices for minima. Closedness alone does not: $e^x$ on $\mathbb R$ has no minimum. Example: projections onto nonempty closed sets exist, because $\|x-y\|$ is continuous and coercive in $x$.

Suprema over inputs, signals, policies. $\sup_{u\in[-1,1]}(a+bu)=a+|b|$ at $u=\operatorname{sign}(b)$, but $+\infty$ over $u\in\mathbb R$ when $b\ne0$: a condition $\sup_{u\in U}[L_fh+L_gh\,u+\alpha(h)]\ge0$ is automatic where $L_gh\ne0$ if inputs are unbounded, and a real restriction for bounded $U$. A supremum inequality need not provide an input: $\sup_{u\in(0,1)}u\ge1$, yet no $u\in(0,1)$ has $u\ge1$; attainment needs e.g. compact $U$ and continuity. For signals, $\|d\|_\infty=\sup_{t\ge0}\|d(t)\|_2$ is a supremum over time of the Euclidean norm, not the largest coordinate of a vector (measurable signals use the essential supremum). Optimising over a policy class or over controllers uses the same definitions on sets of functions; attainment is an assumption. If $\varphi:[0,\infty)\to\mathbb R$ is strictly increasing, $\varphi^{-1}(s)$ exists only for $s$ in its range, below $\sup\varphi$.

Infima, distances, level searches, max-min. $\inf_t\bar g(x_t)$ need not be attained at a visited state ($x_t=2^{-t}$, $\bar g(x)=x$: infimum $0$, every value positive). $\operatorname{dist}(x,S)=\inf_{s\in S}\|x-s\|$ is attained for closed nonempty $S$. A level search $c^\ast=\inf\{V(x):x\in B\}$ is $+\infty$ for empty $B$, and the acceptable levels may form $[0,c^\ast)$, with a supremum but no largest element. To choose a backup, first take each candidate's worst constraint margin, then the best candidate, $s^\star\in\operatorname{arg\,max}_s\min_im_i(s)$: margins $(0.4,0.1)$, $(0.3,0.25)$, $(0.5,-0.1)$ have worst cases $0.1,\ 0.25,\ -0.1$, so the second wins although the third has the best single margin.

Theorem — Max-min inequality, saddle points, minimax
Always $\sup_y\inf_xL(x,y)\le\inf_x\sup_yL(x,y)$: for all $x',y'$, $\inf_xL(x,y')\le L(x',y')\le\sup_yL(x',y)$; the left side is free of $x'$, the right of $y'$. A saddle point satisfies $L(x^\star,y)\le L(x^\star,y^\star)\le L(x,y^\star)$ for all $x,y$, and then both sides equal $L(x^\star,y^\star)$. Minimax theorem (von Neumann, Sion; statement): for convex $X,Y$, one of them compact, and continuous $L$ convex in $x$ and concave in $y$, $\inf_x\sup_yL=\sup_y\inf_xL$.

Examples. $x^2-y^2$ on $[-1,1]^2$: saddle $(0,0)$, value $0$. $(x-y)^2$ on $[0,1]^2$ is not concave in $y$: $\min_x\max_y=\min_x\max(x^2,(1-x)^2)=\tfrac14$ but $\max_y\min_x=0$. Matching pennies, $x,y\in\{\pm1\}$, $L=xy$: $\min\max=1$, $\max\min=-1$; with mixed strategies ($p,q$ = probabilities of $+1$) the payoff $(2p-1)(2q-1)$ is bilinear with saddle $p=q=\tfrac12$ and value $0$: randomising convexifies the game. If both players run no-regret learners, their time-averaged strategies approach a saddle point (statement).

Where min-max appears: duality, since $\sup_{\lambda\ge0}(f_0+\lambda^{\top}f)$ is $f_0(x)$ for feasible $x$ and $+\infty$ otherwise, so $\inf_x\sup_\lambda$ is the primal, $\sup_\lambda\inf_x$ the dual, weak duality is the max-min inequality, and strong duality means these two values are equal (e.g. under Slater's condition). A saddle point exists exactly when they are equal and both optima are attained; equal values alone do not give one ($\inf_xe^x$ s.t. $-1\le0$ satisfies Slater's condition and has $p^\star=d^\star=0$ and $\lambda^\star=0$, but no minimiser) (Module 2; running example: $d(\lambda)=\lambda-\lambda^2/4$, $d^\star=1=p^\star$); robust control, min over controllers of the max over disturbances; adversarial training, min over weights of the max loss over a perturbation ball, the inner max approximated by projected gradient ascent. With several objectives the nondominated trade-offs form a Pareto front (Primer E).

Where this is used
  • argmax, ties, attainment: $\pi^\star=\operatorname{arg\,max}_\pi$, $\sup_{u\in U}$ (Module 1, Module 1); maximisers and ties (Module 4, Module 6); $\sup$ vs $\max$, $\varepsilon$-optimal policies (Module 8); policy classes (Module 9); $\sup_{u\in U}$ in CBFs (Module 10); $L^\star=\sup_x$ and unique argmax classes (Module 12); existence of a minimising action (Module 7).
  • Infima and level searches: dual functions equal to $-\infty$ (Module 2); $\sup|f|$ and designs (Module 3); $\sup_{r\ge0}\phi(r)$, $\phi^{-1}$ (Module 5); trajectory minima (Module 6); suprema over controllers (Module 7); $\|d\|_\infty$ (Module 10); $c^\ast=\inf\{\dots\}$ (Module 11).
  • Max-min and saddles: the backup with the largest margin (Module 6), Lagrangian saddle points (Module 8), no-regret updates of $\lambda$ (Module 9).

Practice: Optimisers, worst cases and saddle points

Work from Easy to Medium before trying Hard. Use the review link for a missing definition, then try again with the explanation closed.

Exercise B.8a — Easy: Distinguish a best value from the decisions attaining it

Find the supremum and argmax of f(x)=x on (0,1), and of $g(x)=x^2$ on [-1,1]. Give a 0.01-optimal point for the first problem.

Review: Optimisers, worst cases and saddle points

Show hint

An argmax is a set of inputs. A supremum can be a value never attained.

Show worked solution

Open interval: all f-values are below 1, but values approach 1, so the supremum is 1 and the argmax is the empty set. There is no admissible point x=1.

Approximation: x=0.99 belongs to (0,1) and has $f(x)=1-0.01$, meeting the epsilon-optimal condition. If a strict approximation is desired, x=0.995 also works.

Closed interval: $x^2\le1$ on [-1,1], and equality holds at both -1 and 1. Thus the supremum is the attained maximum 1, while the argmax is the two-element set {-1,1}. The optimal value does not specify a unique decision.

Exercise B.8b — Medium: Choose a backup by its worst margin

Three controllers have constraint margins A=(0.6,0.1), B=(0.35,0.3), and C=(0.8,-0.05). Safety means both margins are nonnegative. Which controllers are safe? Which maximises the worst margin? Compare with choosing by the largest single margin.

Review: Optimisers, worst cases and saddle points

Show hint

Take the minimum within each controller before taking the maximum across controllers.

Show worked solution

Safety: A and B have both margins nonnegative. C fails its second constraint because $-0.05\lt0$. A very good first margin does not compensate for this violation.

Worst margin: A has minimum 0.1, B has 0.3 and C has -0.05. Therefore B is the unique max-min choice, with robust margin 0.3 across the two constraints.

Different objective: choosing the largest single margin would prefer C because 0.8 is the largest entry. That rule ignores which constraint is worst and can select an unsafe controller. The order of aggregation expresses the actual requirement: every constraint must hold for the one controller chosen.

Exercise B.8c — Hard: Locate a saddle and test both defining inequalities

For $L(x,y)=(x-1)^2-(y+2)^2$ on $X=[0,2]$, $Y=[-3,0]$, find $\min_x\max_y L$ and $\max_y\min_x L$. Give a saddle point and verify its two inequalities for every x,y. Why is separate minimisation of both variables the wrong operation?

Review: Optimisers, worst cases and saddle points

Show hint

The maximising y-player chooses y=-2 to eliminate the negative square. The minimising x-player chooses x=1.

Show worked solution

Min-max: for fixed x, the largest value over y occurs at y=-2 and is $(x-1)^2$. Minimising it over X gives 0 at x=1.

Max-min: for fixed y, the smallest value over x occurs at x=1 and is $-(y+2)^2$. Maximising it over Y gives 0 at y=-2. Thus both orders have value 0.

Saddle inequalities: at $(x^\star,y^\star)=(1,-2)$, $L(1,y)=-(y+2)^2\le0=L(1,-2)\le(x-1)^2=L(x,-2)$ for every permitted x,y. This verifies the definition directly, not merely equality of two optimal values.

Roles: the y-player maximises L. Minimising in both variables would choose the most negative square instead (y=0 gives -4 at x=1), solving a different problem. Convexity in x and concavity in y are aligned with opposite optimisation directions here.

Interactive: Descent, Projection & Barriers in 2-D

Minimise $f(x)=\tfrac12(x-c)^{\top}Q(x-c)$, $c=(1.5,1.1)$, $Q=R_\theta\operatorname{diag}(1,\kappa)R_\theta^{\top}$ (so $\mu=1$, $L=\kappa$), over a convex set $C$ that excludes $c$. From the black point (click to move it) run gradient descent ignoring $C$, projected gradient $x_{k+1}=P_C(x_k-\eta\nabla f(x_k))$ started at $x_0=P_C(\text{black point})$, the penalty minimisers of $f+\tfrac\rho2\sum_i(f_i)_+^2$ for $\rho=1,4,\dots,1024$, and the barrier method (damped Newton on $tf+\phi$, $t\leftarrow4t$ until $m/t\lt10^{-3}$). Green dot: a reference optimum (closed form for the half-space, numerical bisection for the disc, or 5000 projected steps for the box). The latter two are numerical approximations, with accuracy limited by their stopping rules.

Descent, Projection & Barriers in 2-D

Grey: level sets of $f$ (cross: $c$). Green: $C$. Blue: gradient descent and orange: projected gradient from $P_C$(black point), with a dashed link when the start lies outside $C$ (from a start inside $C$ the two coincide while gradient descent stays feasible); red: penalty minimisers, outside $C$; purple: barrier Newton iterates with dots at the centres $x^\star(t)$, inside $C$.

What to look for. (1) Gradient descent heads for $c$ and leaves $C$; projected gradient slides along the boundary to $x^\star$. (2) Beyond $\eta L=2$ the guarantee is gone: the steepest error component is multiplied by $|1-\eta L|\gt1$ per step, so gradient descent diverges from every start with such a component (almost every start), and at $\eta L=2$ that component flips sign forever without decaying. Larger $\kappa$ means zig-zags and more steps. (3) Penalty minimisers stay infeasible and the violation shrinks like $1/\rho$. The Hessian condition number usually grows with $\rho$, because the penalty adds curvature $\rho$ across the constraint only (half-space, disk, a single violated box bound); it does not when curvature is added in every direction: at a box corner with both upper bounds violated the Hessian is $Q+\rho I$ and the condition number falls towards $1$ (exactly $1$ for $\kappa=1$). (4) Barrier iterates never leave $C$, and at each centre $x^\star(t)$ the gap stays below $m/t$ (the readout compares the two at the last centre); from a start outside $C$ the barrier method cannot run.

From the mathematics to a real decision

An optimizer balances preferences inside a set of allowed decisions. Before differentiating, identify which restrictions must hold, what the objective rewards, and where the predictive model is valid. This chapter uses two constructed engineering models: allocating a shared flow budget between two devices and limiting a command with a nonlinear clearance model. The coefficients and requirements are stipulated for teaching; no measured performance or physical certification is being asserted.

Learning objectives
  • Translate a weighted tracking preference and shared resource limit into a convex program.
  • Derive an active-constraint solution and verify every KKT condition.
  • Interpret a multiplier through the actual change in optimal cost when a budget changes.
  • Check nonlinear feasibility and bounded model error before accepting an optimizer's output.

Decide what is a preference and what is a requirement

Two devices request flows of three and one litres per minute. Let the dimensionless commands $u$ and $v$ denote flow divided by one litre per minute. Their requested values are therefore $3$ and $1$. The shared supply permits only $u+v\le3$, and both flows must be nonnegative. Tracking errors are penalized by:

$$J(u,v)=\tfrac12\big[(u-3)^2+4(v-1)^2\big],\qquad u\ge0,\ v\ge0,\ u+v\le3.$$

The factor four makes a unit error in the second command more expensive than the same normalized error in the first. It expresses a design preference, not a law of nature. The supply inequality is a requirement and must hold even when violating it would improve the tracking objective. Putting a finite penalty for excess flow into the objective would describe a different problem unless one separately establishes feasibility.

The objective is strictly convex because its Hessian is $\operatorname{diag}(1,4)$, positive definite in every nonzero direction. The feasible set is a closed bounded triangle, so continuity guarantees a minimum exists. Strict convexity makes that minimum unique. These facts let a checked KKT point certify the global mathematical answer for this model, instead of merely suggesting a plausible candidate.

Worked example — Allocate a shared budget and verify the result

Find the active requirement. Without constraints, zero tracking error occurs at $(3,1)$, whose total is four. The shared limit must bind at the constrained optimum: otherwise a small feasible move toward the requested point would reduce the strictly convex tracking loss. Try the active boundary $u+v=3$, with both commands positive.

Write stationarity. Use constraint $g=u+v-3\le0$ and nonnegative multiplier $\lambda$. The Lagrangian is $J+\lambda g$. Since the nonnegativity constraints are inactive in this candidate, their multipliers are zero. Stationarity gives $u-3+\lambda=0$ and $4(v-1)+\lambda=0$. Thus $u=3-\lambda$ and $v=1-\lambda/4$.

Solve and verify. Substituting into $u+v=3$ gives $4-5\lambda/4=3$, so $\lambda=0.8$ and $(u,v)=(2.2,0.8)$. Both commands are positive, their sum is three, the shared multiplier is nonnegative, and $\lambda g=0$. The stationarity vector is $(-0.8,-0.8)+(0.8,0.8)=0$. These are primal feasibility, dual feasibility, complementary slackness and stationarity, checked separately.

Interpret the answer. The objective is $\tfrac12(0.8^2+4(0.2)^2)=0.4$. Proportional reduction of both requests would give $(2.25,0.75)$ and cost $0.40625$, slightly larger. The optimum protects the more heavily weighted second device. Every feasible point has cost at least $0.4$ by convexity and the checked KKT conditions, not just by comparison with this one alternative.

Give the multiplier a testable meaning

Replace the budget three by $b$. As long as the shared constraint stays active and both commands stay positive, the same equations give $\lambda=0.8(4-b)$, $u=0.8b-0.2$ and $v=0.2b+0.2$. Their validity range is $0.25\lt b\lt4$. Below this range a nonnegativity constraint changes the active set; above it the shared budget stops limiting the requests. A formula derived under one active set must not be extended across these changes without checking.

Substitution gives optimal value $J^\star(b)=0.4(4-b)^2$ in that range. Differentiation yields $dJ^\star/db=-0.8(4-b)=-\lambda$. At $b=3$, one small extra unit of normalized budget initially reduces the best tracking cost at rate $0.8$. For an actual increase of $0.1$, the value changes from $0.4$ to $0.324$: a reduction of $0.076$, close to the first-order prediction $0.08$. Curvature explains the difference. The multiplier is a local marginal value with specified units and assumptions, rather than an unconditional price for any large budget change.

Use a local model within its actual reach

A separate actuator has normalized command $a\in[0,1]$ and desired command one. Suppose a constructed static model predicts clearance $h(a)=0.3-0.2a-0.1a^2$ metres, valid throughout this command interval. The task requires clearance at least $0.1$ metres. We choose the feasible command closest to the desired one, minimizing $\tfrac12(a-1)^2$. This is a predicted endpoint clearance problem, not a proof that a complete continuous motion remains clear between endpoints.

A tangent approximation at zero is $h_{\mathrm{lin}}(a)=0.3-0.2a$. It overestimates the true clearance by $0.1a^2$. The approximation can help explain the local slope, but accepting its boundary without a remainder check could violate the actual modeled requirement. A derivative describes an infinitesimal change; a finite command needs a finite-change argument.

Worked example — Transfer from a tangent prediction to an exact feasible command

Inspect the tempting answer. The linearized requirement $0.3-0.2a\ge0.1$ permits $a=1$, which perfectly tracks the request. But $h(1)=0$, below the required $0.1$ metres. The omitted quadratic term changes the decision, even though its coefficient is smaller than the linear coefficient.

Solve the modeled constraint. The exact requirement becomes $a^2+2a\le2$, or $(a+1)^2\le3$. On $[0,1]$, this gives $0\le a\le\sqrt3-1$. Because the objective decreases while $a\lt1$, the best feasible point is $a^\star=\sqrt3-1\approx0.732051$. Direct substitution gives clearance exactly $0.1$ metres and objective $(7-4\sqrt3)/2\approx0.0358984$.

Check optimality independently. Write $g(a)=0.1a^2+0.2a-0.2\le0$. This convex function describes the requirement. The domain bounds are inactive at $a^\star$. Stationarity is $a^\star-1+\lambda(0.2a^\star+0.2)=0$, giving $\lambda=10/\sqrt3-5\approx0.773503$, which is nonnegative. Feasibility and $\lambda g(a^\star)=0$ hold. Convexity therefore confirms the global optimum.

Report the limitation. There is no spare modeled clearance at this command. If the clearance prediction may be wrong, the constraint must include that error before this command is accepted. A numerically accurate solution cannot supply a missing model-error allowance.

Audit the result as a decision

A solver can stop with a small stationarity residual and still violate a hard requirement. Check primal feasibility in the original units first: total flow, nonnegative commands, and clearance. Then check the objective and optimality residuals. If a command is repaired by projection, re-evaluate all constraints afterward; a repair for one constraint can affect another. The application exercises below make these distinctions concrete.

For a convex objective, feasibility and the appropriate optimality condition have separate roles. A feasible point may be suboptimal; an unconstrained stationary point may be infeasible. At an optimum on a boundary, the objective gradient generally does not vanish, because the profitable direction points outside the feasible set. KKT stationarity balances that gradient against constraint normals. This geometric balance explains why checking only gradient size can mislead in either direction.

Common mistake — letting an approximate answer define the requirement

Accepting $u+v=3.01$ because the objective is almost optimal silently replaces the budget by a larger one. Likewise, accepting the tangent clearance prediction replaces the nonlinear constraint. Repair the calculation by returning to the original constraints, retaining model-error terms and measuring feasibility separately from optimality. A tolerance is part of the numerical method; whether it is acceptable to the device is a further stated requirement.

Application practice: allocation, sensitivity and robust feasibility

Exercise B.B1 — Easy: Find a feasible improvement without a solver

For the two-device allocation problem, assess candidate $(u,v)=(2.4,0.6)$. Compute its cost and check feasibility. Consider transfers $(u,v)=(2.4-t,0.6+t)$ that preserve total flow. Find the best permitted transfer near this candidate and explain why a nonzero objective gradient does not disqualify the constrained optimum.

Review the relevant tools

Show hint

Expand the one-variable objective in t. Keep the sum constraint satisfied throughout the comparison.

Show worked solution

The candidate is feasible because both commands are positive and sum to three. Its cost is $\tfrac12[(-0.6)^2+4(-0.4)^2]=0.5$. Along the transfer, the cost becomes $0.5-t+2.5t^2$, whose derivative is $-1+5t$. It is minimized at $t=0.2$, a feasible transfer giving $(2.2,0.8)$ and cost $0.4$.

At the optimum the gradient is $(-0.8,-0.8)$, not zero. Every tangent transfer $(-t,t)$ has zero dot product with that gradient; reducing both tracking errors simultaneously would require increasing the total flow beyond the budget. The constraint normal balances the gradient. Checking only whether the candidate gradient vanishes would apply an unconstrained condition to a constrained decision.

Exercise B.B2 — Medium: Use a shadow price within its active-set range

The shared budget becomes $b=2.5$. Solve the allocation problem, including its multiplier and optimal cost. Predict the cost decrease from increasing the budget by $0.1$ using the multiplier, then compute the actual decrease. Check that the active-set assumptions hold at both budgets.

Review the relevant tools

Show hint

Keep the sum constraint active and solve u=3-lambda, v=1-lambda/4 with u+v=b. Then substitute into the objective.

Show worked solution

At $b=2.5$, $\lambda=0.8(4-2.5)=1.2$, $u=1.8$, and $v=0.7$. Both commands are positive and sum to the budget, so the assumed active set is consistent. The cost is $0.4(1.5)^2=0.9$.

The multiplier predicts a decrease $1.2(0.1)=0.12$. At $b=2.6$, the commands are $(1.88,0.72)$, the multiplier is $1.12$, and the actual value is $0.4(1.4)^2=0.784$. The decrease is $0.116$, smaller than the local prediction by $0.004$. Expanding the quadratic value function gives exactly this remainder. Both budgets lie between $0.25$ and four, where this active set is valid.

Exercise B.B3 — Medium: Repair a nearly feasible numerical answer

At budget three, a solver reports $(2.21,0.80)$ and shared multiplier $0.8$. Compute the stationarity residual vector and the flow violation. Project the reported point onto the line $u+v=3$ using minimum Euclidean change. Check all primal constraints and compute the repaired point's cost gap relative to the exact optimum. Does a small stationarity residual alone justify accepting the original command?

Review the relevant tools

Show hint

A minimum-length correction to the sum subtracts the same amount from both coordinates. After repair expand the quadratic around (2.2,0.8).

Show worked solution

The gradient is $(-0.79,-0.8)$. Adding multiplier times normal gives stationarity residual $(0.01,0)$, with Euclidean norm $0.01$. The total is $3.01$, violating the hard budget by $0.01$ normalized flow units, equivalent to $0.01$ litres per minute.

The orthogonal projection subtracts $0.005$ from each coordinate, giving $(2.205,0.795)$. This point is nonnegative and sums exactly to three, so it satisfies all primal constraints. Its cost is $0.4000625$, a gap of $0.0000625$. The gap also follows from the feasible displacement $(0.005,-0.005)$: its first-order cost vanishes, leaving $\tfrac12[(0.005)^2+4(0.005)^2]$.

The original command is not allowed under the exact budget, regardless of its small stationarity residual. The repaired command is feasible but slightly suboptimal. Whether that cost gap matters is a preference question; budget feasibility was a separate requirement.

Exercise B.B4 — Hard: Include model error before optimizing clearance

The actual modeled clearance is now $h(a,w)=0.3-0.2a-0.1a^2+w$ metres, with unknown $w\in[-0.03,0.03]$. Require $h\ge0.1$ for every allowed $w$, with $a\in[0,1]$, and minimize $\tfrac12(a-1)^2$. Derive the robust optimum and verify its feasibility and KKT multiplier. Test the earlier nonrobust optimum under the worst disturbance. For a general symmetric error bound $|w|\le d$, when does any feasible command exist?

Review the relevant tools

Show hint

The smallest clearance occurs at the smallest w. Convert that universal constraint into one convex inequality, then use monotonicity of the objective on [0,1].

Show worked solution

The worst error is $w=-0.03$, so nominal clearance must be at least $0.13$. Equivalently $0.1a^2+0.2a-0.17\le0$, or $(a+1)^2\le2.7$. Hence the feasible interval is $[0,\sqrt{2.7}-1]$, and the decreasing objective selects $a^\star=\sqrt{2.7}-1\approx0.643168$.

Nominal clearance is $0.13$ and worst clearance is $0.10$ metres. The cost is $\tfrac12(2-\sqrt{2.7})^2\approx0.0636647$. The multiplier is $(2-\sqrt{2.7})/(0.2\sqrt{2.7})\approx1.085806$, nonnegative. It satisfies stationarity, the convex inequality is active, and the domain bounds are inactive. These conditions verify global optimality of the robust problem.

The earlier command $\sqrt3-1$ has nominal clearance $0.1$, so its worst clearance is $0.07$ and it fails the new requirement. For general $d\ge0$, clearance is largest at $a=0$, where its worst value is $0.3-d$. A feasible command therefore exists exactly when $0\le d\le0.2$; sufficiency follows by choosing zero. Beyond that range, tracking preferences cannot cure infeasibility.

Explain the accepted command, not only the optimum

Reconstruct the allocation from its requirements and weights, and explain which equation changes when the budget changes. Then reconstruct the clearance decision from the original nonlinear inequality, including model error. The objective chooses among feasible commands; it does not excuse violations. Convexity explains global optimality only after the modeled problem and its assumptions have been stated correctly.

For recall, list the four KKT checks and identify which one fails for the reported flow command. Explain why a multiplier predicts a local value change, why the tangent clearance overestimates the exact model, and why adding a worst-case error margin changes the feasible set before optimization. State one limitation of treating an endpoint clearance as a motion-safety statement.

Module 2 develops duality and matrix constraints from these ideas. Module 10 uses quadratic programs to alter commands under dynamic safety constraints. Those applications need additional model, timing and feasibility assumptions; the habit established here is to locate those assumptions before interpreting the solver's answer.

Exercises

Exercise B.1 — Gradient, Hessian and a Taylor check

$f(x)=x_1^2x_2+e^{x_2}$, $x=(1,0)$. (a) Compute $\nabla f(x)$ and $D_vf(x)$ for $v=(0.6,0.8)$. (b) Compute $\nabla^2f(x)$; is it definite? (c) Predict $f(1.1,0.1)$ to first and second order and compare with the true value.

Show answer

(a) $\nabla f=(2x_1x_2,\ x_1^2+e^{x_2})=(0,2)$, so $D_vf=0\cdot0.6+2\cdot0.8=1.6$.

(b) $\nabla^2f=\begin{bmatrix}2x_2 & 2x_1\\ 2x_1 & e^{x_2}\end{bmatrix}=\begin{bmatrix}0 & 2\\ 2 & 1\end{bmatrix}$, determinant $-4$: eigenvalues $(1\pm\sqrt{17})/2\approx2.56,-1.56$, indefinite.

(c) With $\delta=(0.1,0.1)$ and $f(x)=1$: first order $1+\nabla f^{\top}\delta=1.2$; second order adds $\tfrac12\delta^{\top}\nabla^2f\delta=\tfrac12(0.04+0.01)=0.025$, giving $1.225$. The truth is $0.121+e^{0.1}\approx1.226171$; the error is $\approx0.00117$. The Taylor remainder is $O(\|\delta\|^3)$ (halving $\delta$ divides it by about $8$).

Exercise B.2 — The gradient of the Parseval regulariser

$R(W)=\tfrac\beta4\|WW^{\top}-I\|_F^2$. (a) Show $\nabla_WR=\beta(WW^{\top}-I)W$. (b) For $\beta=1$ and $W=\begin{bmatrix}1 & 1\\ 0 & 1\end{bmatrix}$, evaluate $R$ and $\nabla R$ and take one gradient step with $\eta=0.1$. Does $R$ decrease?

Show answer

(a) With $E=WW^{\top}-I$ (symmetric), $d\|E\|_F^2=2\operatorname{tr}(E\,dE)$ and $dE=dW\,W^{\top}+W\,dW^{\top}$. Cyclicity, transposition and $E^{\top}=E$ give $\operatorname{tr}(E\,dW\,W^{\top})=\operatorname{tr}(E\,W\,dW^{\top})=\operatorname{tr}(W^{\top}E\,dW)$, so $dR=\tfrac\beta4\cdot2\cdot2\operatorname{tr}(W^{\top}E\,dW)=\langle\beta EW,dW\rangle$.

(b) $WW^{\top}=\begin{bmatrix}2 & 1\\ 1 & 1\end{bmatrix}$, $E=\begin{bmatrix}1 & 1\\ 1 & 0\end{bmatrix}$, $R=0.75$, $\nabla R=EW=\begin{bmatrix}1 & 2\\ 1 & 1\end{bmatrix}$ (finite differences agree). The step gives $\begin{bmatrix}0.9 & 0.8\\ -0.1 & 0.9\end{bmatrix}$ with $R\approx0.257$: a clear decrease.

Exercise B.3 — Certifying an interval from grid measurements

$f$ is $1.5$-Lipschitz on $[0,2]$, and measurements certify $f\ge\ell=(0.5,\ 0.45,\ 0.3,\ 0.2,\ 0.6)$ at $0,0.5,1,1.5,2$. (a) Which points are certified to satisfy $f\ge0$? (b) Does the uniform grid test of Section 3 certify $[0,2]$? (c) Redo (a) if only $|f(x)-f(x')|\le1.5\sqrt{|x-x'|}$ is known.

Show answer

(a) Exact radii $\ell_g/L=1/3,\ 3/10,\ 1/5,\ 2/15,\ 2/5$ give $[0,1/3]$, $[1/5,4/5]$, $[4/5,6/5]$, $[41/30,49/30]$, $[8/5,2]$: certified is $[0,6/5]\cup[41/30,2]$. Every point of the gap $(6/5,41/30)$ admits a compatible Lipschitz function with a negative value there, so it is not certified by these lower measurements.

(b) $r_c=0.25$, so every node needs $\ell_g\ge Lr_c=0.375$; this fails at $1$ and $1.5$, consistent with the gap.

(c) Exact radii $(\ell/1.5)^2=1/9,\ 9/100,\ 1/25,\ 4/225,\ 4/25$ give the certified set $[0,1/9]\cup[41/100,59/100]\cup[24/25,26/25]\cup[667/450,683/450]\cup[46/25,2]$. All five radii are strictly smaller than their Lipschitz counterparts: the square-root modulus makes these small-margin certificates narrower.

Exercise B.4 — Two conjugates

(a) Compute $f^*$ for $f(x)=\tfrac12x^{\top}Qx$, $Q\succ0$. (b) Compute $f^*$ for $f(w)=\tfrac12(w-1)^2$ on $w\ge0$ ($+\infty$ otherwise). (c) Check Fenchel–Young for (b) at $w=2$ with $e=0.5$ and with $e=1$.

Show answer

(a) $y^{\top}x-\tfrac12x^{\top}Qx$ is concave with gradient $y-Qx$, zero at $x=Q^{-1}y$: $f^*(y)=\tfrac12y^{\top}Q^{-1}y$.

(b) The unconstrained maximiser of $we-\tfrac12(w-1)^2$ is $w=1+e$. For $e\ge-1$ it is admissible: $f^*(e)=(1+e)e-\tfrac12e^2=e+\tfrac12e^2$. For $e\lt-1$ the objective decreases on $w\ge0$, so $w=0$ and $f^*(e)=-\tfrac12$.

(c) $f(2)+f^*(0.5)=0.5+0.625=1.125\ge2\cdot0.5$. With $e=1=f'(2)$: $0.5+1.5=2=2\cdot1$, equality exactly when $e$ is the slope at $w$.

Exercise B.5 — Step sizes, conditioning and Newton

$f(x)=\tfrac12(x_1^2+10x_2^2)$, $x_0=(10,1)$. (a) With $\eta=0.1$, how many gradient steps until $f\le10^{-6}$? (b) What happens for $\eta=0.21$? (c) Repeat (a) with $\eta=2/11$. (d) What does one Newton step do?

Show answer

The coordinates decouple: $x_1\leftarrow(1-\eta)x_1$, $x_2\leftarrow(1-10\eta)x_2$. (a) $x_2=0$ after one step and $f(x_k)=50\cdot0.81^k\le10^{-6}$ iff $k\ge\ln(2\cdot10^{-8})/\ln0.81\approx84.1$: $85$ steps. (b) $1-2.1=-1.1$: $|x_2|$ grows $10\%$ per step, since $\eta\gt2/L=0.2$. (c) Both factors have size $\tfrac9{11}$ (this $\eta=2/(L+\mu)$ is the best constant step for quadratics), $f(x_k)=55(81/121)^k\le10^{-6}$ iff $k\ge44.4$: $45$ steps. (d) $\nabla^2f=\operatorname{diag}(1,10)$, $\nabla f(x_0)=(10,10)$, $\Delta=-(10,1)$: Newton lands on $(0,0)$ in one step, whatever the conditioning.

Exercise B.6 — A safety filter with an input box

Minimise $\tfrac12\|u-u_{\rm ref}\|^2$, $u_{\rm ref}=(2,1)$, subject to $u_1+2u_2\ge4.2$ and $|u_1|,|u_2|\le1.5$. (a) Project onto the half-space alone, then clip to the box: feasible? (b) Guess the active set, solve, and verify KKT (KKT conditions). (c) What if $4.2$ becomes $5$?

Show answer

(a) $a=(1,2)$, $a^{\top}u_{\rm ref}=4$, so $u=u_{\rm ref}+\tfrac{0.2}{5}a=(2.04,1.08)$; clipping gives $(1.5,1.08)$ with $1.5+2.16=3.66\lt4.2$. Projecting onto each constraint in turn is not projecting onto the intersection.

(b) Try $u_1=1.5$ with the half-space active: $u_2=1.35\le1.5$, so $u^\star=(1.5,1.35)$. With $g_1=4.2-u_1-2u_2\le0$, $g_2=u_1-1.5\le0$, stationarity $(-0.5,0.35)+\lambda_1(-1,-2)+\lambda_2(1,0)=0$ gives $\lambda_1=0.175$, $\lambda_2=0.675$, both $\ge0$, so KKT holds and, the problem being convex, $u^\star$ is optimal (cost $0.18625$; a grid search agrees).

(c) On the box $u_1+2u_2\le4.5\lt5$: infeasible. A filter with bounded inputs can have no solution; a slack restores solvability but gives up the guarantee.

Ready to use optimisation in the modules?

Try the Easy and Medium exercises in derivatives, Lipschitz bounds, convexity, and KKT with the solutions closed. You should be able to compute a gradient, explain the norm and domain of a Lipschitz bound, and check feasibility separately from stationarity.

Before a filter or learning algorithm, redo the step-size exercise and the actuator-box QP. Explain why a penalty minimiser can be infeasible and why the minimax order matters. Revisit only the linked section that causes difficulty; the Hard exercises can be spaced over later study sessions. Next: Primer C: probability and uncertainty, then Module 1.

Further Reading

Book / tutorialAuthors, publisher, yearRead it for
Mathematics for Machine LearningDeisenroth, Faisal, Ong; Cambridge University Press, 2020 (free PDF)Ch. 5 vector calculus and backpropagation, Ch. 7 continuous optimisation: the gentlest companion to Sections 1, 2, 5.
Convex OptimizationBoyd, Vandenberghe; Cambridge University Press, 2004 (free PDF)Ch. 2–5 convex sets, functions, conjugates, LP/QP/SOCP/SDP, duality; Ch. 9–11 descent, Newton, interior point.
Numerical Optimization (2nd ed.)Nocedal, Wright; Springer, 2006Line search, trust regions, conjugate gradients, KKT, penalty and augmented-Lagrangian methods.
The Matrix CookbookPetersen, Pedersen; Technical University of Denmark, 2012Tables of trace, determinant and inverse derivatives.
Convex Optimization: Algorithms and ComplexityBubeck; Foundations and Trends in Machine Learning, 2015Short proofs of the gradient, SGD and mirror-descent rates.
Optimization Methods for Large-Scale Machine LearningBottou, Curtis, Nocedal; SIAM Review, 2018SGD, minibatches, noise and step sizes in training.
Distributed Optimization and Statistical Learning via the Alternating Direction Method of MultipliersBoyd, Parikh, Chu, Peleato, Eckstein; Foundations and Trends in Machine Learning, 2011Augmented Lagrangians and ADMM.
Automatic Differentiation in Machine Learning: a SurveyBaydin, Pearlmutter, Radul, Siskind; JMLR, 2018Forward and reverse mode, Hessian-vector products.

Flashcards