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 y=(3,4)\mathbf{y} = (3, 4) so that its norm is at most 11. Rescaling it to unit length returns (0.6,0.8)(0.6, 0.8), which is the point of the unit disk closest to y\mathbf{y}. In other words, (0.6,0.8)(0.6, 0.8) minimizes the squared distance f(x)=12∥x−y∥2f(\mathbf{x}) = \tfrac12\|\mathbf{x} - \mathbf{y}\|^2 over the disk ∥x∥≤1\|\mathbf{x}\| \le 1, reaching the optimal value f=8f = 8. Yet the gradient there is (−2.4,−3.2)(-2.4, -3.2), nowhere near zero. What makes (0.6,0.8)(0.6, 0.8) optimal is that no allowed direction lowers ff: every move that keeps ∥x∥≤1\|\mathbf{x}\| \le 1 either increases ff 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 (0.6,0.8)(0.6, 0.8) the boundary pushes back with strength 44 along the outward normal, so that (−2.4,−3.2)+4 (0.6,0.8)=0(-2.4, -3.2) + 4\,(0.6, 0.8) = \mathbf{0}. 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 (3,4)(3, 4) to (0.6,0.8)(0.6, 0.8) 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 f(x)=12∥x−y∥2f(\mathbf{x}) = \tfrac12\|\mathbf{x} - \mathbf{y}\|^2 with y=(3,4)\mathbf{y} = (3, 4) over the unit circle, written as h(x)=12(∥x∥2−1)=0h(\mathbf{x}) = \tfrac12(\|\mathbf{x}\|^2 - 1) = 0. More generally, we want to minimize a differentiable objective f:Rn→Rf : \mathbb{R}^n \to \mathbb{R} subject to a single equality constraint,

min⁡x  f(x)subject toh(x)=0.\min_{\mathbf{x}}\; f(\mathbf{x}) \quad \textrm{subject to} \quad h(\mathbf{x}) = 0.

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 ff crosses the circle. Then ∇f\nabla f has a nonzero component along the circle, so sliding along the circle opposite that component reduces ff 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 ff unchanged to first order. Since tangent curves share parallel normal vectors, ∇f\nabla f must be a scalar multiple of ∇h\nabla h at the optimum.

Figure 23.6.1:

Minimizing f=12∥x−y∥2f=\tfrac12\|\mathbf{x}-\mathbf{y}\|^2 with y=(3,4)\mathbf{y}=(3,4) on the unit circle h(x)=0h(\mathbf{x})=0. Where a level set crosses the circle, ∇f\nabla f has a component along the constraint, giving a feasible descent direction. At x⋆=(0.6,0.8)\mathbf{x}^\star=(0.6,0.8) the level set is tangent to the circle and ∇f=−4 ∇h\nabla f=-4\,\nabla h. The antipode (−0.6,−0.8)(-0.6,-0.8) also satisfies the tangency condition, with ν=−6\nu=-6, and is the maximum.

Proposition (Lagrange condition). Let x⋆\mathbf{x}^\star be a local minimum of ff on {x:h(x)=0}\{\mathbf{x} : h(\mathbf{x}) = 0\}. Assume that ff is differentiable at x⋆\mathbf{x}^\star, that hh is continuously differentiable near x⋆\mathbf{x}^\star, and that ∇h(x⋆)≠0\nabla h(\mathbf{x}^\star) \neq \mathbf{0}. Then there exists a unique scalar ν⋆\nu^\star, the Lagrange multiplier, such that

∇f(x⋆)+ν⋆ ∇h(x⋆)=0.(23.6.1)\nabla f(\mathbf{x}^\star) + \nu^\star\,\nabla h(\mathbf{x}^\star) = \mathbf{0}. \tag{23.6.1}

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 g(x)=cg(\mathbf{x}) = c and the condition as ∇f=μ ∇g\nabla f = \mu\,\nabla g. Setting h=g−ch = g - c and ν=−μ\nu = -\mu reconciles the two forms; we use the plus sign here because it matches the sign of the Lagrangian introduced next.

Checking the tangent point (0.6,0.8)(0.6, 0.8) in Figure 23.6.1, we have ∇f=x−y=(−2.4,−3.2)\nabla f = \mathbf{x} - \mathbf{y} = (-2.4, -3.2) and ∇h=x=(0.6,0.8)\nabla h = \mathbf{x} = (0.6, 0.8). The two vectors are indeed parallel, with ∇f=−4 ∇h\nabla f = -4\,\nabla h, which gives ν⋆=4\nu^\star = 4.

The assumption ∇h(x⋆)≠0\nabla h(\mathbf{x}^\star) \neq \mathbf{0} is our first example of a constraint qualification, and it is essential rather than a technicality. Consider minimizing f(x)=x1f(\mathbf{x}) = x_1 subject to h(x)=x12+x22=0h(\mathbf{x}) = x_1^2 + x_2^2 = 0. The feasible set consists of the single point 0\mathbf{0}, which is automatically the minimum. Yet ∇f(0)=(1,0)\nabla f(\mathbf{0}) = (1, 0) while ∇h(0)=0\nabla h(\mathbf{0}) = \mathbf{0}, so no multiplier ν⋆\nu^\star 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, x\mathbf{x} and ν\nu, and two requirements: parallel gradients and feasibility. Both requirements can be packaged into the stationarity of a single function of (x,ν)(\mathbf{x}, \nu), called the Lagrangian, which adds the constraint weighted by its multiplier to the objective:

L(x,ν)=f(x)+ν h(x).(23.6.2)\mathcal{L}(\mathbf{x}, \nu) = f(\mathbf{x}) + \nu\, h(\mathbf{x}). \tag{23.6.2}

Setting all partial derivatives of L\mathcal{L} to zero yields

∇xL=∇f+ν ∇h=0and∂L∂ν=h(x)=0,\nabla_{\mathbf{x}} \mathcal{L} = \nabla f + \nu\, \nabla h = \mathbf{0} \qquad\textrm{and}\qquad \frac{\partial \mathcal{L}}{\partial \nu} = h(\mathbf{x}) = 0,

recovering (23.6.1) and the equality constraint together. In this way, a constrained optimization problem in x\mathbf{x} becomes an unconstrained stationarity problem in (x,ν)(\mathbf{x}, \nu).

Let us solve the unit-circle problem using the Lagrangian. Stationarity with respect to x\mathbf{x} gives ∇xL=(x−y)+νx=0\nabla_{\mathbf{x}}\mathcal{L} = (\mathbf{x} - \mathbf{y}) + \nu\mathbf{x} = \mathbf{0}, so x=y/(1+ν)\mathbf{x} = \mathbf{y}/(1 + \nu) must lie on the line through the origin and y\mathbf{y}. Enforcing feasibility, ∥x∥=1\|\mathbf{x}\| = 1, then requires ∣1+ν∣=∥y∥=5|1 + \nu| = \|\mathbf{y}\| = 5, which produces two solutions:

  • ν=4\nu = 4: x=(0.6,0.8)\mathbf{x} = (0.6, 0.8), at distance 44 from y\mathbf{y}, with f=8f = 8;
  • ν=−6\nu = -6: x=(−0.6,−0.8)\mathbf{x} = (-0.6, -0.8), at distance 66 from y\mathbf{y}, with f=18f = 18.

The second solution is the point on the circle farthest from y\mathbf{y}. This highlights an important caveat: the Lagrange condition is necessary, not sufficient, because it holds at every stationary point of ff 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 hj(x)=0h_j(\mathbf{x}) = 0 for j=1,…,pj = 1, \ldots, p, each constraint receives its own multiplier and the Lagrangian becomes L=f+∑jνjhj\mathcal{L} = f + \sum_j \nu_j h_j. Provided that the constraint gradients ∇hj(x⋆)\nabla h_j(\mathbf{x}^\star) are linearly independent, the same reasoning shows that ∇f(x⋆)\nabla f(\mathbf{x}^\star) 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 f(x)=12∥x∥2f(\mathbf{x}) = \tfrac12\|\mathbf{x}\|^2 subject to h(x)=a⊤x−b=0h(\mathbf{x}) = \mathbf{a}^\top\mathbf{x} - b = 0. Setting the gradient of L=12∥x∥2+ν(a⊤x−b)\mathcal{L} = \tfrac12\|\mathbf{x}\|^2 + \nu(\mathbf{a}^\top\mathbf{x} - b) to zero gives x+νa=0\mathbf{x} + \nu\mathbf{a} = \mathbf{0}, so the closest point must lie along the normal vector a\mathbf{a}. Substituting x=−νa\mathbf{x} = -\nu\mathbf{a} into the constraint yields −ν∥a∥2=b-\nu\|\mathbf{a}\|^2 = b, which fixes ν⋆=−b/∥a∥2\nu^\star = -b/\|\mathbf{a}\|^2. The solution and optimal value are therefore

x⋆=b∥a∥2 a,p⋆=b22 ∥a∥2.\mathbf{x}^\star = \frac{b}{\|\mathbf{a}\|^2}\,\mathbf{a}, \qquad p^\star = \frac{b^2}{2\,\|\mathbf{a}\|^2}.

Geometrically, the nearest point sits at distance b/∥a∥b/\|\mathbf{a}\| along the unit normal a/∥a∥\mathbf{a}/\|\mathbf{a}\|, matching the projection formula of Section 21.1.

