Module contents
Lesson 5 of 27Core 110 min

Lagrange multipliers and KKT conditions

Extend optimality conditions to constrained problems, from the geometry of parallel Lagrange gradients to Karush-Kuhn-Tucker conditions with inequalities and complementary slackness. Study the constraint qualifications making them necessary, their sufficiency for convex problems, and second-order conditions on the tangent space.

After this lesson you can

  • Derive Lagrange conditions for equality constraints and interpret them geometrically.
  • Write and solve KKT conditions by hand for problems with inequalities by enumerating active sets.
  • Explain LICQ, MFCQ and Slater's roles using a counterexample where KKT fails without a qualification.
  • Prove that KKT conditions suffice for global optimality in a convex problem.
  • Verify local optimality using the second-order condition for the Lagrangian Hessian on the critical cone.

Before you start

Motivation: optima that cannot be free

In the lesson on formulation and optimality the criterion was clean: at an unconstrained local minimum, ∇f=0\grad f = \vb{0}. But important problems are seldom unconstrained, and their best point is often exactly where something prevents further movement, with a gradient that does not vanish.

  • A budget. Split 1010 units between two goods to maximize a utility product. The optimum uses the whole budget: ff keeps increasing in the forbidden direction.
  • Probabilities. Choose p∈Rnp \in \R^n with pi≥0p_i \ge 0 and ∑ipi=1\sum_i p_i = 1 to maximize entropy subject to moment constraints (the maximum-entropy distribution in the probability lesson arises this way), or project logits onto the simplex.
  • Bounded norms. Minimize a loss with ∥w∥2≤R\norm{\vb{w}}_2 \le R or ∥w∥1≤R\norm{\vb{w}}_1 \le R. Regularizing with λ∥w∥2\lambda\norm{\vb{w}}^2 and constraining the norm are, as you will see, two sides of the same problem.
  • Margins. The support vector machine minimizes 12∥w∥2\tfrac12\norm{\vb{w}}^2 with one inequality yi(w⊤xi+b)≥1y_i(\vb{w}\T\vb{x}_i + b) \ge 1 per datum. Almost all hold with slack; a few, the support vectors, hold with equality. This lesson determines which are support vectors.

A physical image sums it up. A ball rolls toward the bottom of a valley and hits a wall: it stops on the wall where the ground still slopes down. Gravity, −∇f-\grad f, is nonzero; it is balanced by the wall’s reaction force, pointing in the normal direction. That reaction is the multiplier. Two properties of walls foreshadow the theory: a wall only pushes, never pulls (inequality multipliers are ≥0\ge 0), and a wall not touching the ball exerts no force (complementary slackness).

This lesson formalizes the image in three stages: equality constraints (the wall is a curve you cannot leave), inequalities (walls may be active or inactive), and second-order conditions. Along the way, two cautions separate using KKT from understanding it: the conditions are not necessary without an assumption about how constraints are described, and are sufficient only if the problem is convex.

Equality constraints: tangency

Start with the simplest case, a problem with one equality in the plane: minimize f0(x)f_0(\vb{x}) subject to h(x)=0h(\vb{x}) = 0. The feasible set is the zero level curve of hh (a level set). Walk along that curve: the derivative of f0f_0 in the walking direction is ∇f0⋅t\grad f_0 \cdot \vb{t}, with tangent vector t\vb{t}. The walker cannot improve either forward or backward only if ∇f0⋅t=0\grad f_0 \cdot \vb{t} = 0, that is, if ∇f0\grad f_0 is perpendicular to the curve.

But the gradient of hh is also perpendicular to the curve h=0h = 0. In the plane there is only one direction perpendicular to t\vb{t}, so the arrows are parallel: ∇f0=−ν ∇h\grad f_0 = -\nu\,\grad h for some number ν\nu. Geometrically, the level curve of f0f_0 through the optimum is tangent to the constraint: if it crossed, moving along the constraint in one direction would reach points with lower f0f_0.

InteractiveLagrange tangency
  • constraint h(x)=0h(\vb{x}) = 0
  • ∇f0\nabla f_0
  • ∇h\nabla h (own scale)
  • tangential component of ∇f0\nabla f_0
  • normal component −ν∇h-\nu\nabla h
f0f_0 along the curve, as a function of xx
Problem
f0(x)f_0(\vb{x})−6.720
∠(∇f0,∇h)\angle(\nabla f_0, \nabla h)137.4°
ν=−∇f0 ⁣⋅ ⁣∇h/∥∇h∥2\nu = -\nabla f_0\!\cdot\!\nabla h / \|\nabla h\|^21.480
∥∇f0+ν∇h∥\|\nabla f_0 + \nu\nabla h\| (tangential component)3.041
d2f0/dℓ2\mathrm{d}^2 f_0 / \mathrm{d}\ell^2 along the curve0.800
t⊤∇xx2L t\vb{t}\T \nabla^2_{xx} L\, \vb{t}0.800
Maximize the product xyxy subject to a budget x+2y=10x + 2y = 10 (minimize −xy-xy).
What do points on the constraint where f0f_0 stops changing have in common? Drag the point along the thick curve. The blue arrow is ∇f0\nabla f_0 and the aqua arrow ∇h\nabla h (with its own scale); blue decomposes into a normal part, −ν∇h-\nu\nabla h (dashed aqua), and a tangential part in magenta, the only part changing f0f_0 along the curve. Below is f0f_0 along the constraint: its extrema are exactly the points where the tangential part vanishes and arrows align. Try the circle, which has four stationary points, and observe the reading of t⊤∇xx2L t\vb{t}\T\nabla^2_{xx}L\,\vb{t} agrees with the second derivative along the curve there.

Three observations about the figure:

  1. At extrema arrows are parallel, but parallel arrows do not imply an extremum. On the circle there are four stationary points: two minima and two maxima of f0f_0 on the curve. Tangency is necessary, not sufficient. Distinguishing them is the job of the second-order section.
  2. The ratio of lengths is the multiplier. When ∇f0=−ν∇h\grad f_0 = -\nu\grad h, number ν\nu says how large ∇f0\grad f_0 is in units of ∇h\grad h. Its sign says whether arrows point in the same or opposite directions, and for an equality that sign does not matter: a curve’s wall can push from either side.
  3. The constraint need not be convex (the circle) and the condition still holds. Convexity only enters when sufficiency is required.

The Lagrangian and Lagrange’s theorem

Lagrange’s trick turns “minimize with constraints” into “find an unconstrained stationary point” of an expanded function.

With this convention, ∇xL=∇f0+∑jνj∇hj\grad_{\vb{x}} L = \grad f_0 + \sum_j \nu_j \grad h_j, and the preceding section’s tangency says ∇xL=0\grad_{\vb{x}} L = \vb{0}. Viewed as a function of ν\vb{\nu}, ∇νL=h(x)\grad_{\vb{\nu}} L = h(\vb{x}), so the constraint is stationarity with respect to ν\vb{\nu}. A feasible point satisfying the condition is a critical point of the Lagrangian in all variables.

The result needs an assumption, and it helps to see where it enters. The proof needs a lemma turning “tangent directions” into actual curves on the feasible set.

Proof

