23.6 Constrained Optimization
Up to this point, every parameter we optimized was free to take any real value, so finding a minimum meant hunting for a point where the gradient vanishes. Many quantities in deep learning do not have that freedom. Attention weights must be nonnegative and sum to one, gradient clipping caps the norm of an update at a threshold, a norm budget restricts the size of a weight vector, and a support vector machine requires every training margin to be at least one. When the variables must stay inside a feasible set, the gradient rarely vanishes at the optimum, and the zero-gradient test of the earlier sections breaks down. How do we recognize an optimal point under constraints, and how do we compute it?
Gradient clipping offers the simplest concrete example. Suppose we want to clip the vector so that its norm is at most . Rescaling it to unit length returns , which is the point of the unit disk closest to . In other words, minimizes the squared distance over the disk , reaching the optimal value . Yet the gradient there is , nowhere near zero. What makes optimal is that no allowed direction lowers : every move that keeps either increases or leaves it unchanged to first order. To handle problems like this, we need both a replacement for the zero-gradient condition and a replacement for plain gradient descent, which on its own would step right out of the feasible set.
The replacement for "the gradient is zero" introduces one scalar per constraint, called its multiplier, which measures how hard the optimum presses against that constraint. At the boundary pushes back with strength along the outward normal, so that . Multipliers give us the first-order optimality conditions: Lagrange's condition for equality constraints, and the Karush--Kuhn--Tucker (KKT) conditions for inequalities. Meanwhile, the projection that mapped to suggests a direct algorithm: take an ordinary gradient step, then project back to the nearest feasible point. And when a hard boundary is replaced by a kinked penalty, such as the absolute-value penalty that the lasso places on each weight, the projection generalizes to a proximal step, which drives small weights to exact zeros. Throughout the section, convexity (Section 23.3) is what turns these conditions into guarantees of global optimality and ensures that our algorithms converge.
Three ideas carry the section: the KKT conditions and their sufficiency for convex problems, the obtuse-angle inequality that characterizes a projection, and soft-thresholding.
23.6.1 Equality Constraints and Lagrange Multipliers#
23.6.1.1 Tangency and the Lagrange Condition#
Equality constraints are simpler than inequalities, so let us start by replacing the solid disk of the clipping example with its boundary: minimize with over the unit circle, written as . More generally, we want to minimize a differentiable objective subject to a single equality constraint,
Because the feasible set is a surface (a curve in two dimensions) rather than a full-dimensional region, every feasible move must stay on that surface.
Figure 23.6.1 illustrates the geometric signature of an optimum. Suppose we stand at a feasible point where a level set of crosses the circle. Then has a nonzero component along the circle, so sliding along the circle opposite that component reduces without leaving the feasible set. Such a point cannot be optimal. An optimum can occur only where the level set is tangent to the circle, so that every move along the circle leaves unchanged to first order. Since tangent curves share parallel normal vectors, must be a scalar multiple of at the optimum.
Minimizing with on the unit circle . Where a level set crosses the circle, has a component along the constraint, giving a feasible descent direction. At the level set is tangent to the circle and . The antipode also satisfies the tangency condition, with , and is the maximum.
Proposition (Lagrange condition). Let be a local minimum of on . Assume that is differentiable at , that is continuously differentiable near , and that . Then there exists a unique scalar , the Lagrange multiplier, such that
In words, the gradient of the objective is balanced by a multiple of the constraint's normal vector. This is the same Lagrange condition proved in Section 22.2.4, where the constraint is written as and the condition as . Setting and reconciles the two forms; we use the plus sign here because it matches the sign of the Lagrangian introduced next.
Checking the tangent point in Figure 23.6.1, we have and . The two vectors are indeed parallel, with , which gives .
The assumption is our first example of a constraint qualification, and it is essential rather than a technicality. Consider minimizing subject to . The feasible set consists of the single point , which is automatically the minimum. Yet while , so no multiplier can satisfy (23.6.1). Because the feasible set has collapsed to a single point with no tangent directions, the tangency argument has nothing to grab onto.
23.6.1.2 The Lagrangian#
Notice that we have two unknowns, and , and two requirements: parallel gradients and feasibility. Both requirements can be packaged into the stationarity of a single function of , called the Lagrangian, which adds the constraint weighted by its multiplier to the objective:
Setting all partial derivatives of to zero yields
recovering (23.6.1) and the equality constraint together. In this way, a constrained optimization problem in becomes an unconstrained stationarity problem in .
Let us solve the unit-circle problem using the Lagrangian. Stationarity with respect to gives , so must lie on the line through the origin and . Enforcing feasibility, , then requires , which produces two solutions:
- : , at distance from , with ;
- : , at distance from , with .
The second solution is the point on the circle farthest from . This highlights an important caveat: the Lagrange condition is necessary, not sufficient, because it holds at every stationary point of along the surface, including maxima and saddles. Here the sign of the multiplier distinguishes the minimum from the maximum. When we move to inequality constraints in the next section, the KKT conditions will turn that sign into a general rule.
When there are multiple equality constraints for , each constraint receives its own multiplier and the Lagrangian becomes . Provided that the constraint gradients are linearly independent, the same reasoning shows that lies in the span of the constraint normals—that is, the objective gradient is balanced by a linear combination of the constraint gradients.
23.6.1.3 The Closest Point on a Hyperplane#
The simplest constrained problem with a linear constraint asks for the point on a hyperplane closest to the origin: minimize subject to . Setting the gradient of to zero gives , so the closest point must lie along the normal vector . Substituting into the constraint yields , which fixes . The solution and optimal value are therefore
Geometrically, the nearest point sits at distance along the unit normal , matching the projection formula of Section 21.1.
For and , we land on once again, this time with and : the line is tangent to the unit circle at . Notice that the multiplier is more than an algebraic helper. If we nudge from to , pushing the line slightly farther from the origin, the optimal value rises by about . As Section 23.7.3 will show in full generality, this is what a multiplier always measures: the sensitivity of the optimal value to shifting its constraint.
23.6.2 Inequality Constraints and the KKT Conditions#
23.6.2.1 Active and Inactive Constraints#
Most constraints in machine learning are one-sided: a norm must be at most , a probability at least , or a resource budget not exceeded. We write inequality constraints in the standard form
so that each is negative strictly inside its region and zero along its boundary. At a solution , every inequality falls into one of two regimes. If , the constraint is inactive: the solution lies strictly inside the region, so locally the constraint has no effect. If , the constraint is active: the solution sits right on the boundary, where the inequality acts like an equality.
Gradient clipping illustrates both regimes cleanly. Suppose we project a vector onto the Euclidean ball of radius by minimizing subject to . Introducing a multiplier , stationarity of yields , so is always a radial rescaling of . Which regime applies depends on :
- If , then is already feasible and minimizes outright. The constraint is inactive, , and ; for example, with stays untouched.
- If , no interior point can be optimal, because any interior minimum would have to be an unconstrained minimum of , and the only unconstrained minimum is the infeasible point . The constraint must therefore be active, and forces . For and , we get , , and .
Both cases collapse into a single formula,
which leaves short vectors alone and rescales long ones to norm . Applied to
a gradient vector, this is gradient clipping
(Pascanu et al., 2013). In code, the case split becomes a single
max, and we can check directly that at the clipped point the gradient of
is cancelled by times the constraint gradient
.
y, r = np.array([3.0, 4.0]), 1.0
lam = max(np.linalg.norm(y) / r - 1, 0.0) # multiplier: 0 if y is inside the ball
x = y / (1 + lam) # x* = y / max(1, |y|/r)
print('x* =', x, ' lambda* =', lam, ' f(x*) =', 0.5 * ((x - y)**2).sum())
print('grad f(x*) =', x - y, ' lambda* grad g(x*) =', lam * x,
' sum =', (x - y) + lam * x)
x* = [0.6 0.8] lambda* = 4.0 f(x*) = 8.0
grad f(x*) = [-2.4 -3.2] lambda* grad g(x*) = [2.4 3.2] sum = [0. 0.]
Stationarity holds even though is far from zero: the objective gradient and the boundary's push sum to zero, with the multiplier giving the ratio of their lengths.
Notice the geometric meaning of the multiplier's sign. Because increases as we leave the ball, its gradient points outward. Stationarity written as with says that the downhill direction pulls outward, while the boundary wall pushes back. If pointed inward instead, we could step into the interior of the ball to lower , so the point could not be optimal. A negative multiplier is therefore ruled out: would select the far point on the circle, which is a maximum rather than a minimum over the disk. Unlike an equality constraint, an inequality wall pushes in only one direction.
23.6.2.2 The Karush--Kuhn--Tucker Conditions#
Combining inequality and equality constraints gives the general optimization problem
Its Lagrangian assigns one multiplier to each constraint, with the inequality multipliers required to be nonnegative:
At any local minimum where a constraint qualification holds (we specify which ones in the next subsection), there exist multipliers satisfying the four Karush--Kuhn--Tucker (KKT) conditions (Karush, 1939; Kuhn and Tucker, 1951):
We have already seen the first three conditions in our examples: a balance of gradients, satisfaction of the constraints themselves, and the one-way sign restriction on inequality multipliers. The fourth, complementary slackness, states that for each at least one of and must vanish. Consequently, every inactive constraint () automatically gets and drops out of the stationarity equation. Keep in mind a subtle asymmetry: a positive multiplier guarantees that a constraint is active, but an active constraint can still have if it happens to touch without exerting any force. In the ball-projection example, complementary slackness encodes the exact case split we carried out by hand, and at we have .
Figure 23.6.2 shows the geometry of stationarity and dual feasibility together. At the optimum, the descent direction must be a nonnegative linear combination of the outward normals of the active constraints. Equivalently, lies inside the cone spanned by those outward normals (the normal cone), while inactive constraints contribute nothing.
Geometry of the KKT conditions on a feasible region defined by two inequality constraints. In (a), one constraint is active at and the other is inactive: aligns with the active outward normal with , while . In (b), both constraints are active at a corner, so must lie in the shaded normal cone spanned by both outward normals. Orange arcs show level sets of around its unconstrained minimizer (+).
Like the Lagrange condition, the KKT conditions are first-order conditions and are not sufficient on their own. Consider minimizing on , written as and . At , the gradient vanishes, both constraints are inactive, and setting both multipliers to zero satisfies all four KKT conditions—yet is the maximum. The true minima are KKT points too, each with multiplier on its active boundary constraint.
23.6.2.3 Constraint Qualifications and Sufficiency#
This leaves two complementary questions. First, when is a local minimum guaranteed to satisfy the KKT conditions? Second, when is a KKT point guaranteed to be a minimum?
For the first question, the answer parallels the equality case: a minimum must satisfy the KKT conditions whenever a constraint qualification holds. The most common general condition is the linear independence constraint qualification (LICQ). Suppose is a local minimum of (23.6.3) with , , and continuously differentiable. If the gradients of all active inequality constraints together with the gradients of all equality constraints, , are linearly independent, then multipliers satisfying (23.6.5) are guaranteed to exist (Nocedal and Wright (2006), chapter 12). LICQ directly generalizes , and Exercise 1 illustrates what can go wrong when it fails.
For convex problems, there is a much simpler check that requires finding only a single feasible point rather than inspecting gradients at the unknown solution. Call problem (23.6.3) convex when and every are convex and every is affine. A convex problem satisfies Slater's condition (Slater, 1950) if there exists a point such that
In plain terms, must be feasible and lie strictly inside every curved inequality constraint; if all constraints are affine, then mere feasibility already satisfies Slater's condition. (When or some is defined only on a subset of , which will not occur here, must also lie in the relative interior of that domain.) For the Euclidean ball, immediately works because . Whenever Slater's condition holds for a convex problem with differentiable and , every minimum is a KKT point (Boyd and Vandenberghe, 2004). The deeper reason is strong duality, which Section 23.7.2 derives from the very same condition.
Convexity also settles the second question, giving the single most useful result of this section.
Proposition (KKT sufficiency under convexity). In problem (23.6.3), let and every be convex and differentiable and every affine. If satisfies the KKT conditions (23.6.5), then is a global minimum.
Proof. Define . Because , is a nonnegative combination of convex functions plus affine terms, so is convex. Stationarity says , which means is a global minimizer of over all of . Now pick any feasible . Since , , and , we have
where the final equality follows from complementary slackness () and primal feasibility ().
Notice a broader principle tucked inside this short proof. For any fixed multipliers with , the first inequality holds for every feasible , so minimizing the Lagrangian over always yields a lower bound on the constrained optimum; at the KKT multipliers, that lower bound is exact. Section 23.7 builds the entire theory of duality from this observation. For convex problems, then, the KKT conditions are always sufficient—and under Slater's condition they are necessary as well, characterizing the global minima completely.
23.6.3 Projections and Projected Gradient Descent#
The KKT conditions tell us how to recognize an optimum, and for simple constraints they let us solve for one by hand. To compute solutions more generally, we pair gradient descent with the nearest-feasible-point operation: take a standard gradient step, and whenever it leaves the feasible set, project it right back in.
23.6.3.1 Projection onto a Convex Set#
For a nonempty closed convex set , the projection of a point onto is the unique point of closest to ,
Why does a unique minimizer always exist? Because we can intersect with a large closed ball centered at without excluding the optimum; that intersection is closed and bounded (hence compact), so the continuous objective attains its minimum there. Strict convexity of the squared distance then rules out ties, making a well-defined map.
We have already computed two projections in closed form: onto a hyperplane (the closest-point problem) and onto a ball (the clipping formula). Projection onto a half-space follows immediately from the hyperplane formula. If already satisfies the inequality, we leave it alone; if it violates it, we move straight along onto the boundary hyperplane:
Projections onto closed convex sets obey a remarkably clean geometric characterization. Let be the minimizer of over . For any other point , convexity guarantees that the entire line segment from to stays inside . Moving from toward therefore cannot decrease the objective to first order, so its directional derivative is nonnegative: . Flipping the sign gives the obtuse-angle inequality (or variational inequality):
Geometrically, the residual vector forms an angle of at least with the vector from to every point (Figure 23.6.3, panel (a)). Put differently, the hyperplane through with normal is a supporting hyperplane of , keeping the entire set on its far side.
(a) The residual makes an angle of at least with every direction into , so lies entirely on the far side of the supporting line through . (b) Projection onto a closed convex set never increases distances: .
Let us check this inequality on our running example. For projected onto the unit disk, the residual is —once again, the multiplier times the outward normal. For any with ,
where the first inequality uses Cauchy--Schwarz, . The supporting line here is , the very hyperplane from our closest-point example.
Just as importantly, the obtuse-angle inequality is also sufficient. Suppose some point satisfies (23.6.7), and write , whose gradient at is . Because a convex differentiable function always lies above its tangent planes (Section 23.3), we have . The last term is nonnegative for every by assumption, so across all of , proving that . Thus (23.6.7) completely characterizes the projection. Every property we need for projected algorithms flows directly from it, beginning with the fact that projections never stretch distances.
Proposition (projections are nonexpansive). For a nonempty closed convex set and all ,
Proof. Set and . Applying (23.6.7) twice—first at with , then at with —gives
Adding these two inequalities yields , which rearranges to
by Cauchy--Schwarz. Dividing by finishes the proof (and when the claim is trivial).
Panel (b) of Figure 23.6.3 depicts this visually: two points outside the disk are always at least as far apart as their projections. Convexity of is essential here. Take the nonconvex two-point set : then projects to while projects to , turning an input gap of into an output gap of —and at the projection is not even unique. Projecting onto a nonconvex set can be both discontinuous and multivalued.
23.6.3.2 Projected Gradient Descent#
Projected gradient descent (PGD) turns projection into an iterative solver by projecting after every gradient step:
Every iterate stays feasible by construction. Better yet, the fixed points of PGD are precisely the constrained stationary points. For any differentiable , closed convex , and step size , the fixed-point equation holds if and only if satisfies the obtuse-angle inequality (23.6.7) with . Cancelling and dividing by turns that inequality into
In plain words, no feasible direction is a descent direction. This is the general constrained first-order condition, reducing to when . When is convex, the tangent-plane inequality immediately makes this condition sufficient for a global minimum; when is nonconvex, it certifies stationarity. And when for differentiable convex satisfying Slater's condition, it is equivalent to the KKT conditions.
Does the extra projection step slow gradient descent down? Remarkably, no—and nonexpansiveness gives a three-line proof.
Proposition (PGD contracts at least as fast as GD). Let be nonempty, closed, and convex, let be twice continuously differentiable with for some , let be the minimizer of over , and let . Then the iterates of (23.6.8) satisfy
Proof. (i) Because is a fixed point of PGD, we can write with . (ii) That choice of is the key step: applying nonexpansiveness to and strips away the projection altogether,
(iii) By the fundamental theorem of calculus along the segment joining to , we have , where . This averaged Hessian is symmetric with all eigenvalues in , so every eigenvalue of has the form with and magnitude at most . The right-hand side is therefore at most .
Once step (ii) removes the projection, all that remains is the contraction of unconstrained gradient descent. For a quadratic , we have , and step (iii) recovers the exact per-mode factor from Section 23.1, which is strictly less than whenever . For a convex -smooth that is not strongly convex, PGD with likewise preserves gradient descent's objective-value rate (Nesterov, 2018).
Let us test how tight the contraction factor is in practice. Consider the ill-conditioned quadratic with condition number , minimized over the half-space (written ). We can solve the KKT conditions by hand: the unconstrained minimizer is infeasible, so the constraint must be active. Stationarity, , gives and , and plugging these into yields , , and .
Now run PGD with step size , safely below the stability limit . The proposition guarantees a per-step factor of . Starting from at distance from , that bound predicts up to steps to reach distance . The code below runs PGD and inspects the worst single-step ratio, the actual step count, the moment when every step begins hitting the boundary, the contraction ratio along the boundary, and the final gradient.
A = np.diag([1.0, 1000.0]) # f(x) = 1/2 x^T A x, kappa = 1000
x_star = np.array([1000 / 1001, 1 / 1001]) # KKT point of x1 + x2 >= 1
project = lambda y: y + max(0.0, 1 - y.sum()) / 2 # onto the half-space x1 + x2 >= 1
eta = 1.5e-3
rho = max(abs(1 - eta), abs(1 - 1000 * eta)) # the GD contraction factor
x, dist, projected = np.array([3.0, 4.0]), [], []
for k in range(1000):
y = x - eta * A @ x
projected.append(y.sum() < 1) # did the step leave C?
x = project(y)
dist.append(np.linalg.norm(x - x_star))
dist, projected = np.array(dist), np.array(projected)
ratios = dist[1:] / dist[:-1]
steps = np.argmax(dist < 1e-6) + 1
on_line = np.flatnonzero(~projected).max() + 2 # every step from here on is projected
print(f'bound rho = {rho:.4f} largest ratio in a step = '
f'{ratios[dist[:-1] > 1e-12].max():.4f}')
print(f'steps to |x - x*| < 1e-6: {steps} every step projected from step {on_line} on')
print(f'ratio per step on the line: {np.median(ratios[on_line:steps - 1]):.4f}'
f' 1 - 500.5 eta = {1 - 500.5 * eta:.4f}')
print(f'grad f at the end = {A @ x}')
bound rho = 0.9985 largest ratio in a step = 0.9977
steps to |x - x*| < 1e-6: 738 every step projected from step 733 on
ratio per step on the line: 0.2492 1 - 500.5 eta = 0.2492
grad f at the end = [0.999001 0.999001]
The largest single-step ratio, , comes close to , so the worst-case per-step bound is nearly tight. The total step count, however, is a pleasant surprise: steps instead of . The printed diagnostics reveal why—the trajectory unfolds in two distinct phases. During the first phase, the constraint is inactive after the initial step: the stiff coordinate collapses within a few dozen iterations, while the flat coordinate creeps inward by the factor per step, just as in unconstrained gradient descent. Reaching the boundary line from takes roughly steps. From step onward, every update hits the boundary and is projected onto the line . Along that line, the quadratic has curvature , so the distance to shrinks by per step—the exact rate of one-dimensional gradient descent along the line—and just a handful of additional steps finish the run. While must guard against the worst curvature anywhere in the plane, once the constraint becomes active only the curvature along the boundary matters. Finally, notice the gradient at termination: . Far from vanishing, it hands us back the multiplier we derived by hand.
PGD is a workhorse whenever is inexpensive to compute. Nonnegativity constraints project onto the nonnegative orthant simply by zeroing negative entries, and max-norm constraints on the rows of a weight matrix rescale each row onto a ball after every update. Perhaps the most famous deep learning application is generating adversarial examples via projected gradient ascent on an input perturbation with , where projection simply clips each entry to (Madry et al., 2018). Keep in mind that gradient clipping also uses a ball projection, but it projects the gradient vector rather than the parameters, so it is not PGD for any constraint on the weights (Exercise 2 highlights the difference). What clipping does achieve is a step that stays safe where the curvature grows with the gradient (Section 23.1.1.5).
23.6.3.3 Projection onto the Simplex#
Attention weights and class probabilities live on the probability simplex . Given a vector of real scores , how do we find the closest point on ? The problem
is a small quadratic program (QP)—a convex quadratic objective subject to affine constraints—and the KKT conditions collapse it to finding a single scalar. Introduce a multiplier for the sum constraint and multipliers for the nonnegativity constraints . Stationarity gives , and complementary slackness splits the coordinates into two groups. Wherever , we must have and thus . Wherever , stationarity gives , and dual feasibility forces . Putting both cases together gives
In other words, projecting onto the simplex simply shifts every score down by the same threshold and clips negative results to zero. Remarkably, this threshold formula automatically satisfies stationarity, complementary slackness, dual feasibility, and nonnegativity for any ; the unit-sum budget alone pins down . Because the left-hand side is continuous, piecewise linear, and strictly decreasing wherever it is positive, there is a unique that solves .
A quick hand calculation shows how to find . Take the already-sorted vector , and guess that the largest scores survive above zero. Then the budget predicts the candidate threshold , which is self-consistent only if the -th score stays strictly above :
- : , and ;
- : , and ;
- : , but .
The largest valid choice is , giving and (Figure 23.6.4). For comparison, softmax applied to the same scores yields , keeping every entry strictly positive.
Projection of onto the probability simplex in (a): every score is shifted down by the threshold and clipped at zero, with uniquely fixed by . Softmax on the same scores in (b) keeps every coordinate strictly positive.
Two simple observations turn this hand check into a general algorithm. First, the support always consists of the largest scores: if and , then . (The active sign constraints are the remaining zero coordinates.) Second, once the scores are sorted as , the test holds for every up to the true support size and fails beyond it. Indeed, rearranging gives , which is just ; because is strictly decreasing, this is equivalent to . We therefore sort , pick the largest with , and set , taking time (Held et al., 1974; Duchi et al., 2008).
When applied to attention scores, this simplex projection is known as sparsemax (Martins and Astudillo, 2016), because it assigns exact zero weight to low-scoring positions. Softmax and sparsemax differ by just one regularization term: expanding the squared distance shows that sparsemax maximizes over , whereas softmax maximizes , replacing the quadratic penalty with Shannon entropy (Section 23.7).
Whenever we implement a projection, it is good practice to verify its output. The KKT residuals are the natural first test, though we have to be careful about which ones actually discriminate. The cell below tests six random scores at both the computed and a perturbed value , and then checks the optimality certificate from the obtuse-angle inequality (23.6.7). Because the left-hand side of (23.6.7) is affine in , its maximum over occurs at a vertex, so testing the standard basis vectors is enough to certify the entire simplex.
def project_simplex(y):
"""Sort-and-threshold projection onto {x >= 0, sum x = 1}; returns x* and tau."""
u = np.sort(y)[::-1]
tau_k = (np.cumsum(u) - 1) / np.arange(1, len(y) + 1) # tau_k for k = 1..n
k = np.nonzero(u > tau_k)[0][-1] # largest k with u_k > tau_k
return np.maximum(y - tau_k[k], 0.0), tau_k[k]
y = np.random.default_rng().normal(size=6)
x, tau = project_simplex(y)
print('x* =', x.round(3), ' zeros:', int((x == 0).sum()), ' tau =', round(tau, 3))
for t in (tau, tau + 0.3): # three conditions hold for every tau ...
xt, lam = np.maximum(y - t, 0), np.maximum(0, t - y)
print(f'tau = {t:6.3f}: stationarity {abs(xt - y + t - lam).max():.0e}, '
f'comp. slack {abs(lam * xt).max():.0e}, dual feas. {lam.min() >= 0}, '
f'sum x = {xt.sum():.3f}') # ... only the budget differs
cert = ((y - x) @ (np.eye(6) - x).T).max() # max_i (y - x*)^T (e_i - x*)
print(f'certificate max_i (y - x*)^T(e_i - x*) = {cert:.0e} '
f'(<= 0 up to rounding: {cert <= 1e-12})')x* = [0.666 0.334 0. 0. 0. 0. ] zeros: 4 tau = 1.662
tau = 1.662: stationarity 0e+00, comp. slack 0e+00, dual feas. True, sum x = 1.000
tau = 1.962: stationarity 0e+00, comp. slack 0e+00, dual feas. True, sum x = 0.400
certificate max_i (y - x*)^T(e_i - x*) = -3e-16 (<= 0 up to rounding: True)
Typically three to five of the six coordinates are set to exact zero; these are the active nonnegativity constraints, each carrying the positive multiplier . Notice the diagnostic pitfall: stationarity, complementary slackness, and dual feasibility all pass up to rounding error for both the correct and the wrong one. Only the sum constraint catches the error, so checking those three residuals alone cannot confirm the solution. The vertex certificate does: seeing that up to rounding error proves that no point on the simplex lies closer to .
23.6.4 Proximal Operators and Coordinate Descent#
23.6.4.1 Soft-Thresholding and the Proximal Operator#
A hard boundary is not the only way to keep weights under control. The lasso (Tibshirani, 1996) replaces a hard wall with a kinked penalty added to a least-squares loss,
whose minimizer typically sets many coordinates to exact zero. We write the penalty weight as on purpose, because it acts like the Lagrange multiplier for a norm constraint : every minimizer of also minimizes the least-squares loss under the budget that it uses, and conversely every budget corresponds to some penalty . Section 23.7.3.2 proves both directions, for the lasso and for weight decay alike.
To see what happens numerically, let us plant a sparse vector in with five zero coordinates, generate noisy linear observations, and set . We choose the step size , where is the largest eigenvalue of and the smoothness constant of the least-squares term.
rng = np.random.default_rng()
w_planted = np.array([2.0, 0, 0, -1.5, 0, 0, 0, 1.0])
A = rng.normal(size=(100, 8))
b = A @ w_planted + 0.05 * rng.normal(size=100)
lam = 3.0
L = np.linalg.eigvalsh(A.T @ A).max()
eta = 1 / L
F = lambda w: 0.5 * ((A @ w - b)**2).sum() + lam * np.abs(w).sum()
soft = lambda z, t: np.sign(z) * np.maximum(np.abs(z) - t, 0.0) # derived below
print(f'L = lambda_max(A^T A) = {L:.1f}; |a_j|^2 range from '
f'{(A**2).sum(0).min():.0f} to {(A**2).sum(0).max():.0f}')L = lambda_max(A^T A) = 145.6; |a_j|^2 range from 85 to 109
Here typically lands between and , while the squared column norms of sit around .
The most naive algorithm to try is subgradient descent. Recall from Section 23.3 that the subgradients of are for and the entire interval at the kink . Picking at each step gives the update . Does it recover the five zeros?
w_sub, signs = np.zeros(8), []
for k in range(50): # subgradient descent, step 1/L
w_sub = w_sub - eta * (A.T @ (A @ w_sub - b) + lam * np.sign(w_sub))
signs.append(np.sign(w_sub))
null = w_planted == 0
S = np.array(signs)[-20:, null]
print(f'exact zeros: {int((w_sub == 0).sum())} of 8; sign flips of the null '
f'coordinates, last 20 steps: {(S[1:] != S[:-1]).sum()} of 95')
print(f'largest null coordinate: {np.abs(w_sub[null]).max():.3f}; '
f'eta * lam = {eta * lam:.3f}')exact zeros: 0 of 8; sign flips of the null coordinates, last 20 steps: 95 of 95
largest null coordinate: 0.033; eta * lam = 0.021
It fails completely to produce exact zeros. None of the coordinates land on zero, and the five null coordinates (those planted at zero) flip sign on nearly every iteration, bouncing back and forth at an amplitude of about . The culprit is the kink at zero. At the true lasso solution, the smooth gradient on a null coordinate has magnitude strictly smaller than . Near zero, the penalty term therefore dominates the step and kicks the coordinate across zero by about every time. Because subgradient descent commits to a single slope out of the interval at each step, a fixed step size can never settle at the exact slope that cancels the smooth gradient.
The cure is simple: instead of linearizing the kinked penalty, handle it exactly. Start in one dimension by minimizing over . Because the objective is convex, is optimal if and only if belongs to its set of subgradients:
- If , the objective is differentiable at , so . When this gives , which requires ; when it gives , which requires .
- If , the subgradients form the interval , which contains if and only if .
These two cases partition the real line and combine into soft-thresholding,
Any input with magnitude at most is snapped to exact zero, while larger inputs are shrunk toward zero by . For example, with , maps to , maps to , and maps to (Figure 23.6.5). That dead zone is precisely how regularization creates exact sparsity, whereas regularization only shrinks weights toward zero without ever zeroing them out.
Soft-thresholding for (solid). Inputs in the dead zone map to , as does, and every other input moves toward by , as does. The dashed line is the identity. The dotted line is the corresponding map for the squared penalty , which halves every input and sends none but to zero.
Soft-thresholding is one instance of a much more general operation. The proximal operator of a function trades off lowering against staying close to a reference point :
This map is well defined for every proper closed convex function —that is, convex, taking values in , finite at least somewhere, and having a closed epigraph. Under those conditions, the objective in (23.6.12) is -strongly convex and therefore has a unique minimizer (Parikh and Boyd, 2014).
Three special cases reveal how the proximal operator unifies ideas we already know:
- When , the proximal operator is simply the identity map.
- When is the indicator of a closed convex set (equal to on and outside), any minimizer must lie in , so the proximal operator reduces to the Euclidean projection . Proximal operators are projections generalized from sets to functions.
- When , the objective separates completely across coordinates, so the proximal operator applies soft-thresholding (23.6.11) coordinate by coordinate.
Exercise 5 works out the proximal operator of the Euclidean norm, which zeroes an entire block of weights at once, and Exercise 6 shows that the proximal operator of a norm and the projection onto its dual ball sum to the identity.
23.6.4.2 Proximal Gradient Descent#
The lasso objective has the composite form , combining a smooth loss with a nonsmooth penalty whose proximal operator is cheap to evaluate. Suppose is convex with an -Lipschitz gradient, is proper closed convex, and . By the descent lemma (Section 23.1, with ), is bounded above by the quadratic model . Rather than linearizing as well, we minimize this quadratic upper bound on together with the exact . Completing the square shows that the minimizer is
which is an ordinary gradient step on the smooth part followed by a proximal step on the kinked part. Iterating this update,
gives proximal gradient descent, known as ISTA (the iterative shrinkage-thresholding algorithm) when . It subsumes both projected gradient descent (take to be the indicator of ) and plain gradient descent (take ).
Even though is not differentiable, proximal gradient descent with achieves the same rate as smooth gradient descent: (Beck and Teboulle (2009), Theorem 3.1). Moreover, if is twice continuously differentiable and -strongly convex (), our PGD contraction proof carries over verbatim, because all it needs is that is a fixed point and that is nonexpansive just like (Exercise 7 proves this).
For the lasso, the proximal step is soft-thresholding with threshold , which snaps every coordinate within of zero directly to zero. That threshold matches the exact amplitude at which subgradient descent was chattering, so ISTA should hold the null coordinates cleanly at zero. Let us check.
w = np.zeros(8)
for k in range(50): # ISTA: gradient step, then prox
w = soft(w - eta * A.T @ (A @ w - b), eta * lam)
print(f'exact zeros: {int((w == 0).sum())} of 8; support recovered: '
f'{np.array_equal(w != 0, w_planted != 0)}; '
f'max deviation on the support: {np.abs(w - w_planted)[~null].max():.3f}')exact zeros: 5 of 8; support recovered: True; max deviation on the support: 0.029
After the same fifty iterations—at the same cost per step as subgradient descent—ISTA recovers the exact support, setting all five null coordinates to zero and leaving the three active coordinates nonzero. Those three entries sit within about of the planted values; they cannot get much closer, because the penalty shrinks even the true lasso solution toward zero by roughly .
23.6.4.3 Coordinate Descent#
You may skip this subsection on a first reading: coordinate descent is the standard solver for the lasso, though it is not how neural networks are trained.
On the lasso, minimizing along a single coordinate while holding all others fixed reduces to the exact one-dimensional problem we just solved. Let be the residual computed without coordinate . The -th subproblem, , equals up to an additive constant, where . Soft-thresholding with threshold solves it in closed form:
Whenever a feature's correlation with the current residual has magnitude
at most , its weight is set immediately to zero. Cycling through the
coordinates with this update is the algorithm behind the widely used glmnet
package (Friedman et al., 2010). By updating the residual
incrementally after each coordinate change, one full sweep over all
coordinates costs the same as a single gradient evaluation.
The same principle applies to any differentiable objective with coordinate-wise smoothness constants ,
where minimizing the quadratic upper bound over produces the coordinate-descent update
Because measures curvature along a single axis, it can be substantially smaller than the global smoothness constant , allowing larger steps: in our lasso problem, , compared with . For a positive-definite quadratic , the upper bound is exact with , and the update
minimizes exactly along coordinate . Sweeping cyclically through all coordinates recovers the classical Gauss--Seidel iteration for .
How much faster is a coordinate sweep than an ISTA step of the same cost? Let us count how many passes over the data each method takes to push the objective gap below on our lasso problem.
w_ref = np.zeros(8)
for k in range(5000): # reference optimum by ISTA
w_ref = soft(w_ref - eta * A.T @ (A @ w_ref - b), eta * lam)
F_star, col2 = F(w_ref), (A**2).sum(0) # col2[j] = |a_j|^2
w_i, w_c, r = np.zeros(8), np.zeros(8), b.copy() # r = b - A w_c, kept up to date
gap_i, gap_c = [], []
for sweep in range(30):
w_i = soft(w_i - eta * A.T @ (A @ w_i - b), eta * lam) # one ISTA step
for j in range(8): # one coordinate sweep
c_j = A[:, j] @ r + col2[j] * w_c[j] # a_j^T r_{-j}
w_new = soft(c_j, lam) / col2[j]
r -= A[:, j] * (w_new - w_c[j])
w_c[j] = w_new
gap_i.append(F(w_i) - F_star); gap_c.append(F(w_c) - F_star)
passes = lambda gap: next((k + 1 for k, g in enumerate(gap) if g < 1e-8),
'> 30') # not reached in 30 passes
print(f'passes to gap < 1e-8: ISTA {passes(gap_i)}, coordinate descent {passes(gap_c)}')
d2l.plot(np.arange(1, 31), [np.maximum(gap_i, 1e-16), np.maximum(gap_c, 1e-16)],
'passes over the data', 'F - F*', legend=['ISTA', 'coordinate descent'],
yscale='log') # gaps floored at rounding levelpasses to gap < 1e-8: ISTA 12, coordinate descent 5
On the logarithmic plot, both methods trace straight lines—linear convergence—but coordinate descent drops much more steeply, typically reaching a gap of in four to six sweeps compared with a dozen to twenty-five steps for ISTA. Nothing we proved in this section predicts that exact speedup. The sharpest rates for coordinate descent are proved for randomly chosen coordinates (Nesterov, 2012); cyclic sweeps like ours also converge at a guaranteed rate, but with weaker constants (Beck and Tetruashvili, 2013).
Coordinate descent does have an important limitation. If a nonsmooth kink does not separate across coordinates, coordinate descent can get stuck far from the optimum: for at , moving along alone or along alone cannot decrease , even though the global minimum sits at the origin. Coordinate descent succeeds on the lasso specifically because its nonsmooth penalty is separable across coordinates (Tseng, 2001). For sparse linear models and block-alternating minimization, it remains the method of choice. For training dense neural networks, however, it plays no role, because modern accelerators are engineered for parallel matrix multiplications rather than sequential scalar updates.
Notice one pattern running through everything we did in this section: every time we wanted a multiplier, we first solved for . In Section 23.7, we flip the question around and ask how to solve for the multipliers directly—and how any choice of multipliers provides a certificate proving that no feasible point can beat a given lower bound. Our clipping example, with and , will be its opening case.
23.6.5 Summary#
At a constrained optimum, the gradient need not vanish; instead, no feasible direction can decrease the objective. For a single equality constraint with , this means for a Lagrange multiplier that measures how hard the solution presses against the constraint. Adding inequality constraints leads to the four KKT conditions, where dual feasibility () enforces one-way walls and complementary slackness () zeroes out the multiplier of every inactive constraint. For convex problems, every KKT point is a global minimum, and under a constraint qualification (such as LICQ or Slater's condition) every minimum is a KKT point.
To compute constrained solutions iteratively, projected gradient descent follows each gradient step with a Euclidean projection . Because projection onto a closed convex set is unique, characterized by the obtuse-angle inequality, and nonexpansive, projected gradient descent preserves the convergence rate of unconstrained gradient descent. Projections onto a ball, a half-space, and the probability simplex each reduce to solving for a single scalar multiplier. Finally, the proximal operator generalizes projection from sets to nonsmooth functions: soft-thresholding is the proximal operator of , and both ISTA and coordinate descent use it to solve the lasso with exact zeros that subgradient descent cannot attain.
23.6.6 Exercises#
-
Degenerate constraints. The Lagrange condition (23.6.1) and the KKT conditions (23.6.5) hold at a minimum only under a constraint qualification. Each of the following problems violates one.
- Minimize over subject to and . Show that the feasible set is a line, find the minimizer, and show that both constraint gradients are nonzero everywhere. Show that no multipliers satisfy at the minimizer. Describe the same line by two other equality constraints for which multipliers exist. Is a constraint qualification a property of the feasible set or of the functions that describe it?
- Minimize over subject to . Find and show that no satisfies the KKT stationarity condition at the minimizer. Which of LICQ and Slater's condition fails? Explain why for each.
- Minimize over subject to the constraint written twice, . Show that LICQ fails and Slater's condition holds. Find all pairs that satisfy the KKT conditions at the minimizer. Under the relaxed constraints and , compute the optimal value , and verify that every KKT pair satisfies for all . Is differentiable at , and what takes the place of the relation ?
-
Projected fixed points. For a closed convex set , the fixed points of projected gradient descent (23.6.8) are the constrained stationary points, whatever the step size .
- Let . Show that is a fixed point if and only if, for every coordinate , either and , or and . Show that these conditions are the KKT conditions for the constraints , and express the multipliers through .
- Gradient clipping updates , where . Find the fixed points of this update and compare them with those of projected gradient descent onto the parameter ball . Which of the two updates solves a constrained problem?
- Binary weights restrict a parameter to the nonconvex set , and projecting onto rounds to the nearer element (to at a tie). Let with . For which step sizes is a fixed point of (23.6.8), and for which is one? What do the iterates do when exceeds both ranges? Which point minimizes over ? Does either point satisfy for all ? Which step of the fixed-point argument fails for this set?
- Run the PGD cell on the half-space with instead of . The projection is nonexpansive; why does the run still diverge? Which factor of the contraction proposition exceeds ?
-
[code] Sparsemax and the ball. The function
project_simplexcomputes the simplex projection (23.6.10), which is sparsemax; its first output is the projected vector.- Show that adding the same constant to every score leaves the projection unchanged. Divide the scores by a temperature , and let be the two largest entries of . Show that the projection of is one-hot exactly when , and find its limit as . Plot the number of nonzero entries of the projection of against for ten standard normal scores.
- Let be the support of , and suppose that no equals the threshold . Derive the Jacobian from (23.6.10) (Martins and Astudillo, 2016) and check it against central finite differences. How many arithmetic operations does the backward pass through sparsemax need for an input of length ?
- Show that the projection onto the ball
keeps the signs of
and, when , equals
(Duchi et al., 2008). Implement it with
project_simplex. Certify the result with the variational inequality , checked at the points . Why do these points suffice?
-
Second-order conditions on the sphere. ● The Lagrange condition is a first-order condition and cannot tell minima from saddles. A second-order test must account for the curvature of the constraint.
- Let and be twice continuously differentiable, and let satisfy (23.6.1) with multiplier . For every curve on with and , show that
with the Lagrangian (23.6.2). Conclude that for every tangent direction at a local minimum. Why is the Hessian of alone the wrong matrix for this test? Conversely, positive definiteness on the tangent space implies a strict local minimum (Nocedal and Wright (2006), chapter 12).
-
Let be symmetric with distinct eigenvalues and unit eigenvectors , and minimize subject to . Show that the Lagrange points are with , and find the eigenvalues of on the tangent space at . Which Lagrange points are local minima, which are local maxima, and which are saddles? How many independent descent directions does have?
-
Projected gradient descent onto the sphere, , projects onto a nonconvex set. Show that for this it is the power iteration for . Assume . From a random start, what do the iterates and the values do? How does the answer depend on ?
-
Block soft-thresholding (the group lasso). The penalty on a whole vector is kinked only at . Its subgradients are for and every vector of the unit ball at (times ).
- Show that .
- Compare the zero pattern with that of coordinatewise soft-thresholding (23.6.11). When does the block prox return exactly , and can it zero a single coordinate of a block?
- What does the penalty , summed over the vectors of outgoing weights of the hidden units of a network, do to the network?
- [code] Verify (a) against a brute-force minimization on a 2-D grid for and with . The answers are and ; where has appeared in this section?
-
Moreau decomposition. ● The convex conjugate of is . For a proper closed convex , two facts connect it with the proximal operator (23.6.12): exactly when (the set of subgradients), and exactly when (Parikh and Boyd, 2014).
- Derive the Moreau decomposition .
- The conjugate of is the indicator of the box . Show that the decomposition writes soft-thresholding (23.6.11) as minus a clipped copy of .
- The conjugate of is the indicator of the ball of radius , whose prox is the projection onto the ball, the clip-by-norm map of gradient clipping. Use the decomposition to recover the block soft-thresholding formula of the group-lasso exercise from the clipping formula. For and , which two vectors of this section add up to ?
-
[code] Accelerated proximal gradient. ● FISTA (Beck and Teboulle, 2009) adds momentum to the ISTA update (23.6.13) for . With and , it iterates for
With its objective gap satisfies , against for ISTA.
- Show that the prox is nonexpansive, , by adding the two subgradient inequalities that characterize and , as in the proof for projections.
- Add FISTA to the ISTA cell, on the same lasso, and plot of both methods over 100 steps on a logarithmic axis, with taken from ISTA steps. Which method is ahead after 10 steps, and which after 30? Explain the straight line of ISTA with the PGD contraction proposition and part (a).
- Is monotone along the FISTA iterates?
- Replace by a Gaussian matrix, plant the same three nonzero coefficients, and run both methods for 1000 steps. Over which range of is FISTA ahead now? Why does ISTA still end with a fast linear phase, although is singular?