For a=(3,4)\mathbf{a} = (3, 4) and b=5b = 5, we land on (0.6,0.8)(0.6, 0.8) once again, this time with ν⋆=−0.2\nu^\star = -0.2 and p⋆=12p^\star = \tfrac12: the line 3x1+4x2=53x_1 + 4x_2 = 5 is tangent to the unit circle at (0.6,0.8)(0.6, 0.8). Notice that the multiplier is more than an algebraic helper. If we nudge bb from 55 to 5.15.1, pushing the line slightly farther from the origin, the optimal value rises by about 0.02=−ν⋆⋅0.10.02 = -\nu^\star \cdot 0.1. 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 rr, a probability at least 00, or a resource budget not exceeded. We write inequality constraints in the standard form

min⁡x  f(x)subject togi(x)≤0,  i=1,…,m,\min_{\mathbf{x}}\; f(\mathbf{x}) \quad \textrm{subject to} \quad g_i(\mathbf{x}) \le 0,\; i = 1, \ldots, m,

so that each gig_i is negative strictly inside its region and zero along its boundary. At a solution x⋆\mathbf{x}^\star, every inequality falls into one of two regimes. If gi(x⋆)<0g_i(\mathbf{x}^\star) \lt 0, the constraint is inactive: the solution lies strictly inside the region, so locally the constraint has no effect. If gi(x⋆)=0g_i(\mathbf{x}^\star) = 0, 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 y\mathbf{y} onto the Euclidean ball of radius rr by minimizing f(x)=12∥x−y∥2f(\mathbf{x}) = \tfrac12\|\mathbf{x} - \mathbf{y}\|^2 subject to g(x)=12(∥x∥2−r2)≤0g(\mathbf{x}) = \tfrac12(\|\mathbf{x}\|^2 - r^2) \le 0. Introducing a multiplier λ\lambda, stationarity of f+λgf + \lambda g yields (x−y)+λx=0(\mathbf{x} - \mathbf{y}) + \lambda\mathbf{x} = \mathbf{0}, so x=y/(1+λ)\mathbf{x} = \mathbf{y}/(1 + \lambda) is always a radial rescaling of y\mathbf{y}. Which regime applies depends on ∥y∥\|\mathbf{y}\|:

  • If ∥y∥≤r\|\mathbf{y}\| \le r, then y\mathbf{y} is already feasible and minimizes ff outright. The constraint is inactive, λ⋆=0\lambda^\star = 0, and x⋆=y\mathbf{x}^\star = \mathbf{y}; for example, y=(0.3,0.4)\mathbf{y} = (0.3, 0.4) with r=1r = 1 stays untouched.
  • If ∥y∥>r\|\mathbf{y}\| > r, no interior point can be optimal, because any interior minimum would have to be an unconstrained minimum of ff, and the only unconstrained minimum is the infeasible point y\mathbf{y}. The constraint must therefore be active, and ∥x⋆∥=r\|\mathbf{x}^\star\| = r forces λ⋆=∥y∥/r−1>0\lambda^\star = \|\mathbf{y}\|/r - 1 > 0. For y=(3,4)\mathbf{y} = (3, 4) and r=1r = 1, we get λ⋆=4\lambda^\star = 4, x⋆=(0.6,0.8)\mathbf{x}^\star = (0.6, 0.8), and p⋆=12⋅42=8p^\star = \tfrac12 \cdot 4^2 = 8.

Both cases collapse into a single formula,

x⋆=ymax⁡(1,  ∥y∥/r),\mathbf{x}^\star = \frac{\mathbf{y}}{\max\left(1,\; \|\mathbf{y}\|/r\right)},

which leaves short vectors alone and rescales long ones to norm rr. 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 ff is cancelled by λ⋆\lambda^\star times the constraint gradient ∇g(x)=x\nabla g(\mathbf{x}) = \mathbf{x}.

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 ∇f\nabla f is far from zero: the objective gradient (−2.4,−3.2)(-2.4, -3.2) and the boundary's push (2.4,3.2)(2.4, 3.2) sum to zero, with the multiplier λ⋆=4\lambda^\star = 4 giving the ratio of their lengths.

Notice the geometric meaning of the multiplier's sign. Because g(x)g(\mathbf{x}) increases as we leave the ball, its gradient ∇g=x\nabla g = \mathbf{x} points outward. Stationarity written as −∇f=λ∇g-\nabla f = \lambda\nabla g with λ>0\lambda > 0 says that the downhill direction −∇f-\nabla f pulls outward, while the boundary wall pushes back. If −∇f-\nabla f pointed inward instead, we could step into the interior of the ball to lower ff, so the point could not be optimal. A negative multiplier is therefore ruled out: λ=−6\lambda = -6 would select the far point (−0.6,−0.8)(-0.6, -0.8) 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

min⁡x  f(x)subject togi(x)≤0,  i=1,…,m,hj(x)=0,  j=1,…,p.(23.6.3)\min_{\mathbf{x}}\; f(\mathbf{x}) \quad \textrm{subject to} \quad g_i(\mathbf{x}) \le 0,\; i = 1, \ldots, m, \qquad h_j(\mathbf{x}) = 0,\; j = 1, \ldots, p. \tag{23.6.3}

Its Lagrangian assigns one multiplier to each constraint, with the inequality multipliers required to be nonnegative:

L(x,λ,ν)=f(x)+∑i=1mλi gi(x)+∑j=1pνj hj(x),λi≥0.(23.6.4)\mathcal{L}(\mathbf{x}, \boldsymbol{\lambda}, \boldsymbol{\nu}) = f(\mathbf{x}) + \sum_{i=1}^m \lambda_i\, g_i(\mathbf{x}) + \sum_{j=1}^p \nu_j\, h_j(\mathbf{x}), \qquad \lambda_i \ge 0. \tag{23.6.4}

At any local minimum x⋆\mathbf{x}^\star 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):

stationarity:∇f(x⋆)+∑iλi⋆∇gi(x⋆)+∑jνj⋆∇hj(x⋆)=0,primal feasibility:gi(x⋆)≤0,hj(x⋆)=0,dual feasibility:λi⋆≥0,complementary slackness:λi⋆ gi(x⋆)=0for every i.(23.6.5)\begin{aligned} &\textrm{stationarity:} && \nabla f(\mathbf{x}^\star) + \textstyle\sum_i \lambda_i^\star \nabla g_i(\mathbf{x}^\star) + \sum_j \nu_j^\star \nabla h_j(\mathbf{x}^\star) = \mathbf{0}, \\ &\textrm{primal feasibility:} && g_i(\mathbf{x}^\star) \le 0, \qquad h_j(\mathbf{x}^\star) = 0, \\ &\textrm{dual feasibility:} && \lambda_i^\star \ge 0, \\ &\textrm{complementary slackness:} && \lambda_i^\star\, g_i(\mathbf{x}^\star) = 0 \quad \textrm{for every } i. \end{aligned} \tag{23.6.5}

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 ii at least one of λi⋆\lambda_i^\star and gi(x⋆)g_i(\mathbf{x}^\star) must vanish. Consequently, every inactive constraint (gi(x⋆)<0g_i(\mathbf{x}^\star) \lt 0) automatically gets λi⋆=0\lambda_i^\star = 0 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 λi⋆=0\lambda_i^\star = 0 if it happens to touch x⋆\mathbf{x}^\star without exerting any force. In the ball-projection example, complementary slackness encodes the exact case split we carried out by hand, and at (0.6,0.8)(0.6, 0.8) we have λ⋆g(x⋆)=4⋅0=0\lambda^\star g(\mathbf{x}^\star) = 4 \cdot 0 = 0.

Figure 23.6.2 shows the geometry of stationarity and dual feasibility together. At the optimum, the descent direction −∇f-\nabla f must be a nonnegative linear combination of the outward normals of the active constraints. Equivalently, −∇f-\nabla f lies inside the cone spanned by those outward normals (the normal cone), while inactive constraints contribute nothing.

Figure 23.6.2:

Geometry of the KKT conditions on a feasible region defined by two inequality constraints. In (a), one constraint is active at x⋆\mathbf{x}^\star and the other is inactive: −∇f-\nabla f aligns with the active outward normal with λ1>0\lambda_1 > 0, while λ2=0\lambda_2 = 0. In (b), both constraints are active at a corner, so −∇f-\nabla f must lie in the shaded normal cone spanned by both outward normals. Orange arcs show level sets of ff around its unconstrained minimizer (+).

Like the Lagrange condition, the KKT conditions are first-order conditions and are not sufficient on their own. Consider minimizing f(x)=−x2f(x) = -x^2 on [−1,1][-1, 1], written as x−1≤0x - 1 \le 0 and −1−x≤0-1 - x \le 0. At x=0x = 0, the gradient vanishes, both constraints are inactive, and setting both multipliers to zero satisfies all four KKT conditions—yet x=0x = 0 is the maximum. The true minima x=±1x = \pm 1 are KKT points too, each with multiplier 22 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 x⋆\mathbf{x}^\star is a local minimum of (23.6.3) with ff, gig_i, and hjh_j continuously differentiable. If the gradients of all active inequality constraints together with the gradients of all equality constraints, {∇gi(x⋆):gi(x⋆)=0}∪{∇hj(x⋆):j=1,…,p}\{\nabla g_i(\mathbf{x}^\star) : g_i(\mathbf{x}^\star) = 0\} \cup \{\nabla h_j(\mathbf{x}^\star) : j = 1, \ldots, p\}, are linearly independent, then multipliers satisfying (23.6.5) are guaranteed to exist (Nocedal and Wright (2006), chapter 12). LICQ directly generalizes ∇h(x⋆)≠0\nabla h(\mathbf{x}^\star) \neq \mathbf{0}, 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 ff and every gig_i are convex and every hjh_j is affine. A convex problem satisfies Slater's condition (Slater, 1950) if there exists a point xˉ\bar{\mathbf{x}} such that

