13 / 16 · Optimization
Lagrange multipliers and KKT conditions
Minimizing under constraints: why the gradient at a constrained minimum is balanced by the constraint normals, what the multipliers measure, the KKT conditions for inequalities, and projections, maximum entropy and PCA worked out with them.
Unconstrained optimization · Symmetric matrices and quadratic forms
On this page 8
Minimize over the points of the line . Here the constraint can be solved for one variable. Substituting leaves a function of alone:
So , and .
Elimination rarely goes this smoothly. On the unit circle it gives two branches with infinite slopes at their ends. With the inequalities of a probability vector it turns into a case split over which coordinates are zero, cases in dimensions. The SVM has one inequality per training point. These problems need a method that keeps all the variables and treats every constraint the same way.
It starts from an observation about the minimum itself. Over all of , as in the previous note, a minimum has a zero gradient. Under a constraint it need not: the function may keep decreasing, but only in directions the constraint forbids.
Equality constraints: the gradient is parallel to the normal#
A constrained minimum: the level set touches the constraint
At a constrained minimum, no direction that stays on the constraint surface can decrease to first order. So the gradient of is perpendicular to the surface, and so is the gradient of the constraint. Two vectors perpendicular to the same surface of dimension are parallel. For one constraint with , a local minimum therefore satisfies
for some number , together with .
The proof takes three steps. Write .
Step 1: the gradient is orthogonal to every tangent direction. Take any smooth curve on the surface with and velocity . The chain rule at gives two facts:
The first holds because is constant, so its derivative is zero. The second holds because, for small , is a minimum of the one-variable function , so its derivative vanishes there.
Step 2: every with is a tangent direction. Correct the straight line along the normal: look for a curve . The function has and . The implicit function theorem (Lebl, 2026, Theorem 8.5.6) gives a differentiable with and near , with derivative
So the curve stays on the surface, and its velocity is .
Step 3: orthogonal to all tangents means parallel to . Split with , so that . By step 2, is a tangent direction, and by step 1
So and , which is the boxed condition with .
With several constraints , stack the gradients as the rows of a matrix . The tangent directions are those with . Step 2 corrects along with , and needs the matrix to be invertible. It is, when the rows of are linearly independent: gives , so and . Step 3 splits into plus a with , and gives
Linear independence of the is a constraint qualification. Without it the multipliers may not exist; the section on failures below has an example.
For the opening problem, and . At , , parallel to , with . At the feasible point , instead, is not parallel to . Its component along the line, in the unit direction , is , so moving along the line towards larger lowers . In the figure, the level set of through touches the line; through it crosses it.
The Lagrangian#
The conditions are the stationarity conditions of one function. The Lagrangian adds each constraint to the objective with its multiplier (Deisenroth, Faisal and Ong, 2020, Section 7.2):
Its gradient in is , and its gradient in is the vector of constraint values . Setting both to zero gives the conditions above: a constrained problem in variables becomes equations in unknowns, with no constraints left. For the opening problem they are , and , a linear system with the solution .
The point is only a stationary point of . At any off the constraint, the Lagrangian is linear in with the nonzero slope , so it is unbounded below and has no minimum. Like a zero gradient, the conditions give candidates. The section on failures below shows how to sort them, and the duality note when they give the answer.
The nearest point on a plane#
The shortest path from a point to a plane runs along the plane’s normal. For the plane and a point , minimize with the Lagrangian . Stationarity in , then the constraint, give
Putting back gives the nearest point and its distance:
The objective is convex and the constraint affine, so by the sufficiency result below this stationary point is the global minimum. The distance formula is the one the SVM note uses for the margin of a hyperplane.
For , and : , and . The nearest point is , which satisfies , at distance .
Maximum entropy#
Among all distributions with a given mean, which one spreads its probability most evenly? Take values and maximize the entropy subject to and . Equivalently, minimize with a multiplier for the normalization and for the mean. The derivative of the Lagrangian in is , and setting it to zero gives
where the normalization fixes , and is chosen so that the mean is . Such a exists when lies strictly between the smallest and the largest . The mean of this is continuous in ; it tends to the largest as and to the smallest as , so by the intermediate value theorem it passes through . A constraint on any expected value gives, by the same steps, an exponential of the constrained quantity (Jaynes, 1957).
Every is positive, so the omitted constraints are inactive. The objective is convex: its Hessian is diagonal with entries . The constraints are affine, so by the sufficiency result below the stationary point is the global minimum of , the maximum of the entropy. Without the mean constraint, and the answer is the uniform distribution.
A die with faces constrained to the mean gives:
| Quantity | Value |
|---|---|
| entropy | nats |
| entropy of the fair die, | nats |
The probabilities grow geometrically, by the factor per face, the least committal way to raise the mean.
The formula is the softmax of the scores . The softmax is the maximum-entropy distribution with prescribed expected scores, and the exponential families of statistics arise the same way. Replace the entropy by minus a KL divergence to a reference distribution, and move the reward from a constraint into the objective, and the same steps give the optimum of KL-regularized reinforcement learning: the reference reweighted by an exponential of the reward. Entropy itself is the subject of the entropy note.
What the multiplier measures#
The multiplier is the price of the constraint. Move the constraint to and let the solution depend smoothly on . The optimal value then changes at the rate
The first line is the chain rule, the second the stationarity , and the third the chain rule backwards: has derivative 1.
For the plane, , whose derivative at is ; here , so moving is moving . For the opening problem, on the line , with derivative at . In economics the multiplier is called a shadow price (Boyd and Vandenberghe, 2004, §5.4.4; §5.6.3 derives the same rate under strong duality, assuming only that the optimal value is differentiable in ). In the SVM it measures how much the optimal objective would fall if the margin required of one training point were relaxed a little.
Inequality constraints: active or inactive#
An inequality constraint: active or inactive
An inequality constraint is active at if and inactive if . At a local minimum there are two cases.
If the constraint is inactive, every small move keeps the point feasible, so is an unconstrained local minimum and . The constraint plays no role; give it the multiplier .
If it is active, is also a local minimum of on the smaller set , which contains it. The equality case then gives for some , provided . Now the sign matters: . Suppose , so that , and step from along the descent direction . First-order Taylor expansions in give
for small . The step stays feasible and lowers , which contradicts the minimum. With the descent direction points outward, against the wall.
In one variable: minimize subject to , that is . The unconstrained minimum is infeasible, so the constraint is active, , and gives . With the looser constraint , the unconstrained minimum is feasible, the constraint is inactive and . The multiplier is again a price: moving the wall from 1 to lowers the optimal value at the rate .
Both panels of the figure minimize over the triangle , , , written as , and , all . For inside the triangle the answer is itself, no constraint is active and every multiplier is zero. For outside it the answer is on the slanted side, with and , so ; and are inactive and .
The KKT conditions#
The general problem has inequalities and equalities, all with differentiable functions:
A point that satisfies all constraints is feasible. Each inequality gets a multiplier and each equality a multiplier . Combining the Lagrange condition for the equalities with the two cases for each inequality, a point with multipliers satisfies the Karush–Kuhn–Tucker conditions if
The four lines are called stationarity, primal feasibility, dual feasibility and complementary slackness.
Complementary slackness encodes the case split. The product of a non-negative and a non-positive number is zero only if one factor is zero. Either the constraint is active () and its multiplier may be positive, or it is inactive and its multiplier is zero. A positive multiplier certifies that the constraint is tight; a slack constraint has no price. In the SVM, the training points with positive multipliers are exactly the support vectors, which lie on or inside the margin. Both factors can vanish at once, for a constraint that touches the solution without pushing on it.
At a local minimum the KKT conditions hold if a constraint qualification holds there. The one derived below is LICQ: the gradients of the active inequalities and of the equalities are linearly independent at . Two others are stated with references. For a convex problem, Slater’s condition, a point that satisfies every inequality strictly, makes the KKT conditions necessary and sufficient (Boyd and Vandenberghe, 2004, §5.5.3); the duality note proves the key step. Affine constraints need no qualification at all (Merkulov, 2024, lecture 6).
Derivation: the KKT conditions under LICQ
Let be the set of active inequalities at . Stack the gradients for and as the rows of a matrix ; LICQ says these rows are independent. An inactive constraint has and, by continuity, stays negative near , so it plays no role: give it . This makes complementary slackness hold.
Stationarity. The point is a local minimum of on the smaller set where every active constraint holds with equality. That set is defined by equalities with independent gradients, so the equality case gives multipliers with .
Signs. Fix and let be the vector with in the row of and zeros elsewhere. Independent rows make invertible, so solves . Stack the active constraint functions into and apply step 2 of the equality case to . It gives a curve with along which , the other active constraints stay at zero, and the inactive ones stay negative. For small the curve is feasible, so and the derivative at is non-negative:
because and every other row of is zero.
For a convex problem, with and every convex and every affine, the conditions are also sufficient: any point that satisfies them is a global minimum. For every feasible ,
The first line holds because each and each . The third holds because , a non-negative combination of convex functions plus affine terms, is convex and stationary at , so it lies above its tangent there (convexity note). The last uses complementary slackness and (Boyd and Vandenberghe, 2004, §5.5.3). In the figure, the multipliers and the point satisfy all four conditions, so the point is the global minimum.
Projection onto a box and onto the simplex#
Many algorithms need the nearest point of a convex set to a given , the projection
Projected gradient descent alternates a gradient step with a projection, , and so solves constrained problems with the machinery of the previous note. For two sets used constantly in machine learning, the KKT conditions give the projection in closed form.
The box . The problem separates into coordinates. For one coordinate, with multipliers for and for , stationarity reads . If , the upper bound must be active, since otherwise would be infeasible; then and . The lower bound is symmetric. So the projection is clipping,
with multipliers equal to the amounts clipped away. For and the unit box, , with , and all other multipliers zero. The soft-margin SVM dual is a problem over a box, , and the duality note solves it by projected gradient ascent with exactly this clipping.
The probability simplex . Take the multiplier for and for . Stationarity of is , and the two cases of complementary slackness give
The second case happens exactly when , so both cases are one formula:
Subtract the same threshold from every coordinate and cut at zero. The left side of the condition on is continuous in , tends to infinity as , is 0 once , and strictly decreases wherever it is positive. So exactly one works. Sort in decreasing order, ; for compute the candidate , and take the largest with . The sort dominates the cost, operations (Martins and Astudillo, 2016, Proposition 1 and Algorithm 1).
Derivation: why the largest such r gives the threshold
Let be the number of positive coordinates of the projection. They are the largest , and the condition gives . At the test passes, since . For we have , and every with is at least , so
and the test fails. So is the largest that passes.
For the sorted values are :
| 1 | ||
| 2 | ||
| 3 |
So , and . Applied to the logits of a classifier, this projection is sparsemax (Martins and Astudillo, 2016), an alternative to the softmax that gives exactly zero probability to low-scoring classes. The softmax was the maximum-entropy answer above; sparsemax is the nearest-point answer.
The direction of maximum variance is an eigenvector#
The symmetric matrices note bounds the Rayleigh quotient using the spectral theorem. The Lagrange conditions reach the same answer without it and show why only eigenvectors can be candidates. For a covariance matrix , the variance of the data projected on a unit vector is , and PCA maximizes it subject to . With the Lagrangian and for symmetric :
Every stationary point is a unit eigenvector, and the objective there is its eigenvalue. The sphere is closed and bounded, so the continuous variance attains a maximum and a minimum on it. The constraint gradient never vanishes there, so both are stationary points, and comparing the candidates picks the largest eigenvalue as the maximum and the smallest as the minimum. The multiplier is the variance captured.
For , the covariance of the multivariate Gaussian note, the eigenvalues are 2.8 and 0.2. The direction captures variance 2.8 of the total 3, and a search over 100,001 unit vectors finds the same maximum. The dimensionality reduction note builds PCA on it.
Where it breaks: candidates that are not minima#
Without convexity the conditions list stationary points, and some of them are neither minima nor maxima. In three dimensions the maximum-variance problem shows it. Take with eigenvectors , the coordinate axes. All three are KKT points, with . At the variance is 2, yet turning by radians towards raises it to , and turning it towards lowers it to . The middle eigenvector is a saddle of the variance on the sphere.
A second-order test sorts the candidates. Why the Hessian of the Lagrangian, and not of ? Take a curve on the surface through with velocity . On the surface , so , and two differentiations by the chain rule give
since . The acceleration , the bending of the surface, drops out only for ; with alone it would stay. The test: if for every nonzero tangent , those with , the KKT point is a strict local minimum (Merkulov, 2024, lecture 6). Applied to , negative values for every such mean a strict local maximum.
Here , and at , , it gives and : mixed signs, a saddle. At both tangent directions give negative values, a strict maximum. For one active inequality with the same test runs over the directions with (Merkulov, lecture 6).
The first-order conditions can also miss the answer. Minimize subject to . The only feasible point, , is the solution, but there , and has no solution. The constraint qualification fails: the constraint’s gradient vanishes, so no multiple of it can balance .
Even when everything is regular, the KKT system is hard to solve in general, because nobody knows in advance which constraints are active. Guessing the active set is the combinatorial core of constrained optimization; for the box and the simplex above it is trivial, but a projection onto a general polyhedron is already a quadratic program.
What you should remember#
- With equality constraints, at a minimum: the Lagrangian is stationary.
- The multiplier is the price of the constraint: for .
- KKT: stationarity, feasibility, , ; necessary under a constraint qualification, sufficient for convex problems.
- Projection on a box clips; on the simplex it is .
- Maximum entropy with a fixed mean gives ; maximum variance on the sphere gives the top eigenvector.
- Without convexity, check the Hessian of the Lagrangian on tangent directions.
Code#
The opening problem as a linear system, the plane, maximum entropy, the two KKT cases of the figure, the box and simplex projections checked against SciPy’s SLSQP solver, the maximum-variance direction, and the saddle among its KKT points. Exact digits can differ slightly across platforms and library versions.
import numpy as np
from scipy.optimize import brentq, minimize
# min x1^2 + 2 x2^2 s.t. x1 + x2 = 1: the stationarity equations of the Lagrangian are linear
K = np.array([[2., 0, 1], [0, 4, 1], [1, 1, 0]]) # 2 x1 + nu = 0, 4 x2 + nu = 0, x1 + x2 = 1
x1, x2, nu = np.linalg.solve(K, [0, 0, 1])
print(round(x1, 4), round(x2, 4), round(nu, 4), round(x1**2 + 2 * x2**2, 4))
# 0.6667 0.3333 -1.3333 0.6667
fstar = lambda s: np.linalg.solve(K, [0, 0, s])[:2] @ np.diag([1., 2]) @ np.linalg.solve(K, [0, 0, s])[:2]
print(round((fstar(1 + 1e-6) - fstar(1 - 1e-6)) / 2e-6, 4)) # d f*/ds = -nu
# 1.3333
# the nearest point on the plane a.x = b to p
a, b, p = np.array([1., 2, 2]), 3.0, np.array([1., 1, 1])
nu = 2 * (a @ p - b) / (a @ a); x = p - nu / 2 * a
print(x.round(4), round(a @ x, 10), round(np.linalg.norm(x - p), 4), round(nu, 4))
pst = lambda b: (a @ p - b) ** 2 / (a @ a) # the optimal value as a function of b
print(round((pst(b + 1e-6) - pst(b - 1e-6)) / 2e-6, 4))
# [0.7778 0.5556 0.5556] 3.0 0.6667 0.4444
# -0.4444
# maximum entropy on {1, ..., 6} with mean 4.5: p_i proportional to exp(-beta i)
k = np.arange(1, 7)
mean = lambda beta: k @ np.exp(-beta * k) / np.exp(-beta * k).sum()
beta = brentq(lambda t: mean(t) - 4.5, -5, 5)
pm = np.exp(-beta * k); pm /= pm.sum()
res = minimize(lambda q: q @ np.log(q), np.ones(6) / 6, method='SLSQP', bounds=[(1e-9, 1)] * 6,
constraints=[{'type': 'eq', 'fun': lambda q: q.sum() - 1}, {'type': 'eq', 'fun': lambda q: q @ k - 4.5}],
options={'ftol': 1e-14, 'maxiter': 500})
print(round(beta, 4), pm.round(4), round(-pm @ np.log(pm), 4), round(np.log(6), 4), np.abs(res.x - pm).max() < 1e-5)
print(round(np.exp(-beta), 3)) # the ratio of neighbouring probabilities
# -0.371 [0.0544 0.0788 0.1142 0.1654 0.2398 0.3475] 1.6136 1.7918 True
# 1.449
# KKT with active and inactive constraints: min |x - c|^2 s.t. x1 + x2 <= 2, x1 >= 0, x2 >= 0
for c in (np.array([2., 1]), np.array([0.8, 0.6])):
r = minimize(lambda x: (x - c) @ (x - c), np.zeros(2), method='SLSQP', bounds=[(0, None)] * 2,
constraints=[{'type': 'ineq', 'fun': lambda x: 2 - x.sum()}], options={'ftol': 1e-14})
xs = r.x; lam1 = -2 * (xs - c)[0] if abs(xs.sum() - 2) < 1e-9 else 0.0 # stationarity: 2(x - c) + lam1 (1, 1) = 0
print(c, xs.round(4), round(lam1, 4), abs(round(lam1 * (xs.sum() - 2), 12)))
# [2. 1.] [1.5 0.5] 1.0 0.0
# [0.8 0.6] [0.8 0.6] 0.0 0.0
# projection onto a box is clipping; the multiplier of a bound is the distance clipped away
v = np.array([1.7, -0.4, 0.3]); xb = np.clip(v, 0, 1)
print(xb, np.maximum(v - 1, 0), np.maximum(-v, 0)) # x, multipliers of x <= 1, multipliers of x >= 0
# [1. 0. 0.3] [0.7 0. 0. ] [0. 0.4 0. ]
# projection onto the probability simplex: x = max(v - tau, 0), tau from the sorted values
def proj_simplex(v):
u = np.sort(v)[::-1]; css = np.cumsum(u) - 1
rho = np.nonzero(u - css / np.arange(1, len(v) + 1) > 0)[0][-1]
tau = css[rho] / (rho + 1)
return np.maximum(v - tau, 0), tau
v = np.array([0.5, 1.2, -0.3]); xs, tau = proj_simplex(v)
lam = xs - v + tau # stationarity of 1/2|x - v|^2 + tau (sum x - 1) - lam.x
r = minimize(lambda x: 0.5 * (x - v) @ (x - v), np.ones(3) / 3, method='SLSQP', bounds=[(0, None)] * 3,
constraints=[{'type': 'eq', 'fun': lambda x: x.sum() - 1}], options={'ftol': 1e-14})
print(xs, tau, lam.round(4), lam @ xs, np.abs(r.x - xs).max() < 1e-6)
rng = np.random.default_rng(0) # 1,000 random vectors against SLSQP
print(max(np.abs(proj_simplex(w)[0] - minimize(lambda x: 0.5 * (x - w) @ (x - w), np.ones(5) / 5, method='SLSQP', bounds=[(0, None)] * 5,
constraints=[{'type': 'eq', 'fun': lambda x: x.sum() - 1}], options={'ftol': 1e-14}).x).max() for w in rng.normal(size=(1000, 5))) < 1e-6)
# [0.15 0.85 0. ] 0.35 [0. 0. 0.65] 0.0 True
# True
# the direction of maximum variance: stationary points of u' S u on the unit circle are eigenvectors
S = np.array([[2., 1.2], [1.2, 1]])
ang = np.linspace(0, np.pi, 100_001); U = np.stack([np.cos(ang), np.sin(ang)])
var = np.einsum('in,ij,jn->n', U, S, U)
w, V = np.linalg.eigh(S)
print(w, np.abs(V[:, 1]).round(3), round(var.max(), 6), round(var.min(), 6), U[:, var.argmax()].round(3))
# [0.2 2.8] [0.832 0.555] 2.8 0.2 [0.832 0.555]
# in three dimensions the middle eigenvector is a KKT point but a saddle: S = diag(3, 2, 1)
S = np.diag([3., 2, 1]); q1, q2, q3 = np.eye(3)
turn = lambda q, s: (np.cos(s) * q2 + np.sin(s) * q) @ S @ (np.cos(s) * q2 + np.sin(s) * q) # variance after turning q2 by s
H = 2 * (S - 2 * np.eye(3)) # Hessian of the Lagrangian at u = q2, nu = 2
print(round(turn(q1, 0.1), 4), round(turn(q3, 0.1), 4), q1 @ H @ q1, q3 @ H @ q3)
# 2.01 1.99 2.0 -2.0
Next#
The sufficiency proof compared with the Lagrangian, which on the feasible set is never larger than the objective. The next note makes that bound the main object. Minimizing the Lagrangian over for fixed multipliers gives a function of the multipliers alone, the dual function, and its maximum is the best such lower bound. For convex problems it equals the optimum, which turns the SVM into a problem over its multipliers and gives every solver a certificate of how far it is from optimal.
References#
- S. Boyd, L. Vandenberghe. Convex Optimization. Cambridge University Press, 2004. §5.4.4 (price interpretation, shadow prices), §5.5.3 (KKT optimality conditions; necessary and sufficient under Slater’s condition), §5.6.3 (local sensitivity analysis).
- D. Merkulov. Optimization for ML, HSE University, 2024. Course site; lecture 6 (optimality conditions, the Lagrange function, KKT conditions, constraint qualifications, second-order conditions, projections onto a hyperplane and the simplex).
- J. Lebl. Basic Analysis II: Introduction to Real Analysis, Volume II, version 6.3, 2026. Section 8.5, Theorem 8.5.6 (the implicit function theorem).
- M. P. Deisenroth, A. A. Faisal, C. S. Ong. Mathematics for Machine Learning. Cambridge University Press, 2020. Section 7.2 (constrained optimization and Lagrange multipliers).
- E. T. Jaynes. Information theory and statistical mechanics. Physical Review, 106(4), 1957. The maximum-entropy principle.
- A. F. T. Martins, R. F. Astudillo. From softmax to sparsemax: a sparse model of attention and multi-label classification. ICML, 2016. Proposition 1 and Algorithm 1 (projection onto the simplex by sorting).