Since the rank is pp, there are pp linearly independent columns of Dh(x⋆)\mathrm{D}h(\vb{x}^\star); reorder coordinates so x=(u,w)\vb{x} = (\vb{u}, \vb{w}) with w∈Rp\vb{w} \in \R^p and Dwh(x⋆)\mathrm{D}_{\vb{w}}h(\vb{x}^\star) invertible. By the implicit function theorem, there is a C1C^1 function w(u)\vb{w}(\vb{u}) defined near u⋆\vb{u}^\star with w(u⋆)=w⋆\vb{w}(\vb{u}^\star) = \vb{w}^\star and h(u,w(u))=0h(\vb{u}, \vb{w}(\vb{u})) = \vb{0}, and derivative Dw=−(Dwh)−1Duh\mathrm{D}\vb{w} = -(\mathrm{D}_{\vb{w}}h)\inv \mathrm{D}_{\vb{u}}h. Define γ(t)=(u⋆+tdu, w(u⋆+tdu))\vb{\gamma}(t) = (\vb{u}^\star + t\vb{d}_u,\ \vb{w}(\vb{u}^\star + t\vb{d}_u)). Then h(γ(t))=0h(\vb{\gamma}(t)) = \vb{0} and γ′(0)=(du, −(Dwh)−1Duh du)\vb{\gamma}'(0) = (\vb{d}_u,\ -(\mathrm{D}_{\vb{w}}h)\inv \mathrm{D}_{\vb{u}}h\,\vb{d}_u). Since Dh(x⋆)d=Duh du+Dwh dw=0\mathrm{D}h(\vb{x}^\star)\vb{d} = \mathrm{D}_{\vb{u}}h\,\vb{d}_u + \mathrm{D}_{\vb{w}}h\,\vb{d}_w = \vb{0}, the second component is exactly dw\vb{d}_w. ■\blacksquare

∎
Proof

Let d∈null⁡Dh(x⋆)\vb{d} \in \nullsp \mathrm{D}h(\vb{x}^\star) and γ\vb{\gamma} be the lemma’s curve. Function φ(t)=f0(γ(t))\varphi(t) = f_0(\vb{\gamma}(t)) is C1C^1 and has a local minimum at t=0t = 0 (points γ(t)\vb{\gamma}(t) are feasible and close to x⋆\vb{x}^\star), so by the first-order necessary condition, 0=φ′(0)=∇f0(x⋆)⋅d0 = \varphi'(0) = \grad f_0(\vb{x}^\star) \cdot \vb{d}. Thus ∇f0(x⋆)\grad f_0(\vb{x}^\star) is orthogonal to the whole nullspace of Dh(x⋆)\mathrm{D}h(\vb{x}^\star), meaning it lies in its orthogonal complement, the row space: ∇f0(x⋆)∈span⁡{∇h1,…,∇hp}\grad f_0(\vb{x}^\star) \in \spn\{\grad h_1, \dots, \grad h_p\}. Coefficients are unique because ∇hj\grad h_j are independent. ■\blacksquare

∎

Linear independence is not a technical detail. If it fails, the theorem is false: minimizing f0(x)=xf_0(x) = x over h(x)=x2=0h(x) = x^2 = 0 has the sole feasible point x⋆=0x^\star = 0, hence the minimum, and there f0′=1f_0' = 1 while h′=0h' = 0: no ν\nu satisfies 1+ν⋅0=01 + \nu \cdot 0 = 0. This is the first example of a phenomenon developed in the qualifications section.

Inequalities: active and inactive walls

With inequalities the problem becomes

minimizef0(x)subject tofi(x)≤0 (i=1,…,m),hj(x)=0 (j=1,…,p).\begin{aligned} \text{minimize} \quad & f_0(\vb{x}) \quad \text{subject to} \quad f_i(\vb{x}) \le 0 \ (i = 1,\dots,m), \quad h_j(\vb{x}) = 0 \ (j = 1,\dots,p). \end{aligned}

Constraint fif_i is active at feasible x\vb{x} if fi(x)=0f_i(\vb{x}) = 0 (the point is on its wall), and inactive if fi(x)<0f_i(\vb{x}) < 0. The set of active indices is written A(x)\mathcal{A}(\vb{x}).

Two local facts explain almost everything.

Inactive constraints disappear. If fi(x⋆)<0f_i(\vb{x}^\star) < 0, continuity gives fi<0f_i < 0 in a neighborhood of x⋆\vb{x}^\star, so locally that constraint does not exist. A local minimum of the full problem is a local minimum of the problem keeping only active constraints.

Active constraints behave like one-sided walls. An equality forbids movement in both normal directions; an active inequality only forbids the one increasing fif_i. A direction d\vb{d} is linearly feasible if ∇fi(x⋆)⋅d≤0\grad f_i(\vb{x}^\star) \cdot \vb{d} \le 0 for i∈Ai \in \mathcal{A} and ∇hj(x⋆)⋅d=0\grad h_j(\vb{x}^\star)\cdot\vb{d} = 0 for every jj. These directions form a polyhedral cone L(x⋆)\mathcal{L}(\vb{x}^\star), the linearized cone. If x⋆\vb{x}^\star is optimal, no direction in L\mathcal{L} should decrease f0f_0 (this is the idea; the assumption making it true appears in the qualifications section). In cone language: ∇f0(x⋆)⋅d≥0\grad f_0(\vb{x}^\star)\cdot\vb{d} \ge 0 for every d∈L\vb{d} \in \mathcal{L}, meaning ∇f0\grad f_0 belongs to the dual cone of L\mathcal{L} (or −∇f0-\grad f_0 to its opposite, the polar cone), and for a polyhedral cone this is calculated using Farkas’ lemma, an alternative theorem related to Gordan’s proved below:

−∇f0(x⋆)∈{∑i∈Aλi∇fi(x⋆)+∑jνj∇hj(x⋆) : λi≥0}.-\grad f_0(\vb{x}^\star) \in \Big\{ \textstyle\sum_{i \in \mathcal{A}} \lambda_i \grad f_i(\vb{x}^\star) + \sum_j \nu_j \grad h_j(\vb{x}^\star) \ :\ \lambda_i \ge 0 \Big\}.

The geometric reading matters: the downhill gradient −∇f0-\grad f_0 must be a conic combination (nonnegative coefficients) of the outward normals of active walls, plus any combination of equality normals. The motivation’s ball pushes outward with −∇f0-\grad f_0 and the walls support it by pushing inward with −λi∇fi-\lambda_i\grad f_i. Hence λi≥0\lambda_i \ge 0: a wall cannot pull the ball.

The next figure makes this tangible using a problem solved exactly: projecting point c\vb{c} onto a convex region, that is minimizing 12∥x−c∥2\tfrac12\norm{\vb{x} - \vb{c}}^2. Thus −∇f0(x)=c−x-\grad f_0(\vb{x}) = \vb{c} - \vb{x} is the vector from the optimum to the attracting point c\vb{c}.

InteractiveActive constraints and multipliers
  • contours of f0f_0 (circles around c\vb{c})
  • −∇f0=c−x⋆-\nabla f_0 = \vb{c} - \vb{x}^\star
  • λi∇fi\lambda_i\nabla f_i chained to c\vb{c}
  • cone of active gradients
Move
Shift constraints
2.00
1.35
1.45
1.10
f1f_1 (disk)λ = 0.896
f2f_2 (line)λ = 0.703
f3f_3 (line)inactive (−1.36)
f4f_4 (line)inactive (−3.06)
f0(x⋆)f_0(\vb{x}^\star)1.074
∥∇f0+∑iλi∇fi∥\|\nabla f_0 + \sum_i \lambda_i \nabla f_i\|0.000000
∑iλifi(x⋆)\sum_i \lambda_i f_i(\vb{x}^\star)0.000000
Two active constraints: −∇f0-\nabla f_0 lies within the cone generated by their gradients and both multipliers are positive.
How does the problem decide which walls matter and by how much? Drag c\vb{c}, the unconstrained minimum of f0f_0. The optimum x⋆\vb{x}^\star is the projection of c\vb{c} onto the region. Chained arrows decompose c−x⋆=−∇f0\vb{c} - \vb{x}^\star = -\nabla f_0 as combination ∑iλi∇fi\sum_i\lambda_i\nabla f_i of active gradients, and the panel gives each λi\lambda_i. Move c\vb{c} outside through a face: that face's λ\lambda grows from 00 and equals the distance from c\vb{c} to the wall. Move toward a corner: two positive multipliers at once. Put c\vb{c} inside the region and all vanish. The “Degenerate active” button places c\vb{c} exactly on a wall: active, with zero multiplier. Sliders move the walls themselves.