gi(xˉ)<0for every gi that is not affine,gi(xˉ)≤0for every affine gi,hj(xˉ)=0for every j.(23.6.6)\begin{aligned} g_i(\bar{\mathbf{x}}) &\lt 0 \quad\textrm{for every } g_i \textrm{ that is not affine}, \\ g_i(\bar{\mathbf{x}}) &\le 0 \quad\textrm{for every affine } g_i, \\ h_j(\bar{\mathbf{x}}) &= 0 \quad\textrm{for every } j. \end{aligned} \tag{23.6.6}

In plain terms, xˉ\bar{\mathbf{x}} 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 ff or some gig_i is defined only on a subset of Rn\mathbb{R}^n, which will not occur here, xˉ\bar{\mathbf{x}} must also lie in the relative interior of that domain.) For the Euclidean ball, xˉ=0\bar{\mathbf{x}} = \mathbf{0} immediately works because g(0)=−r2/2<0g(\mathbf{0}) = -r^2/2 \lt 0. Whenever Slater's condition holds for a convex problem with differentiable ff and gig_i, 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 ff and every gig_i be convex and differentiable and every hjh_j affine. If (x⋆,λ⋆,ν⋆)(\mathbf{x}^\star, \boldsymbol{\lambda}^\star, \boldsymbol{\nu}^\star) satisfies the KKT conditions (23.6.5), then x⋆\mathbf{x}^\star is a global minimum.

Proof. Define φ(x)=L(x,λ⋆,ν⋆)\varphi(\mathbf{x}) = \mathcal{L}(\mathbf{x}, \boldsymbol{\lambda}^\star, \boldsymbol{\nu}^\star). Because λi⋆≥0\lambda_i^\star \ge 0, φ\varphi is a nonnegative combination of convex functions plus affine terms, so φ\varphi is convex. Stationarity says ∇φ(x⋆)=0\nabla\varphi(\mathbf{x}^\star) = \mathbf{0}, which means x⋆\mathbf{x}^\star is a global minimizer of φ\varphi over all of Rn\mathbb{R}^n. Now pick any feasible x\mathbf{x}. Since λi⋆≥0\lambda_i^\star \ge 0, gi(x)≤0g_i(\mathbf{x}) \le 0, and hj(x)=0h_j(\mathbf{x}) = 0, we have

f(x)  ≥  f(x)+∑iλi⋆gi(x)+∑jνj⋆hj(x)=φ(x)  ≥  φ(x⋆)=f(x⋆),f(\mathbf{x}) \;\ge\; f(\mathbf{x}) + \sum_i \lambda_i^\star g_i(\mathbf{x}) + \sum_j \nu_j^\star h_j(\mathbf{x}) = \varphi(\mathbf{x}) \;\ge\; \varphi(\mathbf{x}^\star) = f(\mathbf{x}^\star),

where the final equality follows from complementary slackness (∑iλi⋆gi(x⋆)=0\sum_i \lambda_i^\star g_i(\mathbf{x}^\star) = 0) and primal feasibility (hj(x⋆)=0h_j(\mathbf{x}^\star) = 0). ■\blacksquare

Notice a broader principle tucked inside this short proof. For any fixed multipliers with λ≥0\boldsymbol{\lambda} \ge 0, the first inequality holds for every feasible x\mathbf{x}, so minimizing the Lagrangian over x\mathbf{x} 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 C⊆RnC \subseteq \mathbb{R}^n, the projection of a point y\mathbf{y} onto CC is the unique point of CC closest to y\mathbf{y},

ΠC(y)=argminx∈C  12∥x−y∥2.\Pi_C(\mathbf{y}) = \mathop{\mathrm{argmin}}_{\mathbf{x} \in C}\; \tfrac12 \|\mathbf{x} - \mathbf{y}\|^2.

Why does a unique minimizer always exist? Because we can intersect CC with a large closed ball centered at y\mathbf{y} 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 ΠC\Pi_C 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 {x:a⊤x≥b}\{\mathbf{x} : \mathbf{a}^\top\mathbf{x} \ge b\} follows immediately from the hyperplane formula. If y\mathbf{y} already satisfies the inequality, we leave it alone; if it violates it, we move straight along a\mathbf{a} onto the boundary hyperplane:

Π(y)=y+max⁡(0,  b−a⊤y)∥a∥2 a.\Pi(\mathbf{y}) = \mathbf{y} + \frac{\max(0,\; b - \mathbf{a}^\top\mathbf{y})}{\|\mathbf{a}\|^2}\,\mathbf{a}.

Projections onto closed convex sets obey a remarkably clean geometric characterization. Let x^=ΠC(y)\hat{\mathbf{x}} = \Pi_C(\mathbf{y}) be the minimizer of 12∥x−y∥2\tfrac12\|\mathbf{x} - \mathbf{y}\|^2 over CC. For any other point x∈C\mathbf{x} \in C, convexity guarantees that the entire line segment from x^\hat{\mathbf{x}} to x\mathbf{x} stays inside CC. Moving from x^\hat{\mathbf{x}} toward x\mathbf{x} therefore cannot decrease the objective to first order, so its directional derivative is nonnegative: (x^−y)⊤(x−x^)≥0(\hat{\mathbf{x}} - \mathbf{y})^\top(\mathbf{x} - \hat{\mathbf{x}}) \ge 0. Flipping the sign gives the obtuse-angle inequality (or variational inequality):

(y−ΠC(y))⊤(x−ΠC(y))  ≤  0for all x∈C.(23.6.7)\left(\mathbf{y} - \Pi_C(\mathbf{y})\right)^\top \left(\mathbf{x} - \Pi_C(\mathbf{y})\right) \;\le\; 0 \qquad \textrm{for all } \mathbf{x} \in C. \tag{23.6.7}

Geometrically, the residual vector y−ΠC(y)\mathbf{y} - \Pi_C(\mathbf{y}) forms an angle of at least 90∘90^\circ with the vector from ΠC(y)\Pi_C(\mathbf{y}) to every point x∈C\mathbf{x} \in C (Figure 23.6.3, panel (a)). Put differently, the hyperplane through ΠC(y)\Pi_C(\mathbf{y}) with normal y−ΠC(y)\mathbf{y} - \Pi_C(\mathbf{y}) is a supporting hyperplane of CC, keeping the entire set CC on its far side.

Figure 23.6.3:

(a) The residual y−ΠC(y)\mathbf{y}-\Pi_C(\mathbf{y}) makes an angle of at least 90∘90^\circ with every direction into CC, so CC lies entirely on the far side of the supporting line through ΠC(y)\Pi_C(\mathbf{y}). (b) Projection onto a closed convex set never increases distances: ∥u−v∥≤∥x−x′∥\|\mathbf{u}-\mathbf{v}\|\le\|\mathbf{x}-\mathbf{x}'\|.

Let us check this inequality on our running example. For y=(3,4)\mathbf{y} = (3, 4) projected onto the unit disk, the residual is (2.4,3.2)=4 (0.6,0.8)(2.4, 3.2) = 4\,(0.6, 0.8)—once again, the multiplier times the outward normal. For any x\mathbf{x} with ∥x∥≤1\|\mathbf{x}\| \le 1,

(2.4,3.2)⊤(x−(0.6,0.8))=4 (0.6x1+0.8x2)−4  ≤  4 ∥x∥−4  ≤  0,(2.4, 3.2)^\top\bigl(\mathbf{x} - (0.6, 0.8)\bigr) = 4\,(0.6x_1 + 0.8x_2) - 4 \;\le\; 4\,\|\mathbf{x}\| - 4 \;\le\; 0,

where the first inequality uses Cauchy--Schwarz, u⊤v≤∥u∥ ∥v∥\mathbf{u}^\top\mathbf{v} \le \|\mathbf{u}\|\,\|\mathbf{v}\|. The supporting line here is 3x1+4x2=53x_1 + 4x_2 = 5, the very hyperplane from our closest-point example.

Just as importantly, the obtuse-angle inequality is also sufficient. Suppose some point x^∈C\hat{\mathbf{x}} \in C satisfies (23.6.7), and write φ(x)=12∥x−y∥2\varphi(\mathbf{x}) = \tfrac12\|\mathbf{x} - \mathbf{y}\|^2, whose gradient at x^\hat{\mathbf{x}} is x^−y\hat{\mathbf{x}} - \mathbf{y}. Because a convex differentiable function always lies above its tangent planes (Section 23.3), we have φ(x)≥φ(x^)+(x^−y)⊤(x−x^)\varphi(\mathbf{x}) \ge \varphi(\hat{\mathbf{x}}) + (\hat{\mathbf{x}} - \mathbf{y})^\top(\mathbf{x} - \hat{\mathbf{x}}). The last term is nonnegative for every x∈C\mathbf{x} \in C by assumption, so φ(x)≥φ(x^)\varphi(\mathbf{x}) \ge \varphi(\hat{\mathbf{x}}) across all of CC, proving that x^=ΠC(y)\hat{\mathbf{x}} = \Pi_C(\mathbf{y}). 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 CC and all x,y∈Rn\mathbf{x}, \mathbf{y} \in \mathbb{R}^n,

