Part 1Math for LLMs

Optimality Conditions: Part 1 - Intuition To Conceptual Bridge

Multivariate Calculus / Optimality Conditions

Private notes
0/8000

Notes stay private to your browser until account sync is configured.

Part 1
30 min read18 headingsSplit lesson page

Lesson overview | Lesson overview | Next part

Optimality Conditions: Part 1: Intuition to Conceptual Bridge

1. Intuition

1.1 The Optimization Landscape

Imagine standing in a hilly landscape and trying to find the lowest valley. The gradient f(x)\nabla f(\mathbf{x}) tells you the direction of steepest ascent at your current position - to descend, move against the gradient. But this strategy can strand you in a local valley that is not the deepest one, or trap you at a mountain pass (saddle point) where the gradient is zero but you are not at a minimum.

THE OPTIMIZATION LANDSCAPE IN 1D AND 2D


  1D loss curve:              2D loss surface (contour view):

                                    
                           local     saddle  
                             min       x   
          local   global            
         min      min              global
                                     min 

  Key players:
  
   Point type       Characterisation                             
  
   Local minimum    nablaf = 0,  H  0  (all eigenvalues > 0)       
   Local maximum    nablaf = 0,  H  0  (all eigenvalues < 0)       
   Saddle point     nablaf = 0,  H indefinite (mixed signs)          
   Regular point    nablaf != 0  (not a critical point)              
  


The core difficulty: the gradient condition f(x)=0\nabla f(\mathbf{x}^*) = \mathbf{0} is necessary but not sufficient for a minimum. A zero gradient could mark a minimum, a maximum, or a saddle point. Second-order conditions (the Hessian) are needed to distinguish between them.

Constraints add further complexity. If the solution must lie on a curve or within a region, the unconstrained minimum may be infeasible, and the optimum occurs at a very different location - possibly on the boundary of the feasible region.

1.2 Why ML Needs Optimality Theory

Every core ML algorithm is secretly an optimisation problem, and the optimality conditions determine its solution structure:

ML AlgorithmOptimisation ProblemOptimality Condition Used
Linear regressionminwXwy2\min_\mathbf{w} \|X\mathbf{w} - \mathbf{y}\|^2=0\nabla = 0 -> normal equations
Ridge regressionminwXwy2+λw2\min_\mathbf{w} \|X\mathbf{w}-\mathbf{y}\|^2 + \lambda\|\mathbf{w}\|^2Lagrangian of constrained form
LassominwXwy2+λw1\min_\mathbf{w} \|X\mathbf{w}-\mathbf{y}\|^2 + \lambda\|\mathbf{w}\|_1Subdifferential conditions
SVMmin12w2\min \tfrac{1}{2}\|\mathbf{w}\|^2 s.t. margin 1\geq 1KKT -> support vectors
PCAmaxvvCv\max_\mathbf{v} \mathbf{v}^\top C \mathbf{v} s.t. v=1\|\mathbf{v}\|=1Lagrange -> eigenvalue problem
Logistic regressionminlogpi\min -\sum \log p_iConvex -> unique global minimum
Neural networkminL(θ)\min \mathcal{L}(\theta) (non-convex)Saddle point dominance; NTK
Attention (softmax)maxpsp\max_\mathbf{p} \mathbf{s}^\top\mathbf{p} s.t. pΔ\mathbf{p} \in \DeltaMaximum entropy via Lagrange
SAM trainingminθmaxϵρL(θ+ϵ)\min_\theta \max_{\|\epsilon\|\leq\rho} \mathcal{L}(\theta+\epsilon)KKT of inner max

For AI: Understanding that the SVM dual problem depends only on inner products xixj\mathbf{x}_i^\top \mathbf{x}_j (from the KKT conditions) is what enables the kernel trick - the foundation of kernel methods. Understanding that softmax is the solution to a maximum entropy problem under linear constraints connects attention to thermodynamics and information theory.

1.3 Historical Context

YearPersonContribution
1788LagrangeMcanique Analytique - method of multipliers for equality constraints
1847CauchySteepest descent algorithm
1939KarushMaster's thesis: inequality constraints with multipliers (KKT conditions - unpublished)
1951Kuhn & TuckerIndependent rediscovery and publication of KKT conditions
1952Arrow, Hurwicz, UzawaSaddle point theorem for convex optimisation
1970RockafellarConvex Analysis - definitive treatment of duality and subdifferentials
1995Boser, Guyon, VapnikSVM uses the dual to derive the kernel trick
1996Boyd & VandenbergheConvex Optimization (textbook; full text freely available online)
2014Dauphin et al.Saddle point dominance in deep networks
2021Foret et al.SAM: sharpness-aware minimisation as constrained min-max
2022Papyan et al.Neural collapse: KKT characterisation of terminal training phase

1.4 Unconstrained vs Constrained

There are three fundamental problem classes:

THREE PROBLEM CLASSES


  UNCONSTRAINED                    EQUALITY CONSTRAINED
                      
  min f(x)                         min f(x)
   xinR                            s.t. g(x) = 0, i=1,...,m

  Solution: nablaf = 0                 Solution: Lagrange multipliers
  Theory: 2nd-order conditions      nablaf + lambdanablag = 0,  g(x) = 0

  INEQUALITY CONSTRAINED
  
  min f(x)
  s.t. g(x) = 0,  i = 1,...,m
       h(x) <= 0,  j = 1,...,p

  Solution: KKT conditions
  nablaf + lambdanablag + munablah = 0,  g=0,  h<=0,  mu>=0,  muh=0 for allj

  KEY INSIGHT: Equality constraints are special case of KKT
  (set mu = 0 for inequalities, keep lambda free for equalities)


The feasible set F={x:gi(x)=0,hj(x)0}\mathcal{F} = \{\mathbf{x} : g_i(\mathbf{x}) = 0,\, h_j(\mathbf{x}) \leq 0\} is the set of points satisfying all constraints. The optimisation problem asks for the minimum of ff over F\mathcal{F}.


2. First-Order Necessary Conditions

2.1 The Gradient Condition

Theorem (First-Order Necessary Condition): Let f:RnRf: \mathbb{R}^n \to \mathbb{R} be differentiable. If x\mathbf{x}^* is a local minimum of ff, then:

f(x)=0\nabla f(\mathbf{x}^*) = \mathbf{0}

Proof: Suppose x\mathbf{x}^* is a local minimum but f(x)0\nabla f(\mathbf{x}^*) \neq \mathbf{0}. Define the direction d=f(x)\mathbf{d} = -\nabla f(\mathbf{x}^*). By the directional derivative formula:

ddtf(x+td)t=0=f(x)d=f(x)2<0\frac{d}{dt} f(\mathbf{x}^* + t\mathbf{d})\Big|_{t=0} = \nabla f(\mathbf{x}^*)^\top \mathbf{d} = -\|\nabla f(\mathbf{x}^*)\|^2 < 0

By continuity of ff, there exists ϵ>0\epsilon > 0 such that f(x+td)<f(x)f(\mathbf{x}^* + t\mathbf{d}) < f(\mathbf{x}^*) for all t(0,ϵ)t \in (0, \epsilon). But this contradicts x\mathbf{x}^* being a local minimum. \square

Warning - necessity only: The gradient condition is necessary but not sufficient. The function f(x)=x3f(x) = x^3 has f(0)=0f'(0) = 0 at x=0x=0 but no local extremum there (it's an inflection point). The function f(x,y)=x2y2f(x,y) = x^2 - y^2 has f(0,0)=0\nabla f(0,0) = \mathbf{0} but a saddle point. Second-order conditions are needed to determine which type of critical point we have.

Critical points (also called stationary points) are all x\mathbf{x} satisfying f(x)=0\nabla f(\mathbf{x}) = \mathbf{0}. They are candidates for minima, maxima, or saddle points - the Hessian distinguishes between them.

2.2 Critical Points and Their Classification

In R2\mathbb{R}^2, a function f(x,y)f(x,y) has four types of critical points, determined by the sign of the Hessian determinant detH=fxxfyyfxy2\det H = f_{xx}f_{yy} - f_{xy}^2 and the sign of fxxf_{xx}:

SECOND-DERIVATIVE TEST IN R^2


  At critical point (nablaf = 0):

  det(H) > 0 and f_xx > 0  ->  LOCAL MINIMUM
                                  (all eigenvalues of H positive)

  det(H) > 0 and f_xx < 0  ->  LOCAL MAXIMUM
                                  (all eigenvalues of H negative)

  det(H) < 0                ->  SADDLE POINT
                                  (H has mixed-sign eigenvalues)

  det(H) = 0                ->  DEGENERATE (test inconclusive)
                                  (need higher-order analysis)

  Geometric picture for each:
  
     Min           Max           Saddle        Degenerate 
                                x                      
                                                  
                                          
   bowl shape    hill shape    mountain       flat region 
                                 pass                     
  


Standard examples:

  • f(x,y)=x2+y2f(x,y) = x^2 + y^2: unique global minimum at origin; H=2I0H = 2I \succ 0
  • f(x,y)=(x2+y2)f(x,y) = -(x^2 + y^2): unique global maximum at origin; H=2I0H = -2I \prec 0
  • f(x,y)=x2y2f(x,y) = x^2 - y^2: saddle point at origin; H=diag(2,2)H = \text{diag}(2,-2) indefinite
  • f(x,y)=x4+y4f(x,y) = x^4 + y^4: minimum at origin; H(0,0)=0H(0,0) = 0 (degenerate - minimum confirmed by inspection)

In higher dimensions (n>2n > 2): A critical point is a strict local minimum iff H(x)0H(\mathbf{x}^*) \succ 0 (all eigenvalues positive). It is a strict local maximum iff H(x)0H(\mathbf{x}^*) \prec 0. Any other case (indefinite HH or semidefinite HH) requires further analysis.

2.3 Saddle Points in Deep Learning

The classical concern was that neural networks might converge to poor local minima. Empirically, gradient descent finds solutions of similar quality regardless of initialisation for overparameterised networks. This was theoretically explained in a landmark 2014 paper.

Dauphin et al. (2014) - Identifying and attacking the saddle point problem: For a function f:RnRf: \mathbb{R}^n \to \mathbb{R} with nn large, a random critical point with loss ϵ\epsilon above the global minimum is a saddle point with overwhelming probability (under a statistical physics model). The fraction of critical points that are local minima decreases exponentially with both ϵ\epsilon and nn.