As you interact, observe: on a face, one positive multiplier and x⋆\vb{x}^\star is the orthogonal projection; at a corner, −∇f0-\grad f_0 falls inside the cone generated by both normals and both multipliers are positive; at the exact boundary where c\vb{c} passes from outside to inside a wall, the multiplier continuously vanishes while the wall remains active. This last case is degenerate active, with fi(x⋆)=0f_i(\vb{x}^\star) = 0 and λi=0\lambda_i = 0.

The KKT conditions

Complementary slackness precisely expresses “a wall that does not touch does not push”: λi⋆fi(x⋆)=0\lambda_i^\star f_i(\vb{x}^\star) = 0 means each constraint is either active or has zero multiplier. There are four cases per constraint:

fi(x⋆)f_i(\vb{x}^\star)λi⋆\lambda_i^\starWhat happens
<0< 000Inactive: the wall is far away and has no effect.
=0= 0>0> 0Active and “binding”: the wall supports the point.
=0= 000Degenerate active: touches but does not push; removing it does not change the optimum.
<0< 0>0> 0Impossible by complementary slackness.

When every active constraint has λi>0\lambda_i > 0 we have strict complementarity, the generic case in which active-set identification is stable.

The structure is a combinatorial puzzle. Each constraint is active or inactive: there are 2m2^m possible active sets, and for each the KKT system reduces to a system of equalities (active constraints treated as fi=0f_i = 0, the rest fixed with λi=0\lambda_i = 0) which can be solved. An active set is the solution if the resulting candidate is feasible and all multipliers are ≥0\ge 0. In a convex problem this is also sufficient (below). This is the hand calculation.

Why KKT is necessary (under an assumption)

The proof that multipliers exist at a local optimum has two ingredients: the curve lemma and an alternative theorem proved with a separating hyperplane.

Proof

Both cannot hold: multiplying equality (2) by d\vb{d} gives ∑iθi ai⋅d=0\sum_i \theta_i\,\vb{a}_i\cdot\vb{d} = 0 with every term ≤0\le 0 and at least one <0< 0, a contradiction. Suppose (2) fails, let M=span⁡{bj}M = \spn\{\vb{b}_j\} and let a~i\tilde{\vb{a}}_i be the orthogonal projection of ai\vb{a}_i onto M⊥M^\perp. If 0∈conv⁡{a~i}0 \in \operatorname{conv}\{\tilde{\vb{a}}_i\}, there would be nonzero θi≥0\theta_i \ge 0 with ∑iθia~i=0\sum_i \theta_i \tilde{\vb{a}}_i = \vb{0}, meaning ∑iθiai∈M\sum_i\theta_i\vb{a}_i \in M, which is (2). Thus 0∉conv⁡{a~i}0 \notin \operatorname{conv}\{\tilde{\vb{a}}_i\}, a compact convex set, and by the separating hyperplane theorem there is d\vb{d} with a~i⋅d<0\tilde{\vb{a}}_i\cdot\vb{d} < 0 for every ii. Replacing d\vb{d} with its projection onto M⊥M^\perp (which does not change those products, since the difference lies in MM and a~i∈M⊥\tilde{\vb{a}}_i \in M^\perp) gives bj⋅d=0\vb{b}_j\cdot\vb{d} = 0 and ai⋅d=a~i⋅d<0\vb{a}_i\cdot\vb{d} = \tilde{\vb{a}}_i\cdot\vb{d} < 0: this is (1). ■\blacksquare

∎

The second ingredient is the assumption. In optimization, how constraints are written matters; the simplest qualification making the argument work is Mangasarian-Fromovitz.

Proof

Step 1: no improving direction. I claim there is no d\vb{d} with ∇hj⋅d=0\grad h_j\cdot\vb{d} = 0, ∇fi⋅d<0\grad f_i\cdot\vb{d} < 0 for i∈Ai \in \mathcal{A} and ∇f0⋅d<0\grad f_0\cdot\vb{d} < 0. If there were, the curve lemma gives γ(t)\vb{\gamma}(t) with h(γ(t))=0h(\vb{\gamma}(t)) = \vb{0} and γ′(0)=d\vb{\gamma}'(0) = \vb{d}. By the chain rule, fi(γ(t))=t ∇fi⋅d+o(t)<0f_i(\vb{\gamma}(t)) = t\,\grad f_i\cdot\vb{d} + o(t) < 0 for small t>0t > 0 if i∈Ai \in \mathcal{A}, while for i∉Ai \notin \mathcal{A} we still have fi<0f_i < 0 by continuity; thus γ(t)\vb{\gamma}(t) is feasible. And f0(γ(t))=f0(x⋆)+t ∇f0⋅d+o(t)<f0(x⋆)f_0(\vb{\gamma}(t)) = f_0(\vb{x}^\star) + t\,\grad f_0\cdot\vb{d} + o(t) < f_0(\vb{x}^\star), contradicting the local minimality of x⋆\vb{x}^\star.

Step 2: Gordan. By the lemma, with a0=∇f0\vb{a}_0 = \grad f_0, ai=∇fi\vb{a}_i = \grad f_i (i∈Ai \in \mathcal{A}) and bj=∇hj\vb{b}_j = \grad h_j, there are θ0\theta_0, θi≥0\theta_i \ge 0 not all zero and ν\vb{\nu} with θ0∇f0+∑i∈Aθi∇fi+∑jνj∇hj=0\theta_0\grad f_0 + \sum_{i\in\mathcal{A}} \theta_i\grad f_i + \sum_j \nu_j\grad h_j = \vb{0}.

Step 3: θ0>0\theta_0 > 0. If θ0=0\theta_0 = 0, let d0\vb{d}_0 be the MFCQ direction. Multiplying by d0\vb{d}_0: ∑i∈Aθi ∇fi⋅d0=0\sum_{i\in\mathcal{A}} \theta_i\,\grad f_i\cdot\vb{d}_0 = 0 with every term ≤0\le 0, so θi=0\theta_i = 0 for every i∈Ai \in \mathcal{A}. All θ\theta would vanish, contradicting the lemma. (Independence of ∇hj\grad h_j, the other half of MFCQ, was used in step 1 to construct the curve.)

Divide by θ0\theta_0 and set λi=0\lambda_i = 0 for i∉Ai \notin \mathcal{A} to obtain the four KKT conditions. Under LICQ the combination is unique by independence. ■\blacksquare

∎

Two things can already be said. First: equalities are a special case (without inequalities, step 2 is Lagrange). Second: the proof does not use convexity. KKT is a necessary first-order condition for any C1C^1 problem satisfying a qualification; convexity is only needed for the converse.

Sufficiency in the convex case