∥ΠC(x)−ΠC(y)∥  ≤  ∥x−y∥.\|\Pi_C(\mathbf{x}) - \Pi_C(\mathbf{y})\| \;\le\; \|\mathbf{x} - \mathbf{y}\|.

Proof. Set u=ΠC(x)\mathbf{u} = \Pi_C(\mathbf{x}) and v=ΠC(y)\mathbf{v} = \Pi_C(\mathbf{y}). Applying (23.6.7) twice—first at x\mathbf{x} with v∈C\mathbf{v} \in C, then at y\mathbf{y} with u∈C\mathbf{u} \in C—gives

(x−u)⊤(v−u)≤0,(y−v)⊤(u−v)≤0.(\mathbf{x} - \mathbf{u})^\top(\mathbf{v} - \mathbf{u}) \le 0, \qquad (\mathbf{y} - \mathbf{v})^\top(\mathbf{u} - \mathbf{v}) \le 0.

Adding these two inequalities yields (x−y−(u−v))⊤(v−u)≤0(\mathbf{x} - \mathbf{y} - (\mathbf{u} - \mathbf{v}))^\top(\mathbf{v} - \mathbf{u}) \le 0, which rearranges to

∥u−v∥2  ≤  (x−y)⊤(u−v)  ≤  ∥x−y∥ ∥u−v∥\|\mathbf{u} - \mathbf{v}\|^2 \;\le\; (\mathbf{x} - \mathbf{y})^\top (\mathbf{u} - \mathbf{v}) \;\le\; \|\mathbf{x} - \mathbf{y}\|\, \|\mathbf{u} - \mathbf{v}\|

by Cauchy--Schwarz. Dividing by ∥u−v∥\|\mathbf{u} - \mathbf{v}\| finishes the proof (and when ∥u−v∥=0\|\mathbf{u} - \mathbf{v}\| = 0 the claim is trivial). ■\blacksquare

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 CC is essential here. Take the nonconvex two-point set C={−1,1}C = \{-1, 1\}: then y=0.01y = 0.01 projects to 11 while y=−0.01y = -0.01 projects to −1-1, turning an input gap of 0.020.02 into an output gap of 22—and at y=0y = 0 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:

xk+1=ΠC(xk−η ∇f(xk)).(23.6.8)\mathbf{x}_{k+1} = \Pi_C\left(\mathbf{x}_k - \eta\, \nabla f(\mathbf{x}_k)\right). \tag{23.6.8}

Every iterate stays feasible by construction. Better yet, the fixed points of PGD are precisely the constrained stationary points. For any differentiable ff, closed convex CC, and step size η>0\eta > 0, the fixed-point equation x⋆=ΠC(x⋆−η∇f(x⋆))\mathbf{x}^\star = \Pi_C(\mathbf{x}^\star - \eta \nabla f(\mathbf{x}^\star)) holds if and only if x⋆∈C\mathbf{x}^\star \in C satisfies the obtuse-angle inequality (23.6.7) with y=x⋆−η∇f(x⋆)\mathbf{y} = \mathbf{x}^\star - \eta\nabla f(\mathbf{x}^\star). Cancelling x⋆\mathbf{x}^\star and dividing by η>0\eta > 0 turns that inequality into

∇f(x⋆)⊤(x−x⋆)  ≥  0for all x∈C.\nabla f(\mathbf{x}^\star)^\top (\mathbf{x} - \mathbf{x}^\star) \;\ge\; 0 \qquad \textrm{for all } \mathbf{x} \in C.

In plain words, no feasible direction is a descent direction. This is the general constrained first-order condition, reducing to ∇f(x⋆)=0\nabla f(\mathbf{x}^\star) = \mathbf{0} when C=RnC = \mathbb{R}^n. When ff is convex, the tangent-plane inequality immediately makes this condition sufficient for a global minimum; when ff is nonconvex, it certifies stationarity. And when C={x:gi(x)≤0}C = \{\mathbf{x} : g_i(\mathbf{x}) \le 0\} for differentiable convex gig_i 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 CC be nonempty, closed, and convex, let ff be twice continuously differentiable with μI⪯∇2f⪯LI\mu\mathbf{I} \preceq \nabla^2 f \preceq L\mathbf{I} for some 0<μ≤L0 \lt \mu \le L, let x⋆\mathbf{x}^\star be the minimizer of ff over CC, and let η>0\eta > 0. Then the iterates of (23.6.8) satisfy

∥xk+1−x⋆∥  ≤  ρ ∥xk−x⋆∥,ρ=max⁡(∣1−ημ∣,  ∣1−ηL∣).(23.6.9)\|\mathbf{x}_{k+1} - \mathbf{x}^\star\| \;\le\; \rho\, \|\mathbf{x}_k - \mathbf{x}^\star\|, \qquad \rho = \max\left(|1 - \eta\mu|,\; |1 - \eta L|\right). \tag{23.6.9}

Proof. (i) Because x⋆\mathbf{x}^\star is a fixed point of PGD, we can write x⋆=ΠC(b)\mathbf{x}^\star = \Pi_C(\mathbf{b}) with b=x⋆−η∇f(x⋆)\mathbf{b} = \mathbf{x}^\star - \eta\nabla f(\mathbf{x}^\star). (ii) That choice of b\mathbf{b} is the key step: applying nonexpansiveness to xk−η∇f(xk)\mathbf{x}_k - \eta\nabla f(\mathbf{x}_k) and b\mathbf{b} strips away the projection altogether,

∥xk+1−x⋆∥  ≤  ∥(xk−x⋆)−η(∇f(xk)−∇f(x⋆))∥.\|\mathbf{x}_{k+1} - \mathbf{x}^\star\| \;\le\; \left\|(\mathbf{x}_k - \mathbf{x}^\star) - \eta\left(\nabla f(\mathbf{x}_k) - \nabla f(\mathbf{x}^\star)\right)\right\|.

(iii) By the fundamental theorem of calculus along the segment joining x⋆\mathbf{x}^\star to xk\mathbf{x}_k, we have ∇f(xk)−∇f(x⋆)=Hˉ(xk−x⋆)\nabla f(\mathbf{x}_k) - \nabla f(\mathbf{x}^\star) = \bar{\mathbf{H}}(\mathbf{x}_k - \mathbf{x}^\star), where Hˉ=∫01∇2f(x⋆+t(xk−x⋆)) dt\bar{\mathbf{H}} = \int_0^1 \nabla^2 f(\mathbf{x}^\star + t(\mathbf{x}_k - \mathbf{x}^\star))\,dt. This averaged Hessian is symmetric with all eigenvalues in [μ,L][\mu, L], so every eigenvalue of I−ηHˉ\mathbf{I} - \eta\bar{\mathbf{H}} has the form 1−ηh1 - \eta h with h∈[μ,L]h \in [\mu, L] and magnitude at most ρ\rho. The right-hand side is therefore at most ρ ∥xk−x⋆∥\rho\,\|\mathbf{x}_k - \mathbf{x}^\star\|. ■\blacksquare

Once step (ii) removes the projection, all that remains is the contraction of unconstrained gradient descent. For a quadratic f=12x⊤Axf = \tfrac12\mathbf{x}^\top\mathbf{A}\mathbf{x}, we have Hˉ=A\bar{\mathbf{H}} = \mathbf{A}, and step (iii) recovers the exact per-mode factor ∣1−ηλi(A)∣|1 - \eta\lambda_i(\mathbf{A})| from Section 23.1, which is strictly less than 11 whenever 0<η<2/L0 \lt \eta \lt 2/L. For a convex LL-smooth ff that is not strongly convex, PGD with η=1/L\eta = 1/L likewise preserves gradient descent's O(1/k)O(1/k) objective-value rate (Nesterov, 2018).

Let us test how tight the contraction factor ρ\rho is in practice. Consider the ill-conditioned quadratic f(x)=12(x12+1000 x22)f(\mathbf{x}) = \tfrac12(x_1^2 + 1000\,x_2^2) with condition number κ=103\kappa = 10^3, minimized over the half-space x1+x2≥1x_1 + x_2 \ge 1 (written g(x)=1−x1−x2≤0g(\mathbf{x}) = 1 - x_1 - x_2 \le 0). We can solve the KKT conditions by hand: the unconstrained minimizer 0\mathbf{0} is infeasible, so the constraint must be active. Stationarity, (x1,1000 x2)−λ(1,1)=0(x_1, 1000\,x_2) - \lambda(1, 1) = \mathbf{0}, gives x1=λx_1 = \lambda and x2=λ/1000x_2 = \lambda/1000, and plugging these into x1+x2=1x_1 + x_2 = 1 yields λ⋆=1000/1001≈0.999\lambda^\star = 1000/1001 \approx 0.999, x⋆=(1000/1001,  1/1001)≈(0.999,0.001)\mathbf{x}^\star = (1000/1001,\; 1/1001) \approx (0.999, 0.001), and p⋆=500/1001≈0.4995p^\star = 500/1001 \approx 0.4995.