SADDLE POINT DOMINANCE


  Distribution of critical points at energy level epsilon above global min:

  Fraction that are local minima:  ~exp(-n * c(epsilon))

  For n = 10^9 (GPT-3),  c(epsilon) > 0  ->  essentially zero local minima

  What gradient descent actually encounters:
  
    High-loss region:   many saddle points, few local minima  
    Low-loss region:    many saddle points, even fewer local  
    Near global min:    flat regions (many equivalent minima) 
  

  SGD noise + momentum helps escape saddles (saddle-free Newton
  methods explicitly use the negative curvature direction).


Why does SGD escape saddle points? At a saddle point, the Hessian has at least one negative eigenvalue. The corresponding eigenvector is a descent direction - the function decreases along it. SGD's noise perturbations project onto this direction with nonzero probability, enabling escape. Deterministic gradient descent can be trapped at strict saddle points, but this is a measure-zero set.

For AI: The practical implication is that for overparameterised models (where parameters \gg data), gradient descent on a non-convex loss converges to global or near-global optima. This is one theoretical explanation for why training large language models with SGD/Adam works so well.

2.4 Stationary Points of Common ML Loss Functions

MSE (Linear Regression): f(w)=Xwy2f(\mathbf{w}) = \|X\mathbf{w} - \mathbf{y}\|^2

wf=2X(Xwy)=0    XXw=Xy\nabla_\mathbf{w} f = 2X^\top(X\mathbf{w} - \mathbf{y}) = \mathbf{0} \implies X^\top X \mathbf{w} = X^\top \mathbf{y}

This is the normal equation. It has a unique solution w=(XX)1Xy\mathbf{w}^* = (X^\top X)^{-1} X^\top \mathbf{y} when XX has full column rank. The Hessian H=2XX0H = 2X^\top X \succeq 0 - MSE is convex, so the critical point is the global minimum.

Cross-Entropy (Logistic Regression): f(w)=i=1n[yilogσ(wxi)+(1yi)log(1σ(wxi))]f(\mathbf{w}) = -\sum_{i=1}^n [y_i \log \sigma(\mathbf{w}^\top \mathbf{x}_i) + (1-y_i)\log(1-\sigma(\mathbf{w}^\top \mathbf{x}_i))]

wf=i=1n(yiσ(wxi))xi=X(σy)\nabla_\mathbf{w} f = -\sum_{i=1}^n (y_i - \sigma(\mathbf{w}^\top \mathbf{x}_i))\mathbf{x}_i = X^\top(\boldsymbol{\sigma} - \mathbf{y})