No qualification is needed: if multipliers exist, there is a certificate. The proof, a guided exercise at the end, fits in four lines: with λi⋆≥0\lambda_i^\star \ge 0, Lagrangian L(⋅,λ⋆,ν⋆)L(\cdot, \vb{\lambda}^\star, \vb{\nu}^\star) is convex in x\vb{x} and its gradient vanishes at x⋆\vb{x}^\star, so x⋆\vb{x}^\star globally minimizes it. At feasible points the Lagrangian lies below f0f_0 (added terms are ≤0\le 0), and at x⋆\vb{x}^\star equals it (complementary slackness), so f0(x)≥L(x)≥L(x⋆)=f0(x⋆)f_0(\vb{x}) \ge L(\vb{x}) \ge L(\vb{x}^\star) = f_0(\vb{x}^\star).

The same argument proves the motivation’s claim about constraining and regularizing. Let ℓ\ell be convex and differentiable. KKT conditions for minimizing ℓ(w)\ell(\vb{w}) with ∥w∥2≤R2\norm{\vb{w}}^2 \le R^2 are ∇ℓ(w⋆)+2λ⋆w⋆=0\grad\ell(\vb{w}^\star) + 2\lambda^\star\vb{w}^\star = \vb{0}, λ⋆≥0\lambda^\star \ge 0 and λ⋆(∥w⋆∥2−R2)=0\lambda^\star(\norm{\vb{w}^\star}^2 - R^2) = 0, and the first is exactly the optimality condition of the convex regularized problem min⁡ℓ(w)+λ⋆∥w∥2\min \ell(\vb{w}) + \lambda^\star\norm{\vb{w}}^2. Thus the constrained solution solves the regularized problem with coefficient λ⋆\lambda^\star (the multiplier); conversely, if wλ\vb{w}_\lambda minimizes ℓ+λ∥w∥2\ell + \lambda\norm{\vb{w}}^2 with λ≥0\lambda \ge 0, it satisfies KKT for the constrained problem with R=∥wλ∥R = \norm{\vb{w}_\lambda} and multiplier λ\lambda, so solves it. Each radius has its coefficient and vice versa.

When KKT fails: qualifications

The necessity proof used an assumption, MFCQ. This is a constraint qualification: a condition on how the feasible set is described that ensures linearized cone L\mathcal{L} (what gradients see) coincides with the cone of directions actually traversable (the tangent cone T\mathcal{T}, what geometry sees). Without it the theorem is false.

The implications are LICQ⇒MFCQ\text{LICQ} \Rightarrow \text{MFCQ} in any problem and, for convex problems, Slater⇒MFCQ\text{Slater} \Rightarrow \text{MFCQ} at every feasible point (in strict form, fi(x^)<0f_i(\hat{\vb{x}}) < 0 for all ii; the refined form does not imply it: x≤0x \le 0 and −x≤0-x \le 0 satisfy it with x^=0\hat x = 0 and no direction decreases both). The second is a good application of the first-order convexity condition: with d0=x^−x⋆\vb{d}_0 = \hat{\vb{x}} - \vb{x}^\star, for i∈Ai \in \mathcal{A} we have ∇fi(x⋆)⋅d0≤fi(x^)−fi(x⋆)=fi(x^)<0\grad f_i(\vb{x}^\star)\cdot\vb{d}_0 \le f_i(\hat{\vb{x}}) - f_i(\vb{x}^\star) = f_i(\hat{\vb{x}}) < 0, and for affine equalities, Ad0=Ax^−Ax⋆=0\mat{A}\vb{d}_0 = \mat{A}\hat{\vb{x}} - \mat{A}\vb{x}^\star = \vb{0}. Slater’s condition returns in the duality lesson because it guarantees strong duality.

To see what breaks without a qualification, the textbook example is a region with a cusp.

InteractiveWhen KKT fails
  • feasible region
  • level curve of f0=−xf_0 = -x through x⋆\vb{x}^\star
  • f1=y−(1−x)3≤0f_1 = y - (1-x)^3 \le 0
  • f2=−y≤0f_2 = -y \le 0
  • cone of ∇f1,∇f2\nabla f_1, \nabla f_2
  • tangent cone TT (leftward ray)
  • linearized cone LL (band: entire xx axis)
log⁡10λ\log_{10}\lambda versus log⁡10ε\log_{10}\varepsilon: the multipliers grow as ε−2/3\varepsilon^{-2/3} (line of slope −2/3-2/3)
Problem
−1.30
ε\varepsilon0
Optimum x⋆\vb{x}^\star(1.000, 0.000)
∇f1(x⋆)\nabla f_1(\vb{x}^\star)(0.0000, 1)
∇f2(x⋆)\nabla f_2(\vb{x}^\star)(0, −1)
LICQfails
MFCQfails
min⁡λ≥0∥∇f0+∑iλi∇fi∥\min_{\lambda\ge 0}\|\nabla f_0 + \sum_i\lambda_i\nabla f_i\|1.000
λ1=λ2\lambda_1 = \lambda_2does not exist
At the cusp, ∇f1\nabla f_1 and ∇f2\nabla f_2 are antiparallel: their cone is a vertical line and −∇f0=(1,0)-\nabla f_0 = (1, 0) lies outside it. The optimum exists, but KKT does not hold.
What happens to multipliers when two active constraints are parallel? Minimize −x-x subject to y≤(1−x)3y \le (1-x)^3 and y≥−εy \ge -\varepsilon. With ε=0\varepsilon = 0 the region is a cusp with optimum vertex (1,0)(1, 0); there ∇f1\nabla f_1 and ∇f2\nabla f_2 are antiparallel and −∇f0=(1,0)-\nabla f_0 = (1, 0) is outside their generated cone: multipliers do not exist and the minimum residual never falls below 11. With ε>0\varepsilon > 0 normals cease to be parallel and multipliers reappear, but equal 1/(3ε2/3)1/(3\varepsilon^{2/3}): they diverge as ε→0\varepsilon \to 0. Press “Play” to see this, and enable cones TT and LL to compare geometry with gradients.

The problem minimizes −x-x subject to f1=y−(1−x)3≤0f_1 = y - (1-x)^3 \le 0 and f2=−y≤0f_2 = -y \le 0. The region is {0≤y≤(1−x)3}\{0 \le y \le (1-x)^3\}, existing only for x≤1x \le 1 and tapering to (1,0)(1, 0), hence the optimum. There ∇f0=(−1,0)\grad f_0 = (-1, 0), ∇f1=(3(1−x)2,1)=(0,1)\grad f_1 = (3(1-x)^2, 1) = (0, 1) and ∇f2=(0,−1)\grad f_2 = (0, -1). The active normals are antiparallel, generating only the vertical axis, and stationarity asks (−1,0)+λ1(0,1)+λ2(0,−1)=0(-1, 0) + \lambda_1(0, 1) + \lambda_2(0, -1) = \vb{0}: the first component gives −1=0-1 = 0. The optimum does not satisfy KKT, not due to theorem failure: LICQ fails (dependent gradients) and MFCQ fails (no direction decreases both f1f_1 and f2f_2, whose gradients oppose each other).

The figure explains why. The linearized cone is L={d:∇f1⋅d≤0, ∇f2⋅d≤0}={dy=0}\mathcal{L} = \{\vb{d} : \grad f_1\cdot\vb{d} \le 0,\ \grad f_2\cdot\vb{d} \le 0\} = \{d_y = 0\}, the whole xx axis, containing direction (1,0)(1, 0) that decreases f0f_0. But the region’s tangent cone at the vertex is T={(−s,0):s≥0}\mathcal{T} = \{(-s, 0) : s \ge 0\}, only the leftward ray: the cusp cannot be traversed rightward. The optimum is genuine for T\mathcal{T} and false for L\mathcal{L}. KKT looks at L\mathcal{L}.

