23.7 Duality
When an iterative solver stops making progress and reports convergence, a natural question remains: is the point it returned actually optimal? For an unconstrained convex function, a zero gradient settles the question at once (Section 23.3). With constraints, however, the optimum usually sits on the boundary with a nonzero gradient (Section 23.6), so that simple test disappears. Both numerical solvers and mathematical proofs therefore need a different tool: a reliable lower bound on the optimal value. In this section we develop a systematic way to construct such bounds and uncover what the Lagrange multipliers of the KKT conditions actually measure.
To see the difficulty concretely, return to the clipping problem of Section 23.6.2. There we minimized the squared distance to the target over the unit disk , finding the optimum with optimal value . (We write here instead of , reserving for labels and for the argument of the convex conjugate later.) Now imagine an iterative solver stops at . This point is feasible, since , and achieves an objective value of . How can we tell whether is nearly optimal, or whether some other point in the disk reaches ? The gradient at the true optimum is , nowhere near zero, and the disk contains infinitely many points, so checking them one by one is out of the question.
The key idea is to fold the constraint into the objective. Add a nonnegative multiple of the constraint function to the objective. At every feasible point this added term is nonpositive, so minimizing the modified objective over all of must yield a value no larger than the constrained optimum. Each choice of thus produces a lower bound through an unconstrained minimization, and gives a bound of —proving immediately that the solver's is within of optimal. Searching for the tightest such bound defines a companion optimization problem, the dual problem. Remarkably, the dual problem is always convex, even when the original problem is not. For a convex problem with a strictly feasible point, its optimal value matches the constrained optimum, and its optimal multipliers tell us how rapidly the optimal value improves when each constraint is relaxed.
In what follows, we first use this bounding idea to prove optimality for the
clipping problem and state weak duality, a two-line argument that holds for
every optimization problem. We then establish strong duality for convex
problems, whose proof contains the one subtle geometric step in the section,
and interpret the optimal multipliers as shadow prices, connecting weight
decay directly to norm constraints. After introducing the convex conjugate as
a convenient tool for computing duals of linearly constrained problems (which
can be skimmed on a first reading), we work through three revealing examples:
the support vector machine, water-filling power allocation, and a nonconvex
problem whose best dual bound stays strictly below its optimum. All
computations are small enough for NumPy, and d2l handles the plots.
23.7.1 The Dual Problem#
Our first goal is to prove that no feasible point of the clipping problem achieves a value below , without checking feasible points one by one. Every lower bound in this section rests on a single elementary observation: at any feasible point, every inequality constraint function is nonpositive.
23.7.1.1 A Lower Bound from One Multiplier#
Recall the clipping problem: minimize with , subject to . Including the factor of in simply makes its gradient equal to . From the KKT conditions we already know the solution: with optimal value , and optimal multiplier , determined by the stationarity condition .
Now pick any multiplier and any feasible point . Because and , their product is nonpositive, which means . Minimizing the left-hand side over all of can only make it smaller still, so that unconstrained minimum is at most . Since this holds for every feasible , it also holds for the best feasible :
Let us evaluate the left-hand side explicitly. The function being minimized is the Lagrangian . For any , this is a convex quadratic in with Hessian , so its unique minimizer occurs where the gradient vanishes: . Increasing shrinks more strongly toward the origin. Substituting back into the Lagrangian—using and —gives and . Combining these two fractions cancels a factor of , leaving the minimum value as a simple function of :
The two terms pull in opposite directions. As grows, the first term rises toward , while the second term—coming from the constant inside —drops linearly without bound. The tightest lower bound sits where these two effects balance.
Plugging in a few numbers makes this balance concrete: , , , , , , and . Every single one of these values is a valid lower bound on . Differentiating gives , which vanishes when , or . Since , is the unique maximum, attaining . The best lower bound equals the true optimum, and the multiplier that achieves it is the KKT multiplier. This certifies that the solver's value of is within of optimal; even an unoptimized guess like already certifies that it is within .
Why does hit the optimum? Look at the constraint value at the Lagrangian minimizer: . When , the multiplier is too weak to pull the minimizer inside the unit disk (for example, has norm ), so and the bound reflects an infeasible point. When , the multiplier pulls the minimizer too far inside (for example, has norm ), so drags the bound back down. Right at , the minimizer lands on the boundary circle, the penalty term vanishes, and the bound coincides with the objective of a feasible point.
Let us plot alongside across a grid of values to see how these bounds behave.
x0 = np.array([3.0, 4.0]) # the point to clip
f = lambda x: 0.5 * np.sum((x - x0) ** 2) # objective
g = lambda x: 0.5 * (np.sum(x ** 2) - 1.0) # constraint g(x) <= 0
x_of = lambda lam: x0 / (1 + lam) # minimizer of L(., lam)
q = lambda lam: f(x_of(lam)) + lam * g(x_of(lam)) # dual function
p_star = f(x0 / np.linalg.norm(x0)) # value at the clipped point
lams = np.linspace(0.0, 12.0, 1201)
qs = np.array([q(l) for l in lams])
d2l.plot(lams, [qs, np.full_like(lams, p_star)], 'lambda', 'value',
legend=['dual function q(lambda)', 'p* = 8'])The resulting curve is concave and stays everywhere below the horizontal line , touching it once at . Surprisingly, concavity here has nothing to do with the geometry of the disk: as we now show, the dual function is concave for every optimization problem.
23.7.1.2 The Lagrange Dual Function#
Nothing in the bounding argument above depended on the clipping problem. Let us apply the same construction to the general constrained problem from Section 23.6.2,
with optimal value , defined as the infimum of over all feasible points (with if no feasible point exists). Here is the domain on which and all constraint functions are defined; it is simply unless we keep a set as a hard constraint, as we will do with in the duality-gap example at the end of this section. The Lagrangian introduces one multiplier per constraint,
with for inequalities and unconstrained in sign for equalities. We write to mean for every coordinate .
Minimizing the Lagrangian over for fixed multipliers turns our lower-bound construction into a function of . The Lagrange dual function is
In words, asks how low can go once we drop the hard constraints and replace them with linear penalties weighted by and . For the clipping problem this gave (23.7.1). In general, the infimum need not be attained, and it can even be . For example, suppose we minimize subject to : the Lagrangian is unbounded below unless , so and for all other . A bound of is trivially valid but useless. The set of multipliers where is called the effective domain of ; when we derive the support vector machine dual below, this implicit domain restriction will surface as an explicit equality constraint.
Two fundamental properties of hold with no assumptions whatsoever on , , or —not even convexity or differentiability.
Proposition (the dual function is concave). For any primal problem, in (23.7.2) is concave.
Proof. Fix any . Because the multipliers enter linearly, the map is affine. The dual function is the pointwise infimum of this family of affine functions. Its hypograph—the set of points lying on or below its graph—is therefore the intersection of the half-spaces below these affine functions. Since any intersection of convex sets is convex, is concave.
Figure 23.7.1 draws this construction for the clipping problem. Each dashed line is the Lagrangian of one fixed as a function of , and is the curve that stays below all of them. The objective of the clipping problem happens to be convex, but the argument never used that: a lower envelope of lines is concave whatever shape and have.
The dual function of the clipping problem as a lower envelope. Each fixed contributes one line (dashed), and is the lowest value that any of these lines takes at . The lines drawn belong to the minimizers for several values of , and each touches at its own (dots). The line of is flat because ; it touches at the maximum .
Proposition (weak duality). If is feasible and , then . Consequently,
Proof. For any feasible and any , we have (since and ) and . Therefore,
Taking the supremum over with on the left and the infimum over feasible on the right yields (23.7.3).
Weak duality is the two-line inequality that turned every in the clipping problem into a certified lower bound. It is also the exact engine behind KKT sufficiency in Section 23.6.2, where evaluating the same chain at the KKT multipliers makes both inequalities tight via complementary slackness.
Maximizing over and is called the dual problem. Because it maximizes a concave function over a convex set, the dual problem is always a convex optimization problem, even when the primal problem is badly nonconvex. Its optimal value is the tightest lower bound this construction can provide, and every dual-feasible gives a valid lower bound. The nonnegative difference is the duality gap. For the clipping problem the gap was zero, whereas our final worked example will exhibit a strict gap. The natural next question is when we can guarantee in advance that the gap vanishes.
23.7.2 Strong Duality#
In the clipping problem, the best dual bound matched the primal optimum exactly. For a nonconvex problem, however, the dual bound can fall strictly short, certifying only part of the answer. Fortunately, two mild ingredients— convexity and a single strictly feasible point—are enough to close the gap. A simple geometric view of the attainable constraint and objective values shows why both are needed.
23.7.2.1 Slater's Condition#
Proposition (Slater's condition implies strong duality). Suppose the problem is convex ( and every convex, every affine) and satisfies Slater's condition (Section 23.6.2.3): there exists a feasible point in the relative interior of such that for every inequality constraint that is not affine. Then , and whenever is finite, the dual optimum is attained.
This is the same constraint qualification introduced for convex problems in Section 23.6.2: at least one point must sit strictly inside all curved inequality constraints. (See Boyd and Vandenberghe (2004), section 5.3.2 for the full proof in multiple dimensions.) The clipping problem satisfies Slater's condition effortlessly: both and are convex, and the origin satisfies . Thus was guaranteed before we ever computed a derivative.
To understand why convexity and strict feasibility close the gap, consider a problem with a single inequality constraint . Map every point to the pair of its constraint value and objective value, and collect all points lying above and to the right of these pairs:
In this -plane, feasible points correspond to , so the primal optimum is simply the lowest height that reaches on the vertical axis . Now fix . Over all contributed by a given , the linear function is minimized at , so . Geometrically, we take a line of slope and push it upward from below until it just supports ; its intercept on the vertical axis is . Because the entire set lies on or above this supporting line, the intercept can never exceed . This is weak duality made visible (Figure 23.7.2).
The supporting-line geometry of duality. Every maps to ; the shaded set contains these pairs and all points above and to the right of them. Evaluating the dual at pushes a line of slope up until it supports from below, and its intercept at is . (a) The clipping problem: is convex and is strictly feasible, so the optimal supporting line touches at with slope , giving . (b) Minimizing on subject to : is nonconvex, so the highest supporting line passes strictly below , leaving .
With this geometry in place, the proof of strong duality for a single inequality constraint becomes transparent.
Proof (one inequality constraint with , finite). First, is convex. Take any two points and in , contributed by and , and any . By convexity of , the midpoint satisfies , and the same inequality holds for . Hence the convex combination of and belongs to .
Second, lies on the boundary of : it is a limit of points in , whereas for every . Every boundary point of a convex set admits a supporting line: there exists a nonzero vector such that for all (Boyd and Vandenberghe (2004), section 2.5.2; this is the same geometric fact that produces subgradients in Section 23.3). Because extends indefinitely upward and to the right, we must have and .
Could ? If so, the supporting line is vertical and , forcing (and thus ) throughout . That contradicts the strictly feasible point , which contributes . Therefore . Dividing by yields for all , which means . Combined with weak duality, : the dual optimum is attained and equals .
Notice how cleanly the two hypotheses separate in the proof. Convexity is used once, to make convex so that a supporting line exists at . Slater's condition is used once, to prevent that supporting line from being vertical, which would correspond to an infinite multiplier. In panel (a) of Figure 23.7.2, for the clipping problem, a point of norm has minimum objective and constraint value , so the lower boundary of is the curve . Its slope at is , matching the optimal supporting line of slope . Panel (b) previews the nonconvex example at the end of this section: there bends the wrong way, so every line below passes strictly underneath .
23.7.2.2 Saddle Points#
Strong duality can also be restated purely in terms of the Lagrangian, without even mentioning the dual function. Observe that we can rewrite the primal problem as a min--max problem: for any ,
If violates any constraint, we can scale the corresponding multiplier to drive to ; if is feasible, the best the multipliers can do is set on every slack constraint, leaving . Consequently, , while by definition . Weak duality is simply the universal inequality , which holds for any function of two variables. Strong duality says that we can swap the order of minimization and maximization without changing the value. When both optima are attained, this swapability is equivalent to the existence of a saddle point of the Lagrangian.
Proposition (strong duality is a saddle point). Suppose strong duality holds and both optima are attained, at a primal optimum and a dual optimum . Then is a saddle point of the Lagrangian: for all , all , and all ,
Conversely, any saddle point of over and closes the duality gap, with saddle value .
Proof. By definition of and weak duality,
where the final inequality holds because and make every penalty term nonpositive. Strong duality () forces every inequality in this chain to be an equality. Equality on the left means minimizes , giving the right-hand inequality of (23.7.4). Equality on the right forces , which is complementary slackness. Hence, for any and , , giving the left-hand inequality of (23.7.4).
Conversely, if is a saddle point, then
which shows . Weak duality supplies the reverse inequality, so .
In our clipping example, the saddle point is : perturbing away from increases , while varying leaves flat because .
Strong duality brings three practical benefits:
- The dual can be simpler or smaller than the primal. The support vector machine dual has one variable per data point with simple sign constraints and at most one equality; the ridge regression dual in Exercise 8 reduces to a linear system of size equal to the number of examples rather than the feature dimension.
- Every dual point gives a stopping criterion. For any primal-feasible and any dual-feasible , the gap upper-bounds how far can be from .
- The dual solution helps recover the primal solution. By (23.7.4), is among the minimizers of . When that minimizer is unique (for instance, when is strictly convex), it immediately gives , as in the clipping problem where . When the minimizer is not unique, feasibility and complementary slackness pick out of the minimizer set. In a linear program, is flat in ; in the SVM with an unpenalized offset below, minimizing the Lagrangian leaves the offset undetermined, and complementary slackness pins it down.
The saddle-point proposition also settles the necessity of the KKT conditions, which Section 23.6.2 established as sufficient for convex problems. Suppose a convex problem with differentiable , , and on satisfies Slater's condition and attains its optimum at . Then strong duality holds with an attained dual optimum . Because minimizes over all of , its gradient vanishes there, and as we just saw, complementary slackness holds as well. Combined with primal and dual feasibility, these are precisely the four KKT conditions: under Slater's condition, they are both necessary and sufficient.
Finally, the min--max structure appears even in deep learning problems that have no explicit constraints. Generative adversarial networks (Section 16.1) and adversarial training are formulated directly as games (Goodfellow et al., 2014; Madry et al., 2018). Without a saddle point, a gap can separate their and values. Even when a saddle point does exist, taking simultaneous gradient descent steps in the minimizing variable and ascent steps in the maximizing variable can fail to converge: for the simple bilinear objective , whose saddle point is the origin, simultaneous descent--ascent spirals outward for every positive step size (Exercise 5).
23.7.3 Multipliers as Prices#
What is a constraint worth? In the clipping problem, if we slightly enlarge the unit disk, how much closer to can we get? The optimal Lagrange multiplier answers that question directly. Even better, the same sensitivity argument reveals that for a convex loss, weight decay and a norm constraint on the weights trace out the exact same family of solutions.
23.7.3.1 Shadow Prices#
To measure the value of each constraint, perturb its right-hand side and track how the optimal objective changes. For perturbation vectors and , define the perturbed optimal value
At we recover the original optimum , while taking relaxes the -th inequality constraint. We have already seen this function geometrically: for a single inequality constraint, is the lowest height that the set in Figure 23.7.2 reaches at horizontal coordinate . The lower boundary of is the graph of , and the supporting line of slope lies everywhere below it. The next proposition extends that geometric inequality to any number of constraints.
Proposition (multipliers are shadow prices). Suppose strong duality holds with dual optimum . Then for all and ,
and if is differentiable at , then and there.
Proof. Let be any point feasible for the perturbed problem, so and . Using strong duality, the definition of as an infimum, , and the perturbed constraints, we obtain
Taking the infimum over all perturbed-feasible yields (23.7.5). If is differentiable at the origin, the nonnegative function attains its global minimum of at , so its gradient must vanish there.
The optimal multiplier is called the shadow price of constraint : it measures the rate at which the optimal value improves as the constraint is relaxed. Notice that (23.7.5) is global, holding for perturbations of any size. Relaxing constraint by can lower the optimal value by at most , whereas tightening it by the same amount raises the optimal value by at least ; to first order, when is differentiable, the change is . A slack constraint has by complementary slackness, matching intuition: loosening a constraint that is not binding cannot improve the optimum.
Let us check this on the clipping problem. Relaxing to expands the disk to radius , giving —the lower boundary of we computed earlier—whose derivative at is indeed . If we relax the constraint by (a disk of radius ), the new optimum is , safely above the global lower bound guaranteed by (23.7.5).
One subtlety is worth keeping in mind: a multiplier depends on how the constraint is scaled. Here prices , which is half the squared radius, rather than the radius itself. Per unit of radius, the chain rule gives , which equals times the derivative with respect to and matches only because . Rescaling a constraint rescales its multiplier accordingly: writing without the factor of would halve the multiplier to .
The closest-point problem of Section 23.6.1.3 illustrates the equality case. There, the minimum of over the hyperplane is , and is simply (23.7.5) applied to the perturbation , which shifts the hyperplane to . That explains the increase of that we observed numerically in that section.
23.7.3.2 Weight Decay and Norm Constraints#
In deep learning, we regularly control model complexity either by adding weight decay (Section 2.7) to a training loss or by imposing a hard norm constraint on the weights. Using the book's convention, these two problems are
At a stationary point of the penalized problem, . For the constrained problem, introducing a multiplier for produces the KKT stationarity condition : the very same equation, with the weight-decay coefficient playing the role of the Lagrange multiplier.
When the loss is convex, this equivalence works in both directions. Going from penalty to constraint, let minimize the penalized objective and choose the norm budget . Then is feasible, the constraint is active (satisfying complementary slackness), and KKT stationarity holds automatically. Because the KKT conditions are sufficient for convex problems (Section 23.6.2), solves the constrained problem.
Going from constraint to penalty, take any budget . The origin is strictly feasible, so Slater's condition holds. If the constrained minimum is attained at , KKT necessity yields a multiplier , and minimizes the convex penalized objective . Whenever , the quadratic term makes this objective strictly convex, so is its unique minimizer; when the budget is slack, and the penalized problem reduces to unregularized minimization. By the shadow-price proposition, : the weight-decay coefficient is the marginal reduction in training loss per unit of half squared norm.
In fact, neither direction depends on the norm specifically. Replace by any convex penalty , such as the norm used in the lasso (Section 23.6.4.1). Any minimizer of solves the constrained problem with budget , since every within that budget satisfies . Conversely, for convex and any budget strictly above , Slater's condition holds, and the saddle-point proposition ensures that any constrained minimizer also minimizes .
Convexity of , however, is essential for the full equivalence. For a nonconvex loss, a penalized stationary point is still a KKT point of the matching constrained problem, but the global solution sets can differ, and certain norm budgets may be unattainable by any penalty weight (Exercise 6).
It is worth noting a third interpretation of the same quadratic term. For a squared loss with noise variance and an isotropic Gaussian prior on the weights, the penalty with is the negative log-prior up to a constant and overall scale (Section 24.6). Thus a single number can be read three ways: as a weight-decay coefficient, as a Lagrange multiplier for a norm budget, and as a ratio of noise to prior variance.
Let us verify this equivalence numerically. For the convex least-squares loss on random data, we solve the penalized problem in closed form via , set , and then solve the constrained problem using projected gradient descent with step size , projecting onto the -ball by clipping. Does the constrained solver recover the same weights, and does the multiplier computed from stationarity—taking the inner product of with to get —match ?
rng = np.random.default_rng()
A, b = rng.normal(size=(30, 5)), rng.normal(size=30)
grad = lambda w: A.T @ (A @ w - b) # gradient of 1/2 |Aw - b|^2
step = 1.0 / np.linalg.eigvalsh(A.T @ A).max() # 1 / lambda_max(A^T A)
print(' lambda r = |w_pen| |w_con - w_pen| recovered multiplier')
for lam in [0.1, 1.0, 10.0]:
w_pen = np.linalg.solve(A.T @ A + lam * np.eye(5), A.T @ b) # penalty form
r = np.linalg.norm(w_pen) # its norm becomes the budget
w = np.zeros(5) # constraint form: PGD
for _ in range(5000):
w -= step * grad(w)
w *= min(1.0, r / np.linalg.norm(w)) # project onto the r-ball
lam_rec = -(w @ grad(w)) / r ** 2 # KKT: grad l + lam w = 0
print(f'{lam:7.2f} {r:10.4f} {np.linalg.norm(w - w_pen):15.2e} {lam_rec:20.6f}') lambda r = |w_pen| |w_con - w_pen| recovered multiplier
0.10 0.4138 1.28e-16 0.100000
1.00 0.3860 1.58e-16 1.000000
10.00 0.2501 5.72e-17 10.000000
In every row, the constrained solution agrees with the penalized one to machine precision, and the multiplier recovered from stationarity matches to all six printed decimals (the exact budgets vary with the random draw). Penalty and constraint are simply two parameterizations of the same solution path, with the Lagrange multiplier translating between them.
23.7.4 The Convex Conjugate#
Evaluating the dual function normally requires solving a fresh unconstrained minimization for each choice of multipliers. When the constraints are linear, however, we can factor out the shared work and perform that minimization once and for all. For constraints , the Lagrangian is , so
Notice that the infimum depends on and on the single vector , not on or separately. If we compute, once for each common objective , the value of as a function of , then the dual of any linearly constrained problem with objective can be read straight off a lookup table. That lookup table is the convex conjugate.
23.7.4.1 Supporting Lines#
Start in one dimension with and pick a slope . Which lines of slope stay everywhere on or below the parabola? We need for all , meaning , attained at . The highest such line, , touches the parabola tangentially at , where . Lowering a line of slope until it touches the graph lands its vertical intercept at , and the number is minus that intercept, as shown in Figure 23.7.3(a).
The convex conjugate as a supporting line. (a) For and slope , lowering the dashed line of slope until it touches the graph lands at with intercept , giving . (b) For , a line of slope supports the graph at the origin with intercept , whereas a line of slope climbs faster than for every intercept, giving and . Thus the conjugate is finite precisely for the slopes that admit a supporting line below the graph.
The convex conjugate (also known as the Fenchel--Legendre transform) of a function records this negated intercept for every slope vector (we use an asterisk for conjugates and a star for optima):
In geometric terms, is minus the vertical intercept of the highest affine function of slope that lies everywhere below the graph of . Rather than describing by its point values, the conjugate describes by its family of supporting lines. For and any slope , the supremum is attained at , giving : the quadratic is its own conjugate.
Allowing to take the value is a convenient way to encode a restricted domain: points where never contribute to the supremum, and convexity of such an extended-valued function simply means convexity of its epigraph.
The supremum itself can also be . Take and slope . For , grows without bound: no line of slope can stay below the V-shaped graph, no matter how low its intercept. Whenever , on the other hand, with equality at , so the line of slope through the origin supports the graph. Therefore for and otherwise (Figure 23.7.3(b)). In other words, the conjugate of the absolute value is the indicator function of the interval —the function equal to inside the set and outside it.
Two immediate properties follow straight from (23.7.6). First, is always convex, regardless of whether is convex. For each fixed , the expression is affine in , and the pointwise supremum of affine functions is convex because its epigraph is the intersection of the half-spaces above them (the exact mirror image of the argument that made concave).
Second, because is the supremum over all , we have for every and . Rearranging gives the Fenchel--Young inequality,
Equality holds if and only if attains the supremum in (23.7.6). When is convex and differentiable, this happens precisely when , since is then concave and maximized where its gradient vanishes. Convexity matters here: the nonconvex double well has , yet and , because is a local maximum rather than a point where a horizontal line supports the graph from below. For the self-conjugate pair , Fenchel--Young reduces to the familiar inequality .
Does passing to the conjugate lose any information? For any convex function that is proper (never and not identically ) and closed (its epigraph is a closed set), its supporting lines determine the graph completely, and taking the conjugate a second time recovers : (Rockafellar, 1970). When is nonconvex (and bounded below by at least one affine function), is the tightest closed convex function lying below —its convex envelope (Exercise 1d).
Here are the four conjugate pairs we use in this section and its exercises:
- and , the self-conjugate pair;
- and for (attained at );
- and for , taking the value at and for (attained at , so for instance and );
- and the indicator of the box , the vector version of the absolute value above.
23.7.4.2 Duals of Linearly Constrained Problems#
Now return to the linearly constrained problem that motivated the conjugate: minimize subject to . Pulling a minus sign out of the infimum turns it directly into the supremum defining :
For equality constraints , the exact same three lines yield , with unconstrained in sign. Notice that this gives a second explanation for why is concave: is convex, its argument is linear in , and the minus sign flips convexity to concavity.
Let us try (23.7.8) on the smallest possible example: finding the point closest to the origin in a half-plane, subject to , with and . Since the origin violates the constraint (), the constraint must bind at the optimum. Plugging and into (23.7.8) gives the dual function in one step:
Setting yields and . The minimizer of the Lagrangian at is the point attaining the conjugate supremum, . Checking directly, and , so weak duality certifies that is optimal. This matches the projection formula from Section 23.6.1.3, obtained here for a different hyperplane—and where the primal had two variables, the dual had one and fell in a single line.
23.7.4.3 Log-Sum-Exp and Entropy#
Throughout deep learning, softmax converts raw scores into probabilities by exponentiating and normalizing. Why exponentials, rather than some other positive function? The conjugate of the log-sum-exp function, , gives a clean answer. Let denote the probability simplex and the Shannon entropy.
To compute , first check when the supremum can be finite. If any coordinate is negative, sending drives to while stays bounded, so the supremum is . If , shifting all coordinates by a constant gives (since ), which again blows up as . Hence is finite only on the probability simplex .
For in the interior of (all ), setting the gradient with respect to to zero gives , which is solved by (up to an additive constant), yielding the value . If lies on the boundary of with some , no finite maximizer exists because softmax outputs are always strictly positive; nevertheless, sending those coordinates approaches the same value, so the formula extends continuously to all of under the standard convention . Because is convex and finite everywhere, , giving the conjugate pair
Read the second line of (23.7.9) in words: log-sum-exp is the maximum of an expected score plus an entropy bonus over all distributions on outcomes. Which distribution achieves this maximum? By the equality condition of Fenchel--Young, it is , whose -th entry is —precisely the softmax (whose Hessian we computed in Section 23.3). Put another way, among all distributions achieving the same expected score , softmax is the one with the largest entropy, matching the maximum-entropy derivation in Section 24.4.2 (and Exercise 2 derives softmax from that constraint side). Without the entropy term, maximizing over puts all mass on ; adding entropy softens that hard selection into a smooth probability distribution. The very same conjugacy construction, applied to the convex generator of an -divergence, produces the variational bounds used to train -GANs (Section 25.3.4).
23.7.5 Worked Examples#
We now work through three examples that highlight what duality reveals in practice. In the support vector machine, complementary slackness concentrates the solution on a handful of data points, while the dual exposes the data only through inner products. In water-filling, the Lagrange multiplier carries tangible engineering units—communication rate per unit of power. Finally, a one-dimensional nonconvex problem demonstrates the strict duality gap that convexity prevents.
23.7.5.1 The Support Vector Machine Dual#
Given linearly separable training data with labels , the support vector machine (Boser et al., 1992) seeks the separating hyperplane with the widest possible margin. Its primal problem is
Because the distance from a point to the hyperplane is (Section 21.1), the two margin hyperplanes sit at distance on either side of the decision boundary, or apart. Minimizing therefore maximizes the margin. This is a convex quadratic program with one affine inequality per training point. Since the constraints are affine, Slater's condition requires only a feasible point—which we obtain by rescaling any separating until every point has margin at least . Strong duality is thus guaranteed.
Introduce one nonnegative multiplier for each constraint and form the Lagrangian,
To compute the dual function , notice first that is affine in the unpenalized offset , with coefficient . Unless that coefficient vanishes, sending drives to , so whenever . Here we see the effective domain of (23.7.2) in action: the finiteness condition becomes an explicit equality constraint in the dual. On this domain the -term disappears, leaving a strictly convex quadratic in whose unique minimum occurs where :
Thus the optimal weight vector is a linear combination of the training inputs, weighted by their multipliers. Substituting this expression back into yields the SVM dual:
Two striking consequences follow before we even choose a solver. First, complementary slackness, , tells us that any point with must satisfy , lying right on one of the margin hyperplanes. These points are the support vectors. In Figure 23.7.4 they can only be among the four ringed points. Their constraints are active and their normals balance , as in Figure 23.6.2, whereas every point with drops out of completely. Second, the training inputs enter (23.7.11) exclusively through inner products . Replacing those inner products with a kernel function immediately yields a nonlinear classifier—a structure the primal formulation hides.
Maximum-margin separation of the eight points that the code cell below uses. The solid line is the decision boundary with and . The dashed lines are the margin hyperplanes , a distance apart. Only the four ringed points, which lie on a margin hyperplane, can carry .
Notice that the equality constraint arose solely because the unpenalized offset left the Lagrangian affine in one direction. To keep the dual feasible set as simple as the nonnegative orthant (where projection just clips negative entries to zero), we solve a closely related variant in code by folding the offset into the weights: augment each input with a constant feature , set , and minimize subject to . Because this variant penalizes as well, its decision boundary can differ slightly from (23.7.10); in return, its Lagrangian is strictly convex in every primal variable, eliminating the equality constraint. Defining , the dual becomes
a concave quadratic over the nonnegative orthant. Applying projected gradient ascent—the update of Section 23.6.3 with the step sign flipped—iterates using the safe step size . Let us run this ascent on eight points in the plane and check three predictions: does the recovered hyperplane separate the data, do all positive multipliers sit on points of margin , and does the dual value match the primal value?
X = np.array([[1.0, 1.5], [2.0, 0.5], [2.5, 2.0], [1.5, 3.0],
[-1.0, -0.5], [-2.0, 1.0], [-1.5, -2.0], [0.5, -1.5]])
y = np.array([1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0])
Xa = np.hstack([X, np.ones((len(X), 1))]) # fold the offset b into w
G = y[:, None] * Xa # rows y_i x~_i
Q = G @ G.T # Q_ij = y_i y_j x~_i^T x~_j
alpha = np.zeros(len(X))
eta = 1.0 / np.linalg.eigvalsh(Q).max() # 1 / lambda_max(Q)
for _ in range(5000): # projected gradient ascent
alpha = np.maximum(0.0, alpha + eta * (1.0 - Q @ alpha))
w = G.T @ alpha # w~* = sum_i alpha_i y_i x~_i
margins = y * (Xa @ w)
dual, primal = alpha.sum() - 0.5 * alpha @ Q @ alpha, 0.5 * w @ w
print('alpha* =', alpha.round(4))
print('rank of Q =', np.linalg.matrix_rank(Q), ' multipliers > 0:', int((alpha > 1e-8).sum()))
print('w* =', w[:2].round(4), ' b* =', w[2].round(4),
' separates data:', bool((np.sign(Xa @ w) == y).all()))
print('margins y_i (w^T x_i + b) =', margins.round(4))
print(f'primal = {primal:.6f}, dual = {dual:.6f}, gap = {abs(primal - dual):.1e}, '
f'comp. slack = {np.abs(alpha * (margins - 1.0)).max():.1e}')
alpha* = [0.1309 0.0732 0. 0. 0. 0.2442 0. 0.3885]
rank of Q = 3 multipliers > 0: 4
w* = [0.5714 0.5714] b* = -0.4286 separates data: True
margins y_i (w^T x_i + b) = [1. 1. 2.1429 2.1429 1.2857 1. 2.4286 1. ]
primal = 0.418367, dual = 0.418367, gap = 4.4e-16, comp. slack = 3.0e-16
All three predictions hold. Four multipliers are positive, and precisely those four points sit at margin ; the other four have margins between and with . The printed digits match the exact solution —that is, and —with and a duality gap near . (The equality of the primal and dual values also follows directly from the identity at the optimum; see Exercise 4a.)
The printout also highlights a subtle point about interpreting dual solutions. Because the primal objective is strictly convex, the primal optimum is unique. The dual optimum is not. Here , where is the matrix with rows , so has rank at most . Because the four support vectors correspond to four vectors in , they are linearly dependent: there exists a nonzero vector supported on those four indices with . Moving along leaves the quadratic term unchanged (since ) and leaves the linear term unchanged as well, because every support vector has margin : . Thus an entire line segment of multiplier vectors is optimal, all yielding the same and the same dual value; projected ascent from simply returns one point on that segment. At each endpoint of the segment, one of the four margin- points actually has (Exercise 4c). Remember that complementary slackness runs in one direction: guarantees margin , but margin does not force .
23.7.5.2 Water-Filling#
Our second worked example has both a closed-form solution and an unforgettable physical picture. Suppose a transmitter must divide a total power budget across independent communication channels. Channel has background noise power , and allocating power to it yields a transmission rate of nats per use (Cover and Thomas, 1999). (Cover and Thomas include a factor of for a real Gaussian channel, which rescales the Lagrange multiplier below without changing the optimal allocation.) To maximize the total rate, we solve
Maximizing the concave function is equivalent to minimizing the convex function under affine constraints. Because a strictly positive feasible allocation exists, Slater's condition holds, and the KKT conditions are both necessary and sufficient. Introducing a multiplier for the budget equality and multipliers for the nonnegativity constraints , stationarity of the Lagrangian of reads
Now read off the two cases. Whenever channel receives positive power (), complementary slackness forces , so : every active channel ends up at the exact same total level . Whenever channel receives no power (), dual feasibility requires . Writing for this common threshold, the optimal allocation takes the compact form
This is the classic water-filling rule. Imagine each channel as a basin whose floor sits at height , and pour a volume of water into the collection of basins. As Figure 23.7.5 illustrates, the water settles to a uniform surface level , pouring the most power into the quietest channels and leaving any basin whose floor exceeds completely dry. Because is continuous, piecewise linear, zero for , and strictly increasing for , any budget determines a unique water level , which bisection finds effortlessly. (The simplex projection in Section 23.6.3 has the same threshold structure inverted: subtract a common level from each coordinate and clip at zero.)
Water-filling for the noise floors and budget in the code cell below: pouring units of power into basins with floors at fills the three quietest channels to the common level , allocating to each, while the two basins with floors above receive nothing, as complementary slackness requires.
The shadow-price proposition gives an immediate engineering meaning. Since maximizing is minimizing , relaxing the budget from to changes at rate , so : the optimal multiplier is the extra communication rate gained per unit of additional power. Let us compute the water-filling allocation for five channels and check this shadow-price prediction against finite differences at .
N = np.array([0.1, 0.4, 0.8, 1.6, 2.5]) # channel noise levels
P = 3.0 # total power budget
def water_fill(P, N, steps=60):
lo, hi = N.min(), N.min() + P # bracket for the water level
for _ in range(steps): # bisection on the level theta
mid = 0.5 * (lo + hi)
lo, hi = (mid, hi) if np.maximum(0, mid - N).sum() < P else (lo, mid)
theta = 0.5 * (lo + hi)
return theta, np.maximum(0.0, theta - N)
theta, power = water_fill(P, N)
print('water level theta =', f'{theta:.6f}', ' P* =', power.round(4),
' total =', f'{power.sum():.6f}')
print('wet channels at the common level:', (N + power)[power > 0].round(6))
print('dry channels above the level: ', bool((N[power == 0] >= theta).all()))
rate = lambda power: np.log(1.0 + power / N).sum()
dP = 1e-4 # shadow price, two ways
nu = 1.0 / theta
sens = (rate(water_fill(P + dP, N)[1]) - rate(water_fill(P - dP, N)[1])) / (2 * dP)
print(f'nu = 1/theta = {nu:.6f} vs finite-difference dU*/dP = {sens:.6f}')
water level theta = 1.433333 P* = [1.3333 1.0333 0.6333 0. 0. ] total = 3.000000
wet channels at the common level: [1.433333 1.433333 1.433333]
dry channels above the level: True
nu = 1/theta = 0.697674 vs finite-difference dU*/dP = 0.697674
The power budget is met to machine precision, the three active channels all sit at the common level , and the noisy channels at and stay dry, just as dual feasibility requires. Moreover, the multiplier matches the finite-difference sensitivity to all six printed digits.
23.7.5.3 An Explicit Duality Gap#
Weak duality holds for every problem, but strong duality does not. A one-dimensional nonconvex example makes the gap concrete. Over the domain , consider
Because is concave rather than convex, the problem is nonconvex. The feasible set is , and the minimum sits at the right endpoint, . We dualize only the constraint , keeping as a hard domain constraint so that the infimum in (23.7.2) runs over (weak duality applies unchanged). For any , the Lagrangian is concave in , so its minimum on must occur at one of the two endpoints: or . Therefore,
which is piecewise linear and concave, as guaranteed. The two lines intersect at , where : a strict duality gap of . Let us plot alongside to compare this nonconvex dual curve with the clipping plot from the start of the section.
xs = np.linspace(0.0, 1.0, 4001) # the domain D = [0, 1]
fx, gx = -xs**2, xs - 0.5 # objective and constraint on D
p_star = fx[gx <= 0.0].min() # primal optimum: -1/4
lams = np.linspace(0.0, 3.0, 601)
q = np.array([(fx + lam * gx).min() for lam in lams]) # dual function on D
d_star, lam_star = q.max(), lams[q.argmax()]
print(f'p* = {p_star:.4f}, d* = {d_star:.4f} at lambda = {lam_star:.2f},'
f' gap = {p_star - d_star:.4f}')
d2l.plot(lams, [q, np.full_like(lams, p_star)], 'lambda', 'value',
legend=['dual function q(lambda)', 'primal optimum p*'])p* = -0.2500, d* = -0.5000 at lambda = 1.00, gap = 0.2500
Unlike the clipping curve, which rose smoothly to touch , this tent peaks at , a full quarter below the primal optimum. Notice that a strictly feasible point certainly exists— lies in the interior of with —so the gap is caused entirely by the lack of convexity, not by a failure of Slater's condition. Returning to panel (b) of Figure 23.7.2, the image curve bends downward, so no supporting line below can reach ; the highest one, of slope , certifies only .
Two open challenges remain. First, for a nonconvex problem, the dual can bound the optimum but need not reach it. Second, even when a saddle point exists, updating and simultaneously can fail to converge, a central difficulty in minimax training. While training an entire deep network is nonconvex, many of its building blocks (projections, clipped updates, last-layer fits, and convex trust-region subproblems) are convex, and everything in this section applies directly to them. So far, however, every derivation in this chapter has assumed exact real arithmetic; in the next section we turn to what happens when finite floating-point precision, rather than the optimization algorithm itself, determines the answer.
23.7.6 Summary#
For any constrained optimization problem, the Lagrange dual function is concave and satisfies weak duality, , so every choice of certifies a lower bound on the primal optimum. When the primal problem is convex and satisfies Slater's condition (a strictly feasible point for all non-affine inequalities), strong duality closes the gap () and attained primal--dual optima form a saddle point of the Lagrangian. For linear constraints, the dual reduces to the convex conjugate, , which turns conjugate pairs such as log-sum-exp and negative entropy directly into dual formulations. Under strong duality, the optimal multipliers act as shadow prices ( and wherever is differentiable), explaining why weight decay matches a norm constraint for convex losses, why SVM multipliers vanish off the support vectors, and why the water-filling multiplier measures communication rate per unit of power. Without convexity, a strict duality gap can remain, as shown by minimizing on subject to .
23.7.7 Exercises#
-
Conjugate pairs. Compute each conjugate from (23.7.6).
- with .
- with . What does the Fenchel--Young inequality (23.7.7) state for this pair?
- The softplus on . The binary cross-entropy of a logit against a soft label is . Use Fenchel--Young to show that it is at least the binary entropy , with equality exactly when , the sigmoid of . Write the difference as a KL divergence.
- The double well of Section 23.3.4 (the function there without its tilt ) is not convex. Find its convex envelope and the set on which .
Adapted from Boyd and Vandenberghe, Convex Optimization, Examples 3.22 and 3.26.
-
Maximum entropy and temperature. The entropy of a probability vector is . This exercise derives the softmax from the constraint side.
- Maximize subject to with one Lagrange multiplier, ignoring the sign constraints . Show that the only stationary point is the uniform distribution. Why does ignoring the sign constraints not change the answer?
- Fix scores , not all equal, and a target strictly between and , and add the constraint . Show that the maximizer is for a scalar determined by the multiplier of the score constraint. Show that the mean score under increases strictly with , so that exactly one meets the target.
- Let be the maximal entropy. Show that , so that the multiplier prices the score constraint as the multiplier of Section 23.6.1.3 prices the offset . For which targets is negative? What happens to the softmax temperature as approaches ?
-
A dual certificate for minimization. Basis pursuit,
with and , selects a sparse solution of an underdetermined linear system. Its constraints are affine, so Slater's condition needs only a feasible point and gives whenever the system has a solution. The conjugate of is the indicator of the box .
-
Use the equality form of (23.7.8) to show that, after replacing by , the dual problem is subject to .
-
Solve both problems by hand for and , and check .
-
Let and be optimal. Show that wherever , and that wherever . A candidate with is given. Which conditions must a vector satisfy to certify that is optimal without solving the problem?
-
Support vectors and the dual value. For the offset-folded SVM dual (23.7.12), let be optimal and .
- Show that by writing the KKT conditions of the dual over the orthant. Conclude that the dual optimal value equals the primal value .
- Show that deleting a training point with leaves the remaining multipliers optimal for the smaller problem and leaves unchanged. In leave-one-out validation, each of the points is classified by the SVM trained on the other points. Conclude that the leave-one-out error rate is at most the fraction of points with , for every optimal . Which optimal gives the best bound?
- [code] The matrix of the SVM cell has rank . Let
be the four indices with and the
corresponding rows of
G. Find a nonzero with (usenp.linalg.svdof ), and move in each direction until a coordinate reaches zero. Verify that both endpoints are dual feasible, have dual value , and give the same . Which margin- point has at each endpoint? What does this say about reading "support vector" off the multipliers? (You should find the endpoints and .)
-
[code] Gradient descent--ascent. ● Primal--dual methods and GAN training update the minimizing variable by gradient descent and the maximizing variable by gradient ascent at the same time.
- For the bilinear game , whose saddle point is the origin, write simultaneous descent--ascent, and , as a linear map. Show that every nonzero start spirals away from the saddle for every . Show that the alternating version, in which the -update uses the new , is a linear map with determinant . What do its iterates do for ?
- Run simultaneous descent--ascent on the Lagrangian of the closest-point problem of Section 23.6.1.3, here with , , and the start , . Find the step sizes for which the iterates converge to . Derive them from the eigenvalues of the update acting on the pair and on the components of orthogonal to .
- Add with to the objective of the bilinear game. For which step sizes does simultaneous descent--ascent converge now? Which term of the Lagrangian of the previous part plays the role of ?
-
[code] Penalty versus constraint without convexity. ● For a convex loss, Section 23.7.3.2 shows that weight decay and a norm constraint trace the same solutions. Take instead the nonconvex one-dimensional loss , whose local minima lie near and .
- On a fine grid of , compute the penalized minimizers for on a logarithmic grid, and the constrained optimum for . Plot the points on top of the curve . Which budgets are never the norm of a penalized minimizer?
- Show that minimizes if and only if the line of slope through lies below every point of the set . Use this and the supporting-line picture of Figure 23.7.2 to explain the missing budgets.
- Pick a budget in the missing range at which the constraint is active. Compute the KKT multiplier of the constrained solution, with the constraint written as in the text, and find a point where the penalized objective with this is lower. Compute the duality gap of the constrained problem.
-
[extended] Entropic optimal transport. ●● Given probability vectors and and a cost matrix , optimal transport finds the cheapest plan that moves the mass to the mass ,
a linear program with variables. Entropic regularization (Cuturi, 2013) adds to the objective, with ; let be the regularized optimum. Its solution by Sinkhorn iterations is used to compare distributions (Peyré and Cuturi, 2019).
- Form the Lagrangian with the terms for the marginal constraints. Show that with , , and . Why can the sign constraints be left out of the Lagrangian?
- Show that the dual function is
and that maximizing it exactly over with fixed gives the Sinkhorn update , elementwise. Conclude that Sinkhorn's algorithm is block-coordinate ascent on a concave function and that its dual value never decreases. Why is every dual value a lower bound on ?
- Let , and grant that every feasible plan satisfies . Show that .
- Let the costs lie in . In float64, rounds to zero for above about . For which can entries of vanish, and what then happens to the multiplicative updates ? Explain why updating and directly, with a log-sum-exp in place of the products with , avoids the problem.
- [code] The dual of ridge regression. Write
,
with , as
subject to ,
with multiplier .
- Minimize the Lagrangian over and to get , , and the dual function . Why does strong duality hold?
- Maximize to get and . Explain why the solution is a combination of the rows of , as the SVM weight vector is a combination of the data points, and why the data enter only through .
- For examples and features, verify numerically that the primal solve and the dual formula agree to about , and that the primal and dual values coincide. Which solve is cheaper when ? What does replacing by a kernel matrix give?