Now run PGD with step size η=0.0015\eta = 0.0015, safely below the stability limit 2/L=0.0022/L = 0.002. The proposition guarantees a per-step factor of ρ=max⁡(1−η, ∣1−1000 η∣)=0.9985\rho = \max(1 - \eta,\ |1 - 1000\,\eta|) = 0.9985. Starting from (3,4)(3, 4) at distance 4.474.47 from x⋆\mathbf{x}^\star, that bound predicts up to log⁡(4.47×106)/log⁡(1/ρ)≈10,200\log(4.47 \times 10^6)/\log(1/\rho) \approx 10{,}200 steps to reach distance 10−610^{-6}. 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, 0.99770.9977, comes close to ρ=0.9985\rho = 0.9985, so the worst-case per-step bound is nearly tight. The total step count, however, is a pleasant surprise: 738738 steps instead of 10,20010{,}200. 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 x2x_2 collapses within a few dozen iterations, while the flat coordinate x1x_1 creeps inward by the factor 1−η1 - \eta per step, just as in unconstrained gradient descent. Reaching the boundary line from x1=3x_1 = 3 takes roughly log⁡3/η≈730\log 3 / \eta \approx 730 steps. From step 733733 onward, every update hits the boundary and is projected onto the line x1+x2=1x_1 + x_2 = 1. Along that line, the quadratic has curvature (1+1000)/2=500.5(1 + 1000)/2 = 500.5, so the distance to x⋆\mathbf{x}^\star shrinks by 1−500.5 η=0.2491 - 500.5\,\eta = 0.249 per step—the exact rate of one-dimensional gradient descent along the line—and just a handful of additional steps finish the run. While ρ\rho 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: (0.999,0.999)=λ⋆(1,1)=−λ⋆∇g(0.999, 0.999) = \lambda^\star(1, 1) = -\lambda^\star\nabla g. Far from vanishing, it hands us back the multiplier λ⋆=1000/1001\lambda^\star = 1000/1001 we derived by hand.