Perturbing the constraint changes things: with f2=−y−ε≤0f_2 = -y - \varepsilon \le 0 the optimum moves to (1+ε1/3, −ε)(1 + \varepsilon^{1/3},\ -\varepsilon), where ∇f1=(3ε2/3,1)\grad f_1 = (3\varepsilon^{2/3}, 1) is no longer parallel to ∇f2\grad f_2. LICQ holds and multipliers exist, λ1=λ2=1/(3ε2/3)\lambda_1 = \lambda_2 = 1/(3\varepsilon^{2/3}). A useful signal: when a qualification “nearly” fails, multipliers grow huge. In a solver, giant multipliers numerically signal a qualification about to fail (the multiplier is optimal-value sensitivity to constraint change, and here tiny ε\varepsilon moves x⋆x^\star by ε1/3\varepsilon^{1/3}).

Three nuances are not visible in the cusp.

  • Qualification depends on the formula, not the set. Minimizing xx with x2≤0x^2 \le 0 has feasible set {0}\{0\} and is convex (and Slater fails!). At x⋆=0x^\star = 0, ∇f1=0\grad f_1 = 0 and 1+λ⋅0=01 + \lambda\cdot 0 = 0 has no solution: KKT fails. But the same set written as x≤0x \le 0 and −x≤0-x \le 0, or as x=0x = 0, satisfies KKT with ν=−1\nu = -1. Two descriptions, one set, one optimum, and KKT holds for only one. Reformulation can restore the theorem.
  • Qualification is not uniqueness. With x+y≤2x + y \le 2 and x+y≥2x + y \ge 2 (an equality written as two inequalities) in min⁡x2+y2\min x^2 + y^2, optimum (1,1)(1,1) has active gradients (1,1)(1,1) and (−1,−1)(-1,-1), dependent: LICQ fails, but KKT holds (constraints are affine) with infinitely many multipliers: λ1−λ2=−2\lambda_1 - \lambda_2 = -2. Writing an equality as two inequalities spoils LICQ and uniqueness, so retain the equality.
  • Affine constraints need no qualification. If all constraints are affine, KKT is necessary at every local minimum (a linear qualification holds; see Bertsekas, Nonlinear Programming). This is why SVM, simplex projection and QPs do not cause trouble.

Second order: curvature on the tangent space

KKT is a first-order condition. It distinguishes stationary points from others, but not minima from maxima or saddles. Without constraints we inspect the Hessian of ff; with constraints the Hessian that matters is the Lagrangian’s, and only along directions that do not move x\vb{x} away from the walls.

The Hessian of f0f_0 alone is insufficient because curved constraints add curvature. For a curve γ(t)\vb{\gamma}(t) on {h=0}\{h = 0\} with γ(0)=x⋆\vb{\gamma}(0) = \vb{x}^\star and γ′(0)=d\vb{\gamma}'(0) = \vb{d}, differentiate φ(t)=f0(γ(t))\varphi(t) = f_0(\vb{\gamma}(t)) twice:

φ′′(0)=d⊤∇2f0 d+∇f0⋅γ′′(0).\varphi''(0) = \vb{d}\T\hess f_0\,\vb{d} + \grad f_0\cdot\vb{\gamma}''(0).

And differentiating hj(γ(t))=0h_j(\vb{\gamma}(t)) = 0 twice: d⊤∇2hj d+∇hj⋅γ′′(0)=0\vb{d}\T\hess h_j\,\vb{d} + \grad h_j\cdot\vb{\gamma}''(0) = 0. If Lagrange’s condition holds, ∇f0=−∑jνj∇hj\grad f_0 = -\sum_j\nu_j\grad h_j and the acceleration term is replaced: ∇f0⋅γ′′=−∑jνj∇hj⋅γ′′=∑jνj d⊤∇2hjd\grad f_0\cdot\vb{\gamma}'' = -\sum_j\nu_j\grad h_j\cdot\vb{\gamma}'' = \sum_j \nu_j\,\vb{d}\T\hess h_j\vb{d}. Result:

φ′′(0)=d⊤(∇2f0(x⋆)+∑jνj∇2hj(x⋆))d=d⊤ ∇xx2L(x⋆,ν⋆) d.\varphi''(0) = \vb{d}\T\Big(\hess f_0(\vb{x}^\star) + \sum_j \nu_j\hess h_j(\vb{x}^\star)\Big)\vb{d} = \vb{d}\T\,\hess_{\vb{xx}}L(\vb{x}^\star, \vb{\nu}^\star)\,\vb{d}.

The second derivative of f0f_0 along the constraint is the Lagrangian Hessian’s quadratic form. The tangency figure shows two readings agreeing at each stationary point: the second derivative of f0f_0 along the curve (parameterized by arc length) and t⊤∇xx2L t\vb{t}\T\hess_{\vb{xx}}L\,\vb{t}.

With inequalities we must decide which directions to check. They are those that cannot decrease f0f_0 to first order.

The necessary condition is proved as in the unconstrained case, using the curve identity above (Nocedal and Wright, theorem 12.5). Sufficiency is shorter than it looks.

Proof

For contradiction, let feasible xk→x⋆\vb{x}_k \to \vb{x}^\star, xk≠x⋆\vb{x}_k \neq \vb{x}^\star and f0(xk)≤f0(x⋆)f_0(\vb{x}_k) \le f_0(\vb{x}^\star). Write xk=x⋆+tkdk\vb{x}_k = \vb{x}^\star + t_k\vb{d}_k with tk=∥xk−x⋆∥→0t_k = \norm{\vb{x}_k - \vb{x}^\star} \to 0 and ∥dk∥=1\norm{\vb{d}_k} = 1; passing to a subsequence, dk→d\vb{d}_k \to \vb{d} with ∥d∥=1\norm{\vb{d}} = 1.

The limiting direction is critical. Feasibility gives ∇hj⋅d=0\grad h_j\cdot\vb{d} = 0 and ∇fi⋅d≤0\grad f_i\cdot\vb{d} \le 0 (i∈Ai \in \mathcal{A}), and f0(xk)≤f0(x⋆)f_0(\vb{x}_k) \le f_0(\vb{x}^\star) gives ∇f0⋅d≤0\grad f_0\cdot\vb{d} \le 0. But by stationarity, ∇f0⋅d=−∑i∈Aλi∇fi⋅d≥0\grad f_0\cdot\vb{d} = -\sum_{i\in\mathcal{A}}\lambda_i\grad f_i\cdot\vb{d} \ge 0. Thus ∇f0⋅d=0\grad f_0\cdot\vb{d} = 0 and every term λi ∇fi⋅d\lambda_i\,\grad f_i\cdot\vb{d} vanishes: ∇fi⋅d=0\grad f_i\cdot\vb{d} = 0 when λi>0\lambda_i > 0. That is, d∈C∖{0}\vb{d} \in \mathcal{C}\setminus\{\vb{0}\}.

But its curvature is nonpositive. At a feasible point, L(xk)=f0(xk)+∑λifi(xk)≤f0(xk)≤f0(x⋆)=L(x⋆)L(\vb{x}_k) = f_0(\vb{x}_k) + \sum\lambda_i f_i(\vb{x}_k) \le f_0(\vb{x}_k) \le f_0(\vb{x}^\star) = L(\vb{x}^\star) (by complementary slackness at x⋆\vb{x}^\star). Second-order Taylor with ∇xL(x⋆)=0\grad_{\vb{x}}L(\vb{x}^\star) = \vb{0}: 0≥L(xk)−L(x⋆)=12tk2 dk⊤∇xx2L dk+o(tk2)0 \ge L(\vb{x}_k) - L(\vb{x}^\star) = \tfrac12 t_k^2\,\vb{d}_k\T\hess_{\vb{xx}}L\,\vb{d}_k + o(t_k^2). Dividing by tk2t_k^2 and taking the limit, d⊤∇xx2L d≤0\vb{d}\T\hess_{\vb{xx}}L\,\vb{d} \le 0, contradicting the assumption. ■\blacksquare

