14 / 16 · Optimization
Duality
Lower bounds from Lagrange multipliers: weak and strong duality, Slater's condition, the duals of a linear program, of norm-constrained least squares and of the SVM, and the duality gap as a stopping rule.
Lagrange multipliers and KKT conditions · Convex sets and functions
On this page 9
A soft-margin SVM on 40 points is trained by an iterative solver. After 100 iterations its objective is , after 1,000 iterations , after 5,000 iterations . Is that the minimum? The values keep decreasing, and the gradient tests of the unconstrained optimization note do not apply, because the hinge loss has kinks. The optimal value is exactly what is unknown.
An upper bound on is easy: any feasible point gives one. What is missing is a lower bound, a number that provably cannot go below. With both, the optimum is bracketed and the solver can stop with a guarantee. The KKT conditions of the previous note already contained one: on the feasible set, adding the constraints with non-negative multipliers can only lower the objective. Every choice of multipliers gives such a bound, and the best of them is often the optimum itself.
The Lagrange dual function#
The primal problem is the one of the previous note: minimize subject to for and for . Its optimal value is , which is if no point is feasible and if the objective is unbounded below. The problem is convex if and the are convex and the affine. With multipliers and the Lagrangian is
The dual function is its minimum over , for fixed multipliers:
The infimum is over all , feasible or not, so computing is an unconstrained problem, and the result may be . For each fixed the Lagrangian is an affine function of , and a pointwise infimum of affine functions is concave, by the pointwise maximum rule applied to . So the dual function is concave whatever , and are, convex or not.
Weak duality#
Take any feasible and any , . Inequalities between vectors, such as , hold entry by entry. Then
The first line holds because an infimum is at most any of its values, the last because , and . The bound holds for every feasible , hence for the infimum of over them, which is . Nothing in the argument uses convexity.
The dual problem asks for the best lower bound:
It maximizes a concave function subject to , so it is a convex problem even when the primal is not. The difference is the duality gap.
Take the problem: minimize subject to , written as . On the feasible set the objective increases, so at . The Lagrangian is a parabola in with its minimum at , so
At it takes the values , , , and . Every one is a lower bound on , and the best one, at , equals . The minimizer of the Lagrangian at is , and is the stationarity condition of KKT.
Weak duality: every multiplier gives a lower bound
The two problems are the same function optimized in opposite orders (Boyd and Vandenberghe, 2004, §5.4.1; Deisenroth, Faisal and Ong, 2020, Section 7.2). For a fixed , the supremum of over and is if is feasible and if some constraint is violated, since its multiplier can then grow without limit. So
Weak duality is the max–min inequality, which holds for any function of two arguments. For any and ,
The left end does not depend on and the right end does not depend on , so taking the supremum over on the left and the infimum over on the right keeps the inequality: . The player who moves second does at least as well. Strong duality says that the order does not matter; the section below shows that a primal and a dual solution then form a saddle point of .
Strong duality and Slater’s condition#
When , strong duality holds. It can fail, even for convex problems, as an example below shows. The simplest sufficient condition is Slater’s condition: the problem is convex and some point is strictly feasible, with for every and for every . Under it, , and the dual optimum is attained whenever is finite (Boyd and Vandenberghe, 2004, §5.2.3). The folded proof below covers one inequality; the general proof is in §5.3.2.
Inequalities that are affine need not hold strictly: a feasible point is enough for them. In particular every feasible problem with a convex objective defined on all of and only affine constraints, such as least squares with linear constraints or the SVM, has strong duality (§5.2.3, the refined Slater condition).
Proof sketch, for one inequality constraint
Assume is finite. Consider the set of pairs that the problem can achieve, . It contains everything above and to the right of each of its points. It is convex: if achieves and achieves , then by convexity of and the point achieves . The point lies on its boundary: points of come arbitrarily close to it, but is not in for any , since that would need a feasible with .
A nonempty convex set has a supporting line at each boundary point, by the supporting hyperplane theorem (Boyd and Vandenberghe, 2004, §2.5.2): there are with for every . If were negative, letting grow along would break the inequality, and the same holds for and ; so and . If , then and on ; but the Slater point gives a pair with , a contradiction.
So . Every achieves the pair , and dividing by gives for every , that is . With weak duality, , attained at . The full proof, with equality constraints, is in Boyd and Vandenberghe (2004), §5.3.2.
Without a Slater point, even a convex problem can have a gap. Minimize subject to , over . Only is feasible, so . No point satisfies the constraint strictly, since is never negative. The dual function is
for every . Both terms are non-negative, so the infimum is at least 0. Along the Lagrangian is , which for takes the values , , and at and tends to 0. So (Boyd and Vandenberghe, 2004, Exercise 5.21).
Strong duality forces the KKT conditions. If is primal optimal, dual optimal and , then
so both inequalities are equalities. The first says that minimizes over all ; for differentiable functions the gradient at an unconstrained minimum is zero, which gives stationarity. The second says that , a sum of non-positive terms, so every term is zero: complementary slackness. The same chain shows the saddle point: for every and every , ,
The left inequality is weak duality’s last step at the feasible ; the right one holds because minimizes . This is how the SVM note derives its KKT conditions.
The dual of a linear program#
For a linear objective the Lagrangian is linear in , and its infimum is finite only when the coefficient of vanishes. That condition becomes the dual’s constraint. Take the linear program
Give the constraints the multipliers and the constraints the multipliers , and collect the terms in :
A linear function is bounded below only if : otherwise gives . So when and otherwise. The condition is the dual constraint, and the dual is again a linear program:
The constraints of an LP are affine, so by the refined Slater condition above strong duality holds whenever the primal is feasible.
For example, minimize subject to , and . The feasible set is a polyhedron with vertices , and , with costs 4, 5.5 and 9. The cheapest vertex is ; the dual will certify that . The dual is: maximize subject to , and . The point is feasible with value 4. Every dual value is at most and every primal value at least , so the two points certify each other: both are optimal, with no search. Complementary slackness holds pair by pair:
| Constraint | Slack at the optimum | Paired variable |
|---|---|---|
| primal | (tight) | |
| primal | ||
| dual | ||
| dual | (tight) |
Every row has a zero in it. Read as prices of the requirements : raising the first requirement from 2 to , for small , raises the optimal cost by , the multiplier. The same pair certifies it: is feasible with cost , and stays dual feasible with value .
Least squares under a norm constraint#
The constraint enters the Lagrangian as a penalty , so minimizing the Lagrangian is ridge regression. Take
with and one multiplier . The Lagrangian is convex in , and setting its gradient to zero gives the ridge solution:
The dual function is , and its derivative is simple:
The chain rule through , which is differentiable in as a product of a matrix inverse and a fixed vector, gives it:
because at . This is the envelope theorem: only the explicit counts. The point is strictly feasible, so Slater holds and . The dual function is concave, so never increases. If the least-squares solution already has , then and . Otherwise , while as because . So somewhere, which says : complementary slackness. The dual picks the penalty whose ridge solution exactly meets the constraint.
This is the duality that the regularization note invokes: the constrained and the penalized forms of ridge regression trace the same family of solutions, with the multiplier of the radius .
Take with rows , and , and . The least-squares solution has squared norm , so the constraint binds. The dual function gives a lower bound for every :
| 0 | 0.5 | 1 | 2 | 2.085 | 4 | |
|---|---|---|---|---|---|---|
| 0.333 | 1.167 | 1.625 | 1.933 | 1.9348 | 1.400 |
The first value is the unconstrained minimum. The maximum is at , where has squared norm exactly 1. A constrained solver applied to the primal finds the same point and the same value, .
The SVM dual: nearest points of two convex hulls#
The SVM note derives the dual of the soft-margin SVM step by step, by the scheme above, and reads off the support vectors from it. Duality adds a geometric reading of the hard-margin dual (Bennett and Bredensteiner, 2000). Start from
The equality constraint gives the two classes the same total weight . Write , so that sums to 1 on each class. Then , and
where and are convex combinations of the points of each class: points of the two convex hulls. The dual objective becomes a parabola in :
The maximum is at , where . This maximum decreases with the distance, so maximizing over the remaining weights is minimizing over the two hulls. With the distance between the hulls, , and
The weight vector points along , so the hyperplane is perpendicular to the shortest segment between the hulls. It also bisects it. The points with lie on the margin, , by complementary slackness, and are averages of such points, so . Adding the two gives : the midpoint lies on the hyperplane. The margin is half the length of the segment. For the soft margin, the bound caps each at , and the hulls shrink to “reduced” hulls, which can be separated even when the full hulls overlap (Bennett and Bredensteiner, 2000).
The four points of the SVM note make this concrete: negatives and , positives and . The hulls are the segments and . Their nearest points are , the midpoint of , and , at distance . Then , so , and ; , and . These are the numbers the SVM note finds from the KKT conditions.
The duality gap as a stopping criterion#
A primal feasible point gives an upper bound on , a dual feasible point a lower bound, and the optimum lies between them. For any feasible and any , ,
So the computable difference bounds both and : it certifies how far the current point is from optimal without knowing (Boyd and Vandenberghe, 2004, §5.5.1). A solver that stops when the gap is below returns a point within of the optimum. Scikit-learn’s coordinate-descent Lasso, for example, checks a duality gap against its tolerance (scikit-learn documentation). Interior-point methods produce such a pair at every step: the point on their central path with barrier weight comes with dual multipliers whose gap is exactly , for inequalities (Boyd and Vandenberghe, 2004, §11.2.2).
Derivation: the gap m/t on the central path
Take inequality constraints only. The central point minimizes over the strictly feasible points, so its gradient vanishes:
Divide by and set . Then at , so for a convex problem minimizes the convex , and
Take the SVM of the opening. Absorb the bias into the weights by appending a constant feature 1 to every point, as many linear SVM solvers do (Hsieh et al., 2008). The primal is then unconstrained,
with and . The derivation of the SVM note without gives the dual
over the box , with no equality constraint. Projected gradient ascent alternates a gradient step on with clipping to the box. Every iterate is dual feasible, is a primal point, and their gap bounds the error:
| Iteration | gap | true error | ||
|---|---|---|---|---|
| 1 | 19.682 | 0.291 | 19 | 6.5 |
| 10 | 16.260 | 1.744 | 15 | 3.0 |
| 100 | 13.478 | 12.393 | 1.1 | 0.26 |
| 1,000 | 13.231 | 13.222 | ||
| 5,000 | 13.2226 | 13.2226 |
Stopping at a gap below ends the run at iteration 1,422, where the true error is , inside the guarantee. The gap is pessimistic early, when the dual iterate is poor, and tight near the end. At the solution 15 of the 40 points have , the support vectors, and 12 of them sit at the bound . By complementary slackness those have positive slack: they lie inside the margin or are misclassified.
Where it breaks: a non-convex problem#
Weak duality holds for any problem, so the dual still gives a bound when the primal is hard; strong duality is what fails. Split items into two groups to minimize over sign vectors , so that adds when items and share a group and subtracts it when they do not. Written as , the constraints are equalities. The Lagrangian is
a quadratic form whose infimum over is 0 if the matrix is positive semidefinite and otherwise: a direction with gives values that fall without limit along . So when . The choice for every is feasible and gives the bound (Boyd and Vandenberghe, 2004, §5.1.5; Merkulov, 2024, lecture 7).
For a random symmetric matrix , checking all 256 sign vectors gives . The eigenvalue bound is . The best multipliers, found by maximizing the concave dual function numerically, raise it to , so . An upper bound on shows that the gap is real. For any positive semidefinite with unit diagonal and any dual feasible , the trace of a product of two positive semidefinite matrices is non-negative, so
that is . A matrix found numerically gives . So lies between and , and the gap is .
Two smaller failures appear in practice. Recovering a primal solution from a dual one needs the minimizer of the Lagrangian to be unique. It fails for linear programs: at the dual optimum the coefficient of vanishes, the Lagrangian is constant in , and every minimizes it. And the dual can be larger than the primal: the SVM dual has one variable per training point and a dense matrix, so for millions of points the primal is solved instead, by stochastic gradients.
What you should remember#
- The dual function is concave, and whenever .
- and ; weak duality is the max–min inequality.
- Convex problem plus a strictly feasible point (Slater) gives , and with it the KKT conditions.
- LP: the dual of is .
- The hard-margin SVM dual finds the nearest points of the two hulls; the margin is half their distance.
- bounds the suboptimality of both points: a safe stopping rule.
Code#
The bound of the figure, a convex problem with a duality gap, an LP and its dual, norm-constrained least squares, the SVM dual as nearest points, an SVM solver stopped by its duality gap, and the two-way partitioning bound, with NumPy and SciPy. It runs in a few seconds. Exact digits can differ slightly across platforms and library versions.
import numpy as np
import itertools
from scipy.optimize import brentq, linprog, minimize
# min x^2 s.t. 1 - x <= 0: the dual function g(lam) = lam - lam^2/4 lies below p* = 1 and touches it at lam = 2
lam = np.linspace(0, 5, 501); g = lam - lam**2 / 4
print(g.max(), lam[g.argmax()], (g <= 1 + 1e-12).all())
# 1.0 2.0 True
# a convex problem without a Slater point: min e^{-x} s.t. x^2 / y <= 0 (y > 0); p* = 1 but g(lam) = 0
for x in (1., 5., 20., 100.): # along y = x^3 the Lagrangian tends to 0 for every lam
print(x, f'{np.exp(-x) + 1.0 * x**2 / x**3:.4f}', end=' | ')
print()
# 1.0 1.3679 | 5.0 0.2067 | 20.0 0.0500 | 100.0 0.0100
# an LP and its dual: min 3x1 + 2x2 s.t. x1 + x2 >= 2, x1 + 3x2 >= 3, x >= 0; max 2y1 + 3y2 s.t. y1 + y2 <= 3, y1 + 3y2 <= 2, y >= 0
A = np.array([[1., 1], [1, 3]]); b = np.array([2., 3]); c = np.array([3., 2])
pr = linprog(c, A_ub=-A, b_ub=-b, bounds=[(0, None)] * 2)
du = linprog(-b, A_ub=A.T, b_ub=c, bounds=[(0, None)] * 2)
print(pr.x, pr.fun, du.x, -du.fun, A @ pr.x - b, c - A.T @ du.x) # slacks: primal constraints, dual constraints
# [0. 2.] 4.0 [2. 0.] 4.0 [0. 3.] [1. 0.]
# least squares under a norm constraint: min |Ax - b|^2 s.t. |x|^2 <= t; the dual is a function of one multiplier
A = np.array([[1., 0], [0, 1], [1, 1]]); b = np.array([1., 2, 2]); t = 1.0
x_lam = lambda l: np.linalg.solve(A.T @ A + l * np.eye(2), A.T @ b) # the minimizer of the Lagrangian: ridge
gd = lambda l: np.sum((A @ x_lam(l) - b) ** 2) + l * (x_lam(l) @ x_lam(l) - t)
ls = x_lam(0); print(ls.round(4), round(ls @ ls, 4), round(gd(0), 4)) # unconstrained solution is infeasible
lam_s = brentq(lambda l: x_lam(l) @ x_lam(l) - t, 0, 100); xs = x_lam(lam_s)
r = minimize(lambda x: np.sum((A @ x - b) ** 2), np.zeros(2), method='SLSQP',
constraints=[{'type': 'ineq', 'fun': lambda x: t - x @ x}], options={'ftol': 1e-14})
print(round(lam_s, 4), xs.round(4), round(gd(lam_s), 6), round(r.fun, 6), [round(float(gd(l)), 4) for l in (0.5, 1, 2, 4)])
# [0.6667 1.6667] 3.2222 0.3333
# 2.0851 [0.5262 0.8504] 1.934833 1.934833 [1.1667, 1.625, 1.9333, 1.4]
# the hard-margin SVM of the ML note: the dual optimum is the nearest pair of points of the two convex hulls
P = np.array([[1., 2], [3, 3]]); Nn = np.array([[0., 0], [2, 0]]) # positive points C, D; negative points A, B
best = min(((np.linalg.norm(u @ P - v @ Nn), u, v) for s in np.linspace(0, 1, 401) for q in np.linspace(0, 1, 401)
for u, v in [(np.array([s, 1 - s]), np.array([q, 1 - q]))]), key=lambda z: z[0])
D, u, v = best
print(round(D, 4), (u @ P).round(3), (v @ Nn).round(3), round(D / 2, 4), (2 / D**2 * (u @ P - v @ Nn)).round(4), round(2 / D**2, 4))
# 2.0 [1. 2.] [1. 0.] 1.0 [0. 1.] 0.5: distance, nearest points, margin, w = s (c+ - c-), dual optimum 2/D^2
# a soft-margin SVM (bias absorbed into w) solved by projected gradient ascent on its box-constrained dual;
# the duality gap P(w(alpha)) - D(alpha) bounds the suboptimality of every iterate
rng = np.random.default_rng(0)
n, C = 40, 1.0
y = np.repeat([1., -1.], n // 2)
X = rng.normal(size=(n, 2)) + y[:, None] # two overlapping clouds around (1, 1) and (-1, -1)
Z = np.column_stack([X, np.ones(n)]) * y[:, None] # rows y_i (x_i, 1)
Q = Z @ Z.T
Pobj = lambda w: 0.5 * w @ w + C * np.maximum(0, 1 - Z @ w).sum()
Dobj = lambda a: a.sum() - 0.5 * a @ Q @ a
eta = 1 / np.linalg.eigvalsh(Q)[-1]
a, hist = np.zeros(n), []
for k in range(1, 20_001):
a = np.clip(a + eta * (1 - Q @ a), 0, C) # gradient step, then projection onto the box [0, C]
hist.append((Pobj(Z.T @ a), Dobj(a)))
p_star = hist[-1][0]
print(round(p_star, 4), f'{hist[-1][0] - hist[-1][1]:.0e}', (a > 1e-8).sum(), (a > C - 1e-8).sum())
for k in (1, 10, 100, 1000, 5000):
pk, dk = hist[k - 1]
print(k, round(pk, 4), round(dk, 4), f'{pk - dk:.1e}', f'{pk - p_star:.1e}', end=' | ')
print()
stop = next(k for k, (pk, dk) in enumerate(hist, 1) if pk - dk < 1e-3)
print(stop, f'{hist[stop - 1][0] - p_star:.1e}', all(pk - p_star <= pk - dk + 1e-12 for pk, dk in hist))
# 13.2226 4e-15 15 12
# 1 19.6823 0.291 1.9e+01 6.5e+00 | 10 16.2603 1.7443 1.5e+01 3.0e+00 | 100 13.4784 12.3925 1.1e+00 2.6e-01 | 1000 13.2308 13.2224 8.3e-03 8.2e-03 | 5000 13.2226 13.2226 2.1e-11 2.1e-11
# 1422 9.9e-04 True
# a non-convex problem: min x'Wx over x in {-1, 1}^8; the dual is g(nu) = -1'nu where W + diag(nu) is PSD
rng = np.random.default_rng(0)
n = 8
W = rng.normal(size=(n, n)); W = (W + W.T) / 2
p_star = min(np.array(x) @ W @ np.array(x) for x in itertools.product([-1, 1], repeat=n))
def dual(nu): # shift nu to feasibility; value and a supergradient
lam, V = np.linalg.eigh(W + np.diag(nu))
return -nu.sum() + n * lam[0], -1 + n * V[:, 0] ** 2
nu, best = np.zeros(n), -np.inf
for k in range(1, 100_001): # supergradient ascent on the concave dual
val, g = dual(nu)
best = max(best, val)
nu = nu + 0.5 / np.sqrt(k) * g
print(round(p_star, 3), round(n * np.linalg.eigvalsh(W)[0], 3), round(best, 3), round(p_star - best, 1))
V = np.random.default_rng(1).normal(size=(n, n)) # an upper bound on d*: tr(WX) for X = VV' with unit rows
for _ in range(5000):
V = V - 0.01 * W @ V; V /= np.linalg.norm(V, axis=1, keepdims=True)
print(round(np.trace(W @ V @ V.T), 3))
# -22.235 -28.855 -22.834 0.6
# -22.833
Next#
Every number in this section was computed in floating point and treated as exact. Mostly that is harmless, but not always. The Newton step solves a linear system whose matrix can be nearly singular, the ridge solution can be computed through or through a factorization of with very different accuracy, and the softmax of the maximum-entropy solution overflows for large scores. The next note measures how errors in the data and in the arithmetic grow through a computation, and which rewrites keep machine learning code accurate.
References#
- S. Boyd, L. Vandenberghe. Convex Optimization. Cambridge University Press, 2004. §2.5.2 (the supporting hyperplane theorem). Chapter 5: §5.1 (the Lagrange dual function; §5.1.5, two-way partitioning), §5.2 (the dual problem, weak and strong duality, §5.2.3 Slater’s condition and its refinement for affine inequalities), §5.3.2 (proof of strong duality), §5.4.1 (max–min characterization), §5.5.1 (certificates and stopping criteria), Exercise 5.21 (a convex problem with a duality gap). §11.2.2 (dual points from the central path).
- D. Merkulov. Optimization for ML, HSE University, 2024. Course site; lecture 7 (duality: the dual function, weak and strong duality, Slater’s condition, two-way partitioning, sensitivity).
- M. P. Deisenroth, A. A. Faisal, C. S. Ong. Mathematics for Machine Learning. Cambridge University Press, 2020. Section 7.2 (Lagrange duality and the minimax inequality).
- K. P. Bennett, E. J. Bredensteiner. Duality and geometry in SVM classifiers. ICML, 2000, 57–64. The hard-margin dual as nearest points of convex hulls, reduced hulls for the soft margin.
- C.-J. Hsieh, K.-W. Chang, C.-J. Lin, S. S. Keerthi, S. Sundararajan. A dual coordinate descent method for large-scale linear SVM. ICML, 2008. The box-constrained dual with the bias absorbed into the weights.
- scikit-learn documentation.
sklearn.linear_model.Lasso: thetolparameter, a tolerance on the duality gap.