PGD is a workhorse whenever ΠC\Pi_C 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 δ\boldsymbol{\delta} with ∥δ∥∞≤ϵ\|\boldsymbol{\delta}\|_\infty \le \epsilon, where projection simply clips each entry to [−ϵ,ϵ][-\epsilon, \epsilon] (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 Δ={x:x≥0,  ∑ixi=1}\Delta = \{\mathbf{x} : \mathbf{x} \ge 0,\; \sum_i x_i = 1\}. Given a vector of real scores y\mathbf{y}, how do we find the closest point on Δ\Delta? The problem

min⁡x  12∥x−y∥2subject to∑ixi=1,    −xi≤0,\min_{\mathbf{x}}\; \tfrac12\|\mathbf{x} - \mathbf{y}\|^2 \quad \textrm{subject to} \quad \textstyle\sum_i x_i = 1, \;\; -x_i \le 0,

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 τ\tau for the sum constraint and multipliers λi≥0\lambda_i \ge 0 for the nonnegativity constraints −xi≤0-x_i \le 0. Stationarity gives xi−yi+τ−λi=0x_i - y_i + \tau - \lambda_i = 0, and complementary slackness splits the coordinates into two groups. Wherever xi>0x_i > 0, we must have λi=0\lambda_i = 0 and thus xi=yi−τx_i = y_i - \tau. Wherever xi=0x_i = 0, stationarity gives λi=τ−yi\lambda_i = \tau - y_i, and dual feasibility λi≥0\lambda_i \ge 0 forces yi≤τy_i \le \tau. Putting both cases together gives

xi⋆=max⁡(yi−τ, 0),with τ set by ∑imax⁡(yi−τ, 0)=1.(23.6.10)x_i^\star = \max(y_i - \tau,\, 0), \qquad \textrm{with } \tau \textrm{ set by } \sum_i \max(y_i - \tau,\, 0) = 1. \tag{23.6.10}

In other words, projecting onto the simplex simply shifts every score down by the same threshold τ\tau and clips negative results to zero. Remarkably, this threshold formula automatically satisfies stationarity, complementary slackness, dual feasibility, and nonnegativity for any τ\tau; the unit-sum budget ∑ixi=1\sum_i x_i = 1 alone pins down τ\tau. Because the left-hand side φ(τ)=∑imax⁡(yi−τ,0)\varphi(\tau) = \sum_i \max(y_i - \tau, 0) is continuous, piecewise linear, and strictly decreasing wherever it is positive, there is a unique τ\tau that solves φ(τ)=1\varphi(\tau) = 1.

A quick hand calculation shows how to find τ\tau. Take the already-sorted vector y=(0.9,0.5,−0.2)\mathbf{y} = (0.9, 0.5, -0.2), and guess that the kk largest scores survive above zero. Then the budget ∑j≤k(yj−τ)=1\sum_{j \le k}(y_j - \tau) = 1 predicts the candidate threshold τk=(∑j≤kyj−1)/k\tau_k = (\sum_{j \le k} y_j - 1)/k, which is self-consistent only if the kk-th score stays strictly above τk\tau_k:

  • k=1k = 1: τ1=−0.1\tau_1 = -0.1, and y1=0.9>τ1y_1 = 0.9 > \tau_1;
  • k=2k = 2: τ2=0.2\tau_2 = 0.2, and y2=0.5>τ2y_2 = 0.5 > \tau_2;
  • k=3k = 3: τ3≈0.067\tau_3 \approx 0.067, but y3=−0.2<τ3y_3 = -0.2 \lt \tau_3.

The largest valid choice is k=2k = 2, giving τ=0.2\tau = 0.2 and x⋆=(0.7,0.3,0)\mathbf{x}^\star = (0.7, 0.3, 0) (Figure 23.6.4). For comparison, softmax applied to the same scores yields (0.50,0.33,0.17)(0.50, 0.33, 0.17), keeping every entry strictly positive.

Figure 23.6.4:

Projection of y=(0.9,0.5,−0.2)\mathbf{y}=(0.9,0.5,-0.2) onto the probability simplex in (a): every score is shifted down by the threshold τ=0.2\tau=0.2 and clipped at zero, with τ\tau uniquely fixed by ∑ixi=1\sum_i x_i=1. 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 {i:xi⋆>0}\{i : x_i^\star > 0\} always consists of the largest scores: if yi>yjy_i > y_j and xj⋆>0x_j^\star > 0, then xi⋆≥yi−τ>yj−τ=xj⋆>0x_i^\star \ge y_i - \tau > y_j - \tau = x_j^\star > 0. (The active sign constraints are the remaining zero coordinates.) Second, once the scores are sorted as u1≥⋯≥unu_1 \ge \cdots \ge u_n, the test uk>τku_k > \tau_k holds for every kk up to the true support size and fails beyond it. Indeed, rearranging uk>τku_k > \tau_k gives ∑j<k(uj−uk)<1\sum_{j \lt k}(u_j - u_k) \lt 1, which is just φ(uk)<1=φ(τ)\varphi(u_k) \lt 1 = \varphi(\tau); because φ\varphi is strictly decreasing, this is equivalent to uk>τu_k > \tau. We therefore sort y\mathbf{y}, pick the largest kk with uk>τku_k > \tau_k, and set τ=τk\tau = \tau_k, taking O(nlog⁡n)O(n \log n) 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 y⊤x−12∥x∥2\mathbf{y}^\top\mathbf{x} - \tfrac12\|\mathbf{x}\|^2 over Δ\Delta, whereas softmax maximizes y⊤x+H(x)\mathbf{y}^\top\mathbf{x} + H(\mathbf{x}), 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 τ\tau and a perturbed value τ+0.3\tau + 0.3, 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 x\mathbf{x}, its maximum over Δ\Delta occurs at a vertex, so testing the nn standard basis vectors ei\mathbf{e}_i 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 τ−yi\tau - y_i. Notice the diagnostic pitfall: stationarity, complementary slackness, and dual feasibility all pass up to rounding error for both the correct τ\tau 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 max⁡i(y−x⋆)⊤(ei−x⋆)≤0\max_i (\mathbf{y} - \mathbf{x}^\star)^\top(\mathbf{e}_i - \mathbf{x}^\star) \le 0 up to rounding error proves that no point on the simplex lies closer to y\mathbf{y}.

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 ℓ1\ell_1 penalty added to a least-squares loss,

F(w)=12∥Aw−b∥2+λ∥w∥1,A∈Rn×d,F(\mathbf{w}) = \tfrac12\|\mathbf{A}\mathbf{w} - \mathbf{b}\|^2 + \lambda\|\mathbf{w}\|_1, \qquad \mathbf{A} \in \mathbb{R}^{n \times d},

whose minimizer typically sets many coordinates to exact zero. We write the penalty weight as λ\lambda on purpose, because it acts like the Lagrange multiplier for a norm constraint ∥w∥1≤c\|\mathbf{w}\|_1 \le c: every minimizer of FF also minimizes the least-squares loss under the ℓ1\ell_1 budget cc that it uses, and conversely every budget c>0c > 0 corresponds to some penalty λ\lambda. Section 23.7.3.2 proves both directions, for the lasso and for ℓ2\ell_2 weight decay alike.

To see what happens numerically, let us plant a sparse vector w\mathbf{w} in R8\mathbb{R}^8 with five zero coordinates, generate n=100n = 100 noisy linear observations, and set λ=3\lambda = 3. We choose the step size η=1/L\eta = 1/L, where L=λmax⁡(A⊤A)L = \lambda_{\max}(\mathbf{A}^\top\mathbf{A}) is the largest eigenvalue of A⊤A\mathbf{A}^\top\mathbf{A} 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 LL typically lands between 130130 and 190190, while the squared column norms ∥aj∥2\|\mathbf{a}_j\|^2 of A\mathbf{A} sit around 100100.

The most naive algorithm to try is subgradient descent. Recall from Section 23.3 that the subgradients of ∣w∣|w| are sign(w)\mathrm{sign}(w) for w≠0w \neq 0 and the entire interval [−1,1][-1, 1] at the kink w=0w = 0. Picking sign(w)\mathrm{sign}(\mathbf{w}) at each step gives the update w←w−η(A⊤(Aw−b)+λ sign(w))\mathbf{w} \leftarrow \mathbf{w} - \eta\left(\mathbf{A}^\top(\mathbf{A}\mathbf{w} - \mathbf{b}) + \lambda\,\mathrm{sign}(\mathbf{w})\right). 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 ηλ\eta\lambda. The culprit is the kink at zero. At the true lasso solution, the smooth gradient on a null coordinate has magnitude strictly smaller than λ\lambda. Near zero, the penalty term −ηλ sign(wj)-\eta\lambda\,\mathrm{sign}(w_j) therefore dominates the step and kicks the coordinate across zero by about ηλ\eta\lambda every time. Because subgradient descent commits to a single slope out of the interval [−λ,λ][-\lambda, \lambda] 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 λ∣x∣+12(x−z)2\lambda|x| + \tfrac12(x - z)^2 over x∈Rx \in \mathbb{R}. Because the objective is convex, xx is optimal if and only if 00 belongs to its set of subgradients:

  • If x≠0x \neq 0, the objective is differentiable at xx, so λ sign(x)+x−z=0\lambda\,\mathrm{sign}(x) + x - z = 0. When x>0x > 0 this gives x=z−λx = z - \lambda, which requires z>λz > \lambda; when x<0x \lt 0 it gives x=z+λx = z + \lambda, which requires z<−λz \lt -\lambda.
  • If x=0x = 0, the subgradients form the interval [−λ,λ]−z[-\lambda, \lambda] - z, which contains 00 if and only if ∣z∣≤λ|z| \le \lambda.

These two cases partition the real line and combine into soft-thresholding,

proxλ∣⋅∣(z)  =  sign(z) max⁡(∣z∣−λ, 0).(23.6.11)\mathrm{prox}_{\lambda|\cdot|}(z) \;=\; \mathrm{sign}(z)\, \max\left(|z| - \lambda,\, 0\right). \tag{23.6.11}

Any input with magnitude at most λ\lambda is snapped to exact zero, while larger inputs are shrunk toward zero by λ\lambda. For example, with λ=0.7\lambda = 0.7, z=0.5z = 0.5 maps to 00, z=2z = 2 maps to 1.31.3, and z=−2z = -2 maps to −1.3-1.3 (Figure 23.6.5). That dead zone [−λ,λ][-\lambda, \lambda] is precisely how ℓ1\ell_1 regularization creates exact sparsity, whereas ℓ2\ell_2 regularization only shrinks weights toward zero without ever zeroing them out.

Figure 23.6.5:

Soft-thresholding proxλ∣⋅∣(z)\mathrm{prox}_{\lambda|\cdot|}(z) for λ=0.7\lambda = 0.7 (solid). Inputs in the dead zone [−λ,λ][-\lambda, \lambda] map to 00, as z=0.5z = 0.5 does, and every other input moves toward 00 by λ\lambda, as z=2z = 2 does. The dashed line is the identity. The dotted line is the corresponding map for the squared penalty 12x2\tfrac12 x^2, which halves every input and sends none but z=0z = 0 to zero.

Soft-thresholding is one instance of a much more general operation. The proximal operator of a function ψ\psi trades off lowering ψ(x)\psi(\mathbf{x}) against staying close to a reference point z\mathbf{z}:

proxψ(z)  =  argminx  (ψ(x)+12 ∥x−z∥2).(23.6.12)\mathrm{prox}_{\psi}(\mathbf{z}) \;=\; \mathop{\mathrm{argmin}}_{\mathbf{x}}\; \left( \psi(\mathbf{x}) + \tfrac12\, \|\mathbf{x} - \mathbf{z}\|^2 \right). \tag{23.6.12}

This map is well defined for every proper closed convex function ψ\psi—that is, convex, taking values in R∪{+∞}\mathbb{R} \cup \{+\infty\}, finite at least somewhere, and having a closed epigraph. Under those conditions, the objective in (23.6.12) is 11-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 ψ=0\psi = 0, the proximal operator is simply the identity map.
  • When ψ\psi is the indicator of a closed convex set CC (equal to 00 on CC and +∞+\infty outside), any minimizer must lie in CC, so the proximal operator reduces to the Euclidean projection proxψ=ΠC\mathrm{prox}_\psi = \Pi_C. Proximal operators are projections generalized from sets to functions.
  • When ψ=λ∥⋅∥1\psi = \lambda\|\cdot\|_1, 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 F=s+ψF = s + \psi, combining a smooth loss ss with a nonsmooth penalty ψ\psi whose proximal operator is cheap to evaluate. Suppose ss is convex with an LL-Lipschitz gradient, ψ\psi is proper closed convex, and 0<η≤1/L0 \lt \eta \le 1/L. By the descent lemma (Section 23.1, with 1/η≥L1/\eta \ge L), ss is bounded above by the quadratic model s(xk)+∇s(xk)⊤(x−xk)+12η∥x−xk∥2s(\mathbf{x}_k) + \nabla s(\mathbf{x}_k)^\top(\mathbf{x} - \mathbf{x}_k) + \tfrac{1}{2\eta}\|\mathbf{x} - \mathbf{x}_k\|^2. Rather than linearizing ψ\psi as well, we minimize this quadratic upper bound on ss together with the exact ψ\psi. Completing the square shows that the minimizer is

argminx  ψ(x)+12η∥x−(xk−η∇s(xk))∥2  =  proxηψ(xk−η ∇s(xk)),\mathop{\mathrm{argmin}}_{\mathbf{x}}\; \psi(\mathbf{x}) + \frac{1}{2\eta}\left\|\mathbf{x} - \left(\mathbf{x}_k - \eta\nabla s(\mathbf{x}_k)\right)\right\|^2 \;=\; \mathrm{prox}_{\eta\psi}\left(\mathbf{x}_k - \eta\, \nabla s(\mathbf{x}_k)\right),

which is an ordinary gradient step on the smooth part followed by a proximal step on the kinked part. Iterating this update,

xk+1=proxηψ(xk−η ∇s(xk)),(23.6.13)\mathbf{x}_{k+1} = \mathrm{prox}_{\eta\psi}\left(\mathbf{x}_k - \eta\, \nabla s(\mathbf{x}_k)\right), \tag{23.6.13}

gives proximal gradient descent, known as ISTA (the iterative shrinkage-thresholding algorithm) when ψ=λ∥⋅∥1\psi = \lambda\|\cdot\|_1. It subsumes both projected gradient descent (take ψ\psi to be the indicator of CC) and plain gradient descent (take ψ=0\psi = 0).

Even though FF is not differentiable, proximal gradient descent with η=1/L\eta = 1/L achieves the same O(1/k)O(1/k) rate as smooth gradient descent: F(xk)−F⋆≤L∥x0−x⋆∥2/(2k)F(\mathbf{x}_k) - F^\star \le L\|\mathbf{x}_0 - \mathbf{x}^\star\|^2/(2k) (Beck and Teboulle (2009), Theorem 3.1). Moreover, if ss is twice continuously differentiable and μ\mu-strongly convex (μI⪯∇2s\mu\mathbf{I} \preceq \nabla^2 s), our PGD contraction proof carries over verbatim, because all it needs is that x⋆\mathbf{x}^\star is a fixed point and that proxηψ\mathrm{prox}_{\eta\psi} is nonexpansive just like ΠC\Pi_C (Exercise 7 proves this).

For the lasso, the proximal step is soft-thresholding with threshold ηλ\eta\lambda, which snaps every coordinate within ηλ\eta\lambda 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 0.050.05 of the planted values; they cannot get much closer, because the ℓ1\ell_1 penalty shrinks even the true lasso solution toward zero by roughly λ/∥aj∥2≈0.03\lambda/\|\mathbf{a}_j\|^2 \approx 0.03.

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 wjw_j while holding all others fixed reduces to the exact one-dimensional problem we just solved. Let r−j=b−∑i≠jaiwi\mathbf{r}_{-j} = \mathbf{b} - \sum_{i \neq j}\mathbf{a}_i w_i be the residual computed without coordinate jj. The jj-th subproblem, 12∥ajwj−r−j∥2+λ∣wj∣\tfrac12\|\mathbf{a}_j w_j - \mathbf{r}_{-j}\|^2 + \lambda|w_j|, equals ∥aj∥2(12(wj−cj/∥aj∥2)2+(λ/∥aj∥2)∣wj∣)\|\mathbf{a}_j\|^2\left(\tfrac12(w_j - c_j/\|\mathbf{a}_j\|^2)^2 + (\lambda/\|\mathbf{a}_j\|^2)|w_j|\right) up to an additive constant, where cj=aj⊤r−jc_j = \mathbf{a}_j^\top\mathbf{r}_{-j}. Soft-thresholding with threshold λ/∥aj∥2\lambda/\|\mathbf{a}_j\|^2 solves it in closed form:

wj←sign(cj) max⁡(∣cj∣−λ, 0)∥aj∥2,cj=aj⊤r−j.(23.6.14)w_j \leftarrow \frac{\mathrm{sign}(c_j)\,\max(|c_j| - \lambda,\, 0)}{\|\mathbf{a}_j\|^2}, \qquad c_j = \mathbf{a}_j^\top\mathbf{r}_{-j}. \tag{23.6.14}

Whenever a feature's correlation cjc_j with the current residual has magnitude at most λ\lambda, 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 dd coordinates costs the same as a single gradient evaluation.

The same principle applies to any differentiable objective ff with coordinate-wise smoothness constants LjL_j,

f(x+tej)≤f(x)+t ∂jf(x)+12Ljt2,(23.6.15)f(\mathbf x+t\mathbf e_j) \le f(\mathbf x)+t\,\partial_jf(\mathbf x)+\tfrac12L_jt^2, \tag{23.6.15}

where minimizing the quadratic upper bound over tt produces the coordinate-descent update

xj←xj−1Lj∂jf(x).(23.6.16)x_j\leftarrow x_j-\frac{1}{L_j}\partial_jf(\mathbf x). \tag{23.6.16}

Because LjL_j measures curvature along a single axis, it can be substantially smaller than the global smoothness constant LL, allowing larger steps: in our lasso problem, Lj=∥aj∥2≈100L_j = \|\mathbf{a}_j\|^2 \approx 100, compared with L∈[130,190]L \in [130, 190]. For a positive-definite quadratic f(x)=12x⊤Ax−b⊤xf(\mathbf x)=\tfrac12\mathbf x^\top\mathbf{A}\mathbf x-\mathbf b^\top\mathbf x, the upper bound is exact with Lj=AjjL_j = A_{jj}, and the update

xj←xj−(Ax−b)jAjj(23.6.17)x_j\leftarrow x_j-\frac{(\mathbf{A}\mathbf x-\mathbf b)_j}{A_{jj}} \tag{23.6.17}

minimizes ff exactly along coordinate jj. Sweeping cyclically through all coordinates recovers the classical Gauss--Seidel iteration for Ax=b\mathbf{A}\mathbf x = \mathbf b.

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 F(w)−F⋆F(\mathbf{w}) - F^\star below 10−810^{-8} 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 level
passes 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 10−810^{-8} 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 f(x,y)=max⁡(∣x∣,∣y∣)f(x, y) = \max(|x|, |y|) at (1,1)(1, 1), moving along xx alone or along yy alone cannot decrease ff, even though the global minimum 00 sits at the origin. Coordinate descent succeeds on the lasso specifically because its nonsmooth penalty λ∑j∣wj∣\lambda\sum_j |w_j| 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 x\mathbf{x}. 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 λ⋆=4\lambda^\star = 4 and p⋆=8p^\star = 8, 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 ∇h(x⋆)≠0\nabla h(\mathbf{x}^\star) \neq \mathbf{0}, this means ∇f+ν∇h=0\nabla f + \nu\nabla h = \mathbf{0} for a Lagrange multiplier ν\nu that measures how hard the solution presses against the constraint. Adding inequality constraints leads to the four KKT conditions, where dual feasibility (λi≥0\lambda_i \ge 0) enforces one-way walls and complementary slackness (λigi=0\lambda_i g_i = 0) 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 ΠC\Pi_C. 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 λ∣⋅∣\lambda|\cdot|, and both ISTA and coordinate descent use it to solve the lasso with exact zeros that subgradient descent cannot attain.

23.6.6 Exercises#

  1. 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.

    1. Minimize f(x)=x1+x22f(\mathbf{x}) = x_1 + x_2^2 over R3\mathbb{R}^3 subject to h1(x)=x3=0h_1(\mathbf{x}) = x_3 = 0 and h2(x)=x3−x12=0h_2(\mathbf{x}) = x_3 - x_1^2 = 0. Show that the feasible set is a line, find the minimizer, and show that both constraint gradients are nonzero everywhere. Show that no multipliers ν1,ν2\nu_1, \nu_2 satisfy ∇f+ν1∇h1+ν2∇h2=0\nabla f + \nu_1 \nabla h_1 + \nu_2 \nabla h_2 = \mathbf{0} 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?
    2. Minimize f(x)=xf(x) = x over R\mathbb{R} subject to x2≤0x^2 \le 0. Find p⋆p^\star and show that no λ≥0\lambda \ge 0 satisfies the KKT stationarity condition at the minimizer. Which of LICQ and Slater's condition fails? Explain why for each.
    3. Minimize f(x)=xf(x) = x over R\mathbb{R} subject to the constraint −x≤0-x \le 0 written twice, g1(x)=g2(x)=−xg_1(x) = g_2(x) = -x. Show that LICQ fails and Slater's condition holds. Find all pairs (λ1⋆,λ2⋆)(\lambda_1^\star, \lambda_2^\star) that satisfy the KKT conditions at the minimizer. Under the relaxed constraints −x≤u1-x \le u_1 and −x≤u2-x \le u_2, compute the optimal value p⋆(u1,u2)p^\star(u_1, u_2), and verify that every KKT pair satisfies p⋆(u)≥p⋆(0)−λ⋆⊤up^\star(\mathbf{u}) \ge p^\star(\mathbf{0}) - \boldsymbol{\lambda}^{\star\top}\mathbf{u} for all u\mathbf{u}. Is p⋆p^\star differentiable at 0\mathbf{0}, and what takes the place of the relation λ⋆=−∇p⋆(0)\boldsymbol{\lambda}^\star = -\nabla p^\star(\mathbf{0})?
  2. Projected fixed points. For a closed convex set CC, the fixed points of projected gradient descent (23.6.8) are the constrained stationary points, whatever the step size η>0\eta > 0.

    1. Let C={x:x≥0}C = \{\mathbf{x} : \mathbf{x} \ge 0\}. Show that x⋆\mathbf{x}^\star is a fixed point if and only if, for every coordinate ii, either ∂f/∂xi(x⋆)=0\partial f / \partial x_i (\mathbf{x}^\star) = 0 and xi⋆≥0x_i^\star \ge 0, or ∂f/∂xi(x⋆)>0\partial f / \partial x_i (\mathbf{x}^\star) > 0 and xi⋆=0x_i^\star = 0. Show that these conditions are the KKT conditions for the constraints −xi≤0-x_i \le 0, and express the multipliers through ∇f(x⋆)\nabla f(\mathbf{x}^\star).
    2. Gradient clipping updates xk+1=xk−η ΠBc(∇f(xk))\mathbf{x}_{k+1} = \mathbf{x}_k - \eta\,\Pi_{B_c}(\nabla f(\mathbf{x}_k)), where Bc={z:∥z∥≤c}B_c = \{\mathbf{z} : \|\mathbf{z}\| \le c\}. Find the fixed points of this update and compare them with those of projected gradient descent onto the parameter ball {x:∥x∥≤r}\{\mathbf{x} : \|\mathbf{x}\| \le r\}. Which of the two updates solves a constrained problem?
    3. Binary weights restrict a parameter to the nonconvex set C={−1,1}C = \{-1, 1\}, and projecting onto CC rounds to the nearer element (to 11 at a tie). Let f(x)=12(x−a)2f(x) = \tfrac12 (x - a)^2 with 0<a<10 \lt a \lt 1. For which step sizes is x=1x = 1 a fixed point of (23.6.8), and for which is x=−1x = -1 one? What do the iterates do when η\eta exceeds both ranges? Which point minimizes ff over CC? Does either point satisfy f′(x⋆)(x−x⋆)≥0f'(x^\star)(x - x^\star) \ge 0 for all x∈Cx \in C? Which step of the fixed-point argument fails for this set?
    4. Run the PGD cell on the half-space with η=2.2/1000\eta = 2.2/1000 instead of 0.00150.0015. The projection is nonexpansive; why does the run still diverge? Which factor of the contraction proposition exceeds 11?
  3. [code] Sparsemax and the ℓ1\ell_1 ball. The function project_simplex computes the simplex projection (23.6.10), which is sparsemax; its first output is the projected vector.

    1. Show that adding the same constant to every score leaves the projection unchanged. Divide the scores by a temperature T>0T > 0, and let u1>u2u_1 > u_2 be the two largest entries of y\mathbf{y}. Show that the projection of y/T\mathbf{y} / T is one-hot exactly when T≤u1−u2T \le u_1 - u_2, and find its limit as T→∞T \to \infty. Plot the number of nonzero entries of the projection of y/T\mathbf{y} / T against TT for ten standard normal scores.
    2. Let SS be the support of x⋆\mathbf{x}^\star, and suppose that no yiy_i equals the threshold τ\tau. Derive the Jacobian ∂x⋆/∂y\partial \mathbf{x}^\star / \partial \mathbf{y} 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 nn?
    3. Show that the projection onto the ℓ1\ell_1 ball {x:∥x∥1≤z}\{\mathbf{x} : \|\mathbf{x}\|_1 \le z\} keeps the signs of y\mathbf{y} and, when ∥y∥1>z\|\mathbf{y}\|_1 > z, equals sign(y)⊙z ΠΔ(∣y∣/z)\mathrm{sign}(\mathbf{y}) \odot z\,\Pi_\Delta(|\mathbf{y}| / z) (Duchi et al., 2008). Implement it with project_simplex. Certify the result with the variational inequality (y−x^)⊤(x−x^)≤0(\mathbf{y} - \hat{\mathbf{x}})^\top(\mathbf{x} - \hat{\mathbf{x}}) \le 0, checked at the 2n2n points ±z ei\pm z\,\mathbf{e}_i. Why do these points suffice?
  4. 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.

    1. Let ff and hh be twice continuously differentiable, and let x⋆\mathbf{x}^\star satisfy (23.6.1) with multiplier ν⋆\nu^\star. For every curve x(t)\mathbf{x}(t) on {h=0}\{h = 0\} with x(0)=x⋆\mathbf{x}(0) = \mathbf{x}^\star and x˙(0)=v\dot{\mathbf{x}}(0) = \mathbf{v}, show that
d2dt2f(x(t))∣t=0=v⊤∇x2L(x⋆,ν⋆) v,\left.\frac{d^2}{dt^2} f(\mathbf{x}(t))\right|_{t=0} = \mathbf{v}^\top \nabla^2_{\mathbf{x}} \mathcal{L}(\mathbf{x}^\star, \nu^\star)\, \mathbf{v},

with the Lagrangian (23.6.2). Conclude that v⊤∇x2L v≥0\mathbf{v}^\top \nabla^2_{\mathbf{x}} \mathcal{L}\, \mathbf{v} \ge 0 for every tangent direction v\mathbf{v} at a local minimum. Why is the Hessian of ff 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).

  1. Let A\mathbf{A} be symmetric with distinct eigenvalues a1<a2<⋯<ana_1 \lt a_2 \lt \cdots \lt a_n and unit eigenvectors q1,…,qn\mathbf{q}_1, \ldots, \mathbf{q}_n, and minimize f(x)=x⊤Axf(\mathbf{x}) = \mathbf{x}^\top \mathbf{A} \mathbf{x} subject to x⊤x=1\mathbf{x}^\top \mathbf{x} = 1. Show that the Lagrange points are ±qi\pm \mathbf{q}_i with ν⋆=−ai\nu^\star = -a_i, and find the eigenvalues of ∇x2L\nabla^2_{\mathbf{x}} \mathcal{L} on the tangent space at qi\mathbf{q}_i. Which Lagrange points are local minima, which are local maxima, and which are saddles? How many independent descent directions does qi\mathbf{q}_i have?

  2. Projected gradient descent onto the sphere, x←(x−η∇f(x))/∥x−η∇f(x)∥\mathbf{x} \leftarrow (\mathbf{x} - \eta \nabla f(\mathbf{x})) / \|\mathbf{x} - \eta \nabla f(\mathbf{x})\|, projects onto a nonconvex set. Show that for this ff it is the power iteration for I−2ηA\mathbf{I} - 2\eta \mathbf{A}. Assume a1+an>0a_1 + a_n > 0. From a random start, what do the iterates xk\mathbf{x}_k and the values f(xk)f(\mathbf{x}_k) do? How does the answer depend on η>0\eta > 0?

  3. Block soft-thresholding (the group lasso). The penalty λ∥w∥2\lambda\|\mathbf{w}\|_2 on a whole vector is kinked only at w=0\mathbf{w} = \mathbf{0}. Its subgradients are w/∥w∥\mathbf{w}/\|\mathbf{w}\| for w≠0\mathbf{w} \neq \mathbf{0} and every vector of the unit ball at 0\mathbf{0} (times λ\lambda).

    1. Show that proxλ∥⋅∥2(z)=max⁡(0,  1−λ/∥z∥)z\mathrm{prox}_{\lambda\|\cdot\|_2}(\mathbf{z}) = \max\left(0,\; 1 - \lambda/\|\mathbf{z}\|\right)\mathbf{z}.
    2. Compare the zero pattern with that of coordinatewise soft-thresholding (23.6.11). When does the block prox return exactly 0\mathbf{0}, and can it zero a single coordinate of a block?
    3. What does the penalty λ∑u∥wu∥2\lambda\sum_u\|\mathbf{w}_u\|_2, summed over the vectors wu\mathbf{w}_u of outgoing weights of the hidden units uu of a network, do to the network?
    4. [code] Verify (a) against a brute-force minimization on a 2-D grid for z=(0.3,0.4)\mathbf{z} = (0.3, 0.4) and z=(3,4)\mathbf{z} = (3, 4) with λ=1\lambda = 1. The answers are 0\mathbf{0} and (2.4,3.2)(2.4, 3.2); where has (2.4,3.2)(2.4, 3.2) appeared in this section?
  4. Moreau decomposition. ● The convex conjugate of ψ\psi is ψ∗(y)=sup⁡x(y⊤x−ψ(x))\psi^*(\mathbf{y}) = \sup_{\mathbf{x}}\left(\mathbf{y}^\top\mathbf{x} - \psi(\mathbf{x})\right). For a proper closed convex ψ\psi, two facts connect it with the proximal operator (23.6.12): x=proxψ(z)\mathbf{x} = \mathrm{prox}_\psi(\mathbf{z}) exactly when z−x∈∂ψ(x)\mathbf{z} - \mathbf{x} \in \partial \psi(\mathbf{x}) (the set of subgradients), and y∈∂ψ(x)\mathbf{y} \in \partial \psi(\mathbf{x}) exactly when x∈∂ψ∗(y)\mathbf{x} \in \partial \psi^*(\mathbf{y}) (Parikh and Boyd, 2014).

    1. Derive the Moreau decomposition z=proxψ(z)+proxψ∗(z)\mathbf{z} = \mathrm{prox}_\psi(\mathbf{z}) + \mathrm{prox}_{\psi^*}(\mathbf{z}).
    2. The conjugate of ψ=λ∥⋅∥1\psi = \lambda\|\cdot\|_1 is the indicator of the box {y:∥y∥∞≤λ}\{\mathbf{y} : \|\mathbf{y}\|_\infty \le \lambda\}. Show that the decomposition writes soft-thresholding (23.6.11) as z\mathbf{z} minus a clipped copy of z\mathbf{z}.
    3. The conjugate of ψ=λ∥⋅∥2\psi = \lambda\|\cdot\|_2 is the indicator of the ℓ2\ell_2 ball of radius λ\lambda, 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 z=(3,4)\mathbf{z} = (3, 4) and λ=1\lambda = 1, which two vectors of this section add up to z\mathbf{z}?
  5. [code] Accelerated proximal gradient. ● FISTA (Beck and Teboulle, 2009) adds momentum to the ISTA update (23.6.13) for F=s+ψF = s + \psi. With v1=x0\mathbf{v}_1 = \mathbf{x}_0 and t1=1t_1 = 1, it iterates for k≥1k \ge 1