∎

The budget example is opposite. There ∇2f0=[0−1−10]\hess f_0 = \begin{bmatrix}0&-1\\-1&0\end{bmatrix} is indefinite (eigenvalues ±1\pm 1), yet (5,2.5)(5, 2.5) is the minimum: the constraint is a line, so the only direction space is tangent t=(2,−1)/5\vb{t} = (2, -1)/\sqrt5 and t⊤∇2f0 t=4/5>0\vb{t}\T\hess f_0\,\vb{t} = 4/5 > 0. This is the common mistake of applying the Hessian criterion on all of Rn\R^n (see mistakes section).

In the Rayleigh example, the matrix is ∇xx2L=2(A−μI)\hess_{\vb{xx}}L = 2(\mat{A} - \mu\mat{I}) and the tangent space at eigenvector v\vb{v} is v⊥\vb{v}^\perp: the quadratic form is positive definite there if and only if μ\mu is the smallest eigenvalue and simple; in general its index (number of negative directions) equals the number of eigenvalues smaller than μ\mu. With distinct eigenvalues: the smallest is a strict minimum, the largest a strict maximum (index n−1n - 1, the whole tangent space), and the others saddles. This is checked numerically below.

Implementation from scratch

Three pieces, from simplest to actually used: the KKT system for an equality-constrained QP, an active-set method for a QP with inequalities, and projections derived using KKT.

The block KKT system

To minimize 12x⊤Px+q⊤x\tfrac12\vb{x}\T\mat{P}\vb{x} + \vb{q}\T\vb{x} subject to Ax=b\mat{A}\vb{x} = \vb{b}, the Lagrangian is L=12x⊤Px+q⊤x+ν⊤(Ax−b)L = \tfrac12\vb{x}\T\mat{P}\vb{x} + \vb{q}\T\vb{x} + \vb{\nu}\T(\mat{A}\vb{x} - \vb{b}) and KKT is linear:

[PA⊤A0][xν]=[−qb].\begin{bmatrix} \mat{P} & \mat{A}\T \\ \mat{A} & \mat{0} \end{bmatrix}\begin{bmatrix} \vb{x} \\ \vb{\nu} \end{bmatrix} = \begin{bmatrix} -\vb{q} \\ \vb{b} \end{bmatrix}.

The matrix is symmetric but indefinite; with P≻0\mat{P} \succ 0 and full-row-rank A\mat{A} it is invertible, with nn positive and pp negative eigenvalues.

[ ]Equality QP: the KKT systemBrowser
import numpy as np
from scipy.optimize import minimize

def solve_eq_qp(P, q, A, b):
    """min ½xᵀPx + qᵀx  s.t.  Ax = b  (resuelve el sistema KKT por bloques)."""
    P, q = np.asarray(P, float), np.asarray(q, float)
    A, b = np.atleast_2d(np.asarray(A, float)), np.atleast_1d(np.asarray(b, float))
    n, m = len(q), A.shape[0]
    K = np.block([[P, A.T], [A, np.zeros((m, m))]])
    sol = np.linalg.solve(K, np.concatenate([-q, b]))
    x, nu = sol[:n], sol[n:]
    return x, nu, (np.linalg.norm(P @ x + q + A.T @ nu), np.linalg.norm(A @ x - b))

# Un ejemplo que se comprueba a mano: min x² + y² s.t. x + 2y = 5   (P = 2I)
x, nu, res = solve_eq_qp(2 * np.eye(2), np.zeros(2), [[1, 2]], [5])
print("x* =", x, "  nu =", nu, "  residuos = (%.1e, %.1e)" % res)

# Un QP con n = 3 y p = 2
P = np.array([[4., 1., 0.], [1., 3., 1.], [0., 1., 2.]]); q = np.array([1., -2., 0.5])
A = np.array([[1., 1., 1.], [1., -1., 0.]]); b = np.array([1., 0.])
x, nu, res = solve_eq_qp(P, q, A, b)
K = np.block([[P, A.T], [A, np.zeros((2, 2))]])
w = np.linalg.eigvalsh(K)
print("x* =", x.round(5), "  nu =", nu.round(5))
print("autovalores de K: %d positivos y %d negativos" % ((w > 0).sum(), (w < 0).sum()))

r = minimize(lambda z: 0.5 * z @ P @ z + q @ z, np.zeros(3), jac=lambda z: P @ z + q,
             constraints=[{"type": "eq", "fun": lambda z: A @ z - b, "jac": lambda z: A}],
             method="SLSQP", options={"ftol": 1e-12})
print("SLSQP:", r.x.round(5), "  diferencia máxima", np.abs(r.x - x).max())

The first result is x⋆=(1,2)\vb{x}^\star = (1, 2) with ν=−2\nu = -2, checked by hand: ∇f0=(2,4)=−ν(1,2)\grad f_0 = (2, 4) = -\nu(1, 2). Residuals are on the order of machine precision and SLSQP, a general numerical method, reaches the same point. Matrix inertia (3,2)(3, 2) is that of a saddle: nn positive and pp negative.

An active-set method

For convex QPs with inequalities Gx≤h\mat{G}\vb{x} \le \vb{h} and P≻0\mat{P} \succ 0, the primal active-set method (Nocedal and Wright, algorithm 16.3) intelligently enumerates active sets without visiting all 2m2^m. It maintains a working set WW of constraints treated as equalities and repeats:

  1. Solve the equality QP “minimize the model on GWp=0\mat{G}_W\vb{p} = \vb{0}” with the block KKT system: it gives a step p\vb{p} and multipliers μ\vb{\mu}.
  2. If p≠0\vb{p} \neq \vb{0}, move with the largest step α≤1\alpha \le 1 violating no constraint outside WW; if one blocks, add it to WW.
  3. If p=0\vb{p} = \vb{0}, we are at the face optimum. If all μi≥0\mu_i \ge 0, KKT holds and we are done. Otherwise remove the constraint with most negative μi\mu_i: a wall that “pulls” is not needed.

Multiplier signs guide the algorithm. A feasible starting point is needed (here 0\vb{0}, with h>0\vb{h} > \vb{0}) and the implementation does not handle degeneracy (cycles with redundant constraints), which production code does.

[ ]Primal active-set method for a convex QPBrowser
import numpy as np
from scipy.optimize import minimize

def active_set_qp(P, q, G, h, x0, verbose=False):
    """min ½xᵀPx + qᵀx  s.t.  Gx ≤ h,  con P ≻ 0 y x0 factible."""
    x = np.array(x0, float); n = len(x)
    W = [i for i in range(len(h)) if abs(G[i] @ x - h[i]) < 1e-10]
    for it in range(100):
        g = P @ x + q
        AW = G[W]; k = len(W)
        K = np.block([[P, AW.T], [AW, np.zeros((k, k))]])
        sol = np.linalg.solve(K, np.concatenate([-g, np.zeros(k)]))
        p, mu = sol[:n], sol[n:]
        if verbose:
            print(f"it {it}: W = {sorted(W)}  |p| = {np.linalg.norm(p):.1e}  f = {0.5 * x @ P @ x + q @ x:.4f}")
        if np.linalg.norm(p) < 1e-10:
            if k == 0 or mu.min() >= -1e-10:
                lam = np.zeros(len(h)); lam[W] = mu
                return x, lam
            W.pop(int(np.argmin(mu)))              # sale la pared con multiplicador negativo
        else:
            alpha, block = 1.0, None
            for i in range(len(h)):
                if i not in W and G[i] @ p > 1e-12:
                    a = (h[i] - G[i] @ x) / (G[i] @ p)
                    if a < alpha: alpha, block = a, i
            x = x + alpha * p
            if block is not None: W.append(block)  # entra la pared que bloquea
    raise RuntimeError("no converge")