No closed-form solution (transcendental equation). The Hessian H=Xdiag(σi(1σi))X0H = X^\top \text{diag}(\sigma_i(1-\sigma_i)) X \succeq 0 confirms convexity. Gradient descent (or Newton's method) converges to the unique global minimum if it exists (may not if data is linearly separable).

Cross-Entropy (Softmax / LLM output): Setting z[logpy]=pey=0\nabla_\mathbf{z} [-\log p_y] = \mathbf{p} - \mathbf{e}_y = \mathbf{0} (as derived in 03) gives py=1p_y = 1 and pk=0p_k = 0 for kyk \neq y. This is a perfectly confident prediction - the loss approaches zero but never reaches it for finite logits.


3. Second-Order Conditions

First-order conditions identify candidates; second-order conditions distinguish minima from maxima from saddle points. The Hessian matrix-the matrix of second partial derivatives-encodes all the local curvature information needed for this classification.

3.1 Second-Order Necessary Condition (SONC)

Theorem (SONC). If x\mathbf{x}^* is a local minimum of f:RnRf: \mathbb{R}^n \to \mathbb{R} and fC2f \in C^2 near x\mathbf{x}^*, then:

2f(x)0\nabla^2 f(\mathbf{x}^*) \succeq 0

(the Hessian is positive semi-definite).

Proof. Let dRn\mathbf{d} \in \mathbb{R}^n be any direction. Taylor expansion gives:

f(x+td)=f(x)+tf(x)d=0+t22d2f(x)d+O(t3)f(\mathbf{x}^* + t\mathbf{d}) = f(\mathbf{x}^*) + t \underbrace{\nabla f(\mathbf{x}^*)^\top \mathbf{d}}_{=0} + \frac{t^2}{2} \mathbf{d}^\top \nabla^2 f(\mathbf{x}^*) \mathbf{d} + O(t^3)

Since x\mathbf{x}^* is a local minimum, f(x+td)f(x)f(\mathbf{x}^* + t\mathbf{d}) \geq f(\mathbf{x}^*) for all small tt. Thus:

t22dHd+O(t3)0\frac{t^2}{2} \mathbf{d}^\top H \mathbf{d} + O(t^3) \geq 0

Dividing by t2t^2 and letting t0+t \to 0^+:

dHd0dRn\mathbf{d}^\top H \mathbf{d} \geq 0 \quad \forall \mathbf{d} \in \mathbb{R}^n

which is exactly H0H \succeq 0. \square

Note: SONC is necessary but not sufficient. f(x)=x4f(x) = x^4 at x=0x^* = 0 has f(0)=00f''(0) = 0 \succeq 0 yet x=0x^* = 0 is a minimum. f(x,y)=x2y3f(x,y) = x^2 - y^3 at origin has H=diag(2,0)H = \text{diag}(2, 0) but origin is not a minimum.

3.2 Second-Order Sufficient Condition (SOSC)

Theorem (SOSC). If f(x)=0\nabla f(\mathbf{x}^*) = \mathbf{0} and 2f(x)0\nabla^2 f(\mathbf{x}^*) \succ 0 (positive definite), then x\mathbf{x}^* is a strict local minimum.

Proof. Since H=2f(x)0H = \nabla^2 f(\mathbf{x}^*) \succ 0, its smallest eigenvalue satisfies λmin(H)>0\lambda_{\min}(H) > 0. By continuity of the Hessian, there exists δ>0\delta > 0 such that 2f(x)λmin2I\nabla^2 f(\mathbf{x}) \succ \frac{\lambda_{\min}}{2} I for all xx<δ\|\mathbf{x} - \mathbf{x}^*\| < \delta.

For any d\mathbf{d} with d=1\|\mathbf{d}\| = 1 and small t>0t > 0:

f(x+td)=f(x)+t22dHd+O(t3)f(x)+t2λmin2+O(t3)>f(x)f(\mathbf{x}^* + t\mathbf{d}) = f(\mathbf{x}^*) + \frac{t^2}{2} \mathbf{d}^\top H \mathbf{d} + O(t^3) \geq f(\mathbf{x}^*) + \frac{t^2 \lambda_{\min}}{2} + O(t^3) > f(\mathbf{x}^*)

for sufficiently small tt. \square

Gap between SONC and SOSC: The boundary case H0H \succeq 0 but H⊁0H \not\succ 0 (degenerate, semidefinite Hessian) requires higher-order analysis. This is common in deep learning where flat directions proliferate.

SECOND-ORDER TEST SUMMARY


  Critical point x*: nablaf(x*) = 0

  H = nabla^2f(x*)     Result          Name
  
  H  0           Strict local minimum        SOSC satisfied
  H  0           Strict local maximum        (max version of SOSC)
  H indefinite    Saddle point               Eigenvalues of both signs
  H  0, != 0     Might be min (degenerate)  Higher order needed
  H = 0           Need Taylor term >=3        Flat critical point
  

  For R^2 via determinant test (when nablaf = 0):
    det(H) > 0, H_1_1 > 0  ->  local minimum
    det(H) > 0, H_1_1 < 0  ->  local maximum
    det(H) < 0             ->  saddle point
    det(H) = 0             ->  inconclusive


3.3 Indefinite Hessian and Saddle Points

When H=2f(x)H = \nabla^2 f(\mathbf{x}^*) has both positive and negative eigenvalues, x\mathbf{x}^* is a saddle point: a local minimum along some directions, a local maximum along others.

Morse Theory Preview. For a smooth function f:RnRf: \mathbb{R}^n \to \mathbb{R}, a critical point x\mathbf{x}^* is non-degenerate if H(x)H(\mathbf{x}^*) is invertible. The Morse index of x\mathbf{x}^* is:

k=#{λi(H)<0}k = \#\{\lambda_i(H) < 0\}

(the number of descent directions). A non-degenerate minimum has index 0; a saddle has index 1,2,,n11, 2, \ldots, n-1; a maximum has index nn. Morse theory relates the topology of the sublevel sets {fc}\{f \leq c\} to the critical points and their indices.

For deep learning: The loss landscape of an nn-parameter network at a critical point near a good solution tends to have many positive eigenvalues and few (often negligible) negative ones. The ratio k/nk/n is typically very small at good solutions-confirming that most critical points found in practice are near-minima, not true saddles with large negative Hessian components.

3.4 Global Optimality from Convexity

For convex functions, the local-global distinction disappears entirely:

Theorem. If ff is convex and x\mathbf{x}^* is a local minimum, then x\mathbf{x}^* is a global minimum.

Proof. Suppose x\mathbf{x}^* is a local min but not global: there exists y\mathbf{y} with f(y)<f(x)f(\mathbf{y}) < f(\mathbf{x}^*). For t(0,1)t \in (0,1), convexity gives:

f((1t)x+ty)(1t)f(x)+tf(y)<f(x)f((1-t)\mathbf{x}^* + t\mathbf{y}) \leq (1-t)f(\mathbf{x}^*) + tf(\mathbf{y}) < f(\mathbf{x}^*)

As t0+t \to 0^+, the point (1t)x+ty(1-t)\mathbf{x}^* + t\mathbf{y} approaches x\mathbf{x}^* arbitrarily closely while having lower function value-contradicting x\mathbf{x}^* being a local minimum. \square

Corollary. For differentiable convex ff: f(x)=0\nabla f(\mathbf{x}^*) = \mathbf{0} iff x\mathbf{x}^* is a global minimum.

This is the fundamental reason convex optimization is "easy" compared to non-convex: any local search algorithm that finds a stationary point has found the global optimum.

3.5 Hessian at ML Optima

Understanding the Hessian at key ML critical points provides geometric insight into learning:

Linear Regression. For f(w)=12nXwy2f(\mathbf{w}) = \frac{1}{2n}\|X\mathbf{w} - \mathbf{y}\|^2:

2f(w)=1nXX\nabla^2 f(\mathbf{w}) = \frac{1}{n} X^\top X

independent of w\mathbf{w}. The Hessian is constant-this is a quadratic. Eigenvalues are σi2(X)/n\sigma_i^2(X)/n (squared singular values scaled). If XX has full column rank, H0H \succ 0 everywhere, so the unique critical point is a global minimum.

Logistic Regression. For f(w)=1ni[yiwxi+log(1+ewxi)]f(\mathbf{w}) = \frac{1}{n}\sum_i [-y_i \mathbf{w}^\top \mathbf{x}_i + \log(1 + e^{\mathbf{w}^\top \mathbf{x}_i})]:

2f(w)=1nXdiag(σi(1σi))X\nabla^2 f(\mathbf{w}) = \frac{1}{n} X^\top \text{diag}(\sigma_i(1-\sigma_i)) X

where σi=σ(wxi)\sigma_i = \sigma(\mathbf{w}^\top \mathbf{x}_i). Since σ(z)(1σ(z))(0,1/4]\sigma(z)(1-\sigma(z)) \in (0, 1/4], the Hessian is PSD everywhere (and PD if XX has full column rank), making logistic regression a convex problem.

Neural Networks. At a minimum w\mathbf{w}^*, the Hessian H(w)H(\mathbf{w}^*) typically has:

  • A bulk of near-zero eigenvalues (flat landscape in many directions)
  • A few large positive eigenvalues (steep curvature in a small subspace)
  • Occasional small negative eigenvalues (slight non-convexity)

The ratio of large-to-small eigenvalues is the condition number-high condition numbers cause slow gradient descent convergence and motivate adaptive methods like Adam.


4. Convex Analysis

Convexity is the mathematical property that makes optimization tractable. Understanding convex sets and functions-their definitions, characterisations, and preservation rules-is prerequisite to deploying convex duality and KKT theory.

4.1 Convex Sets

Definition. A set CRnC \subseteq \mathbb{R}^n is convex if for all x,yC\mathbf{x}, \mathbf{y} \in C and θ[0,1]\theta \in [0,1]:

θx+(1θ)yC\theta \mathbf{x} + (1-\theta)\mathbf{y} \in C

Geometrically: the line segment between any two points stays inside the set.

Standard examples:

  • Hyperplanes {x:ax=b}\{\mathbf{x} : \mathbf{a}^\top \mathbf{x} = b\} and halfspaces {x:axb}\{\mathbf{x} : \mathbf{a}^\top \mathbf{x} \leq b\}
  • Balls {x:xcr}\{\mathbf{x} : \|\mathbf{x} - \mathbf{c}\| \leq r\} under any norm
  • Polyhedra {x:Axb}\{\mathbf{x} : A\mathbf{x} \leq \mathbf{b}\} (intersection of halfspaces)
  • Positive semidefinite cone S+n={SRn×n:S=S,S0}\mathbb{S}_+^n = \{S \in \mathbb{R}^{n\times n} : S = S^\top,\, S \succeq 0\}
  • The probability simplex Δn={p0:1p=1}\Delta^n = \{\mathbf{p} \geq 0 : \mathbf{1}^\top \mathbf{p} = 1\}

Non-examples:

  • The unit sphere Sn1\mathbb{S}^{n-1} (boundary only, not the ball): the segment between two points on the sphere passes through the interior
  • The set {(x,y):xy1,x,y>0}\{(x,y) : xy \geq 1,\, x,y > 0\}: take (1,1)(1,1) and (2,1/2)(2, 1/2); the midpoint (3/2,3/4)(3/2, 3/4) has 3/23/4=9/8>13/2 \cdot 3/4 = 9/8 > 1-wait, this is actually convex. A cleaner non-example: {(x,y):x2+y2=1}\{(x,y) : x^2 + y^2 = 1\} (circle)

Convexity-preserving operations:

  • Intersection: C1,C2C_1, C_2 convex \Rightarrow C1C2C_1 \cap C_2 convex
  • Affine image: f(C)={Ax+b:xC}f(C) = \{A\mathbf{x} + \mathbf{b} : \mathbf{x} \in C\} is convex if CC is convex
  • Cartesian product, Minkowski sum

4.2 Convex Functions: Definition and First-Order Characterisation

Definition. A function f:CRf: C \to \mathbb{R} on a convex set CC is convex if:

f(θx+(1θ)y)θf(x)+(1θ)f(y)x,yC,θ[0,1]f(\theta \mathbf{x} + (1-\theta)\mathbf{y}) \leq \theta f(\mathbf{x}) + (1-\theta)f(\mathbf{y}) \quad \forall \mathbf{x},\mathbf{y} \in C,\, \theta \in [0,1]

Strict convexity: replace \leq with << for xy\mathbf{x} \neq \mathbf{y}, θ(0,1)\theta \in (0,1).

First-Order Characterisation. For fC1f \in C^1, ff is convex iff its graph lies above all tangent hyperplanes:

f(y)f(x)+f(x)(yx)x,yCf(\mathbf{y}) \geq f(\mathbf{x}) + \nabla f(\mathbf{x})^\top (\mathbf{y} - \mathbf{x}) \quad \forall \mathbf{x}, \mathbf{y} \in C

This is the inequality that makes f(x)=0\nabla f(\mathbf{x}^*) = \mathbf{0} sufficient for global minimality in the convex case: if f(x)=0\nabla f(\mathbf{x}^*) = \mathbf{0}, then f(y)f(x)+0=f(x)f(\mathbf{y}) \geq f(\mathbf{x}^*) + 0 = f(\mathbf{x}^*) for all y\mathbf{y}.

Proof sketch. (\Rightarrow) Fix x,y\mathbf{x}, \mathbf{y} and let ϕ(t)=f(x+t(yx))\phi(t) = f(\mathbf{x} + t(\mathbf{y}-\mathbf{x})). Convexity implies ϕ(1)ϕ(0)+ϕ(0)\phi(1) \geq \phi(0) + \phi'(0), which gives the tangent inequality. (\Leftarrow) The tangent inequality with the two points x\mathbf{x} and y\mathbf{y} evaluated at z=θx+(1θ)y\mathbf{z} = \theta\mathbf{x} + (1-\theta)\mathbf{y} yields the convexity definition after combining.

4.3 Second-Order Characterisation

Theorem. For fC2f \in C^2: ff is convex iff 2f(x)0\nabla^2 f(\mathbf{x}) \succeq 0 for all x\mathbf{x} in the domain.

Proof. (\Rightarrow) If ff is convex, the first-order characterisation gives f(x+td)f(x)+tf(x)df(\mathbf{x} + t\mathbf{d}) \geq f(\mathbf{x}) + t \nabla f(\mathbf{x})^\top \mathbf{d}. Expanding the Taylor series and applying this inequality yields dH(x)d0\mathbf{d}^\top H(\mathbf{x})\mathbf{d} \geq 0. (\Leftarrow) With H0H \succeq 0 everywhere, integrate along the line from x\mathbf{x} to y\mathbf{y} using the second-order Taylor remainder to establish the first-order characterisation.

Examples of convex functions:

  • Affine: f(x)=ax+bf(\mathbf{x}) = \mathbf{a}^\top \mathbf{x} + b (both convex and concave)
  • Quadratic: f(x)=12xQxf(\mathbf{x}) = \frac{1}{2}\mathbf{x}^\top Q \mathbf{x} when Q0Q \succeq 0
  • Norms: f(x)=xpf(\mathbf{x}) = \|\mathbf{x}\|_p for p1p \geq 1 (triangle inequality = convexity)
  • Log-sum-exp: f(x)=logiexif(\mathbf{x}) = \log \sum_i e^{x_i} (smooth convex approximation to max)
  • Negative entropy: f(p)=ipilogpif(\mathbf{p}) = \sum_i p_i \log p_i on the simplex
  • Cross-entropy loss: ylogσ(z)(1y)log(1σ(z))-y \log \sigma(z) - (1-y)\log(1-\sigma(z)) in zz

Non-convex in ML:

  • f(w)=sin(w)f(w) = \sin(w), any neural network loss, f(A,B)=ABMF2f(A,B) = \|AB - M\|_F^2 (matrix factorisation)

4.4 Strongly Convex Functions

Definition. ff is μ\mu-strongly convex (μ>0\mu > 0) if:

f(y)f(x)+f(x)(yx)+μ2yx2f(\mathbf{y}) \geq f(\mathbf{x}) + \nabla f(\mathbf{x})^\top(\mathbf{y}-\mathbf{x}) + \frac{\mu}{2}\|\mathbf{y}-\mathbf{x}\|^2

Equivalently: f(x)μ2x2f(\mathbf{x}) - \frac{\mu}{2}\|\mathbf{x}\|^2 is convex; or 2f(x)μI\nabla^2 f(\mathbf{x}) \succeq \mu I everywhere.

Strong convexity has powerful consequences:

  1. Unique minimiser: the quadratic lower bound forces a unique optimal point
  2. Linear convergence: gradient descent converges geometrically at rate (1μ/L)(1 - \mu/L) per step where LL is the Lipschitz constant of f\nabla f
  3. Self-concordance: the function cannot become arbitrarily flat

For AI: Ridge regression f(w)=12nXwy2+λ2w2f(\mathbf{w}) = \frac{1}{2n}\|X\mathbf{w} - \mathbf{y}\|^2 + \frac{\lambda}{2}\|\mathbf{w}\|^2 is λ\lambda-strongly convex (the 2\ell_2 regulariser adds λI\lambda I to the Hessian). This is why L2L_2 regularisation speeds up convergence and ensures a unique solution-crucial for ill-conditioned problems.

Condition number: For μ\mu-strongly convex, LL-smooth functions, κ=L/μ\kappa = L/\mu governs convergence. In transformer training, very high condition numbers of the loss landscape motivate adaptive optimisers.

4.5 Preservation Rules and Calculus of Convex Functions

Convexity is preserved under many operations, making it composable:

OperationConditionResult
Non-negative combinationαi0\alpha_i \geq 0, fif_i convexiαifi\sum_i \alpha_i f_i convex
Composition with affineff convex, A,bA, \mathbf{b} anyg(x)=f(Ax+b)g(\mathbf{x}) = f(A\mathbf{x}+\mathbf{b}) convex
Pointwise maxfif_i convexg(x)=maxifi(x)g(\mathbf{x}) = \max_i f_i(\mathbf{x}) convex
Compositionff convex nondecreasing, gg convexfgf \circ g convex
Partial minf(x,y)f(\mathbf{x}, \mathbf{y}) convex in (x,y)(\mathbf{x},\mathbf{y})g(x)=infyf(x,y)g(\mathbf{x}) = \inf_\mathbf{y} f(\mathbf{x},\mathbf{y}) convex
Perspectiveff convexg(x,t)=tf(x/t)g(\mathbf{x},t) = tf(\mathbf{x}/t) convex on {t>0}\{t>0\}

For AI: The cross-entropy loss (w)=logσ(wx)\ell(\mathbf{w}) = -\log \sigma(\mathbf{w}^\top \mathbf{x}) is convex in w\mathbf{w} because it is log-\log composed with a concave function (affine composed with sigmoid). Convexity preservation rules let us verify this without computing the Hessian directly.


5. Lagrange Multipliers

When optimization problems come with constraints, unconstrained optimality conditions no longer apply directly. Lagrange multipliers transform constrained problems into unconstrained ones by incorporating the constraint into the objective-at the cost of introducing auxiliary variables.

5.1 Setup: Equality-Constrained Problems

Problem form:

minxRnf(x)subject togi(x)=0,i=1,,m\min_{\mathbf{x} \in \mathbb{R}^n} f(\mathbf{x}) \quad \text{subject to} \quad g_i(\mathbf{x}) = 0, \quad i = 1, \ldots, m

where f,giC1f, g_i \in C^1 and m<nm < n (fewer constraints than variables).

The Lagrangian: Define L:Rn×RmR\mathcal{L}: \mathbb{R}^n \times \mathbb{R}^m \to \mathbb{R} by:

L(x,λ)=f(x)+i=1mλigi(x)=f(x)+λg(x)\mathcal{L}(\mathbf{x}, \boldsymbol{\lambda}) = f(\mathbf{x}) + \sum_{i=1}^m \lambda_i g_i(\mathbf{x}) = f(\mathbf{x}) + \boldsymbol{\lambda}^\top \mathbf{g}(\mathbf{x})

The scalars λi\lambda_i are Lagrange multipliers (or dual variables).

5.2 Geometric Derivation

The deepest way to understand why Lagrange's method works is geometric. At a constrained minimum x\mathbf{x}^*:

Claim: f(x)\nabla f(\mathbf{x}^*) must lie in the span of {g1(x),,gm(x)}\{\nabla g_1(\mathbf{x}^*), \ldots, \nabla g_m(\mathbf{x}^*)\}.

Why: The feasible set near x\mathbf{x}^* is approximately the linear manifold {x:gi(x)(xx)=0,i}\{\mathbf{x} : \nabla g_i(\mathbf{x}^*)^\top (\mathbf{x} - \mathbf{x}^*) = 0, \, \forall i\}-the tangent plane to each constraint surface. Any feasible direction d\mathbf{d} from x\mathbf{x}^* must satisfy gi(x)d=0\nabla g_i(\mathbf{x}^*)^\top \mathbf{d} = 0 for all ii.

If f(x)\nabla f(\mathbf{x}^*) had a component orthogonal to all gi(x)\nabla g_i(\mathbf{x}^*), that component would be a feasible direction along which ff decreases-contradicting x\mathbf{x}^* being a local constrained minimum.

Therefore f(x)\nabla f(\mathbf{x}^*) has no component in the tangent space; it must lie entirely in the normal space spanned by {gi}\{\nabla g_i\}:

f(x)=i=1mλigi(x)xL(x,λ)=0\nabla f(\mathbf{x}^*) = -\sum_{i=1}^m \lambda_i^* \nabla g_i(\mathbf{x}^*) \quad \Longleftrightarrow \quad \nabla_\mathbf{x} \mathcal{L}(\mathbf{x}^*, \boldsymbol{\lambda}^*) = \mathbf{0}
LAGRANGE MULTIPLIER GEOMETRY (R^2)


  Constraint: g(x,y) = 0  (a curve in the plane)
  Objective: minimize f(x,y)

          y
                   f = c_3  (level curves of f)
    
                   f = c_2
       
                 f = c_1  <- tangent to constraint at x*
           x*
          
         g = 0
         

  At x*: level curve of f is tangent to constraint g=0
          nablaf  nablag    nablaf = -lambdanablag

  nablag points normal to g=0; nablaf points normal to f=c_1
  Tangency means these normals are parallel.


5.3 The Lagrange Multiplier Theorem

Theorem (Lagrange, 1788). Let x\mathbf{x}^* be a local minimum of ff subject to g(x)=0\mathbf{g}(\mathbf{x}) = \mathbf{0}. If the Linear Independence Constraint Qualification (LICQ) holds at x\mathbf{x}^*-i.e., {g1(x),,gm(x)}\{\nabla g_1(\mathbf{x}^*), \ldots, \nabla g_m(\mathbf{x}^*)\} are linearly independent-then there exists λRm\boldsymbol{\lambda}^* \in \mathbb{R}^m such that:

xL(x,λ)=f(x)+λg(x)=0\nabla_\mathbf{x} \mathcal{L}(\mathbf{x}^*, \boldsymbol{\lambda}^*) = \nabla f(\mathbf{x}^*) + \boldsymbol{\lambda}^* {}^\top \nabla \mathbf{g}(\mathbf{x}^*) = \mathbf{0} g(x)=0\mathbf{g}(\mathbf{x}^*) = \mathbf{0}

Together these are n+mn + m equations in n+mn + m unknowns (x,λ)(\mathbf{x}^*, \boldsymbol{\lambda}^*).

LICQ matters: Without LICQ the theorem can fail. Example: minx\min x subject to x2=0x^2 = 0 and x3=0x^3 = 0. The constraints both vanish at x=0x^* = 0 with gradients 00 and 00-linearly dependent. No Lagrange multiplier exists.

5.4 Sensitivity Interpretation: Shadow Prices

The Lagrange multiplier λi\lambda_i^* has a precise economic interpretation: it measures how much the optimal value changes as constraint ii is relaxed.

Theorem (Envelope). Let p(b)p^*(b) be the optimal value of minxf(x)\min_\mathbf{x} f(\mathbf{x}) subject to gi(x)=big_i(\mathbf{x}) = b_i. Then:

pbi=λi\frac{\partial p^*}{\partial b_i} = \lambda_i^*

Proof sketch. Differentiating the Lagrangian optimality conditions with respect to bib_i and applying the chain rule yields dp/dbi=λidp^*/db_i = \lambda_i^* (the Implicit Function Theorem controls how x\mathbf{x}^* moves with bib_i).

For AI: In constrained training (e.g., "minimize loss subject to w2=c\|\mathbf{w}\|^2 = c"), λ\lambda^* tells you how much more you could improve the loss by relaxing the norm constraint by one unit. This motivates choosing the right regularisation strength: λ\lambda^* is the value of the weight decay penalty that enforces the constraint.

5.5 Multiple Constraints and Second-Order Conditions

Multiple equality constraints: With mm equality constraints, the KKT point satisfies n+mn + m stationarity equations. Second-order analysis requires the bordered Hessian or, equivalently, the Hessian of the Lagrangian restricted to the tangent space of the constraints:

dxx2L(x,λ)d>0d0 with g(x)d=0\mathbf{d}^\top \nabla^2_{\mathbf{x}\mathbf{x}} \mathcal{L}(\mathbf{x}^*, \boldsymbol{\lambda}^*) \mathbf{d} > 0 \quad \forall \mathbf{d} \neq \mathbf{0} \text{ with } \nabla \mathbf{g}(\mathbf{x}^*)^\top \mathbf{d} = \mathbf{0}

is the second-order sufficient condition for a constrained local minimum.

5.6 ML Applications of Lagrange Multipliers

PCA as constrained optimisation. Find v1Rd\mathbf{v}_1 \in \mathbb{R}^d maximising variance v1Σv1\mathbf{v}_1^\top \Sigma \mathbf{v}_1 subject to v12=1\|\mathbf{v}_1\|^2 = 1:

L=vΣvλ(vv1)\mathcal{L} = \mathbf{v}^\top \Sigma \mathbf{v} - \lambda(\mathbf{v}^\top \mathbf{v} - 1)

Stationarity: 2Σv=2λv2\Sigma \mathbf{v} = 2\lambda \mathbf{v}, i.e., Σv=λv\Sigma \mathbf{v} = \lambda \mathbf{v}. The optimal direction is the top eigenvector; λ=\lambda^* = top eigenvalue == maximum variance. PCA is literally solving Lagrange conditions.

Unit-norm attention. In some attention formulations, query/key vectors are L2-normalized before the dot product. The normalization constraint q=1\|{\bf q}\|=1 is enforced via Lagrange multiplier; the shadow price reveals how much the attention energy would increase if the norm bound were relaxed.

LoRA rank constraints. Low-Rank Adaptation constrains the weight update ΔW=AB\Delta W = AB where ARd×rA \in \mathbb{R}^{d \times r}, BRr×kB \in \mathbb{R}^{r \times k}, with rmin(d,k)r \ll \min(d,k). The rank-rr constraint is implicit in the factorised parameterisation, and the Lagrange multiplier interpretation illuminates why the singular values of ΔW\Delta W concentrate: the effective constraint is on the nuclear norm (sum of singular values).


6. KKT Conditions

Lagrange multipliers handle equality constraints. When inequality constraints are present-which is the norm in machine learning (budget constraints, margin constraints, non-negativity)-the Karush-Kuhn-Tucker (KKT) conditions provide the generalisation.

6.1 The Full Problem and Lagrangian

General form:

minxf(x)s.t.hj(x)0,  j=1,,pandgi(x)=0,  i=1,,m\min_{\mathbf{x}} f(\mathbf{x}) \quad \text{s.t.} \quad h_j(\mathbf{x}) \leq 0,\; j = 1,\ldots,p \quad \text{and} \quad g_i(\mathbf{x}) = 0,\; i = 1,\ldots,m

Lagrangian:

L(x,μ,λ)=f(x)+j=1pμjhj(x)+i=1mλigi(x)\mathcal{L}(\mathbf{x}, \boldsymbol{\mu}, \boldsymbol{\lambda}) = f(\mathbf{x}) + \sum_{j=1}^p \mu_j h_j(\mathbf{x}) + \sum_{i=1}^m \lambda_i g_i(\mathbf{x})

where μj0\mu_j \geq 0 are the multipliers for inequality constraints and λiR\lambda_i \in \mathbb{R} for equality constraints.

6.2 The Four KKT Conditions

At an optimal x\mathbf{x}^* (under a suitable constraint qualification):

1. Stationarity:

xL(x,μ,λ)=f(x)+jμjhj(x)+iλigi(x)=0\nabla_\mathbf{x} \mathcal{L}(\mathbf{x}^*, \boldsymbol{\mu}^*, \boldsymbol{\lambda}^*) = \nabla f(\mathbf{x}^*) + \sum_j \mu_j^* \nabla h_j(\mathbf{x}^*) + \sum_i \lambda_i^* \nabla g_i(\mathbf{x}^*) = \mathbf{0}

2. Primal Feasibility:

hj(x)0jandgi(x)=0ih_j(\mathbf{x}^*) \leq 0 \quad \forall j \qquad \text{and} \qquad g_i(\mathbf{x}^*) = 0 \quad \forall i

3. Dual Feasibility:

μj0j\mu_j^* \geq 0 \quad \forall j

4. Complementary Slackness:

μjhj(x)=0j\mu_j^* h_j(\mathbf{x}^*) = 0 \quad \forall j

Interpreting complementary slackness: For each inequality constraint jj, either:

  • hj(x)=0h_j(\mathbf{x}^*) = 0: the constraint is active (the optimum is on the boundary)-μj\mu_j^* can be nonzero
  • μj=0\mu_j^* = 0: the constraint is inactive (the optimum is strictly interior)-the constraint doesn't affect the optimum

This is the geometric signature of which constraints "matter" at the solution.

6.3 Geometric Interpretation

The KKT conditions say: at optimum, you cannot improve ff while satisfying all constraints. The stationarity condition generalises Lagrange's condition: f(x)-\nabla f(\mathbf{x}^*) must lie in the cone generated by the active constraint gradients.

KKT COMPLEMENTARY SLACKNESS GEOMETRY


  Case 1: Constraint inactive (h(x*) < 0)
  
  The optimum is in the interior of the feasible region.
  The inequality constraint plays no role.
  mu* = 0 (it would be wrong to "push" against a slack constraint).

  Case 2: Constraint active (h(x*) = 0)
  
  The optimum lies ON the constraint boundary.
  The gradient nablaf(x*) points into the infeasible region.
  mu* > 0 "pushes back" to prevent crossing the boundary.
  The objective would improve if the constraint were relaxed.

  In both cases: mu* * h(x*) = 0 * (neg) = 0  
                          or:  (pos) * 0 = 0  


6.4 KKT as Necessary Conditions: LICQ Proof

Theorem. If x\mathbf{x}^* is a local minimum and the LICQ holds (active constraint gradients are linearly independent), then the KKT conditions hold.

Proof sketch. Let A={j:hj(x)=0}A = \{j : h_j(\mathbf{x}^*) = 0\} be the active set. By LICQ, {hj(x)}jA{gi(x)}i\{\nabla h_j(\mathbf{x}^*)\}_{j \in A} \cup \{\nabla g_i(\mathbf{x}^*)\}_i are linearly independent.

Any feasible descent direction d\mathbf{d} (satisfying hj(x)d0\nabla h_j(\mathbf{x}^*)^\top \mathbf{d} \leq 0 for jAj \in A and gi(x)d=0\nabla g_i(\mathbf{x}^*)^\top \mathbf{d} = 0) cannot have f(x)d<0\nabla f(\mathbf{x}^*)^\top \mathbf{d} < 0 (otherwise x\mathbf{x}^* not local min).

By Farkas' lemma, f(x)-\nabla f(\mathbf{x}^*) is a conic combination of active constraint gradients: f=jAμjhj+iλigi-\nabla f = \sum_{j \in A} \mu_j \nabla h_j + \sum_i \lambda_i \nabla g_i with μj0\mu_j \geq 0. Setting μj=0\mu_j = 0 for jAj \notin A gives all four conditions. \square

Other constraint qualifications: LICQ is sufficient but not necessary for KKT. Alternatives include Mangasarian-Fromovitz (MFCQ), Slater's condition (for convex problems), and linear independence of the Jacobian at the active set.

6.5 KKT as Sufficient Conditions (Convex Case)

For convex problems, KKT conditions are not just necessary-they are also sufficient:

Theorem. If ff and hjh_j are convex, gig_i are affine, and (x,μ,λ)(\mathbf{x}^*, \boldsymbol{\mu}^*, \boldsymbol{\lambda}^*) satisfy all four KKT conditions, then x\mathbf{x}^* is a global minimum.

Proof. For any feasible y\mathbf{y}:

f(y)f(x)+f(x)(yx)(convexity of f)f(\mathbf{y}) \geq f(\mathbf{x}^*) + \nabla f(\mathbf{x}^*)^\top(\mathbf{y}-\mathbf{x}^*) \quad \text{(convexity of } f) =f(x)(jμjhj(x)+iλigi(x))(yx)= f(\mathbf{x}^*) - \left(\sum_j \mu_j^* \nabla h_j(\mathbf{x}^*) + \sum_i \lambda_i^* \nabla g_i(\mathbf{x}^*)\right)^\top (\mathbf{y}-\mathbf{x}^*) f(x)jμjhj(y)+jμjhj(x)iλi(gi(y)gi(x))\geq f(\mathbf{x}^*) - \sum_j \mu_j^* h_j(\mathbf{y}) + \sum_j \mu_j^* h_j(\mathbf{x}^*) - \sum_i \lambda_i^* (g_i(\mathbf{y}) - g_i(\mathbf{x}^*))

Using primal feasibility (hj(y)0h_j(\mathbf{y}) \leq 0), dual feasibility (μj0\mu_j^* \geq 0), complementary slackness (μjhj(x)=0\mu_j^* h_j(\mathbf{x}^*) = 0), and gi(y)=gi(x)=0g_i(\mathbf{y}) = g_i(\mathbf{x}^*) = 0, each term is 0\geq 0, so f(y)f(x)f(\mathbf{y}) \geq f(\mathbf{x}^*). \square

6.6 LP Worked Example

Linear Program: minx12x2\min -x_1 - 2x_2 subject to x1+x24x_1 + x_2 \leq 4, x1,x20x_1, x_2 \geq 0.

Rewriting as h1=x1+x240h_1 = x_1 + x_2 - 4 \leq 0, h2=x10h_2 = -x_1 \leq 0, h3=x20h_3 = -x_2 \leq 0.

Lagrangian: L=x12x2+μ1(x1+x24)μ2x1μ3x2\mathcal{L} = -x_1 - 2x_2 + \mu_1(x_1+x_2-4) - \mu_2 x_1 - \mu_3 x_2.

Stationarity: 1+μ1μ2=0-1 + \mu_1 - \mu_2 = 0, 2+μ1μ3=0-2 + \mu_1 - \mu_3 = 0.

The constraint x20x_2 \geq 0 is never active at the optimum (we want x2x_2 large), so μ3=0\mu_3 = 0. The budget constraint is active: x1+x2=4x_1 + x_2 = 4, x1=0x_1 = 0. From stationarity: μ1=2\mu_1 = 2, μ2=1\mu_2 = 1. Optimal: (x1,x2)=(0,4)(x_1^*, x_2^*) = (0, 4), objective =8= -8.


7. Duality Theory

The Lagrangian dual offers a second approach to constrained optimisation: instead of minimising over x\mathbf{x}, we maximise over the multipliers (μ,λ)(\boldsymbol{\mu}, \boldsymbol{\lambda}). The resulting dual problem often has better structure (always convex, regardless of the primal), reveals hidden geometric properties, and-for convex problems-gives exactly the same optimal value.

7.1 The Dual Function and Dual Problem

Definition (Lagrangian dual function):

q(μ,λ)=infxL(x,μ,λ)=infx[f(x)+μh(x)+λg(x)]q(\boldsymbol{\mu}, \boldsymbol{\lambda}) = \inf_{\mathbf{x}} \mathcal{L}(\mathbf{x}, \boldsymbol{\mu}, \boldsymbol{\lambda}) = \inf_{\mathbf{x}} \left[ f(\mathbf{x}) + \boldsymbol{\mu}^\top \mathbf{h}(\mathbf{x}) + \boldsymbol{\lambda}^\top \mathbf{g}(\mathbf{x}) \right]

Key property: qq is always concave in (μ,λ)(\boldsymbol{\mu}, \boldsymbol{\lambda})-it is a pointwise infimum of affine functions of the multipliers.

Dual problem:

d=maxμ0,λq(μ,λ)d^* = \max_{\boldsymbol{\mu} \geq 0, \boldsymbol{\lambda}} q(\boldsymbol{\mu}, \boldsymbol{\lambda})

This is always a convex optimisation problem (maximising concave = minimising convex).

7.2 Weak Duality

Theorem (Weak Duality). dpd^* \leq p^* always, where pp^* is the primal optimal value.

Proof. For any feasible primal x\mathbf{x} (satisfying hj(x)0h_j(\mathbf{x}) \leq 0, gi(x)=0g_i(\mathbf{x}) = 0) and any dual-feasible (μ,λ)(\boldsymbol{\mu}, \boldsymbol{\lambda}) (with μ0\boldsymbol{\mu} \geq 0):

q(μ,λ)=infyL(y,μ,λ)L(x,μ,λ)=f(x)+μh(x)0+λg(x)=0f(x)q(\boldsymbol{\mu}, \boldsymbol{\lambda}) = \inf_{\mathbf{y}} \mathcal{L}(\mathbf{y}, \boldsymbol{\mu}, \boldsymbol{\lambda}) \leq \mathcal{L}(\mathbf{x}, \boldsymbol{\mu}, \boldsymbol{\lambda}) = f(\mathbf{x}) + \underbrace{\boldsymbol{\mu}^\top \mathbf{h}(\mathbf{x})}_{\leq 0} + \underbrace{\boldsymbol{\lambda}^\top \mathbf{g}(\mathbf{x})}_{=0} \leq f(\mathbf{x})

Taking supremum over dual and infimum over primal: dpd^* \leq p^*. \square

The gap pd0p^* - d^* \geq 0 is the duality gap.

7.3 Strong Duality and Slater's Condition

Theorem (Slater's Condition -> Strong Duality). For convex ff and hjh_j, affine gig_i: if there exists a strictly feasible point x^\hat{\mathbf{x}} (with hj(x^)<0h_j(\hat{\mathbf{x}}) < 0 strictly for all jj), then d=pd^* = p^* (zero duality gap) and the dual optimum is attained.

Slater's condition is a constraint qualification: it says the feasible region is non-degenerate. For LP and QP (quadratic programs), strong duality holds under much weaker conditions.

Implications for ML:

  • The SVM dual problem is equivalent to the primal (strong duality holds by Slater)
  • The dual variables μ\boldsymbol{\mu}^* from strong duality are exactly the KKT multipliers
  • Duality gap as a stopping criterion: if primal value - dual value <ϵ< \epsilon, we have an ϵ\epsilon-optimal solution

7.4 Saddle Point Characterisation

Theorem. (x,μ,λ)(\mathbf{x}^*, \boldsymbol{\mu}^*, \boldsymbol{\lambda}^*) is primal-dual optimal with zero duality gap iff it is a saddle point of the Lagrangian:

L(x,μ,λ)L(x,μ,λ)L(x,μ,λ)x,μ0,λ\mathcal{L}(\mathbf{x}^*, \boldsymbol{\mu}, \boldsymbol{\lambda}) \leq \mathcal{L}(\mathbf{x}^*, \boldsymbol{\mu}^*, \boldsymbol{\lambda}^*) \leq \mathcal{L}(\mathbf{x}, \boldsymbol{\mu}^*, \boldsymbol{\lambda}^*) \quad \forall \mathbf{x}, \boldsymbol{\mu} \geq 0, \boldsymbol{\lambda}

The minimax equals the maximin: minxmaxμ0,λL=maxμ0,λminxL\min_\mathbf{x} \max_{\boldsymbol{\mu} \geq 0, \boldsymbol{\lambda}} \mathcal{L} = \max_{\boldsymbol{\mu} \geq 0, \boldsymbol{\lambda}} \min_\mathbf{x} \mathcal{L}.

This saddle-point view is foundational for adversarial training in ML: GAN training is exactly seeking a saddle point of the value function V(θG,θD)V(\theta_G, \theta_D).

7.5 SVM Dual: A Complete Example

The SVM is the canonical example of duality in ML. Start with the hard-margin SVM primal:

minw,b12w2s.t.yi(wxi+b)1,i=1,,n\min_{\mathbf{w}, b} \frac{1}{2}\|\mathbf{w}\|^2 \quad \text{s.t.} \quad y_i(\mathbf{w}^\top \mathbf{x}_i + b) \geq 1, \quad i = 1, \ldots, n

Rewrite constraints as hi=1yi(wxi+b)0h_i = 1 - y_i(\mathbf{w}^\top \mathbf{x}_i + b) \leq 0. Lagrangian:

L(w,b,α)=12w2+iαi(1yi(wxi+b))\mathcal{L}(\mathbf{w}, b, \boldsymbol{\alpha}) = \frac{1}{2}\|\mathbf{w}\|^2 + \sum_i \alpha_i (1 - y_i(\mathbf{w}^\top \mathbf{x}_i + b))

KKT stationarity conditions:

Lw=wiαiyixi=0w=iαiyixi\frac{\partial \mathcal{L}}{\partial \mathbf{w}} = \mathbf{w} - \sum_i \alpha_i y_i \mathbf{x}_i = \mathbf{0} \quad \Rightarrow \quad \mathbf{w}^* = \sum_i \alpha_i^* y_i \mathbf{x}_i Lb=iαiyi=0\frac{\partial \mathcal{L}}{\partial b} = -\sum_i \alpha_i y_i = 0

Substituting back into L\mathcal{L} to form the dual:

q(α)=iαi12i,jαiαjyiyjxixjq(\boldsymbol{\alpha}) = \sum_i \alpha_i - \frac{1}{2} \sum_{i,j} \alpha_i \alpha_j y_i y_j \mathbf{x}_i^\top \mathbf{x}_j

Dual problem: maxα0q(α)\max_{\boldsymbol{\alpha} \geq 0} q(\boldsymbol{\alpha}) subject to iαiyi=0\sum_i \alpha_i y_i = 0.

This depends only on inner products xixj\mathbf{x}_i^\top \mathbf{x}_j-the kernel trick replaces these with k(xi,xj)k(\mathbf{x}_i, \mathbf{x}_j) for nonlinear boundaries without ever computing features explicitly.

Support vectors: By complementary slackness, αi>0\alpha_i^* > 0 only when hi(x,b)=0h_i(\mathbf{x}^*, b^*) = 0, i.e., when the constraint is active: yi(wxi+b)=1y_i(\mathbf{w}^{*\top}\mathbf{x}_i + b^*) = 1. These are exactly the support vectors-the training points on the margin boundary that determine w\mathbf{w}^*.


8. Machine Learning Applications

The optimality conditions developed above appear directly in the mathematics underlying every major ML system. This section demonstrates these connections concretely.

8.1 Linear and Ridge Regression

Ordinary Least Squares. Minimise f(w)=12nXwy2f(\mathbf{w}) = \frac{1}{2n}\|X\mathbf{w} - \mathbf{y}\|^2. Setting the gradient to zero:

f(w)=1nX(Xwy)=0XXw=Xy\nabla f(\mathbf{w}) = \frac{1}{n} X^\top(X\mathbf{w} - \mathbf{y}) = \mathbf{0} \quad \Rightarrow \quad X^\top X \mathbf{w} = X^\top \mathbf{y}

These are the normal equations. When XX has full column rank, (XX)0(X^\top X) \succ 0 (SOSC), and the unique solution is w=(XX)1Xy\mathbf{w}^* = (X^\top X)^{-1} X^\top \mathbf{y}.

Ridge Regression. Adding 2\ell_2 regularisation: minw12nXwy2+λ2w2\min_\mathbf{w} \frac{1}{2n}\|X\mathbf{w}-\mathbf{y}\|^2 + \frac{\lambda}{2}\|\mathbf{w}\|^2.

Normal equations: (XX+nλI)w=Xy(X^\top X + n\lambda I)\mathbf{w} = X^\top \mathbf{y}. The regulariser shifts all eigenvalues by nλn\lambda, making the system always well-conditioned (strongly convex with μ=λ\mu = \lambda).

8.2 Lasso and the Subdifferential

Lasso: minw12nXwy2+λw1\min_\mathbf{w} \frac{1}{2n}\|X\mathbf{w}-\mathbf{y}\|^2 + \lambda\|\mathbf{w}\|_1.

The 1\ell_1 norm is not differentiable at wj=0w_j = 0. The first-order optimality condition uses the subdifferential w1\partial \|\mathbf{w}\|_1:

01nX(Xwy)+λw10 \in \frac{1}{n} X^\top(X\mathbf{w}^* - \mathbf{y}) + \lambda \, \partial \|\mathbf{w}^*\|_1

Coordinate-wise, for the jj-th weight:

  • If wj0w_j^* \neq 0: 1n(X(Xwy))j+λsgn(wj)=0\frac{1}{n}(X^\top(X\mathbf{w}^* - \mathbf{y}))_j + \lambda \, \text{sgn}(w_j^*) = 0
  • If wj=0w_j^* = 0: 1n(X(Xwy))jλ\left|\frac{1}{n}(X^\top(X\mathbf{w}^* - \mathbf{y}))_j\right| \leq \lambda

The second condition (correlation of feature jj with residual is small enough) determines sparsity: feature jj is excluded when its correlation with the residual is below the threshold λ\lambda. This is the mathematical source of Lasso's sparsity-inducing property.

8.3 SVM: Full KKT Analysis

The SVM soft-margin formulation extends the hard-margin case with slack variables ξi0\xi_i \geq 0:

minw,b,ξ12w2+Ciξis.t.yi(wxi+b)1ξi,ξi0\min_{\mathbf{w}, b, \boldsymbol{\xi}} \frac{1}{2}\|\mathbf{w}\|^2 + C\sum_i \xi_i \quad \text{s.t.} \quad y_i(\mathbf{w}^\top\mathbf{x}_i + b) \geq 1 - \xi_i, \quad \xi_i \geq 0

The KKT conditions include multipliers αi\alpha_i for the margin constraints and βi\beta_i for ξi0\xi_i \geq 0. Complementary slackness gives:

  • αi=0\alpha_i = 0: correctly classified, not a support vector
  • 0<αi<C0 < \alpha_i < C: on the margin, ξi=0\xi_i = 0 (standard support vector)
  • αi=C\alpha_i = C: inside the margin or misclassified, ξi>0\xi_i > 0

The parameter CC controls the trade-off between margin width and training error through the dual feasibility constraint 0αiC0 \leq \alpha_i \leq C.

8.4 PCA via Constrained Optimisation

Principal Component Analysis seeks directions of maximum variance subject to orthonormality. The full PCA problem is:

maxVRd×ktr(VΣV)s.t.VV=Ik\max_{V \in \mathbb{R}^{d \times k}} \text{tr}(V^\top \Sigma V) \quad \text{s.t.} \quad V^\top V = I_k

Lagrangian: L=tr(VΣV)tr(Λ(VVI))\mathcal{L} = \text{tr}(V^\top \Sigma V) - \text{tr}(\Lambda(V^\top V - I)) where Λ\Lambda is a k×kk \times k symmetric multiplier matrix.

Stationarity: 2ΣV=2VΛ2\Sigma V = 2V\Lambda, i.e., ΣV=VΛ\Sigma V = V\Lambda. Each column vj\mathbf{v}_j satisfies Σvj=λjvj\Sigma \mathbf{v}_j = \lambda_j \mathbf{v}_j-an eigenvalue equation. The optimal VV is the matrix of top-kk eigenvectors; the multipliers λj\lambda_j are the eigenvalues (= captured variance).

8.5 Maximum Entropy and Softmax

Maximum Entropy Principle. Given constraints Ep[fk]=ck\mathbb{E}_p[f_k] = c_k for k=1,,Kk=1,\ldots,K, the distribution maximising entropy H(p)=ipilogpiH(p) = -\sum_i p_i \log p_i subject to ipi=1\sum_i p_i = 1 has the Boltzmann/Gibbs form:

pi=exp(kλkfk(i))Z(λ)p_i^* = \frac{\exp(\sum_k \lambda_k^* f_k(i))}{Z(\boldsymbol{\lambda}^*)}

Derivation. Lagrangian with multipliers λ0\lambda_0 (normalisation) and λk\lambda_k (feature constraints):

L=ipilogpiλ0(ipi1)kλk(ipifk(i)ck)\mathcal{L} = -\sum_i p_i \log p_i - \lambda_0 \left(\sum_i p_i - 1\right) - \sum_k \lambda_k \left(\sum_i p_i f_k(i) - c_k\right)

Stationarity in pip_i: logpi1λ0kλkfk(i)=0-\log p_i - 1 - \lambda_0 - \sum_k \lambda_k f_k(i) = 0, giving piexp(kλkfk(i))p_i^* \propto \exp(\sum_k \lambda_k^* f_k(i)).

Softmax as max entropy. The softmax function pi=ezi/jezjp_i = e^{z_i}/\sum_j e^{z_j} is exactly the max-entropy distribution over {1,,n}\{1,\ldots,n\} subject to Ep[ei]=const\mathbb{E}_p[e_i] = \text{const} constraints (Lagrange multipliers are the logits ziz_i). This gives the softmax a principled statistical interpretation beyond "normalised exponentials."

8.6 Attention as Constrained Optimisation

The attention mechanism in transformers can be viewed as a constrained optimisation problem. Given queries QQ, keys KK, values VV, standard attention computes:

Attn(Q,K,V)=softmax(QKdk)V\text{Attn}(Q,K,V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

Constrained interpretation. Attention computes the memory retrieval that solves:

v=argmaxpΔnpKV1βipilogpi\mathbf{v}^* = \arg\max_{\mathbf{p} \in \Delta^n} \mathbf{p}^\top K V - \frac{1}{\beta} \sum_i p_i \log p_i

where β=1/dk\beta = 1/\sqrt{d_k} is a temperature and Δn\Delta^n is the probability simplex. The KKT condition for this maximum-entropy retrieval gives exactly softmax attention weights.

The Lagrange multiplier for the simplex constraint ipi=1\sum_i p_i = 1 becomes the log-partition function logZ\log Z (the log-sum-exp normaliser), confirming that attention is a principled probabilistic retrieval operation.


9. Non-Convex Landscapes in Deep Learning

Deep learning operates almost entirely in the non-convex regime. Yet neural networks train successfully-why? The answer lies in the special geometric structure of high-dimensional non-convex landscapes.

9.1 Loss Landscape Geometry

An nn-parameter neural network defines a loss landscape L:RnR+\mathcal{L}: \mathbb{R}^n \to \mathbb{R}_+ with structure that differs fundamentally from classical non-convex functions:

Key empirical observations:

  • No spurious local minima (approximately): for sufficiently overparameterised networks on tractable data, all local minima have near-identical loss values. Gradient descent doesn't get "trapped" because there are no deep local minima to get trapped in.
  • Saddle point dominance: most critical points are saddle points, not local minima. The index (number of negative eigenvalue directions) of these saddles is typically large.
  • Loss barriers between solutions: two different global minima can be separated by high barriers in weight space, but connected by loss valleys in higher-dimensional paths.

For AI: The practical consequence is that SGD with good initialisation reliably finds good solutions, and model merging (linear combination of two trained models) often produces competitive performance-evidence of basin connectivity.

9.2 The Role of Overparameterisation

Theorem (informal, Kawaguchi 2016; Du et al. 2018). For a wide class of networks trained on generic data, when the number of parameters nn exceeds the number of training points NN, every local minimum is a global minimum.

Intuition. With nNn \gg N parameters, the loss function has nNn - N approximate degrees of freedom. The "level set" {w:L(w)0}\{\mathbf{w} : \mathcal{L}(\mathbf{w}) \approx 0\} is a high-dimensional manifold. Any point trying to be a local minimum with non-zero loss would need the gradient to vanish while the Hessian is positive definite in all nn directions-this becomes geometrically impossible when the loss can be driven to zero by moving in any of the nNn - N flat directions.

Neural Tangent Kernel (NTK) perspective. In the infinite-width limit, training dynamics become linear: w˙=ηK(w)e\dot{\mathbf{w}} = -\eta K^\infty (\mathbf{w}) \mathbf{e} where KK^\infty is the NTK matrix. If K0K^\infty \succ 0, gradient descent converges globally at a linear rate-a convex analysis result applied to a formally non-convex problem.

9.3 Sharpness-Aware Minimisation (SAM)

Motivated by the observation that flat minima generalise better than sharp ones, Sharpness-Aware Minimisation (Foret et al. 2021) solves:

minwmaxϵ2ρL(w+ϵ)\min_\mathbf{w} \max_{\|\boldsymbol{\epsilon}\|_2 \leq \rho} \mathcal{L}(\mathbf{w} + \boldsymbol{\epsilon})

KKT analysis of the inner problem. Fix w\mathbf{w}. The inner maximisation maxϵρL(w+ϵ)\max_{\|\boldsymbol{\epsilon}\| \leq \rho} \mathcal{L}(\mathbf{w} + \boldsymbol{\epsilon}) is a constrained problem with one inequality constraint h(ϵ)=ϵ2ρ20h(\boldsymbol{\epsilon}) = \|\boldsymbol{\epsilon}\|^2 - \rho^2 \leq 0.

KKT conditions: ϵL(w+ϵ)=2μϵ\nabla_{\boldsymbol{\epsilon}} \mathcal{L}(\mathbf{w} + \boldsymbol{\epsilon}^*) = 2\mu^* \boldsymbol{\epsilon}^*, giving ϵwL(w)\boldsymbol{\epsilon}^* \parallel \nabla_\mathbf{w} \mathcal{L}(\mathbf{w}).

The adversarial perturbation is: ϵ^=ρwL(w)/wL(w)\hat{\boldsymbol{\epsilon}} = \rho \cdot \nabla_\mathbf{w} \mathcal{L}(\mathbf{w}) / \|\nabla_\mathbf{w} \mathcal{L}(\mathbf{w})\|

SAM gradient step: wwηwL(w+ϵ^)\mathbf{w} \leftarrow \mathbf{w} - \eta \nabla_\mathbf{w} \mathcal{L}(\mathbf{w} + \hat{\boldsymbol{\epsilon}}).

This is a direct application of KKT: solving the constrained inner problem analytically gives the SAM update formula.

9.4 Neural Collapse

At the terminal phase of training, when networks reach near-zero training loss, a remarkable geometric structure called Neural Collapse (Papyan et al. 2020) emerges:

  1. Within-class variability collapse: all training examples of class cc have the same last-layer representation h=μc\mathbf{h} = \boldsymbol{\mu}_c
  2. Equinorm ETF: the class means μ1,,μC\boldsymbol{\mu}_1, \ldots, \boldsymbol{\mu}_C form an Equiangular Tight Frame-they have equal norms and equal pairwise cosine similarities =1/(C1)= -1/(C-1)
  3. Self-duality: the weight vectors wc\mathbf{w}_c align with the class means up to scaling

KKT characterisation. Neural collapse is the KKT point of the Unconstrained Features Model (UFM):

minH,W,bLCE(WH+b)+λ2(HF2+WF2)\min_{\mathbf{H}, \mathbf{W}, \mathbf{b}} \mathcal{L}_{\text{CE}}(\mathbf{W}\mathbf{H} + \mathbf{b}) + \frac{\lambda}{2}(\|\mathbf{H}\|_F^2 + \|\mathbf{W}\|_F^2)

The KKT stationarity conditions, combined with symmetry of the cross-entropy loss at balanced class distributions, force the ETF structure. Neural collapse is not an empirical coincidence-it is the unique KKT point of this simplified training problem.

9.5 Mode Connectivity

Loss valley hypothesis: Two local minima w1\mathbf{w}_1^* and w2\mathbf{w}_2^* of a neural network can be connected by a low-loss path (Garipov et al. 2018). Specifically, there exists a piecewise linear or quadratic curve ϕ:[0,1]Rn\phi: [0,1] \to \mathbb{R}^n with ϕ(0)=w1\phi(0) = \mathbf{w}_1^*, ϕ(1)=w2\phi(1) = \mathbf{w}_2^* and L(ϕ(t))L(w1)\mathcal{L}(\phi(t)) \approx \mathcal{L}(\mathbf{w}_1^*) for all t[0,1]t \in [0,1].

Implication for model merging. The success of weight averaging (WA) methods like Model Soups and SLERP model merging is explained by mode connectivity: if the merged model lies near the connecting path in weight space, it inherits the performance of both endpoints.

Optimality connection. Mode connectivity is a non-convex analogue of the fundamental theorem of convex analysis: convex functions have connected sublevel sets. For "sufficiently trained" neural networks, the sublevel set {w:L(w)L(w1)+ϵ}\{\mathbf{w} : \mathcal{L}(\mathbf{w}) \leq \mathcal{L}(\mathbf{w}_1^*) + \epsilon\} is approximately path-connected-not because the landscape is convex, but because overparameterisation creates high-dimensional flat regions.


10. Common Mistakes

#MistakeWhy It's WrongFix
1Treating f(x)=0\nabla f(\mathbf{x}^*) = \mathbf{0} as sufficient for a minimumIt's necessary, not sufficient. Saddle points and maxima also satisfy this.Always check second-order conditions (Hessian PSD/PD) or verify global minimum via convexity arguments
2Forgetting to check constraint qualificationKKT conditions require LICQ (or another CQ). Without CQ, a minimum may exist with no Lagrange multiplierVerify that active constraint gradients are linearly independent at the candidate point
3Setting μj<0\mu_j < 0 for inequality constraintsNegative multipliers on hj0h_j \leq 0 constraints violate dual feasibility; the Lagrangian is then unbounded belowDual feasibility requires μj0\mu_j \geq 0 for all inequality constraints (the convention matters: h0h \leq 0 needs μ0\mu \geq 0)
4Ignoring complementary slacknessMissing the condition μjhj=0\mu_j h_j = 0 leads to wrong determination of which constraints are activeFor each inequality constraint, exactly one of μj=0\mu_j = 0 or hj=0h_j = 0 must hold (or both)
5Concluding strong duality without SlaterWeak duality always holds, but strong duality (d=pd^* = p^*) requires a constraint qualification like Slater's conditionVerify strict feasibility (Slater's point exists) before asserting zero duality gap
6Using the det(H)\text{det}(H) test in Rn\mathbb{R}^n, n>2n > 2The determinant test (det >0> 0 and H11>0H_{11} > 0) is specific to R2\mathbb{R}^2. In higher dimensions, need to check all nn leading principal minors or eigenvaluesIn Rn\mathbb{R}^n: compute all eigenvalues of HH; or use Sylvester's criterion (all leading principal minors >0> 0 iff PD)
7Confusing local and global optimality for non-convex problemsFor non-convex functions, local minima may not be global. KKT conditions identify local critical points, not global optimaUse global analysis: prove convexity, or use branch-and-bound, or accept local optimality
8Wrong sign convention for the LagrangianDifferent texts define L=f+λg\mathcal{L} = f + \lambda g vs. fλgf - \lambda g. Mixing conventions gives wrong multiplier signsPick one convention and be consistent: for minf\min f s.t. g=0g = 0, use L=f+λg\mathcal{L} = f + \lambda g (add constraints to objective)
9Forgetting that the Lagrange multiplier theorem is for C1C^1 functionsAt non-smooth points (e.g., 1\ell_1 constraints), the standard gradient condition failsUse subdifferentials and subgradient conditions; or smooth the problem with a differentiable approximation
10Concluding "no constrained minimum exists" when KKT has no solutionKKT conditions failing to have a solution means the constraint qualification fails OR no minimum exists. These are differentFirst check whether the feasible set is closed and bounded (Weierstrass guarantees existence); then debug the CQ
11Misidentifying support vectorsOnly points with αi>0\alpha_i > 0 (active margin constraint) are support vectors; incorrectly classified interior points are notCheck complementary slackness: αi>0yi(wxi+b)=1\alpha_i > 0 \Leftrightarrow y_i(\mathbf{w}^\top\mathbf{x}_i + b) = 1 (on the margin boundary)
12Applying first-order conditions to discrete or combinatorial constraintsGradient = 0 requires differentiability; discrete feasible sets (e.g., integer programs) don't satisfy thisFor discrete/combinatorial problems, use integer programming methods, branch-and-bound, or relaxations

11. Exercises

Exercise 1 - Critical Point Classification

Let f(x,y)=x33xy2+y4f(x,y) = x^3 - 3xy^2 + y^4.

(a) Find all critical points by solving f=0\nabla f = \mathbf{0}.

(b) Compute the Hessian at each critical point and classify using the second-order test.

(c) Verify numerically: check that gradient descent from each critical point stays put (up to numerical noise).

(d) Sketch the level curves of ff near each critical point.

Exercise 2 - Lagrange Multipliers: Constrained Extremum

Maximise f(x)=x1x2x3f(\mathbf{x}) = x_1 x_2 x_3 subject to x1+x2+x3=12x_1 + x_2 + x_3 = 12, x0\mathbf{x} \geq \mathbf{0}.

(a) Write the Lagrangian and derive KKT conditions.

(b) Solve analytically and verify that the maximum is f=64f^* = 64.

(c) Interpret the Lagrange multiplier: by how much does ff^* change if the constraint becomes x1+x2+x3=13x_1 + x_2 + x_3 = 13?

(d) Confirm numerically using scipy.optimize.minimize.

Exercise 3 - KKT Conditions for Quadratic Program

Solve: min12(x12+x22)\min \frac{1}{2}(x_1^2 + x_2^2) subject to x1+x23x_1 + x_2 \geq 3, x1,x20x_1, x_2 \geq 0.

(a) Write the KKT conditions in full.

(b) Determine the active constraint(s) and solve the KKT system.

(c) Verify the solution is a global minimum by checking convexity.

(d) Compute the duality gap (should be zero).

Exercise 4 - Convexity Analysis

For each function, determine if it is convex, strictly convex, or neither, on the specified domain:

(a) f(x)=exx1f(x) = e^x - x - 1 on R\mathbb{R}

(b) f(x)=x22+x1f(\mathbf{x}) = \|\mathbf{x}\|_2^2 + \|\mathbf{x}\|_1 on Rn\mathbb{R}^n

(c) f(A)=logdetAf(A) = -\log \det A on S++n\mathbb{S}_{++}^n (positive definite matrices)

(d) f(x,y)=x2/yf(x,y) = x^2/y for y>0y > 0

(e) f(w)=LCE(w)f(\mathbf{w}) = \mathcal{L}_{\text{CE}}(\mathbf{w}) for logistic regression with linearly separable data

Exercise 5 - SVM Dual Derivation

Derive the dual of the hard-margin SVM from scratch.

(a) Write the primal as a standard form QP with inequality constraints.

(b) Form the Lagrangian and derive the dual function q(α)q(\boldsymbol{\alpha}).

(c) Write the dual problem and verify its constraints.

(d) Show that the dual is concave in α\boldsymbol{\alpha}.

(e) Implement and solve both primal and dual for a small dataset; verify they give the same optimal value.

Exercise 6 - Maximum Entropy Distribution

Find the maximum entropy distribution on {1,2,3,4}\{1, 2, 3, 4\} subject to: ipi=1\sum_i p_i = 1 and E[X]=2.5\mathbb{E}[X] = 2.5.

(a) Write the Lagrangian with multipliers λ0,λ1\lambda_0, \lambda_1.

(b) Derive that pi=eλ0λ1i/Zp_i^* = e^{-\lambda_0 - \lambda_1 i}/Z.

(c) Find λ0,λ1\lambda_0, \lambda_1 numerically by solving the constraint equations.

(d) Compare to the uniform distribution: which has higher entropy?

(e) Verify: compute H(p)H(p^*) and confirm it exceeds H(uniform restricted to E[X]=2.5)H(\text{uniform restricted to } \mathbb{E}[X]=2.5).

Exercise 7 - SAM: KKT Analysis

Analyse Sharpness-Aware Minimisation rigorously.

(a) Write the inner maximisation maxϵρL(w+ϵ)\max_{\|\boldsymbol{\epsilon}\| \leq \rho} \mathcal{L}(\mathbf{w} + \boldsymbol{\epsilon}) as a constrained problem.

(b) Write the KKT conditions and solve for ϵ\boldsymbol{\epsilon}^* in closed form.

(c) Show that ϵ^=ρL(w)/L(w)\hat{\boldsymbol{\epsilon}} = \rho \nabla\mathcal{L}(\mathbf{w})/\|\nabla\mathcal{L}(\mathbf{w})\| satisfies the KKT conditions.

(d) Implement one SAM step and compare to vanilla gradient descent on a sharp quadratic.

(e) Empirically verify that SAM finds flatter minima on a small neural network.

Exercise 8 - Duality Gap and Convergence

Implement a primal-dual interior-point method for a small LP.

(a) Formulate: mincx\min \mathbf{c}^\top \mathbf{x} s.t. Ax=bA\mathbf{x} = \mathbf{b}, x0\mathbf{x} \geq 0 as a standard LP.

(b) Implement the primal-dual path-following method tracking both primal and dual variables.

(c) Plot the duality gap vs. iteration and verify it converges to zero.

(d) Verify the optimal solution satisfies all KKT conditions numerically.

(e) Compare convergence to simplex method on the same problem.


12. Why This Matters for AI (2026 Perspective)

ConceptImpact on AI/ML
First-order necessary conditionsEvery modern optimiser (SGD, Adam, AdamW) terminates at approximate stationarity L0\|\nabla\mathcal{L}\| \approx 0. Training stopping criteria are gradient-norm thresholds.
Hessian spectrumAdaptive learning rate methods (Adam, Adagrad) implicitly approximate H1LH^{-1}\nabla\mathcal{L} to normalise curvature. Sharpness-aware methods (SAM, ASAM) explicitly minimise spectral norm of HH.
Saddle pointsThe prevalence of saddle points (not local minima) in deep network landscapes explains why gradient descent with noise (SGD, dropout) escapes them efficiently. Perturbed gradient descent has provable saddle-escape guarantees.
ConvexityConvex relaxations of combinatorial ML problems (e.g., 1\ell_1 relaxation of sparse recovery) are solvable to global optimality. Convex loss functions (logistic, square) give unique solutions independent of initialisation.
Lagrange multipliersPCA, LDA, CCA are all Lagrange multiplier problems. QLoRA's 4-bit quantisation uses a constrained optimisation where the quantisation constraint is relaxed via Lagrange multipliers in the mixed-precision framework.
KKT conditionsSVM training, LP relaxations of beam search, constrained decoding (e.g., budget-forcing), and RLHF reward-constrained optimisation all use KKT theory for optimality analysis.
DualityThe SVM dual gives the kernel trick. Max-margin training of LLMs (via RLHF) can be analysed as a dual problem where the Lagrange multiplier on the KL constraint is the reward temperature β\beta.
Strong convexityL2L_2 regularisation makes the loss strongly convex, giving linear convergence guarantees. The condition number κ=L/μ\kappa = L/\mu governs convergence; warmup schedules and weight decay are practitioner responses to ill-conditioning.
Max entropy / softmaxLanguage model next-token prediction is max-entropy inference subject to observed statistics. Temperature scaling adjusts the implicit Lagrange multiplier on the cross-entropy constraint, controlling distribution sharpness.
SAM/sharpnessFlat minima empirically generalise better. SAM (Foret et al. 2021) is now standard in SOTA image classification and LLM fine-tuning. The optimality condition for the inner problem is the KKT stationarity condition.
Neural collapseThe ETF structure at convergence (proven via KKT of the UFM) informs classifier weight initialisation strategies and explains why the last layer of a fine-tuned model can be reset and retrained cheaply.
Mode connectivityModel merging (Model Soups, TIES, DARE) and model interpolation are enabled by the path-connectivity of loss basins-a direct consequence of overparameterised non-convex landscape geometry.

Conceptual Bridge

This section occupies the pivot between two phases of the curriculum. Everything before 04 established the tools for computing derivatives-limits, continuity, partial derivatives, gradients, Jacobians, chain rule. This section asks the deeper question: what do these derivatives tell us about where the best solutions are?

Looking backward. The first-order conditions derive directly from the gradient machinery of 01-03. The Hessian-the matrix of second partial derivatives-extends the single-variable second derivative test to functions of many variables, connecting to the matrix theory of 02. The chain rule and product rule for derivatives underpin every step of the Lagrangian analysis.

Looking forward. The optimality conditions here are used constantly in the chapters ahead:

  • 05/05 (Gradient Descent) and 08 (Optimisation Algorithms): gradient descent is precisely the process of iterating toward f=0\nabla f = \mathbf{0}; convergence analysis requires the strong convexity and Lipschitz smoothness properties defined here
  • 06 (Probability & Statistics): maximum likelihood estimation is an unconstrained minimisation whose optimality conditions give the maximum likelihood equations; Bayesian MAP estimation introduces prior constraints handled by Lagrange multipliers
  • 07 (Information Theory): the maximum entropy principle (8.5) is a direct application of Lagrange multipliers; the KL divergence minimisation underlying variational inference is a constrained optimisation whose KKT conditions are the ELBO
POSITION IN THE CALCULUS CURRICULUM


  04: Calculus Fundamentals
   01: Limits and Continuity           Foundation for 02
   02: Derivatives and Differentiation  Foundation for 03, 04
   03: Integration                     Foundation for 06 (probability)
   04: Optimality Conditions  YOU ARE HERE
          
            Uses: gradients, Hessians, chain rule, Jacobians
            Introduces: critical points, KKT, duality, convexity
          
          
  05: Multivariate Calculus
   01: Partial Derivatives (prerequisite)
   02: Gradient and Hessian (prerequisite)
   03: Chain Rule & Backpropagation (prerequisite)
   04: Optimality Conditions  YOU ARE HERE
   05: Gradient Descent and Convergence  Uses 04's convexity theory

  08: Optimisation Algorithms  Deep dive into algorithms enabled by 04
  09: Probabilistic Graphical Models  MAP/MLE via 04's Lagrange theory


The central insight. Optimality conditions are not merely a tool for finding optima-they are a language for describing what it means for a solution to be right. The KKT conditions don't just tell you where to stop searching; they tell you why the answer is the answer: which constraints are binding, how sensitive the solution is to perturbations, what trade-offs are implicit in the optimal choice. Every time a language model outputs a softmax distribution, every time a recommender system solves a constrained relevance problem, every time a reinforcement learning agent balances reward and KL penalty-the KKT conditions are operating in the background, whether or not the engineer knows it.


Skill Check

Test this lesson

Answer 4 quick questions to lock in the lesson and feed your adaptive practice queue.

--
Score
0/4
Answered
Not attempted
Status
1

Which module does this lesson belong to?

2

Which section is covered in this lesson content?

3

Which term is most central to this lesson?

4

What is the best way to use this lesson for real learning?

Your answers save locally first, then sync when account storage is available.
Practice queue