xk=proxηψ(vk−η∇s(vk)),tk+1=12(1+1+4tk2),vk+1=xk+tk−1tk+1 (xk−xk−1).(23.6.18)\begin{aligned}\mathbf{x}_k &= \mathrm{prox}_{\eta \psi}\bigl(\mathbf{v}_k - \eta \nabla s(\mathbf{v}_k)\bigr), \\ t_{k+1} &= \tfrac12\Bigl(1 + \sqrt{1 + 4t_k^2}\Bigr), \\ \mathbf{v}_{k+1} &= \mathbf{x}_k + \frac{t_k - 1}{t_{k+1}}\,(\mathbf{x}_k - \mathbf{x}_{k-1}).\end{aligned} \tag{23.6.18}

With η=1/L\eta = 1/L its objective gap satisfies F(xk)−F⋆≤2L∥x0−x⋆∥2/(k+1)2F(\mathbf{x}_k) - F^\star \le 2L\|\mathbf{x}_0 - \mathbf{x}^\star\|^2/(k+1)^2, against O(1/k)O(1/k) for ISTA.

  1. Show that the prox is nonexpansive, ∥proxηψ(u)−proxηψ(v)∥≤∥u−v∥\|\mathrm{prox}_{\eta\psi}(\mathbf{u}) - \mathrm{prox}_{\eta\psi}(\mathbf{v})\| \le \|\mathbf{u} - \mathbf{v}\|, by adding the two subgradient inequalities that characterize proxηψ(u)\mathrm{prox}_{\eta\psi}(\mathbf{u}) and proxηψ(v)\mathrm{prox}_{\eta\psi}(\mathbf{v}), as in the proof for projections.
  2. Add FISTA to the ISTA cell, on the same lasso, and plot F(xk)−F⋆F(\mathbf{x}_k) - F^\star of both methods over 100 steps on a logarithmic axis, with F⋆F^\star taken from 10410^4 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).
  3. Is F(xk)F(\mathbf{x}_k) monotone along the FISTA iterates?
  4. Replace A\mathbf{A} by a 30×10030 \times 100 Gaussian matrix, plant the same three nonzero coefficients, and run both methods for 1000 steps. Over which range of kk is FISTA ahead now? Why does ISTA still end with a fast linear phase, although A⊤A\mathbf{A}^\top\mathbf{A} is singular?

Discussions