rng = np.random.default_rng(26)
n, m = 5, 9
M = rng.normal(size=(n, n)); P = M @ M.T + 0.5 * np.eye(n); q = 3 * rng.normal(size=n)
G = rng.normal(size=(m, n)); h = rng.uniform(0.5, 1.5, size=m)

x, lam = active_set_qp(P, q, G, h, np.zeros(n), verbose=True)
r = minimize(lambda z: 0.5 * z @ P @ z + q @ z, np.zeros(n), jac=lambda z: P @ z + q,
             constraints=[{"type": "ineq", "fun": lambda z: h - G @ z, "jac": lambda z: -G}],
             method="SLSQP", options={"ftol": 1e-13})
print("conjunto activo:", np.round(x, 5))
print("SLSQP:          ", np.round(r.x, 5), "  diferencia", f"{np.abs(x - r.x).max():.1e}")
print("multiplicadores:", np.round(lam, 4))
print("KKT: |estacionariedad| = %.1e,  máx f_i = %.1e,  mín λ = %.1e,  |λ·f| = %.1e" % (
    np.linalg.norm(P @ x + q + G.T @ lam), (G @ x - h).max(), lam.min(), abs(lam @ (G @ x - h))))

The trace shows the algorithm working: the working set grows when a wall blocks, and an iteration removes a constraint whose multiplier is negative. Finally, all four KKT conditions are checked on the result, certifying it: a solution without multipliers cannot be audited.

Projections derived using KKT

The simplex derivation gave xi=max⁡(vi−ν,0)x_i = \max(v_i - \nu, 0) and a monotone scalar equation for ν\nu. Solve it by bisection. For the ℓ1\ell_1 ball the same reasoning (inequality ∥x∥1≤r\norm{\vb{x}}_1 \le r with multiplier θ≥0\theta \ge 0; since the norm is nondifferentiable, stationarity uses subgradients, or reduces to the simplex with ∣v∣\abs{\vb{v}} and each coordinate’s sign) gives, when ∥v∥1>r\norm{\vb{v}}_1 > r, xi=sign⁡(vi)max⁡(∣vi∣−θ,0)x_i = \operatorname{sign}(v_i)\max(\abs{v_i} - \theta, 0): soft thresholding. Compare with the projection library of the convex sets lesson, which uses a different algorithm (sorting).

[ ]KKT projections versus library projectionsBrowser
import numpy as np

def theta_biseccion(v, r, tol=1e-13):
    """Raíz de s(theta) = sum max(v - theta, 0) - r: decreciente y lineal a trozos."""
    lo, hi = v.min() - r / len(v), v.max()
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if np.maximum(v - mid, 0).sum() > r: lo = mid
        else: hi = mid
        if hi - lo < tol: break
    return 0.5 * (lo + hi)

def proj_simplex_kkt(v, z=1.0):
    th = theta_biseccion(v, z)
    return np.maximum(v - th, 0.0), th

def proj_l1_kkt(v, r=1.0):
    if np.abs(v).sum() <= r: return v.copy(), 0.0
    th = theta_biseccion(np.abs(v), r)
    return np.sign(v) * np.maximum(np.abs(v) - th, 0.0), th

# Biblioteca de la lección 2 (ordenación, O(n log n))
def project_simplex(v, z=1.0):
    u = np.sort(v)[::-1]; css = np.cumsum(u) - z; j = np.arange(1, len(v) + 1)
    rho = np.nonzero(u - css / j > 0)[0][-1]
    return np.maximum(v - css[rho] / (rho + 1), 0.0)

def project_l1_ball(v, r=1.0):
    if np.abs(v).sum() <= r: return v.copy()
    return np.sign(v) * project_simplex(np.abs(v), r)

v = np.array([0.9, 0.4, -0.3, 1.6])
x, nu = proj_simplex_kkt(v)
mu = x - v + nu                                    # estacionariedad: mu_i = x_i - v_i + nu
print("x* =", x.round(4), " nu =", round(nu, 4), " suma =", round(x.sum(), 6))
print("mu =", mu.round(4), " (>= 0)   máx |mu_i x_i| =", np.abs(mu * x).max())

rng = np.random.default_rng(3)
peor = 0.0
for _ in range(500):
    v = rng.normal(scale=2, size=8)
    peor = max(peor, np.abs(proj_simplex_kkt(v)[0] - project_simplex(v)).max())
    peor = max(peor, np.abs(proj_l1_kkt(v, 1.5)[0] - project_l1_ball(v, 1.5)).max())
print("máxima diferencia con la biblioteca en 1000 proyecciones: %.1e" % peor)

The projection of (0.9,0.4,−0.3,1.6)(0.9, 0.4, -0.3, 1.6) is (0.15,0,0,0.85)(0.15, 0, 0, 0.85) with ν=0.75\nu = 0.75: two coordinates become zero, and their multipliers μ=(0.35,1.05)\mu = (0.35, 1.05) are positive, as KKT requires. The implementations, derived differently, agree up to rounding.

Checking second order using the nullspace

For the Rayleigh example, the tangent space at v\vb{v} is the nullspace of v⊤\vb{v}\T and its matrix Z\mat{Z} (orthonormal basis) lets us work with the reduced Hessian Z⊤∇xx2L Z\mat{Z}\T\hess_{\vb{xx}}L\,\mat{Z}.

[ ]Reduced Hessian index on the sphereBrowser
import numpy as np
from scipy.linalg import null_space

rng = np.random.default_rng(5)
M = rng.normal(size=(5, 5)); A = (M + M.T) / 2
mu, V = np.linalg.eigh(A)
print(" k    autovalor   nu = -mu   índice de Zᵀ(∇²L)Z   tipo")
for k in range(5):
    v = V[:, k]
    HL = 2 * (A - mu[k] * np.eye(5))               # ∇²L = ∇²f + nu ∇²h con nu = -mu
    Z = null_space(v[None, :])                     # base del espacio tangente v^⊥
    e = np.linalg.eigvalsh(Z.T @ HL @ Z)
    tipo = "mínimo" if (e > 1e-9).all() else "máximo" if (e < -1e-9).all() else "silla"
    print(f"{k:2d}   {mu[k]:9.4f}   {-mu[k]:8.4f}   {(e < -1e-9).sum():12d}             {tipo}")

Only the smallest eigenvalue has a positive definite reduced Hessian and only the largest a negative definite one (index 4=n−14 = n - 1, a maximum). Intermediate ones are saddles of index kk, the number of smaller eigenvalues. In R5\R^5 the full Hessian 2(A−μkI)2(\mat{A} - \mu_k\mat{I}) also has eigenvalue 00 in the normal direction v\vb{v}, which is not admissible: again, without the tangent space they cannot be distinguished.

The library version

In practice we do not program an active set. For QPs use a solver with a certificate (OSQP, Clarabel, HiGHS for LP), and for a general low-dimensional NLP, SLSQP or trust-constr. With cvxpy multipliers come for free: they are constraint duals, and under this module’s convention (inequalities ≤\le) they are ≥0\ge 0.

import cvxpy as cp

x = cp.Variable(5)
restr = [G @ x <= h]
prob = cp.Problem(cp.Minimize(0.5 * cp.quad_form(x, P) + q @ x), restr)
prob.solve()
lam = restr[0].dual_value        # vector de multiplicadores, no negativos

With scipy.optimize.minimize, trust-constr returns multipliers in res.v and recent SciPy versions (including the lab’s 1.18) also return them for SLSQP in res.multipliers, under SciPy’s convention L=f0−∑kμkckL = f_0 - \sum_k \mu_k c_k for constraints ck(x)=0c_k(\vb{x}) = 0 or ck(x)≥0c_k(\vb{x}) \ge 0: inequality multipliers match this lesson’s λi≥0\lambda_i \ge 0 and equality multipliers are −νj-\nu_j. If your version does not return them, recover them by least-squares stationarity on active constraints: λA=arg⁡min⁡∥GA⊤λ+∇f0∥\vb{\lambda}_{\mathcal{A}} = \arg\min\norm{\mat{G}_{\mathcal{A}}\T\vb{\lambda} + \grad f_0}. Under LICQ the residual is zero and the solution unique.

Common mistakes

Exercises

NumericThe budget multiplier
Maximize xyxy subject to x+2y=10x + 2y = 10 with x,y>0x, y > 0, written as minimizing f0=−xyf_0 = -xy with Lagrangian L=−xy+λ(x+2y−10)L = -xy + \lambda(x + 2y - 10). What is multiplier λ\lambda at the optimum?
NumericMultipliers at a corner
Minimize f0=(x−3)2+(y−2.5)2f_0 = (x - 3)^2 + (y - 2.5)^2 subject to f1=x+y−2≤0f_1 = x + y - 2 \le 0 and f2=x−1≤0f_2 = x - 1 \le 0. The optimum is at corner (1,1)(1, 1). What is multiplier λ2\lambda_2 of f2f_2?
QuizSign convention
Minimize ff subject to g(x)≥0g(\vb{x}) \ge 0. What are the stationarity and multiplier-sign conditions at a qualified optimum?
QuizDoes LICQ hold?
For which problems does LICQ hold at the optimum?

More than one answer may be correct.

QuizActive with zero multiplier
At a convex problem's KKT optimum, fi(x⋆)=0f_i(\vb{x}^\star) = 0 and λi⋆=0\lambda_i^\star = 0. What follows?
ProofKKT is sufficient in convex problems
Prove: If the problem is convex (f0f_0, fif_i convex and differentiable, hjh_j affine) and (x⋆,λ⋆,ν⋆)(\vb{x}^\star, \vb{\lambda}^\star, \vb{\nu}^\star) satisfies KKT conditions, then x⋆\vb{x}^\star is a global minimum.
0
Fix multipliers λ⋆,ν⋆\vb{\lambda}^\star, \vb{\nu}^\star and study Lagrangian L(x)=f0(x)+∑iλi⋆fi(x)+∑jνj⋆hj(x)L(\vb{x}) = f_0(\vb{x}) + \sum_i\lambda_i^\star f_i(\vb{x}) + \sum_j\nu_j^\star h_j(\vb{x}) as a function of x\vb{x} alone.

Step 1 of 4. What property does LL have as a function of x\vb{x}?

ProofWater filling with KKT
Prove: Let αi>0\alpha_i > 0. The solution of maximizing ∑ilog⁡(αi+xi)\sum_i \log(\alpha_i + x_i) subject to x≥0\vb{x} \ge \vb{0} and 1⊤x=1\vb{1}\T\vb{x} = 1 is xi⋆=max⁡(0, w−αi)x_i^\star = \max(0,\ w - \alpha_i), where the “water level” ww is chosen so 1⊤x⋆=1\vb{1}\T\vb{x}^\star = 1.
0
Write it as minimizing f0=−∑ilog⁡(αi+xi)f_0 = -\sum_i\log(\alpha_i + x_i) with fi=−xi≤0f_i = -x_i \le 0 (multiplier μi\mu_i) and h=1⊤x−1=0h = \vb{1}\T\vb{x} - 1 = 0 (multiplier ν\nu).

Step 1 of 4. Why are KKT conditions necessary and sufficient?

CodeEquality QP via the KKT system
Implement solve_eq_qp(P, q, A, b) to solve minimization of 12x⊤Px+q⊤x\tfrac12\vb{x}\T\mat{P}\vb{x} + \vb{q}\T\vb{x} subject to Ax=b\mat{A}\vb{x} = \vb{b} by constructing and solving the block KKT system. Return the tuple (x, nu, res), with x the solution, nu the Lagrangian multipliers L=12x⊤Px+q⊤x+ν⊤(Ax−b)L = \tfrac12\vb{x}\T\mat{P}\vb{x} + \vb{q}\T\vb{x} + \vb{\nu}\T(\mat{A}\vb{x} - \vb{b}) and res a tuple of stationarity residual ∥Px+q+A⊤ν∥\norm{\mat{P}\vb{x} + \vb{q} + \mat{A}\T\vb{\nu}} and feasibility residual ∥Ax−b∥\norm{\mat{A}\vb{x} - \vb{b}}. If A has zero rows (no constraints), nu must be an empty vector.
import numpy as np

def solve_eq_qp(P, q, A, b):
  """Devuelve (x, nu, (res_estacionariedad, res_factibilidad))."""
  P = np.asarray(P, dtype=float)
  q = np.asarray(q, dtype=float)
  # tu código: monta K = [[P, Aᵀ], [A, 0]], resuelve K [x; nu] = [-q; b] y calcula los residuos
  return np.zeros(len(q)), np.zeros(0), (1.0, 1.0)
Shift+Enter to run

Summary

Key idea
At a constrained optimum the gradient does not vanish: active walls balance it, and multipliers are reaction forces. KKT conditions (stationarity, primal and dual feasibility, complementary slackness) are necessary under a constraint qualification and sufficient if the problem is convex; at second order, the relevant curvature is the Lagrangian’s on the critical cone.
  • Equalities. At a minimum with independent ∇hj\grad h_j, ∇f0=−∑jνj∇hj\grad f_0 = -\sum_j\nu_j\grad h_j: level curves of f0f_0 are tangent to the constraint. The proof uses the implicit function theorem to construct curves on {h=0}\{h = 0\}.
  • Inequalities. −∇f0-\grad f_0 must be a conic combination of active normals; λi≥0\lambda_i \ge 0 because a wall only pushes. Complementary slackness λifi=0\lambda_i f_i = 0 says “a distant wall does not push”.
  • Solving by hand means enumerating active sets: solve the equality system and accept the feasible candidate with λ≥0\vb{\lambda} \ge \vb{0}. There are 2m2^m possibilities; the active-set method follows promising ones using multiplier signs.
  • Qualifications. LICQ ⇒\Rightarrow MFCQ, and Slater ⇒\Rightarrow MFCQ in convex problems. Without qualification, KKT can fail even at an optimum (the cusp, x2≤0x^2 \le 0), and multipliers grow enormous as a qualification is about to fail.
  • Convexity. With convex f0,fif_0, f_i and affine hjh_j, KKT implies global optimality without extra assumptions: the Lagrangian is convex, below f0f_0 on feasible points and equal to it at x⋆\vb{x}^\star.
  • Second order. Inspect d⊤∇xx2L d\vb{d}\T\hess_{\vb{xx}}L\,\vb{d} for d\vb{d} in the critical cone, never ∇2f0\hess f_0 over all Rn\R^n: constraint curvature can make a point with ∇2f0=0\hess f_0 = \mat{0} a minimum.
  • Where it returns. Complementary slackness explains SVM support vectors; duality (next lesson) turns multipliers into variables of a new problem; simplex projection is sparsemax, the sparse alternative to softmax in attention layers, and a building block of projected-gradient methods.