23.3 Convexity

When a training run finishes, we usually know only one thing about the point where it stopped: the loss no longer decreases there. Gradient descent with a safe step size reliably reaches such a point, where the gradient is nearly zero (Section 23.1), and Newton's method gets there faster, even when the stationary point turns out to be a saddle (Section 23.2). Neither guarantee tells us whether a much better point is hiding somewhere else. In this section we ask when a stationary point is actually the best point available, and how quickly gradient descent converges to it.

A simple one-dimensional experiment shows that this is not an idle question. Suppose we run the exact same gradient-descent loop from 500500 random starting points, first on the bowl f(x)=(x−12)2f(x) = (x - \tfrac12)^2 and then on the tilted double well ϕ(x)=(x2−1)2+x/2\phi(x) = (x^2 - 1)^2 + x/2. On the bowl, every single run lands at the same minimizer. On the double well, nearly half of the runs get trapped in a shallower valley whose loss sits almost a full unit above the global minimum. Those stranded runs still have zero gradient—which is all that a stationarity guarantee promises—and looking at the gradient alone gives no hint that a deeper valley exists nearby.

The difference between the two functions comes down to a single geometric property. Every chord drawn between two points on the bowl lies above its graph, whereas the double well has chords that cut below the curve. Functions whose chords always lie on or above their graph are called convex, and for them our opening question has the cleanest possible answer: every local minimum is a global minimum. The proof takes just three lines (Section 23.3.2.2). Underneath it lies an even more useful fact: any tangent line to a convex function stays below the graph across the entire domain, so local information at a single point constrains the function everywhere. Summing this tangent bound along the iterates of gradient descent yields convergence rates that hold from any starting point. Averaging it over a random variable yields Jensen's inequality, a workhorse of the probability and information-theory chapters.

We cover a fair amount of ground here, and not every result carries the same weight. Three ideas are worth keeping at your fingertips: the tangent lower bound, the fact that local minima are global, and the linear convergence rate of gradient descent—whose proof relies on a single inequality that survives even when convexity fails. We begin with convex sets and three equivalent tests for convex functions, derive their main consequences, and assemble a short calculus for recognizing convex losses. Since deep-network losses are not convex, we close by asking which parts of the theory carry over to them. If you are in a hurry, you can read the chord and tangent conditions in Section 23.3.2 and jump straight to Section 23.3.3. Two examples will accompany us throughout: the chapter's running quadratic 12(x12+1000 x22)\tfrac12(x_1^2 + 1000\,x_2^2) for measuring convergence rates, and the double well ϕ\phi, which fails every test of convexity we throw at it.

23.3.1 Convex Sets#

Because convex functions are defined along line segments between points of their domain, we start with the sets those points live in. The domain of a loss, the feasible region of a constrained problem, and the set of all minimizers are all sets. Fortunately, we need only a short toolkit: one definition, three standard families of examples, and one rule for building new convex sets from old ones.

23.3.1.1 Definition and Examples#

Geometrically, a set is convex if the straight line segment connecting any two of its points stays entirely inside the set. Formally, a set C⊆RdC \subseteq \mathbb{R}^d of dd-dimensional points is convex if

θx+(1−θ) y∈Cfor all x,y∈C and all θ∈[0,1].(23.3.1)\theta \mathbf{x} + (1 - \theta)\, \mathbf{y} \in C \qquad \textrm{for all } \mathbf{x}, \mathbf{y} \in C \textrm{ and all } \theta \in [0, 1]. \tag{23.3.1}

As θ\theta moves from 11 to 00, the combination θx+(1−θ)y\theta\mathbf{x} + (1-\theta)\mathbf{y} sweeps out the line segment from x\mathbf{x} to y\mathbf{y}. Figure 23.3.1 contrasts a convex set with a nonconvex crescent and illustrates the two convex sets that appear most often in deep learning: the probability simplex and a half-space.

Figure 23.3.1:

Convex versus nonconvex sets. Left: a convex set, where the segment between any two points stays inside. Middle: a nonconvex crescent, where a chord between two of its points passes outside the set. Right: the probability simplex {p⪰0, 1⊤p=1}\{\mathbf{p}\succeq0,\ \mathbf{1}^\top\mathbf{p}=1\} and a half-space {x:a⊤x≤b}\{\mathbf{x}:\mathbf{a}^\top\mathbf{x}\leq b\}, both convex.

To see what the definition rules out, consider the annulus {x:1≤∥x∥≤2}\{\mathbf{x} : 1 \le \|\mathbf{x}\| \le 2\}. It contains both (32,0)(\tfrac32, 0) and (−32,0)(-\tfrac32, 0), yet their midpoint is the origin, which lies in the hole. A single missing midpoint is enough to violate (23.3.1).

Three families of convex sets cover almost everything we meet in this chapter. First, any hyperplane {x:a⊤x=b}\{\mathbf{x} : \mathbf{a}^\top\mathbf{x} = b\} and any half-space {x:a⊤x≤b}\{\mathbf{x} : \mathbf{a}^\top\mathbf{x} \le b\} are convex because a⊤x\mathbf{a}^\top\mathbf{x} is linear: a weighted average of two numbers equal to bb (or at most bb) is again equal to bb (or at most bb). Second, any norm ball {x:∥x∥≤r}\{\mathbf{x} : \|\mathbf{x}\| \le r\} is convex by the triangle inequality and homogeneity, ∥θx+(1−θ)y∥≤θ∥x∥+(1−θ)∥y∥≤r\|\theta\mathbf{x} + (1-\theta)\mathbf{y}\| \le \theta\|\mathbf{x}\| + (1-\theta)\|\mathbf{y}\| \le r. This single check covers both the ℓ2\ell_2 balls of weight decay and gradient clipping and the ℓ1\ell_1 balls of sparsity-inducing regularization. Third is the probability simplex Δ={p∈Rd:p⪰0, 1⊤p=1}\Delta = \{\mathbf{p} \in \mathbb{R}^d : \mathbf{p} \succeq 0,\ \mathbf{1}^\top\mathbf{p} = 1\}, where p⪰0\mathbf{p} \succeq 0 means every entry is nonnegative. Attention weights, class probabilities, and mixture weights all live on Δ\Delta, and its convexity follows immediately from our next rule.

23.3.1.2 New Convex Sets from Old#

The intersection of any collection of convex sets, finite or infinite, is always convex. If two points lie in the intersection, then they lie in every set of the collection, so the segment between them stays inside every set and therefore inside the intersection. Intuitively, a convex set has no dents, and carving a dent-free set with another dent-free set cannot create one. Unions, by contrast, have no such guarantee: [0,1]∪[2,3][0,1] \cup [2,3] is a union of two convex intervals, yet the segment from 11 to 22 leaves the set.

This single intersection rule certifies two central sets at once. The probability simplex is the intersection of one hyperplane (1⊤p=1\mathbf{1}^\top\mathbf{p} = 1) with dd half-spaces (−pi≤0-p_i \le 0), so it is convex. Likewise, the set of symmetric positive semidefinite (PSD) matrices is convex because it is an intersection of infinitely many half-spaces: for each fixed vector z\mathbf{z}, the constraint z⊤Az≥0\mathbf{z}^\top \mathbf{A} \mathbf{z} \ge 0 is a single linear inequality in the entries of A\mathbf{A}.

We can also build a convex set from the inside out. The convex hull of a set SS is the collection of all weighted averages ∑iθixi\sum_i \theta_i \mathbf{x}_i of points xi∈S\mathbf{x}_i \in S with θi≥0\theta_i \ge 0 and ∑iθi=1\sum_i \theta_i = 1. It is convex, and in fact it is the smallest convex set containing SS (Exercise 2). Seen this way, the probability simplex is simply the convex hull of the standard basis vectors e1,…,ed\mathbf{e}_1, \ldots, \mathbf{e}_d: every probability distribution is a weighted average of certainties.

23.3.2 Convex Functions#

Just as a convex set has no dents, a convex function is one whose graph curves upward without ever dipping into a second valley. We now develop three equivalent tests for convexity—requiring zero, one, and two derivatives respectively—followed by two refinements: strong convexity, which governs how fast gradient descent converges, and subgradients, which handle losses with corners. If you remember only one of the three tests, make it the second: the tangent lower bound is the engine behind almost every proof in this section.

23.3.2.1 The Chord Condition#

The first test needs no derivatives at all, which means it applies just as easily to the absolute value and the hinge loss as to smooth objectives. A function f:C→Rf : C \to \mathbb{R} on a convex domain CC is convex if its graph lies on or below every chord joining two of its points:

f(θx+(1−θ) y)  ≤  θf(x)+(1−θ)f(y)for all x,y∈C, θ∈[0,1].(23.3.2)f\left(\theta \mathbf{x} + (1 - \theta)\, \mathbf{y}\right) \;\le\; \theta f(\mathbf{x}) + (1 - \theta) f(\mathbf{y}) \qquad \textrm{for all } \mathbf{x}, \mathbf{y} \in C,\ \theta \in [0, 1]. \tag{23.3.2}

Here the left side evaluates ff at a point on the segment between x\mathbf{x} and y\mathbf{y}, while the right side gives the height of the straight chord joining (x,f(x))(\mathbf{x}, f(\mathbf{x})) to (y,f(y))(\mathbf{y}, f(\mathbf{y})) directly above that point. Let us check a concrete case: for f(x)=x2f(x) = x^2 with x=0x = 0, y=2y = 2, and θ=12\theta = \tfrac12, the graph sits at f(1)=1f(1) = 1 while the chord sits at 12⋅0+12⋅4=2\tfrac12 \cdot 0 + \tfrac12 \cdot 4 = 2, and indeed 1≤21 \le 2. For arbitrary xx, yy, and θ\theta, expanding the squares shows that the height gap between chord and graph is

θx2+(1−θ)y2−(θx+(1−θ)y)2=θ(1−θ)(x−y)2  ≥  0.\theta x^2 + (1-\theta) y^2 - \left(\theta x + (1-\theta) y\right)^2 = \theta(1-\theta)(x-y)^2 \;\ge\; 0.

Thus x2x^2 is convex, with a gap that grows quadratically with the separation between the two points. We will meet this exact expression again shortly as the variance in Jensen's inequality.

Two nearby notions are worth naming right away. If the inequality (23.3.2) is strict whenever x≠y\mathbf{x} \neq \mathbf{y} and θ∈(0,1)\theta \in (0, 1), we call ff strictly convex; if −f-f is convex, we call ff concave. Notice that a linear function f(x)=xf(x) = x is convex (and concave) but not strictly convex, because every chord lies directly on its graph. Notice also why the domain CC must be convex: without that requirement, the intermediate point θx+(1−θ)y\theta\mathbf{x} + (1-\theta)\mathbf{y} might not even belong to the domain where ff is defined.

Convex functions and convex sets are two sides of the same geometric coin. The epigraph of ff is the region on and above its graph, {(x,t):t≥f(x)}\{(\mathbf{x}, t) : t \ge f(\mathbf{x})\}. A function ff is convex if and only if its epigraph is a convex set, because a chord between two points of the epigraph stays above the graph precisely when (23.3.2) holds. Convexity also passes from functions to sets via their sublevel sets {x∈C:f(x)≤c}\{\mathbf{x} \in C : f(\mathbf{x}) \le c\}: if f(x)≤cf(\mathbf{x}) \le c and f(y)≤cf(\mathbf{y}) \le c, the chord inequality immediately gives f(θx+(1−θ)y)≤θc+(1−θ)c=cf(\theta\mathbf{x} + (1-\theta)\mathbf{y}) \le \theta c + (1-\theta) c = c. This is why any inequality constraint g(x)≤0g(\mathbf{x}) \le 0 with a convex gg automatically carves out a convex feasible region. Figure 23.3.2(a) shows both sets for a parabola.

Figure 23.3.2:

Epigraphs and sublevel sets. (a) The epigraph of the convex function f(x)=12x2+14f(x) = \tfrac12 x^2 + \tfrac14 (shaded, continuing upward without bound) is a convex set, so the chord between any two of its points stays inside it. Cutting the epigraph at height cc and projecting onto the xx-axis gives the sublevel set {f≤c}\{f \le c\}. (b) Every sublevel set of f(x)=∣x∣f(x) = \sqrt{|x|} is an interval, yet the epigraph is not convex: the midpoint of the chord lies below the graph.

Be careful, though: the converse does not hold. Every sublevel set of f(x)=∣x∣f(x) = \sqrt{|x|} is a convex interval {∣x∣≤c2}\{|x| \le c^2\}, yet ff itself is not convex. At x=0x = 0, y=1y = 1, and θ=12\theta = \tfrac12, the graph sits at 1/2≈0.71\sqrt{1/2} \approx 0.71 while the chord sits below it at 0.50.5 (Figure 23.3.2(b)).

23.3.2.2 Local Minima Are Global#

Remarkably, the chord condition alone is already enough to answer the question we posed at the opening. Figure 23.3.3 contrasts the two landscapes: a single basin on a convex objective versus two competing basins on the double well.

Figure 23.3.3:

(a) On a convex objective, gradient descent with a small fixed step reaches the global minimizer from either start. (b) On a double well, the same update from different starts reaches different minima; the basins meet at the local maximum.

Proposition (local minima are global). If ff is convex on a convex set CC, every local minimizer of ff on CC is a global minimizer.

Proof. Let x⋆\mathbf{x}^\star be a local minimizer and let y∈C\mathbf{y} \in C be any other point. For sufficiently small θ>0\theta > 0, the point zθ=(1−θ)x⋆+θy\mathbf{z}_\theta = (1-\theta)\mathbf{x}^\star + \theta\mathbf{y} along the segment toward y\mathbf{y} falls inside the neighborhood where x⋆\mathbf{x}^\star is minimal. Combining local minimality with the chord inequality gives

f(x⋆)  ≤  f(zθ)  ≤  (1−θ)f(x⋆)+θf(y).f(\mathbf{x}^\star) \;\le\; f(\mathbf{z}_\theta) \;\le\; (1-\theta)f(\mathbf{x}^\star) + \theta f(\mathbf{y}).

Subtract (1−θ)f(x⋆)(1-\theta)f(\mathbf{x}^\star) from both sides and divide by θ>0\theta > 0 to obtain f(x⋆)≤f(y)f(\mathbf{x}^\star) \le f(\mathbf{y}). ■\blacksquare

The geometric picture is just as crisp: if any strictly better point y\mathbf{y} existed anywhere in CC, the chord from x⋆\mathbf{x}^\star toward y\mathbf{y} would slope downward immediately, forcing the graph below f(x⋆)f(\mathbf{x}^\star) arbitrarily close to x⋆\mathbf{x}^\star and contradicting local minimality.

Let us now run the experiment from the opening and see how the proposition plays out numerically. We apply the same gradient-descent loop (step size 0.050.05, 600600 steps) to both the bowl (x−12)2(x - \tfrac12)^2 and the double well ϕ\phi, starting from the same 500500 points drawn uniformly on [−1.5,1.5][-1.5, 1.5]. Because the step is small, each iterate rolls downhill without hopping over the central hump, so a run on ϕ\phi should land in whichever well lies on its own side of the local maximum. We compute that local maximum as a root of ϕ′(x)=4x3−4x+12\phi'(x) = 4x^3 - 4x + \tfrac12 and check whether the fraction of starts to its right matches the fraction of runs that end in the shallower right well.

def gd(grad_fn, x, eta=0.05, steps=600):
    for _ in range(steps):
        x = x - eta * grad_fn(x)
    return x

phi = lambda x: (x**2 - 1)**2 + 0.5 * x        # tilted double well
dphi = lambda x: 4 * x * (x**2 - 1) + 0.5      # its derivative
rng = np.random.default_rng()
inits = rng.uniform(-1.5, 1.5, size=500)       # 500 random starting points
bowl = gd(lambda x: 2 * (x - 0.5), inits)      # convex: (x - 1/2)^2
well = gd(dphi, inits)
left, right = well[well < 0], well[well > 0]
print(f'bowl: all {bowl.size} runs end at x = {bowl.mean():.6f}'
      f' (spread {np.ptp(bowl):.0e})')
for name, w in (('left ', left), ('right', right)):
    print(f'well, {name}: {w.size} runs, x = {w.mean():.4f}, phi = {phi(w.mean()):.4f}')
x_max = np.sort(np.roots([4, 0, -4, 0.5]).real)[1]   # local max of phi
print(f'local max at {x_max:.4f}: predicted share right {(1.5 - x_max) / 3:.3f},'
      f' observed {right.size / inits.size:.3f}')
bowl: all 500 runs end at x = 0.500000 (spread 7e-16)
well, left : 263 runs, x = -1.0575, phi = -0.5148
well, right: 237 runs, x = 0.9304, phi = 0.4833
local max at 0.1271: predicted share right 0.458, observed 0.474

On the bowl, all 500500 runs converge to x=0.5x = 0.5 to within numerical rounding. On the double well, the runs split cleanly into two camps: one at x≈−1.0575x \approx -1.0575 with ϕ≈−0.515\phi \approx -0.515, and another at x≈0.9304x \approx 0.9304 with ϕ≈0.483\phi \approx 0.483—nearly a full unit worse. The local maximum separating the two basins sits at x≈0.127x \approx 0.127, so a fraction (1.5−0.127)/3≈0.458(1.5 - 0.127)/3 \approx 0.458 of uniform starts fall to its right. Across random draws, the observed share hovers within a few percentage points of 46%46\%, matching the prediction up to the sampling noise of 500500 starts.

Both experiments ran the exact same optimizer; only the objective changed. Convexity eliminates the second basin, though it does not by itself guarantee that gradient descent will reach the minimizer—that still requires smoothness and a safe step size, as in Section 23.1.1.

23.3.2.3 The First-Order Condition#

The chord condition has the virtue of needing no derivatives, but optimization proofs are built out of gradients. When ff is differentiable, convexity takes an equivalent first-order form: the tangent hyperplane at any point is a global under-estimator of the function,

f(y)  ≥  f(x)+∇f(x)⊤(y−x)for all x,y∈C.(23.3.3)f(\mathbf{y}) \;\ge\; f(\mathbf{x}) + \nabla f(\mathbf{x})^\top (\mathbf{y} - \mathbf{x}) \qquad \textrm{for all } \mathbf{x}, \mathbf{y} \in C. \tag{23.3.3}

Check this on f(x)=x2f(x) = x^2 at x=1x = 1: the tangent line is 1+2(y−1)=2y−11 + 2(y - 1) = 2y - 1, and the vertical gap between graph and tangent is y2−(2y−1)=(y−1)2≥0y^2 - (2y - 1) = (y - 1)^2 \ge 0 for every yy. Pause to appreciate how strong a statement (23.3.3) is: a single gradient, computed at a single point x\mathbf{x}, bounds ff from below at every other point in the domain. Almost every proof in the rest of this section rests on this one inequality. Figure 23.3.4 places the first two tests side by side: chords lie above the graph, while tangents lie below it.

Figure 23.3.4:

Two equivalent conditions. (a) The chord joining two points of the graph lies above the graph: f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y)f(\theta\mathbf{x}+(1-\theta)\mathbf{y})\le\theta f(\mathbf{x})+(1-\theta)f(\mathbf{y}). (b) The tangent at any point lies below the graph: f(y)≥f(x)+∇f(x)⊤(y−x)f(\mathbf{y})\ge f(\mathbf{x})+\nabla f(\mathbf{x})^\top(\mathbf{y}-\mathbf{x}).

23.3.2.4 The Second-Order Condition#

For smooth objectives, the quickest way to verify convexity is usually a matrix test. When ff is twice differentiable on an open convex domain CC, ff is convex if and only if its Hessian is positive semidefinite everywhere:

∇2f(x)⪰0for all x∈C.\nabla^2 f(\mathbf{x}) \succeq 0 \qquad \textrm{for all } \mathbf{x} \in C.

In one dimension this reduces to the familiar calculus rule f′′(x)≥0f''(x) \ge 0: the curve bends upward. In dd dimensions it says that every one-dimensional slice through x\mathbf{x} bends upward, since v⊤∇2f(x) v\mathbf{v}^\top \nabla^2 f(\mathbf{x})\, \mathbf{v} is the second derivative of ff along the line in direction v\mathbf{v} (Section 22.2).

This matrix test settles three workhorse examples immediately. First, a quadratic 12x⊤Ax+b⊤x\tfrac12\mathbf{x}^\top \mathbf{A} \mathbf{x} + \mathbf{b}^\top\mathbf{x} with symmetric A\mathbf{A} has constant Hessian A\mathbf{A}, so it is convex if and only if A⪰0\mathbf{A} \succeq 0. Second, the least-squares loss 12∥Xw−y∥2\tfrac12\|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2 for a design matrix X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} (nn examples, dd weights) has Hessian X⊤X\mathbf{X}^\top \mathbf{X}; because v⊤X⊤Xv=∥Xv∥2≥0\mathbf{v}^\top \mathbf{X}^\top\mathbf{X} \mathbf{v} = \|\mathbf{X}\mathbf{v}\|^2 \ge 0 for every v\mathbf{v}, least squares is always convex (Section 21.3.2.2). Third, the scalar functions exe^x, −log⁡x-\log x, and xlog⁡xx \log x are all convex on their domains, since their second derivatives exe^x, 1/x21/x^2, and 1/x1/x are positive everywhere.

Why did we insist that the domain CC be open? On a lower-dimensional domain, only directions that stay inside CC matter: for instance, x2−y2x^2 - y^2 is convex when restricted to the line y=0y = 0, even though its full two-dimensional Hessian is indefinite.

We now verify that all three tests single out the exact same class of functions. The proof has four short parts, and the second is the one worth remembering: applying the tangent bound at the intermediate point of a chord makes the gradient terms cancel—the same trick we will use to prove Jensen's inequality.

Proposition (the three characterizations agree). Let ff be differentiable on an open convex domain CC. Then the chord condition (23.3.2) and the first-order condition (23.3.3) are equivalent. If ff is twice differentiable, both are equivalent to ∇2f(x)⪰0\nabla^2 f(\mathbf{x}) \succeq 0 on CC.

Proof. (Chord ⇒\Rightarrow first-order.) Fix x,y∈C\mathbf{x}, \mathbf{y} \in C and θ∈(0,1]\theta \in (0, 1]. Apply the chord inequality at the intermediate point x+θ(y−x)\mathbf{x} + \theta(\mathbf{y} - \mathbf{x}), subtract f(x)f(\mathbf{x}) from both sides, and divide by θ\theta:

f(x+θ(y−x))−f(x)θ  ≤  f(y)−f(x).\frac{f(\mathbf{x} + \theta(\mathbf{y} - \mathbf{x})) - f(\mathbf{x})}{\theta} \;\le\; f(\mathbf{y}) - f(\mathbf{x}).

Letting θ↓0\theta \downarrow 0, the left side approaches the directional derivative ∇f(x)⊤(y−x)\nabla f(\mathbf{x})^\top(\mathbf{y} - \mathbf{x}), yielding (23.3.3).

(First-order ⇒\Rightarrow chord.) Set z=θx+(1−θ)y\mathbf{z} = \theta\mathbf{x} + (1-\theta)\mathbf{y} and apply the tangent lower bound at z\mathbf{z} twice, once toward each endpoint:

f(x)≥f(z)+∇f(z)⊤(x−z),f(y)≥f(z)+∇f(z)⊤(y−z).f(\mathbf{x}) \ge f(\mathbf{z}) + \nabla f(\mathbf{z})^\top(\mathbf{x} - \mathbf{z}), \qquad f(\mathbf{y}) \ge f(\mathbf{z}) + \nabla f(\mathbf{z})^\top(\mathbf{y} - \mathbf{z}).

Multiply the first inequality by θ\theta, the second by 1−θ1 - \theta, and add. The linear terms combine to ∇f(z)⊤(θx+(1−θ)y−z)=0\nabla f(\mathbf{z})^\top(\theta\mathbf{x} + (1-\theta)\mathbf{y} - \mathbf{z}) = 0, leaving (23.3.2).

(Second-order ⇒\Rightarrow first-order.) Restrict ff to the line segment between x\mathbf{x} and y\mathbf{y} by defining g(t)=f(x+t(y−x))g(t) = f(\mathbf{x} + t(\mathbf{y} - \mathbf{x})). Its second derivative is g′′(t)=(y−x)⊤∇2f(x+t(y−x)) (y−x)≥0g''(t) = (\mathbf{y} - \mathbf{x})^\top \nabla^2 f(\mathbf{x} + t(\mathbf{y} - \mathbf{x}))\,(\mathbf{y} - \mathbf{x}) \ge 0. By Taylor's theorem with the Lagrange remainder (Section 22.1), g(1)=g(0)+g′(0)+12g′′(τ)g(1) = g(0) + g'(0) + \tfrac12 g''(\tau) for some τ∈(0,1)\tau \in (0, 1). Dropping the nonnegative remainder yields (23.3.3).

(First-order ⇒\Rightarrow second-order.) Suppose for contradiction that v⊤∇2f(x) v<0\mathbf{v}^\top \nabla^2 f(\mathbf{x})\, \mathbf{v} \lt 0 for some x∈C\mathbf{x} \in C and direction v\mathbf{v}. Expanding ff along v\mathbf{v} gives

f(x+tv)=f(x)+t ∇f(x)⊤v+t22 v⊤∇2f(x) v+o(t2).f(\mathbf{x} + t\mathbf{v}) = f(\mathbf{x}) + t\, \nabla f(\mathbf{x})^\top\mathbf{v} + \frac{t^2}{2}\, \mathbf{v}^\top \nabla^2 f(\mathbf{x})\, \mathbf{v} + o(t^2).

For sufficiently small t>0t > 0, the negative quadratic term dominates the o(t2)o(t^2) remainder, so f(x+tv)f(\mathbf{x} + t\mathbf{v}) drops strictly below the tangent value f(x)+t∇f(x)⊤vf(\mathbf{x}) + t \nabla f(\mathbf{x})^\top\mathbf{v}, contradicting (23.3.3). ■\blacksquare

23.3.2.5 A Numerical Check of the Three Tests#

Let us put all three tests to work numerically on two losses: the least-squares objective f(w)=12∥Xw−y∥2f(\mathbf{w}) = \tfrac12\|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2 with n=20n = 20 random examples and d=2d = 2 weights, and the double well ϕ\phi from our opening experiment. For least squares we already know the exact formulas for the violations: expanding the squares as we did for x2x^2 gives the chord gap (graph minus chord) as −12θ(1−θ)∥X(u−v)∥2-\tfrac12\theta(1-\theta)\|\mathbf{X}(\mathbf{u} - \mathbf{v})\|^2 and the tangent gap (tangent minus graph) as −12∥X(v−u)∥2-\tfrac12\|\mathbf{X}(\mathbf{v} - \mathbf{u})\|^2, both nonpositive. For each loss, the code below samples 1,0001{,}000 random chords and tangents in [−1.5,1.5]d[-1.5, 1.5]^d, reports the largest violation of each kind, and checks the smallest Hessian eigenvalue across the sampled points.

X, y = rng.normal(size=(20, 2)), rng.normal(size=20)  # least squares, d = 2
losses = {'least squares': (2, lambda w: 0.5 * ((X @ w - y) ** 2).sum(),
                            lambda w: X.T @ (X @ w - y), lambda w: X.T @ X),
          'double well': (1, lambda w: phi(w[0]), dphi,  # phi'' = 12 x^2 - 4
                          lambda w: np.diag(12 * w**2 - 4))}
print('               worst chord gap  worst tangent gap  smallest Hessian eig')
for name, (d, f, grad, hess) in losses.items():
    U, V = rng.uniform(-1.5, 1.5, size=(2, 1000, d))  # 1000 random pairs
    T = rng.uniform(size=1000)
    chord = [f(t * u + (1 - t) * v) - (t * f(u) + (1 - t) * f(v))
             for u, v, t in zip(U, V, T)]             # graph minus chord
    tangent = [f(u) + grad(u) @ (v - u) - f(v)        # tangent minus graph
               for u, v in zip(U, V)]
    eig = min(np.linalg.eigvalsh(hess(u))[0] for u in U)
    print(f'{name:15s}{max(chord):15.3f}{max(tangent):19.3f}{eig:22.3f}')
i = int(np.argmax(chord))                             # the double well's worst
print(f'worst chord of the double well: from {U[i, 0]:.2f} to {V[i, 0]:.2f}')
               worst chord gap  worst tangent gap  smallest Hessian eig
least squares           -0.000             -0.003                24.375
double well              0.972              2.997                -4.000
worst chord of the double well: from -0.96 to 1.10

For least squares, not a single sampled chord dips below the graph, no tangent rises above it, and the Hessian eigenvalues stay positive, just as the algebra predicted. The double well fails all three checks: its worst chord cuts nearly one unit below the graph between points in the two valleys, its tangents slice through the curve, and its second derivative drops near −4-4 at the central hump, where ϕ′′(0)=−4\phi''(0) = -4. Notice, however, an asymmetry between the tests. Random sampling can refute convexity—a single bad chord is a complete counterexample for ϕ\phi—but it can never prove convexity; for least squares it only failed to find a violation. What proves convexity for least squares is the Hessian test, because X⊤X\mathbf{X}^\top \mathbf{X} is the same PSD matrix at every w\mathbf{w}.

23.3.2.6 Strict and Strong Convexity#

Plain convexity still permits arbitrarily flat stretches, and on a flat stretch gradient descent can crawl arbitrarily slowly. To guarantee fast convergence, we need curvature that stays bounded away from zero everywhere. Three simple functions illustrate the hierarchy, shown in Figure 23.3.5(a). The line f(x)=xf(x) = x is convex but not strictly convex, because its chords sit right on its graph. The quartic x4x^4 is strictly convex—its second derivative 12x212x^2 vanishes only at 00, so its slope increases strictly everywhere—yet f′′(0)=0f''(0) = 0 leaves it completely flat at the minimizer. The quadratic x2x^2, by contrast, has constant curvature f′′(x)=2f''(x) = 2 at every point.

Strong convexity turns this observation into a quantitative bound. For μ>0\mu > 0, a function ff is μ\mu-strongly convex if subtracting a quadratic of curvature μ\mu leaves a convex function—that is, if h(x)=f(x)−μ2∥x∥2h(\mathbf{x}) = f(\mathbf{x}) - \tfrac{\mu}{2}\|\mathbf{x}\|^2 is convex. When ff is differentiable, applying the first-order condition to hh (whose gradient is ∇f(x)−μx\nabla f(\mathbf{x}) - \mu\mathbf{x}) and using the identity ∥y∥2−∥x∥2−2x⊤(y−x)=∥y−x∥2\|\mathbf{y}\|^2 - \|\mathbf{x}\|^2 - 2\mathbf{x}^\top(\mathbf{y} - \mathbf{x}) = \|\mathbf{y} - \mathbf{x}\|^2 yields the equivalent inequality

f(y)  ≥  f(x)+∇f(x)⊤(y−x)+μ2 ∥y−x∥2for all x,y.(23.3.4)f(\mathbf{y}) \;\ge\; f(\mathbf{x}) + \nabla f(\mathbf{x})^\top(\mathbf{y} - \mathbf{x}) + \frac{\mu}{2}\, \|\mathbf{y} - \mathbf{x}\|^2 \qquad \textrm{for all } \mathbf{x}, \mathbf{y}. \tag{23.3.4}

Geometrically, the graph of ff must sit not merely above its tangent line at x\mathbf{x}, but above a parabola of curvature μ\mu tangent to it there. Applying the second-order condition to hh gives the matrix test: a twice-differentiable ff is μ\mu-strongly convex if and only if ∇2f(x)⪰μI\nabla^2 f(\mathbf{x}) \succeq \mu\mathbf{I} everywhere, where I\mathbf{I} is the identity matrix. Thus x2x^2 is 22-strongly convex, whereas x4x^4 fails to be strongly convex on any neighborhood of 00 because f′′(0)=0<μf''(0) = 0 \lt \mu for every μ>0\mu > 0. Notice also a practical bonus: adding the ridge penalty λ2∥w∥2\tfrac{\lambda}{2}\|\mathbf{w}\|^2 to any convex loss immediately makes the sum λ\lambda-strongly convex, because subtracting λ2∥w∥2\tfrac{\lambda}{2}\|\mathbf{w}\|^2 recovers the original convex loss. Weight decay does not just shrink parameters; it guarantees strong convexity.

Figure 23.3.5:

(a) Convex, strictly convex, strongly convex: xx has chords on its graph, x4x^4 is flat at the origin, x2x^2 curves everywhere. (b) A μ\mu-strongly convex, LL-smooth function, here f(x)=12x2+3log⁡cosh⁡xf(x)=\tfrac12x^2+3\log\cosh x, lies between two parabolas tangent at x0=1x_0=1, with curvatures μ=1\mu=1 and L=4L=4; their ratio is κ\kappa.

Strong convexity is the natural counterpart to smoothness. Recall from Section 23.1.1 that ff is LL-smooth when its gradient is LL-Lipschitz, ∥∇f(x)−∇f(y)∥≤L∥x−y∥\|\nabla f(\mathbf{x}) - \nabla f(\mathbf{y})\| \le L\|\mathbf{x} - \mathbf{y}\|; for a convex twice-differentiable function, this means ∇2f⪯LI\nabla^2 f \preceq L\mathbf{I}. Smoothness places a quadratic ceiling above the graph, f(y)≤f(x)+∇f(x)⊤(y−x)+L2∥y−x∥2f(\mathbf{y}) \le f(\mathbf{x}) + \nabla f(\mathbf{x})^\top(\mathbf{y} - \mathbf{x}) + \tfrac{L}{2}\|\mathbf{y} - \mathbf{x}\|^2, while strong convexity places a quadratic floor (23.3.4) beneath it. Together they sandwich ff between two tangent parabolas of curvatures μ\mu and LL, as illustrated in Figure 23.3.5(b) for f(x)=12x2+3log⁡cosh⁡xf(x) = \tfrac12 x^2 + 3\log\cosh x, whose second derivative f′′(x)=1+3/cosh⁡2xf''(x) = 1 + 3/\cosh^2 x ranges between μ=1\mu = 1 and L=4L = 4.

The ratio κ=L/μ\kappa = L/\mu is the condition number, generalizing the eigenvalue ratio we encountered for quadratics in Section 23.1.2. On our running quadratic 12(x12+1000 x22)\tfrac12(x_1^2 + 1000\,x_2^2), the extreme curvatures are μ=1\mu = 1 and L=1000L = 1000, giving κ=103\kappa = 10^3.

23.3.2.7 Subgradients#

Important losses such as the ℓ1\ell_1 norm ∥x∥1\|\mathbf{x}\|_1 and the hinge loss max⁡(0,1−z)\max(0, 1 - z) have sharp corners, where no gradient exists and (23.3.3) cannot be written as stated. Rather than give up on the tangent bound, we keep the job the gradient was doing—producing a global linear under-estimator—and turn that job into a definition. A vector g\mathbf{g} is a subgradient of ff at x\mathbf{x} if

f(y)  ≥  f(x)+g⊤(y−x)for all y.(23.3.5)f(\mathbf{y}) \;\ge\; f(\mathbf{x}) + \mathbf{g}^\top (\mathbf{y} - \mathbf{x}) \qquad \textrm{for all } \mathbf{y}. \tag{23.3.5}

The set of all subgradients at x\mathbf{x} is called the subdifferential, written ∂f(x)\partial f(\mathbf{x}). Wherever a convex function ff is differentiable, the subdifferential collapses to a single vector, {∇f(x)}\{\nabla f(\mathbf{x})\}. At a corner, however, it fans out into a whole set of supporting slopes (Figure 23.3.6). For f(x)=∣x∣f(x) = |x| at x=0x = 0, every slope g∈[−1,1]g \in [-1, 1] satisfies ∣y∣≥gy|y| \ge g y for all yy, so ∂f(0)=[−1,1]\partial f(0) = [-1, 1]; similarly, for the hinge loss max⁡(0,1−z)\max(0, 1 - z) at the kink z=1z = 1, we get ∂f(1)=[−1,0]\partial f(1) = [-1, 0].

Figure 23.3.6:

At the kink of f(x)=∣x∣f(x) = |x| the gradient does not exist, but the subdifferential is a set: every slope g∈(−1,1)g \in \left(-1, 1\right) defines a supporting line below the V, and the two extreme slopes ±1\pm 1 lie along the branches themselves, so ∂f(0)\partial f(0) is the whole interval from −1-1 to 11. The zero-slope member (orange) is the optimality certificate 0∈∂f(0)0 \in \partial f(0): the corner is a minimum certified without differentiability.

This immediately gives a derivative-free optimality test: x⋆\mathbf{x}^\star minimizes ff if and only if 0∈∂f(x⋆)\mathbf{0} \in \partial f(\mathbf{x}^\star). The proof is a one-line tautology: setting g=0\mathbf{g} = \mathbf{0} in (23.3.5) reads f(y)≥f(x⋆)f(\mathbf{y}) \ge f(\mathbf{x}^\star) for all y\mathbf{y}, which is literally the definition of a global minimizer.

Does a convex function always possess a subgradient? At every interior point of its domain, yes—a fact we will rely on to prove Jensen's inequality. In one dimension the reason is elementary. For any three points a<b<ca \lt b \lt c in an open interval where ff is convex, rearranging the chord inequality at bb gives

f(b)−f(a)b−a  ≤  f(c)−f(a)c−a  ≤  f(c)−f(b)c−b,\frac{f(b) - f(a)}{b - a} \;\le\; \frac{f(c) - f(a)}{c - a} \;\le\; \frac{f(c) - f(b)}{c - b},

meaning that chord slopes are nondecreasing from left to right. Consequently, the difference quotient q(x)=(f(x)−f(x0))/(x−x0)q(x) = (f(x) - f(x_0))/(x - x_0) at any interior point x0x_0 is nondecreasing in xx, so its one-sided limits—the left and right derivatives f−′(x0)≤f+′(x0)f'_-(x_0) \le f'_+(x_0)—both exist and are finite. Every slope g∈[f−′(x0),f+′(x0)]g \in [f'_-(x_0), f'_+(x_0)] is a subgradient: for y>x0y > x_0 we have q(y)≥f+′(x0)≥gq(y) \ge f'_+(x_0) \ge g, which rearranges to f(y)≥f(x0)+g(y−x0)f(y) \ge f(x_0) + g(y - x_0), and the case y<x0y \lt x_0 is symmetric.

The same guarantee extends to dd dimensions: at every interior point of its domain, a convex function has at least one subgradient, so a supporting hyperplane always fits beneath its graph (Rockafellar (1970); Boyd and Vandenberghe (2004), section 2.5). We will use this result without proof. Keep in mind, though, that as a search direction a subgradient is much weaker than a true gradient: stepping along −g-\mathbf{g} need not decrease ff at all (at the minimum x=0x = 0 of ∣x∣|x|, the valid subgradient g=12g = \tfrac12 steps to −η/2-\eta/2, raising the loss). For that reason, the subgradient method requires diminishing step sizes and converges slowly, with error falling only as 1/k1/\sqrt{k}.

23.3.3 Consequences of Convexity#

The rest of this book draws on three major consequences of convexity, and all three spring from the same geometric source: a supporting line or hyperplane that bounds the function from below everywhere. Averaged over a random variable, that bound yields Jensen's inequality. Evaluated at a stationary point, it certifies global optimality—sharpening what Section 23.3.2.2 deduced from the chord condition alone. Summed along the steps of gradient descent, it turns local progress into global convergence rates. Jensen's inequality stands on its own, so if you are reading purely for optimization you can skip directly to the next subsection.

23.3.3.1 Jensen's Inequality#

Expected losses, average log-likelihoods, and KL divergences all confront the same basic question: how does a function of an average compare with the average of the function? The simplest two-point example shows which way the inequality points. Let ZZ take the values 00 and 22 with probability 12\tfrac12 each, and let f(x)=x2f(x) = x^2. Evaluating ff at the mean gives f(E[Z])=f(1)=1f(\mathbb{E}[Z]) = f(1) = 1, whereas averaging ff over the outcomes gives E[f(Z)]=12⋅0+12⋅4=2\mathbb{E}[f(Z)] = \tfrac12 \cdot 0 + \tfrac12 \cdot 4 = 2. The gap of 11 is simply the variance of ZZ; in fact, for f(x)=x2f(x) = x^2 the difference E[Z2]−(E[Z])2\mathbb{E}[Z^2] - (\mathbb{E}[Z])^2 is always the variance. Look back at Figure 23.3.4(a): the chord inequality is making this exact comparison for a two-point distribution with weights θ\theta and 1−θ1 - \theta, and the gap θ(1−θ)(x−y)2\theta(1-\theta)(x - y)^2 we computed earlier for x2x^2 is that distribution's variance.

Nothing about this argument is restricted to two points. Applying (23.3.2) inductively (Exercise 2) gives the finite form

f(∑iθixi)  ≤  ∑iθi f(xi),θi≥0, ∑iθi=1.(23.3.6)f\left(\sum_i \theta_i \mathbf{x}_i\right) \;\le\; \sum_i \theta_i\, f(\mathbf{x}_i), \qquad \theta_i \ge 0,\ \sum_i \theta_i = 1. \tag{23.3.6}

Because nonnegative weights summing to one define a discrete probability distribution on the points xi\mathbf{x}_i, the natural generalization replaces the finite average with an arbitrary expectation.

Proposition (Jensen's inequality). Let ff be convex on a convex set C⊆RdC \subseteq \mathbb{R}^d, and let Z\mathbf{Z} be a random vector taking values in CC, with E∥Z∥<∞\mathbb{E}\|\mathbf{Z}\| \lt \infty and mean m=E[Z]\mathbf{m} = \mathbb{E}[\mathbf{Z}] in the interior of CC. Then

f(m)  ≤  E[f(Z)].(23.3.7)f\left(\mathbf{m}\right) \;\le\; \mathbb{E}\left[f(\mathbf{Z})\right]. \tag{23.3.7}

If ff is strictly convex, equality holds if and only if Z=m\mathbf{Z} = \mathbf{m} with probability one.

Proof. Because m\mathbf{m} lies in the interior of CC, ff has at least one subgradient g∈∂f(m)\mathbf{g} \in \partial f(\mathbf{m}). The supporting hyperplane at m\mathbf{m} bounds ff for every outcome at once: by (23.3.5),

f(Z)  ≥  f(m)+g⊤(Z−m).f(\mathbf{Z}) \;\ge\; f(\mathbf{m}) + \mathbf{g}^\top (\mathbf{Z} - \mathbf{m}).

Now take expectations of both sides. Because E[Z−m]=0\mathbb{E}[\mathbf{Z} - \mathbf{m}] = \mathbf{0}, the linear term vanishes, leaving E[f(Z)]≥f(m)\mathbb{E}[f(\mathbf{Z})] \ge f(\mathbf{m}). When ff is strictly convex, this supporting hyperplane touches the graph only at m\mathbf{m}: if it also touched at some x≠m\mathbf{x} \neq \mathbf{m}, strict convexity would force f(x+m2)<12f(x)+12f(m)f\bigl(\tfrac{\mathbf{x} + \mathbf{m}}{2}\bigr) \lt \tfrac12 f(\mathbf{x}) + \tfrac12 f(\mathbf{m}), placing the graph strictly below the supporting hyperplane at the midpoint, a contradiction. Hence the pointwise inequality is strict whenever Z≠m\mathbf{Z} \neq \mathbf{m}, so equality in expectation forces Z=m\mathbf{Z} = \mathbf{m} with probability one. ■\blacksquare

As a bonus, the same pointwise bound shows that f(Z)f(\mathbf{Z}) is bounded below by an integrable random variable, so E[f(Z)]\mathbb{E}[f(\mathbf{Z})] is always well-defined (possibly +∞+\infty, in which case the inequality holds trivially). In plain terms, spreading a random variable out while keeping its mean fixed can only increase the expected value of a convex function. For a concave function ff, the inequality reverses: E[f(Z)]≤f(E[Z])\mathbb{E}[f(\mathbf{Z})] \le f(\mathbb{E}[\mathbf{Z}]).

In machine learning, the most frequent application of Jensen's inequality is proving that KL divergence is never negative; Section 25.1 meets this same result as Gibbs' inequality.

Corollary (nonnegativity of KL divergence). For probability distributions pp and qq on a common finite alphabet, with q(x)>0q(x) > 0 wherever p(x)>0p(x) > 0,

DKL(p ∥ q)  =  ∑xp(x)log⁡p(x)q(x)  ≥  0,D_{\textrm{KL}}(p \,\|\, q) \;=\; \sum_x p(x) \log \frac{p(x)}{q(x)} \;\ge\; 0,

with equality if and only if p=qp = q.

Proof. Draw Z∼pZ \sim p and apply Jensen's inequality to the strictly convex function −log⁡-\log and the positive random variable R=q(Z)/p(Z)R = q(Z)/p(Z):

DKL(p ∥ q)=Ep[−log⁡R]  ≥  −log⁡Ep[R]=−log⁡∑x:p(x)>0p(x) q(x)p(x)  ≥  −log⁡1=0,D_{\textrm{KL}}(p \,\|\, q) = \mathbb{E}_p\left[-\log R\right] \;\ge\; -\log \mathbb{E}_p[R] = -\log \sum_{x : p(x) > 0} p(x)\, \frac{q(x)}{p(x)} \;\ge\; -\log 1 = 0,

where the last step uses ∑x:p(x)>0q(x)≤1\sum_{x : p(x) > 0} q(x) \le 1. By the equality condition of Jensen's inequality, equality holds if and only if RR is constant with probability one and qq places no mass outside the support of pp—that is, q=c pq = c\,p with c=1c = 1. ■\blacksquare

Applying the same idea to the concave function log⁡\log yields the classical arithmetic–geometric mean inequality: for any positive numbers x1,…,xNx_1, \ldots, x_N, concavity gives log⁡(1N∑ixi)≥1N∑ilog⁡xi\log\bigl(\tfrac1N \sum_i x_i\bigr) \ge \tfrac1N \sum_i \log x_i, and exponentiating both sides produces

1N∑i=1Nxi  ≥  (∏i=1Nxi)1/N,\frac{1}{N} \sum_{i=1}^N x_i \;\ge\; \left(\prod_{i=1}^N x_i\right)^{1/N},

with equality if and only if all xix_i are equal, since log⁡\log is strictly concave. Likewise, the evidence lower bound (ELBO) of Section 24.7, which bounds the logarithm of an expectation from below, is another direct application of Jensen's inequality to log⁡\log.

Let us test both Jensen's gap and the KL equality case numerically. First, for Z∼N(0,1)Z \sim \mathcal{N}(0, 1) and f(x)=exf(x) = e^x, we can compute both sides in closed form—E[eZ]=e≈1.649\mathbb{E}[e^Z] = \sqrt{e} \approx 1.649 versus eE[Z]=1e^{\mathbb{E}[Z]} = 1—and see how closely Monte Carlo matches them. Second, as we blend qq into pp via (1−ε)p+εq(1 - \varepsilon)p + \varepsilon q, how quickly does the KL divergence vanish: linearly in ε\varepsilon, or faster?

rng = np.random.default_rng()
z = rng.normal(size=1_000_000)                 # Z ~ N(0, 1)
print(f'E[exp(Z)] = {np.exp(z).mean():.2f} vs exp(E[Z]) = {np.exp(z.mean()):.2f}'
      f'  (population: {np.exp(0.5):.4f} vs 1)')
kl = lambda p, q: (p * np.log(p / q)).sum(axis=1)
p = rng.dirichlet(np.ones(10), size=1000)      # 1000 random pairs, 10 symbols
q = rng.dirichlet(np.ones(10), size=1000)
print('median KL(p || (1-eps) p + eps q), eps = 1e-2, 1e-3, 1e-4:',
      *[f'{np.median(kl(p, (1 - e) * p + e * q)):.1e}' for e in (1e-2, 1e-3, 1e-4)])
E[exp(Z)] = 1.65 vs exp(E[Z]) = 1.00  (population: 1.6487 vs 1)
median KL(p || (1-eps) p + eps q), eps = 1e-2, 1e-3, 1e-4: 1.6e-04 1.6e-06 1.6e-08

The Monte Carlo averages land right around 1.651.65 versus 1.001.00; drawing more samples shrinks the estimation noise, but the structural Jensen gap remains fixed. In the KL experiment, the divergence vanishes much faster than ε\varepsilon: every tenfold reduction in ε\varepsilon cuts the median divergence roughly a hundredfold. Expanding the logarithm explains why: DKL(p ∥ (1−ε)p+εq)≈ε22∑x(q(x)−p(x))2/p(x)D_{\textrm{KL}}(p \,\|\, (1-\varepsilon)p + \varepsilon q) \approx \tfrac{\varepsilon^2}{2}\sum_x (q(x) - p(x))^2/p(x) once ε q(x)/p(x)\varepsilon\,q(x)/p(x) is small for every xx. (Pairs where pp assigns tiny probability to some symbol enter this quadratic regime last, which is why we report the median rather than the maximum.) Equality is approached quadratically, and attained only in the limit q→pq \to p.

23.3.3.2 Local and Global Minima#

We already proved that every local minimum of a convex function is global (Section 23.3.2.2). Three companion facts follow just as effortlessly, each in a single line. First, the set of all global minimizers is convex: if both x\mathbf{x} and y\mathbf{y} attain the minimum value f⋆f^\star, the chord inequality forces every point between them to lie at or below f⋆f^\star. Second, for a differentiable convex ff on an open set, ∇f(x)=0\nabla f(\mathbf{x}) = \mathbf{0} immediately implies f(x)=f⋆f(\mathbf{x}) = f^\star, because the first-order condition with a zero gradient reads f(y)≥f(x)f(\mathbf{y}) \ge f(\mathbf{x}) for all y\mathbf{y}. Third, a small gradient guarantees a small suboptimality gap: pointing the first-order condition at a minimizer x⋆\mathbf{x}^\star gives f(x)−f⋆≤∇f(x)⊤(x−x⋆)≤∥∇f(x)∥ ∥x−x⋆∥f(\mathbf{x}) - f^\star \le \nabla f(\mathbf{x})^\top(\mathbf{x} - \mathbf{x}^\star) \le \|\nabla f(\mathbf{x})\|\,\|\mathbf{x} - \mathbf{x}^\star\|. Thus the stationarity result of Section 23.1.1—that gradient descent with η=1/L\eta = 1/L drives the smallest gradient norm to zero—upgrades for convex objectives into a guarantee on the loss value itself, provided the iterates stay within a bounded distance of x⋆\mathbf{x}^\star. In Section 23.3.3.3 we will prove that they do, and pin down the exact rate.

Be aware of two things that plain convexity does not guarantee: a minimizer need not be unique (a convex function can be flat along an entire segment), and it need not even exist (exe^x approaches 00 as x→−∞x \to -\infty without ever attaining it). Strict convexity rules out multiple minimizers, and strong convexity guarantees both existence and uniqueness.

Proposition (uniqueness). A strictly convex ff has at most one minimizer. A continuous μ\mu-strongly convex ff on a nonempty closed convex set CC with nonempty interior has exactly one.

Proof. Suppose x≠y\mathbf{x} \neq \mathbf{y} were both global minimizers with value f⋆f^\star. By the strict chord inequality at θ=12\theta = \tfrac12, their midpoint would satisfy f(x+y2)<f⋆f\bigl(\tfrac{\mathbf{x} + \mathbf{y}}{2}\bigr) \lt f^\star, a contradiction. Because strong convexity implies strict convexity, it remains only to prove existence. We prove it for a differentiable ff on C=RdC = \mathbb{R}^d, which covers the unconstrained losses in this book; the general case follows the same steps using a subgradient of f−μ2∥⋅∥2f - \tfrac{\mu}{2}\|\cdot\|^2 at an interior point of CC. Fix any starting point x0\mathbf{x}_0. In (23.3.4), the linear term is at least −∥∇f(x0)∥ ∥y−x0∥-\|\nabla f(\mathbf{x}_0)\|\,\|\mathbf{y} - \mathbf{x}_0\|, so f(y)>f(x0)f(\mathbf{y}) > f(\mathbf{x}_0) whenever ∥y−x0∥>2∥∇f(x0)∥/μ\|\mathbf{y} - \mathbf{x}_0\| > 2\|\nabla f(\mathbf{x}_0)\|/\mu. Hence the sublevel set {y:f(y)≤f(x0)}\{\mathbf{y} : f(\mathbf{y}) \le f(\mathbf{x}_0)\} is bounded, and continuity of ff ensures that it is closed. Every continuous function on a nonempty closed and bounded set attains its minimum, and the minimum over this sublevel set is automatically the global minimum over Rd\mathbb{R}^d. ■\blacksquare

The technical hypotheses on CC and continuity merely exclude pathological functions that jump upward at the boundary of their domain, which never occur for the losses in this book. By contrast, the missing minimizer of exe^x shows up in real machine learning: Exercise 3 traces it directly to logistic regression on linearly separable data.

23.3.3.3 Convergence Rates#

Convexity tells us where gradient descent stops, but not how fast it gets there—and on speed, plain convexity promises surprisingly little. Compare f(x)=x2f(x) = x^2 and f(x)=x4f(x) = x^4: both are strictly convex with unique minimizer 00, yet only x2x^2 is strongly convex. Let us run the exact same gradient-descent loop (η=18\eta = \tfrac18, starting from x0=1x_0 = 1) on both functions for 10410^4 steps and watch how differently they behave.

eta, steps = 1 / 8, 10_000
x2, x4 = np.ones(steps + 1), np.ones(steps + 1)  # iterates from x_0 = 1
for j in range(steps):                         # same start, same step
    x2[j + 1] = x2[j] - eta * 2 * x2[j]        # f(x) = x^2
    x4[j + 1] = x4[j] - eta * 4 * x4[j]**3     # f(x) = x^4
k = np.arange(1, steps + 1)
print('x^2: first k with x_k < 1e-6:', k[x2[1:] < 1e-6][0])
print('x^4: x_k * sqrt(k) at k = 1e2, 1e3, 1e4:',
      (x4[1:] * np.sqrt(k))[[99, 999, 9999]].round(3))
d2l.plot(k, [x4[1:]**4, x2[1:]**2], 'k', 'f(x_k)', xscale='log',
         yscale='log', ylim=(1e-12, 1), legend=['x^4', 'x^2'])
x^2: first k with x_k < 1e-6: 49
x^4: x_k * sqrt(k) at k = 1e2, 1e3, 1e4: [0.973 0.996 1.   ]

The contrast is dramatic. On x2x^2, every step multiplies the iterate by a constant factor 1−2η=0.751 - 2\eta = 0.75, driving it below 10−610^{-6} in just 4949 steps; the loss drops off the bottom of the plot almost immediately. On x4x^4, by contrast, each step multiplies xkx_k by 1−4ηxk21 - 4\eta x_k^2, a contraction factor that creeps closer and closer to 11 as the iterate approaches the flat valley at 00. The printed products xkkx_k\sqrt{k} settle near 11, showing that xkx_k decays only like 1/k1/\sqrt{k} and still sits at 0.010.01 after 10,00010{,}000 steps. On a log–log plot, the loss gap xk4x_k^4 therefore traces a straight line of slope −2-2. Strict convexity rules out multiple minimizers, but it cannot guarantee fast convergence; a geometric rate requires μ>0\mu > 0.

The next two propositions make this contrast completely general: every smooth strongly convex function converges geometrically like x2x^2, whereas without μ>0\mu > 0 we can guarantee only an O(1/k)O(1/k) decay. Both proofs begin with the descent lemma from Section 23.1.1: for an LL-smooth function ff and the gradient step xk+1=xk−1L∇f(xk)\mathbf{x}_{k+1} = \mathbf{x}_k - \tfrac1L\nabla f(\mathbf{x}_k),

f(xk+1)  ≤  f(xk)−12L ∥∇f(xk)∥2.f(\mathbf{x}_{k+1}) \;\le\; f(\mathbf{x}_k) - \frac{1}{2L}\, \|\nabla f(\mathbf{x}_k)\|^2.

Each step reduces the objective by at least ∥∇f(xk)∥2/(2L)\|\nabla f(\mathbf{x}_k)\|^2/(2L). On a general nonconvex function, that only proves the gradient shrinks to zero. Convexity supplies the missing link between the gradient and the suboptimality gap: whenever f(xk)−f⋆f(\mathbf{x}_k) - f^\star is still large, the gradient must be large enough to keep making progress, so the iterates cannot stall far from the optimum.

Proposition (gradient descent on smooth convex functions). Let ff be convex and LL-smooth with a minimizer x⋆\mathbf{x}^\star. Gradient descent with η=1/L\eta = 1/L satisfies, for every k≥1k \ge 1,

f(xk)−f(x⋆)  ≤  L ∥x0−x⋆∥22k.(23.3.8)f(\mathbf{x}_k) - f(\mathbf{x}^\star) \;\le\; \frac{L\, \|\mathbf{x}_0 - \mathbf{x}^\star\|^2}{2k}. \tag{23.3.8}

Thus the loss gap decays at least as fast as 1/k1/k, scaled by the smoothness constant and the squared initial distance to the minimizer. To put numbers on it, if L=1L = 1 and ∥x0−x⋆∥=10\|\mathbf{x}_0 - \mathbf{x}^\star\| = 10, the bound is 50/k50/k, guaranteeing a gap below 10−210^{-2} within 5,0005{,}000 steps.

Proof. Combine the descent lemma with the first-order condition (23.3.3) evaluated at xk\mathbf{x}_k toward the optimum, f(xk)−f(x⋆)≤∇f(xk)⊤(xk−x⋆)f(\mathbf{x}_k) - f(\mathbf{x}^\star) \le \nabla f(\mathbf{x}_k)^\top(\mathbf{x}_k - \mathbf{x}^\star):

f(xk+1)−f(x⋆)  ≤  ∇f(xk)⊤(xk−x⋆)−12L∥∇f(xk)∥2.f(\mathbf{x}_{k+1}) - f(\mathbf{x}^\star) \;\le\; \nabla f(\mathbf{x}_k)^\top (\mathbf{x}_k - \mathbf{x}^\star) - \frac{1}{2L} \|\nabla f(\mathbf{x}_k)\|^2.

Now comes the clever step: complete the square so that the right side turns into a difference of two squared distances to x⋆\mathbf{x}^\star,

∇f(xk)⊤(xk−x⋆)−12L∥∇f(xk)∥2=L2(∥xk−x⋆∥2−∥xk−x⋆−1L∇f(xk)∥2).\begin{aligned} \nabla f(\mathbf{x}_k)^\top (\mathbf{x}_k - \mathbf{x}^\star) &- \frac{1}{2L} \|\nabla f(\mathbf{x}_k)\|^2 \\ &= \frac{L}{2} \left( \|\mathbf{x}_k - \mathbf{x}^\star\|^2 - \left\|\mathbf{x}_k - \mathbf{x}^\star - \tfrac{1}{L}\nabla f(\mathbf{x}_k)\right\|^2 \right). \end{aligned}

Notice that the second norm is simply ∥xk+1−x⋆∥2\|\mathbf{x}_{k+1} - \mathbf{x}^\star\|^2. Summing over j=0,…,k−1j = 0, \ldots, k - 1, the right side telescopes cleanly:

∑j=0k−1(f(xj+1)−f(x⋆))≤L2(∥x0−x⋆∥2−∥xk−x⋆∥2)≤L2 ∥x0−x⋆∥2.\begin{aligned} \sum_{j=0}^{k-1} \left( f(\mathbf{x}_{j+1}) - f(\mathbf{x}^\star) \right) &\le \frac{L}{2} \left( \|\mathbf{x}_0 - \mathbf{x}^\star\|^2 - \|\mathbf{x}_k - \mathbf{x}^\star\|^2 \right) \\ &\le \frac{L}{2}\, \|\mathbf{x}_0 - \mathbf{x}^\star\|^2. \end{aligned}

Because the descent lemma ensures that f(xj)f(\mathbf{x}_j) never increases, the final term f(xk)−f(x⋆)f(\mathbf{x}_k) - f(\mathbf{x}^\star) is the smallest term in the sum, so k(f(xk)−f(x⋆))k\left(f(\mathbf{x}_k) - f(\mathbf{x}^\star)\right) is bounded by the total sum. Dividing by kk gives (23.3.8). ■\blacksquare

Two features of this proof are worth noting. First, the dimension dd never appears: a model with a billion weights and the same LL and initial distance enjoys the exact same worst-case guarantee. Second, before summing, the per-step inequality has a nonnegative left side f(xk+1)−f⋆≥0f(\mathbf{x}_{k+1}) - f^\star \ge 0, which forces ∥xk+1−x⋆∥≤∥xk−x⋆∥\|\mathbf{x}_{k+1} - \mathbf{x}^\star\| \le \|\mathbf{x}_k - \mathbf{x}^\star\|: every single step moves monotonically closer to every minimizer.

Adding strong convexity transforms this 1/k1/k decay into a geometric rate.

Proposition (linear rate under strong convexity). Let ff be μ\mu-strongly convex and LL-smooth, with minimizer x⋆\mathbf{x}^\star. Gradient descent with η=1/L\eta = 1/L satisfies

f(xk)−f(x⋆)  ≤  (1−μL)k(f(x0)−f(x⋆)).(23.3.9)f(\mathbf{x}_k) - f(\mathbf{x}^\star) \;\le\; \left(1 - \frac{\mu}{L}\right)^{k} \left( f(\mathbf{x}_0) - f(\mathbf{x}^\star) \right). \tag{23.3.9}

In words, every iteration shaves off at least a fraction μ/L=1/κ\mu/L = 1/\kappa of the remaining loss gap.

Proof. The proof splits into two short steps. First, strong convexity bounds the squared gradient norm from below in terms of the suboptimality gap. Minimize both sides of (23.3.4) over y\mathbf{y}: the left side attains its minimum f(x⋆)f(\mathbf{x}^\star), while the right side is a simple quadratic in y\mathbf{y} minimized at y=x−1μ∇f(x)\mathbf{y} = \mathbf{x} - \tfrac{1}{\mu}\nabla f(\mathbf{x}), where its value is f(x)−12μ∥∇f(x)∥2f(\mathbf{x}) - \tfrac{1}{2\mu}\|\nabla f(\mathbf{x})\|^2. Rearranging gives

12 ∥∇f(x)∥2  ≥  μ(f(x)−f(x⋆))for all x.(23.3.10)\frac12\, \|\nabla f(\mathbf{x})\|^2 \;\ge\; \mu \left( f(\mathbf{x}) - f(\mathbf{x}^\star) \right) \qquad \textrm{for all } \mathbf{x}. \tag{23.3.10}

Second, substitute (23.3.10) directly into the descent lemma:

f(xk+1)−f(x⋆)≤f(xk)−f(x⋆)−12L∥∇f(xk)∥2≤(1−μL)(f(xk)−f(x⋆)).\begin{aligned} f(\mathbf{x}_{k+1}) - f(\mathbf{x}^\star) &\le f(\mathbf{x}_k) - f(\mathbf{x}^\star) - \frac{1}{2L} \|\nabla f(\mathbf{x}_k)\|^2 \\ &\le \left(1 - \frac{\mu}{L}\right) \left( f(\mathbf{x}_k) - f(\mathbf{x}^\star) \right). \end{aligned}

Applying this contraction kk times completes the proof. ■\blacksquare

Look closely at the second half of that proof: it never invoked convexity at all, only the inequality (23.3.10). We will return to that surprising fact in Section 23.3.5. Notice also the enormous speedup over the non-strongly-convex case: reaching relative accuracy ϵ\epsilon now takes roughly κlog⁡(1/ϵ)\kappa \log(1/\epsilon) steps instead of O(1/ϵ)O(1/\epsilon). On our running quadratic with κ=103\kappa = 10^3, gaining six digits of accuracy, (1−10−3)k≤10−6(1 - 10^{-3})^k \le 10^{-6}, takes about 13,80013{,}800 steps by this bound.

How tight is (23.3.9) in practice? Let us measure it on a least-squares problem whose Hessian X⊤X\mathbf{X}^\top\mathbf{X} has eigenvalues 11 and 1010 by construction (μ=1\mu = 1, L=10L = 10, κ=10\kappa = 10). We run gradient descent with η=1/L\eta = 1/L and track the actual per-step ratio of successive loss gaps, (f(wk+1)−f⋆)/(f(wk)−f⋆)(f(\mathbf{w}_{k+1}) - f^\star)/(f(\mathbf{w}_k) - f^\star).

rng = np.random.default_rng()
Q, _ = np.linalg.qr(rng.normal(size=(20, 2)))  # orthonormal columns
R, _ = np.linalg.qr(rng.normal(size=(2, 2)))   # random rotation
X = Q @ np.diag([1.0, np.sqrt(10.0)]) @ R      # X^T X has eigenvalues 1, 10
y = rng.normal(size=20)
f = lambda w: 0.5 * ((X @ w - y) ** 2).sum()
mu, L = np.linalg.eigvalsh(X.T @ X)[[0, -1]]
w_star = np.linalg.lstsq(X, y, rcond=None)[0]
w, gaps = np.zeros(2), [f(np.zeros(2)) - f(w_star)]
for _ in range(60):                            # gradient descent, eta = 1/L
    w = w - X.T @ (X @ w - y) / L
    gaps.append(f(w) - f(w_star))
r = np.array(gaps[1:]) / np.array(gaps[:-1])   # per-step contraction of f - f*
print(f'mu = {mu:.4f}, L = {L:.4f}: bound 1 - mu/L = {1 - mu / L:.4f},'
      f' its square {(1 - mu / L)**2:.4f}')
print('first three ratios:', r[:3].round(4), ' largest ratio:', r.max().round(4))
mu = 1.0000, L = 10.0000: bound 1 - mu/L = 0.9000, its square 0.8100
first three ratios: [0.6084 0.81   0.81  ]  largest ratio: 0.81

Our bound promises a contraction factor of 0.90.9 per step, yet from the second step onward the measured ratio is 0.810.81—which is (1−μ/L)2(1 - \mu/L)^2. (The very first ratio depends on the random starting direction and varies from run to run.) Viewing the update in the eigenvector coordinates of X⊤X\mathbf{X}^\top\mathbf{X} explains what happened. With η=1/L\eta = 1/L, the first step multiplies the stiff eigen-component of w−w⋆\mathbf{w} - \mathbf{w}^\star by 1−L/L=01 - L/L = 0, wiping it out completely. In two dimensions, only the slow component remains; its distance to w⋆\mathbf{w}^\star shrinks by 1−μ/L1 - \mu/L per step, so the loss gap—which is quadratic in that distance—shrinks by (1−μ/L)2(1 - \mu/L)^2. In higher dimensions, the ratio climbs toward (1−μ/L)2(1 - \mu/L)^2 as the faster eigen-components decay.

Our short proof gave away a square in the contraction factor. A sharper analysis shows that gradient descent with η=1/L\eta = 1/L in fact contracts f−f⋆f - f^\star by (1−μ/L)2(1 - \mu/L)^2 per step on every LL-smooth μ\mu-strongly convex function (Taylor et al., 2018), with quadratics achieving equality; Exercise 5 proves the closely related bound κ(1−μ/L)2k\kappa(1 - \mu/L)^{2k}. Returning to our κ=103\kappa = 10^3 running quadratic, six digits of accuracy in the loss gap (three digits in the distance to the minimizer) cost roughly 13,80013{,}800 steps by our simple bound, about 6,9006{,}900 steps at the true (1−μ/L)2(1 - \mu/L)^2 rate, and half as many, 3,4543{,}454 steps, at the optimal fixed step η=2/(μ+L)\eta = 2/(\mu + L). This is half of the 6,9086{,}908 steps that Section 23.1 counted at the same step for six digits in the distance. One factor of two came from the looseness of our proof, and the second from doubling the step size.

23.3.4 Recognizing Convexity#

Global optimality and clean convergence rates are useful only if we can tell whether a given loss function is convex in the first place. Computing Hessians by hand quickly becomes tedious (and fails altogether at kinks), so in practice we rarely check convexity from scratch. Instead, we recognize convex objectives by assembling them from simple convex building blocks.

23.3.4.1 A Calculus of Convex Functions#

Four elementary operations preserve convexity, and almost every convex loss in machine learning is built from basic convex atoms using just these four rules.

  1. Nonnegative weighted sums. If f1,…,fmf_1, \ldots, f_m are convex and wi≥0w_i \ge 0, then ∑iwifi\sum_i w_i f_i is convex: simply multiply the chord inequality for each fif_i by wiw_i and add. In particular, averaging a convex per-example loss over a training set always yields a convex objective.
  2. Affine pre-composition. If ff is convex, then so is x↦f(Ax+b)\mathbf{x} \mapsto f(\mathbf{A}\mathbf{x} + \mathbf{b}): an affine map carries the line segment between x\mathbf{x} and y\mathbf{y} onto the segment between their images with the exact same weight θ\theta, so the chord inequality transfers directly. As a result, any loss that is convex in a model's predictions is automatically convex in the weights of a linear model producing those predictions.
  3. Pointwise maximum and supremum. If every fif_i is convex, then so is max⁡ifi\max_i f_i. The quickest proof uses epigraphs: the epigraph of a pointwise maximum is the intersection of the individual epigraphs, and intersections of convex sets are convex. Consequently, the upper envelope of any collection of affine functions is convex, no matter how large the collection.
  4. Monotone composition. If gg is convex and hh is both convex and nondecreasing, then the composition h∘gh \circ g is convex. Two lines prove it:
h(g(θx+(1−θ)y))  ≤  h(θg(x)+(1−θ)g(y))  ≤  θ h(g(x))+(1−θ) h(g(y)),h\bigl(g(\theta\mathbf{x} + (1-\theta)\mathbf{y})\bigr) \;\le\; h\bigl(\theta g(\mathbf{x}) + (1-\theta) g(\mathbf{y})\bigr) \;\le\; \theta\, h(g(\mathbf{x})) + (1-\theta)\, h(g(\mathbf{y})),

where the first inequality uses convexity of gg together with monotonicity of hh, and the second uses convexity of hh. Do not forget the monotonicity requirement on hh: h(t)=t2h(t) = t^2 is convex but not nondecreasing, and composing it with the convex function g(x)=x2−1g(x) = x^2 - 1 produces the nonconvex double well (x2−1)2(x^2 - 1)^2 (which becomes ϕ\phi after adding x/2x/2).

These four rules certify nearly all the standard convex losses in one sweep. The hinge loss max⁡(0,1−y w⊤x)\max(0, 1 - y\,\mathbf{w}^\top\mathbf{x}) is the maximum of two affine functions of w\mathbf{w} (rules 3 and 2). The ℓ1\ell_1 norm ∥w∥1=∑imax⁡(wi,−wi)\|\mathbf{w}\|_1 = \sum_i \max(w_i, -w_i) is a sum of maxima of affine functions (rules 1, 3, and 2). The logistic loss log⁡(1+e−y w⊤x)\log(1 + e^{-y\,\mathbf{w}^\top\mathbf{x}}) starts from the scalar function t↦log⁡(1+et)t \mapsto \log(1 + e^t)—convex because its second derivative et/(1+et)2e^t/(1 + e^t)^2 is strictly positive—pre-composed with an affine map (rule 2) and summed over training examples (rule 1). Adding the ridge penalty λ2∥w∥2\tfrac{\lambda}{2}\|\mathbf{w}\|^2 to any of these produces a strongly convex objective. Notice, however, that convexity does not automatically upgrade to strong convexity under rule 3: max⁡(x2,1−x)\max(x^2, 1 - x) is convex, yet it equals the flat affine line 1−x1 - x across the entire interval (−1.618,0.618)(-1.618, 0.618) between the two roots of x2=1−xx^2 = 1 - x, so it is not strongly convex.

Notice what is conspicuously absent from our list: composition with an inner map that is neither affine nor convex. A two-layer neural network W2 relu(W1x)\mathbf{W}_2\,\mathrm{relu}(\mathbf{W}_1\mathbf{x}) is precisely such a composition in its weights, which is the exact point where convexity breaks down (Section 23.3.5).

23.3.4.2 Log-Sum-Exp and the Softmax Covariance#

One fundamental loss sits just outside the four rules above: the log-sum-exp function lse(x)=log⁡∑i=1dexi\mathrm{lse}(\mathbf{x}) = \log \sum_{i=1}^d e^{x_i} at the heart of every softmax cross-entropy loss. Geometrically, lse(x)\mathrm{lse}(\mathbf{x}) is a smooth upper approximation to max⁡ixi\max_i x_i that never overshoots it by more than log⁡d\log d. Rather than force it into the composition rules, we can certify its convexity directly through its Hessian—which turns out to have a remarkably clean probabilistic interpretation.

Proposition (log-sum-exp is convex). The Hessian of lse\mathrm{lse} at x\mathbf{x} is

∇2lse(x)=diag(s)−ss⊤,s=softmax(x),(23.3.11)\nabla^2 \mathrm{lse}(\mathbf{x}) = \mathrm{diag}(\mathbf{s}) - \mathbf{s}\mathbf{s}^\top, \qquad \mathbf{s} = \mathrm{softmax}(\mathbf{x}), \tag{23.3.11}

which is the covariance matrix of the one-hot encoding of a class drawn from s\mathbf{s}. Since every covariance matrix is PSD, lse\mathrm{lse} is convex.

Proof. Differentiating once gives ∂ lse/∂xi=exi/∑kexk=si\partial\, \mathrm{lse} / \partial x_i = e^{x_i} / \sum_k e^{x_k} = s_i, so the gradient of lse\mathrm{lse} is simply the softmax vector s\mathbf{s}. Differentiating si=exi/∑kexks_i = e^{x_i}/\sum_k e^{x_k} a second time by the quotient rule yields

∂si∂xj=δij exi∑kexk−exi exj(∑kexk)2=si (δij−sj),\frac{\partial s_i}{\partial x_j} = \frac{\delta_{ij}\, e^{x_i}}{\sum_k e^{x_k}} - \frac{e^{x_i}\, e^{x_j}}{\left(\sum_k e^{x_k}\right)^2} = s_i\,(\delta_{ij} - s_j),

which is the (i,j)(i, j) entry of diag(s)−ss⊤\mathrm{diag}(\mathbf{s}) - \mathbf{s}\mathbf{s}^\top (the same softmax Jacobian derived in Section 22.4). Now let YY be a random class index drawn with probabilities P(Y=i)=siP(Y = i) = s_i, and let eY\mathbf{e}_Y be its one-hot vector. Then E[eY]=s\mathbb{E}[\mathbf{e}_Y] = \mathbf{s} and E[eYeY⊤]=diag(s)\mathbb{E}[\mathbf{e}_Y \mathbf{e}_Y^\top] = \mathrm{diag}(\mathbf{s}), so the Hessian is literally Cov(eY)=diag(s)−ss⊤\textrm{Cov}(\mathbf{e}_Y) = \mathrm{diag}(\mathbf{s}) - \mathbf{s}\mathbf{s}^\top. Every covariance matrix is PSD; explicitly, for any direction v\mathbf{v},

v⊤∇2lse(x) v=∑isivi2−(∑isivi)2=E[vY2]−(E[vY])2=Var(vY)  ≥  0.  ■\mathbf{v}^\top \nabla^2 \mathrm{lse}(\mathbf{x})\, \mathbf{v} = \sum_i s_i v_i^2 - \left(\sum_i s_i v_i\right)^2 = \mathbb{E}\left[v_Y^2\right] - \left(\mathbb{E}[v_Y]\right)^2 = \textrm{Var}(v_Y) \;\ge\; 0. \;\blacksquare

In other words, the curvature of log-sum-exp along a direction v\mathbf{v} is nothing more than the variance of the coordinate vYv_Y under the softmax distribution.

Three practical consequences follow immediately from this formula. First, the cross-entropy loss as a function of the logits, ℓ(z)=lse(z)−zy\ell(\mathbf{z}) = \mathrm{lse}(\mathbf{z}) - z_y for true class yy, is log-sum-exp minus a linear term, hence convex. Second, softmax regression (Section 3.1) feeds affine logits z=Wx+b\mathbf{z} = \mathbf{W}\mathbf{x} + \mathbf{b} into ℓ(z)\ell(\mathbf{z}), so by rule 2 the loss is convex in the weights: training a linear classifier on fixed features is always a convex problem. Third, the variance formula immediately predicts a zero eigenvalue along the all-ones vector 1\mathbf{1}, because Var(vY)=0\textrm{Var}(v_Y) = 0 whenever all entries viv_i are equal. That flat direction reflects the shift invariance lse(x+c1)=lse(x)+c\mathrm{lse}(\mathbf{x} + c\mathbf{1}) = \mathrm{lse}(\mathbf{x}) + c that makes the numerically stable softmax possible. The very same Jacobian diag(s)−ss⊤\mathrm{diag}(\mathbf{s}) - \mathbf{s}\mathbf{s}^\top also governs the backward pass of every attention head, whose attention weights are a softmax of query–key scores (Section 10.2).

How large can the curvature of log-sum-exp get? As Exercise 6 proves, no eigenvalue of its Hessian ever exceeds 12\tfrac12, regardless of the logits, so 12\tfrac12 is a global smoothness constant. Where is that ceiling approached, and how curved is the loss at typical logits? Below, we draw 10,00010{,}000 random six-class logit vectors, rescale them by a temperature multiplier cc, and report both the largest Hessian eigenvalue across all draws and the median.

z = rng.normal(size=(10_000, 6))               # 10,000 draws of six logits
print('  c   largest eigenvalue   median')
for c in (0.1, 1.0, 3.0, 10.0, 30.0):
    s = np.exp(c * z - (c * z).max(axis=1, keepdims=True))
    s /= s.sum(axis=1, keepdims=True)          # softmax of each row
    hess = s[:, :, None] * np.eye(6) - s[:, :, None] * s[:, None, :]
    top = np.linalg.eigvalsh(hess)[:, -1]      # largest eigenvalue per draw
    print(f'{c:5.1f}  {top.max():14.4f}  {np.median(top):12.4f}')
  c   largest eigenvalue   median
  0.1          0.2193        0.1843
  1.0          0.4546        0.3071
  3.0          0.4983        0.2995
 10.0          0.5000        0.0165
 30.0          0.5000        0.0000

As predicted, the largest eigenvalue never exceeds 12\tfrac12, confirming that softmax cross-entropy is 12\tfrac12-smooth in the logits at every temperature. When the logits are small (c=0.1c = 0.1), the softmax is nearly uniform across the six classes and the curvature hovers just above 16\tfrac16. At moderate scales, the typical curvature peaks with a median near 0.30.3. Push cc larger, however, and a split emerges: a typical draw becomes sharply confident (nearly one-hot), so its median curvature collapses toward zero—the loss is almost completely flat around a confident prediction. Meanwhile, the maximum over the 10,00010{,}000 draws climbs toward 12\tfrac12, coming from the rare draws where the top two logits nearly tie and the softmax splits its probability evenly between two classes.

23.3.5 Beyond Convexity#

Deep neural networks do not have convex loss landscapes. In this final subsection we show why with just two scalar weights, identify the weaker condition that preserves gradient descent's linear convergence rate without convexity, and ask how an optimizer chooses a single solution when infinitely many global minimizers exist.

23.3.5.1 Nonconvex Networks#

Consider f(a,b)=(ab−1)2f(a, b) = (ab - 1)^2: a linear model with two scalar weights stacked in sequence under a squared loss—the simplest possible "deep" network. As Figure 23.3.7 shows, its global minimizers form the hyperbola {ab=1}\{ab = 1\}. We proved in Section 23.3.3 that the minimizer set of any convex function must be convex, yet a hyperbola is manifestly not convex: the midpoint of the two minimizers (1,1)(1, 1) and (−1,−1)(-1, -1) is the origin (0,0)(0, 0), where f(0,0)=1f(0, 0) = 1 sits well above the minimum value 00. The origin is a stationary point, not a minimum—its Hessian ∇2f(0,0)\nabla^2 f(0, 0) has eigenvalues ±2\pm 2, making it a saddle point.

Figure 23.3.7:

The two-weight model (ab−1)2(ab-1)^2. Its minimizers form the hyperbola ab=1ab=1, which is not convex: the midpoint of (1,1)(1,1) and (−1,−1)(-1,-1) is the origin, where f=1f=1 and the Hessian has eigenvalues ±2\pm2.

Real neural networks lose convexity for a closely related structural reason. Permuting the hidden units of any layer—together with their incoming and outgoing weights—leaves the network's input–output function unchanged, so every minimizer automatically comes with a huge number of symmetric copies scattered across parameter space. Generically these copies are distinct, and averaging two of them alters the function and raises the loss, just as averaging (1,1)(1, 1) and (−1,−1)(-1, -1) landed on the saddle at the origin. A minimizer set that contains distinct points without containing their midpoints cannot belong to a convex objective.

Even a tiny network with two ReLU units already exhibits this failure. The parameter vector (w1,v1,w2,v2)=(1,1,−1,1)(w_1, v_1, w_2, v_2) = (1, 1, -1, 1) in v1 relu(w1x)+v2 relu(w2x)v_1\,\mathrm{relu}(w_1 x) + v_2\,\mathrm{relu}(w_2 x) computes ∣x∣|x|, and swapping the two units computes ∣x∣|x| identically. Yet averaging the two parameter vectors cancels the input weights to zero and collapses the network to the zero function.

23.3.5.2 The Polyak–Łojasiewicz Condition#

Remember how our proof of the linear convergence rate under strong convexity worked? It used convexity only in the first step, to derive (23.3.10); the second step never touched convexity at all. That intermediate inequality has a name of its own. A function ff with infimum f⋆f^\star satisfies the Polyak–Łojasiewicz (PL) inequality with constant μ>0\mu > 0 if 12∥∇f(x)∥2≥μ (f(x)−f⋆)\tfrac12\|\nabla f(\mathbf{x})\|^2 \ge \mu\,(f(\mathbf{x}) - f^\star) for all x\mathbf{x}, a condition introduced independently by Polyak and Łojasiewicz in 1963 (Polyak, 1963; \Lojasiewicz, 1963). Intuitively, it says that the gradient is allowed to be small only where the loss is already close to optimal.

Proposition (linear rate under PL). Let ff be LL-smooth, bounded below with f⋆=inf⁡ff^\star = \inf f, and satisfy the PL inequality with constant μ\mu. Then gradient descent with η=1/L\eta = 1/L satisfies f(xk)−f⋆≤(1−μ/L)k (f(x0)−f⋆)f(\mathbf{x}_k) - f^\star \le (1 - \mu/L)^k\,(f(\mathbf{x}_0) - f^\star).

Proof. Repeat the second half of the strong-convexity proof verbatim: combining the descent lemma with the PL inequality yields f(xk+1)−f⋆≤(1−μ/L)(f(xk)−f⋆)f(\mathbf{x}_{k+1}) - f^\star \le (1 - \mu/L)(f(\mathbf{x}_k) - f^\star) (Karimi et al., 2016), and iterating kk times finishes the proof. ■\blacksquare

What makes the PL condition so appealing is how much nonconvexity it tolerates. A PL function can have multiple minimizers, flat manifolds of minimizers, and regions of negative curvature. Two things, however, are non-negotiable: every stationary point must be a global minimizer (since ∇f(x)=0\nabla f(\mathbf{x}) = \mathbf{0} forces f(x)=f⋆f(\mathbf{x}) = f^\star), and f−f⋆f - f^\star must grow at least quadratically away from the minimizer set. The quartic x4x^4 shows why the second requirement matters: it has only one stationary point, its global minimum, yet it fails PL because 12f′(x)2=8x6\tfrac12 f'(x)^2 = 8x^6 cannot stay above μx4\mu x^4 as x→0x \to 0 for any μ>0\mu > 0. That failure is precisely why gradient descent crawled on x4x^4 in Section 23.3.3.3. In short, strong convexity implies PL (as we proved earlier), but the converse is false.

The classic example of a nonconvex PL function is f(x)=x2+3sin⁡2xf(x) = x^2 + 3\sin^2 x, whose second derivative 2+6cos⁡2x2 + 6\cos 2x dips all the way to −4-4 and peaks at L=8L = 8. Let us estimate its PL constant numerically on [−5,5][-5, 5] and run gradient descent from x0=4.5x_0 = 4.5 using step size η=116=1/(2L)\eta = \tfrac1{16} = 1/(2L). (We choose 1/(2L)1/(2L) rather than 1/L1/L because at η=1/L\eta = 1/L the local contraction factor 1−f′′(0) η1 - f''(0)\,\eta vanishes at the origin, hiding the asymptotic rate.) At η=1/(2L)\eta = 1/(2L), the quadratic ceiling guarantees a per-step decrease of 38Lf′(xk)2\tfrac{3}{8L} f'(x_k)^2, which the PL inequality turns into the contraction factor 1−3μ4L1 - \tfrac{3\mu}{4L}.

f_pl = lambda x: x**2 + 3 * np.sin(x)**2       # nonconvex; f* = 0 at x = 0
df_pl = lambda x: 2 * x + 3 * np.sin(2 * x)
xs = np.linspace(-5, 5, 100001)
xs = xs[np.abs(xs) > 1e-3]                     # avoid 0/0 at the minimizer
mu = (0.5 * df_pl(xs)**2 / f_pl(xs)).min()
print(f'PL constant on [-5, 5]: mu = {mu:.4f}')
print(f"min f'' = {(2 + 6 * np.cos(2 * xs)).min():.2f}  (f is not convex)")
path = [4.5]
for _ in range(80):                            # gradient descent, eta = 1/16
    path.append(path[-1] - df_pl(path[-1]) / 16.0)
path = np.array(path)
ratios = f_pl(path[1:]) / f_pl(path[:-1])      # per-step contraction of f - f*
j = ratios.argmax()
print(f'guaranteed {1 - 3 * mu / 32:.4f}; largest ratio {ratios[j]:.4f}'
      f' from x = {path[j]:.2f}; last ratio {ratios[-1]:.4f}')
PL constant on [-5, 5]: mu = 0.1755
min f'' = -4.00  (f is not convex)
guaranteed 0.9835; largest ratio 0.9778 from x = 2.19; last ratio 0.2500

The PL constant on [−5,5][-5, 5] is μ≈0.1755\mu \approx 0.1755, and the minimum of f′′f'' is −4-4: the function is nonconvex yet PL. The window suffices, because outside it the ratio 12f′(x)2/f(x)\tfrac12 f'(x)^2 / f(x) stays well above this value and tends to 22 as ∣x∣→∞|x| \to \infty; Exercise 4 proves the bound.

With this μ\mu the guaranteed factor is about 0.980.98 per step. The largest measured ratio, about 0.9780.978, comes from x≈2.2x \approx 2.2, where 12f′(x)2/f(x)\tfrac12 f'(x)^2/f(x) attains its minimum μ\mu, so there the guarantee is nearly tight. Near the minimizer the ratio settles at 0.250.25. That limit comes from the local quadratic: near 00, f≈12f′′(0) x2f \approx \tfrac12 f''(0)\,x^2 with f′′(0)=8f''(0) = 8, each step multiplies xx by 1−8/16=121 - 8/16 = \tfrac12, and the gap, quadratic in xx, by 14\tfrac14.

PL can also hold on part of the space. For (ab−1)2(ab - 1)^2 the gradient satisfies 12∥∇f∥2=2(a2+b2)f\tfrac12\|\nabla f\|^2 = 2(a^2 + b^2) f, so PL holds with constant 2r22r^2 on the region {a2+b2≥r2}\{a^2 + b^2 \ge r^2\} and with no constant near the saddle at the origin. Analyses of wide networks establish such local PL inequalities near interpolating solutions (Liu et al., 2022), which gives a rate for the training loss and says nothing about generalization.

23.3.5.3 Implicit Bias#

When a loss has many global minimizers, convex or not, the optimizer decides which one it reaches: it has an implicit bias. For deep learning this is not a curiosity. A network with more weights than training examples can fit its data in many ways, all with the same training loss and with different predictions elsewhere, so the choice among them decides how the model generalizes. The simplest case is underdetermined least squares, with fewer examples than weights and X\mathbf{X} of full row rank. Every gradient X⊤(Xw−y)\mathbf{X}^\top(\mathbf{X}\mathbf{w} - \mathbf{y}) lies in the row space of X\mathbf{X}, so iterates started from w0=0\mathbf{w}_0 = \mathbf{0} never leave it. The limit is therefore the one interpolant in the row space, the minimum-norm interpolant that the pseudoinverse computes (Exercise 4 of Section 21.5). For logistic regression on separable data the loss has no minimizer at all, yet the direction of the iterates converges to the maximum-margin separator, the solution of the hard-margin support vector machine (Soudry et al., 2018) (Exercise 8). Which minimizer is selected depends on the model, the loss, the start, and the update rule. A fixed diagonal preconditioner D\mathbf{D}, for instance, leads to the interpolant that minimizes w⊤D−1w\mathbf{w}^\top\mathbf{D}^{-1}\mathbf{w} instead of ∥w∥2\|\mathbf{w}\|^2 (Exercise 7), so the per-coordinate steps of Adam (Section 9.5) need not select the solution that gradient descent selects.

Every result of this section assumes the exact gradient and weights free to range over all of Rd\mathbb{R}^d. Training uses minibatch gradients that are right only on average (Section 23.4), and a weight vector confined to a ball, a simplex, or a half-space needs the projections and multipliers of Section 23.6.

23.3.6 Summary#

A convex function lies below its chords. For differentiable functions this is equivalent to lying above every tangent, and for twice-differentiable functions to a PSD Hessian; at a corner a subgradient takes the place of the gradient. Because one gradient bounds the function everywhere, a stationary point is a global minimizer, and the descent lemma turns into global rates for gradient descent: L∥x0−x⋆∥2/(2k)L\|\mathbf{x}_0 - \mathbf{x}^\star\|^2/(2k) for smooth convex ff, and a factor 1−μ/L1 - \mu/L per step with strong convexity, hence about κlog⁡(1/ϵ)\kappa\log(1/\epsilon) steps. Jensen's inequality is the chord inequality for expectations and gives DKL≥0D_{\textrm{KL}} \ge 0. Four closure rules certify the hinge, ℓ1\ell_1, and logistic losses; log-sum-exp, and with it the softmax cross-entropy, is convex because its Hessian is a covariance. Network losses are generically nonconvex. Where a PL inequality holds, the linear rate survives without convexity, and among many minimizers the optimizer's dynamics pick one.

23.3.7 Exercises#

  1. Subdifferentials of norms and maxima. Compute each subdifferential from the definition (23.3.5).

    1. Compute ∂∥x∥2\partial \|\mathbf{x}\|_2 at every x∈Rd\mathbf{x} \in \mathbb{R}^d, including x=0\mathbf{x} = \mathbf{0}.
    2. Let f(x)=max⁡ixif(\mathbf{x}) = \max_i x_i, and let A(x)={i:xi=f(x)}\mathcal{A}(\mathbf{x}) = \{i : x_i = f(\mathbf{x})\} be its set of active coordinates. Show that ∂f(x)\partial f(\mathbf{x}) is the convex hull of {ei:i∈A(x)}\{\mathbf{e}_i : i \in \mathcal{A}(\mathbf{x})\}. Backpropagation through max pooling passes the incoming gradient to a single maximal input, so it uses one vertex ei\mathbf{e}_i of this hull. Suppose that two or more inputs tie. Show that a small step along −ei-\mathbf{e}_i does not decrease ff. For which g∈∂f(x)\mathbf{g} \in \partial f(\mathbf{x}) is −g-\mathbf{g} a descent direction, and which of them makes the directional derivative of ff along −g/∥g∥-\mathbf{g}/\|\mathbf{g}\| most negative?
    3. Use (a) and the optimality criterion 0∈∂(⋅)\mathbf{0} \in \partial(\cdot) to minimize λ∥w∥2+12∥w−z∥2\lambda\|\mathbf{w}\|_2 + \tfrac12\|\mathbf{w} - \mathbf{z}\|^2 over w∈Rd\mathbf{w} \in \mathbb{R}^d, which gives the proximal operator of λ∥⋅∥2\lambda\|\cdot\|_2. Compare the zero pattern of the solution with that of coordinatewise soft-thresholding, wi=sign(zi)max⁡(∣zi∣−λ,0)w_i = \mathrm{sign}(z_i)\max(|z_i| - \lambda, 0). What does this penalty do when w\mathbf{w} collects the outgoing weights of one hidden unit?
  2. Convex combinations and Jensen's inequality. Write ∑i=1Nθixi\sum_{i=1}^N \theta_i \mathbf{x}_i with θi≥0\theta_i \ge 0 and ∑iθi=1\sum_i \theta_i = 1 for a convex combination of NN points.

    1. Show by induction on NN that a convex set CC contains every convex combination of points of CC. This is the inclusion that completes the description of the convex hull in Section 23.3.1.
    2. Apply (a) to the epigraph of a convex function ff to derive the finite form (23.3.6) of Jensen's inequality.
    3. Let ff be twice differentiable with α≤f′′≤β\alpha \le f'' \le \beta on an interval that contains the values of a random variable ZZ with mean mm and variance s2s^2. Show that the Jensen gap E[f(Z)]−f(m)\mathbb{E}[f(Z)] - f(m) lies between αs2/2\alpha s^2/2 and βs2/2\beta s^2/2. Check the bounds on the two-point example of the text, Z∈{0,2}Z \in \{0, 2\} with f(x)=x2f(x) = x^2, where α=β=2\alpha = \beta = 2. Then apply the result to f=−log⁡f = -\log to bound log⁡E[Z]−E[log⁡Z]\log \mathbb{E}[Z] - \mathbb{E}[\log Z] for ZZ with values in [a,b]⊂(0,∞)[a, b] \subset (0, \infty).
  3. Existence of minimizers. Let ℓ(w)=∑ilog⁡(1+e−yiw⊤xi)\ell(\mathbf{w}) = \sum_i \log\bigl(1 + e^{-y_i \mathbf{w}^\top \mathbf{x}_i}\bigr) be the logistic loss of labels yi∈{±1}y_i \in \{\pm 1\}, and let X\mathbf{X} be the matrix with rows xi⊤\mathbf{x}_i^\top. The uniqueness proposition of Section 23.3.3 states that a strictly convex function has at most one minimizer, and that a continuous, strongly convex function on a nonempty closed convex set with nonempty interior has exactly one.

    1. Suppose that some w\mathbf{w} satisfies yiw⊤xi>0y_i \mathbf{w}^\top \mathbf{x}_i > 0 for every ii, that is, the data are linearly separable by a hyperplane through the origin. Show that inf⁡wℓ(w)=0\inf_{\mathbf{w}} \ell(\mathbf{w}) = 0 and that ℓ\ell has no minimizer.
    2. Show that ℓ\ell is strictly convex whenever X\mathbf{X} has full column rank. Why does this not contradict (a)?
    3. Show that ℓ(w)+λ2∥w∥2\ell(\mathbf{w}) + \tfrac{\lambda}{2}\|\mathbf{w}\|^2 has exactly one minimizer for every λ>0\lambda > 0 and every dataset. Which hypothesis of the uniqueness proposition does the penalty supply?
  4. The PL condition beyond convexity. The cell that studies f(x)=x2+3sin⁡2xf(x) = x^2 + 3\sin^2 x measures its PL constant μ≈0.1755\mu \approx 0.1755 on the window [−5,5][-5, 5].

    1. Bound ∣f′(x)∣|f'(x)| from below and f(x)f(x) from above for ∣x∣≥5|x| \ge 5. Conclude that the PL inequality (23.3.10) holds on all of R\mathbb{R} with the constant measured on the window.
    2. Let X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} with n<dn \lt d have full row rank, and let f(w)=12∥Xw−y∥2f(\mathbf{w}) = \tfrac12\|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2. Show that ff is not strongly convex and has infinitely many minimizers, but satisfies the PL inequality with μ=λmin⁡(XX⊤)\mu = \lambda_{\min}(\mathbf{X}\mathbf{X}^\top), the smallest eigenvalue of XX⊤\mathbf{X}\mathbf{X}^\top. Which linear rate does gradient descent with η=1/L\eta = 1/L then achieve, and how is LL related to XX⊤\mathbf{X}\mathbf{X}^\top?
  5. [code] Contraction of the distance. ● The rate (23.3.9) guarantees the per-step factor 1−μ/L1 - \mu/L for f−f⋆f - f^\star, but the rate-check cell measures (1−μ/L)2(1 - \mu/L)^2. Let ff be twice continuously differentiable with μI⪯∇2f⪯LI\mu \mathbf{I} \preceq \nabla^2 f \preceq L \mathbf{I}, and let xk+1=xk−η∇f(xk)\mathbf{x}_{k+1} = \mathbf{x}_k - \eta \nabla f(\mathbf{x}_k). Two facts from Section 23.1 are used: the quadratic ceiling f(y)≤f(x)+∇f(x)⊤(y−x)+L2∥y−x∥2f(\mathbf{y}) \le f(\mathbf{x}) + \nabla f(\mathbf{x})^\top(\mathbf{y} - \mathbf{x}) + \tfrac{L}{2}\|\mathbf{y} - \mathbf{x}\|^2 and the step η⋆=2/(μ+L)\eta^\star = 2/(\mu + L), the best fixed step on a quadratic.

    1. Write ∇f(xk)=Hˉk(xk−x⋆)\nabla f(\mathbf{x}_k) = \bar{\mathbf{H}}_k (\mathbf{x}_k - \mathbf{x}^\star) with Hˉk=∫01∇2f(x⋆+s(xk−x⋆)) ds\bar{\mathbf{H}}_k = \int_0^1 \nabla^2 f\bigl(\mathbf{x}^\star + s(\mathbf{x}_k - \mathbf{x}^\star)\bigr)\,ds. Show that
∥xk+1−x⋆∥≤max⁡(∣1−ημ∣, ∣1−ηL∣) ∥xk−x⋆∥.(23.3.12)\|\mathbf{x}_{k+1} - \mathbf{x}^\star\| \le \max\bigl(|1 - \eta\mu|,\, |1 - \eta L|\bigr)\, \|\mathbf{x}_k - \mathbf{x}^\star\|. \tag{23.3.12}
  1. Set η=1/L\eta = 1/L and κ=L/μ\kappa = L/\mu. Combine (a) with the lower bound (23.3.4) and the quadratic ceiling, both taken at x⋆\mathbf{x}^\star, to show that f(xk)−f⋆≤κ (1−μ/L)2k (f(x0)−f⋆)f(\mathbf{x}_k) - f^\star \le \kappa\,(1 - \mu/L)^{2k}\,(f(\mathbf{x}_0) - f^\star). From which kk on is this bound stronger than (23.3.9)?
  2. Predict the per-step contraction of f−f⋆f - f^\star on the κ=10\kappa = 10 design of the rate-check cell at η⋆=2/11\eta^\star = 2/11. (Hint: both eigen-components are multiplied by numbers of absolute value 9/119/11.) Verify the prediction by changing the step in that cell, and explain why, unlike at η=1/L\eta = 1/L, the first ratio is no longer special.
  1. Smoothing the maximum. ● A maximum of affine functions, the shape of hinge-type and worst-case objectives, has a kink wherever two of its pieces tie. For a temperature τ>0\tau > 0, let lseτ(z)=τ lse(z/τ)\mathrm{lse}_\tau(\mathbf{z}) = \tau\, \mathrm{lse}(\mathbf{z}/\tau) for z∈Rm\mathbf{z} \in \mathbb{R}^m. This smoothing technique is due to Nesterov (2005).
    1. Show that max⁡jzj≤lse(z)≤max⁡jzj+log⁡m\max_j z_j \le \mathrm{lse}(\mathbf{z}) \le \max_j z_j + \log m, and conclude that max⁡jzj≤lseτ(z)≤max⁡jzj+τlog⁡m\max_j z_j \le \mathrm{lse}_\tau(\mathbf{z}) \le \max_j z_j + \tau\log m.
    2. Use (23.3.11) to show that the largest eigenvalue of ∇2lseτ(z)\nabla^2 \mathrm{lse}_\tau(\mathbf{z}) is at most 1/(2τ)1/(2\tau), by bounding Var(vY)\textrm{Var}(v_Y) by E[(vY−c)2]\mathbb{E}[(v_Y - c)^2] for a well-chosen constant cc. Is the bound attained?
    3. Let F(w)=max⁡j(Aw+r)jF(\mathbf{w}) = \max_j (\mathbf{A}\mathbf{w} + \mathbf{r})_j and Fτ(w)=lseτ(Aw+r)F_\tau(\mathbf{w}) = \mathrm{lse}_\tau(\mathbf{A}\mathbf{w} + \mathbf{r}), and assume that FτF_\tau has a minimizer within distance RR of w0\mathbf{w}_0. Show with (b) that FτF_\tau is LL-smooth for L=∥A∥22/(2τ)L = \|\mathbf{A}\|_2^2/(2\tau), and that kk steps of gradient descent on FτF_\tau with η=1/L\eta = 1/L give
F(wk)−min⁡F≤τlog⁡m+∥A∥22R24τk.(23.3.13)F(\mathbf{w}_k) - \min F \le \tau \log m + \frac{\|\mathbf{A}\|_2^2 R^2}{4\tau k}. \tag{23.3.13}

Choose τ\tau to minimize this bound, and give the number of steps that guarantees accuracy ϵ\epsilon. How does the count change when an accelerated method with error O(LR2/k2)O(LR^2/k^2) replaces gradient descent?

  1. [code] Implicit bias and the optimizer. ● Exercise 4 of Section 21.5 shows on paper that gradient descent on 12∥Xw−y∥2\tfrac12\|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2, for X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} with n<dn \lt d and full row rank, started at w0=0\mathbf{w}_0 = \mathbf{0}, stays in the row space of X\mathbf{X} and converges to the minimum-norm interpolant X+y\mathbf{X}^+\mathbf{y}. Here the start stays at w0=0\mathbf{w}_0 = \mathbf{0} and the algorithm changes. Take a random 4×104 \times 10 system, and compare the limit of each method and its norm with np.linalg.pinv(X) @ y.

    1. Run gradient descent with η=1/λmax⁡(X⊤X)\eta = 1/\lambda_{\max}(\mathbf{X}^\top \mathbf{X}), and track the norm of the component of wk\mathbf{w}_k orthogonal to the row space, computed with the projector I−X+X\mathbf{I} - \mathbf{X}^+\mathbf{X}.
    2. Heavy-ball momentum updates wk+1=wk−η∇f(wk)+β(wk−wk−1)\mathbf{w}_{k+1} = \mathbf{w}_k - \eta\nabla f(\mathbf{w}_k) + \beta(\mathbf{w}_k - \mathbf{w}_{k-1}). Show that its iterates stay in the row space, and predict their limit. Verify the prediction with the step of (a) and β=0.9\beta = 0.9.
    3. Replace the update by the diagonally preconditioned step wk+1=wk−η DX⊤(Xwk−y)\mathbf{w}_{k+1} = \mathbf{w}_k - \eta\, \mathbf{D} \mathbf{X}^\top (\mathbf{X}\mathbf{w}_k - \mathbf{y}), where D\mathbf{D} is a fixed diagonal matrix with entries drawn uniformly from [0.1,10][0.1, 10] and η=1/λmax⁡(D1/2X⊤XD1/2)\eta = 1/\lambda_{\max}(\mathbf{D}^{1/2} \mathbf{X}^\top \mathbf{X} \mathbf{D}^{1/2}). Use the substitution u=D−1/2w\mathbf{u} = \mathbf{D}^{-1/2}\mathbf{w} to find the limit in closed form, and verify it numerically. Is the limit still the minimum-norm interpolant? What does this suggest about the implicit bias of adaptive methods such as Adam (Section 9.5), whose per-coordinate step sizes act like D\mathbf{D}?
    4. Run exact cyclic coordinate descent for 1000 sweeps, with A=X⊤X\mathbf{A} = \mathbf{X}^\top \mathbf{X}, b=X⊤y\mathbf{b} = \mathbf{X}^\top \mathbf{y}, and the update wj←(bj−∑i≠jAjiwi)/Ajjw_j \leftarrow (b_j - \sum_{i \ne j} A_{ji} w_i)/A_{jj} for j=1,…,dj = 1, \ldots, d in turn. Check that the limit interpolates the data. Is it the minimum-norm interpolant, and which step of the row-space argument fails? Repeat the run three times with coordinates drawn uniformly at random. Does the limit depend on the draw?
  2. [extended] Max-margin bias of gradient descent. ●● On data that a hyperplane through the origin separates, the logistic loss has no minimizer (part (a) of Exercise 3). Soudry et al. (2018) prove that gradient descent on it nevertheless diverges in a definite direction: the iterates satisfy wk=w^log⁡k+ρk\mathbf{w}_k = \hat{\mathbf{w}} \log k + \boldsymbol{\rho}_k, with ρk\boldsymbol{\rho}_k bounded for almost every dataset, where

w^=argminw∥w∥subject toyiw⊤xi≥1 for all i(23.3.14)\hat{\mathbf{w}} = \mathop{\mathrm{argmin}}_{\mathbf{w}} \|\mathbf{w}\| \quad \textrm{subject to} \quad y_i \mathbf{w}^\top \mathbf{x}_i \ge 1 \textrm{ for all } i \tag{23.3.14}

is the hard-margin SVM solution, with margin γ=1/∥w^∥\gamma = 1/\|\hat{\mathbf{w}}\|. The vector w^\hat{\mathbf{w}} is characterized by w^=∑iαiyixi\hat{\mathbf{w}} = \sum_i \alpha_i y_i \mathbf{x}_i with αi≥0\alpha_i \ge 0, where αi=0\alpha_i = 0 unless yiw^⊤xi=1y_i \hat{\mathbf{w}}^\top \mathbf{x}_i = 1; the points with equality are the support vectors.

  1. Derive the direction heuristically. Replace the logistic loss by its tail e−qe^{-q} in the margin q=yiw⊤xiq = y_i \mathbf{w}^\top \mathbf{x}_i, and suppose that wk=g(k) u+O(1)\mathbf{w}_k = g(k)\,\mathbf{u} + O(1) with ∥u∥=1\|\mathbf{u}\| = 1 and g(k)→∞g(k) \to \infty. Show that the negative gradient is asymptotically a nonnegative combination of the points yixiy_i\mathbf{x}_i of smallest margin yiu⊤xiy_i \mathbf{u}^\top \mathbf{x}_i. Conclude that u\mathbf{u} is proportional to w^\hat{\mathbf{w}}.
  2. Derive the growth rate. Keep only the support vectors in the gradient flow w˙=−∇ℓ(w)\dot{\mathbf{w}} = -\nabla \ell(\mathbf{w}), show that g˙≈c e−γg\dot g \approx c\, e^{-\gamma g} for a constant c>0c > 0, and conclude that ∥w(t)∥≈∥w^∥log⁡t\|\mathbf{w}(t)\| \approx \|\hat{\mathbf{w}}\| \log t.
  3. Take the support vectors x1=(0.5,1.5)\mathbf{x}_1 = (0.5, 1.5) and x2=(1.5,0.5)\mathbf{x}_2 = (1.5, 0.5) with label +1+1, their negatives with label −1-1, and 12 random points, 6 per class, with yiw^⊤xi>1y_i \hat{\mathbf{w}}^\top \mathbf{x}_i > 1 for w^=(12,12)\hat{\mathbf{w}} = (\tfrac12, \tfrac12). Let X\mathbf{X} be the 16×216 \times 2 matrix with rows xi⊤\mathbf{x}_i^\top. Run gradient descent on the summed logistic loss from w0=0\mathbf{w}_0 = \mathbf{0} with η=1/∥X∥22\eta = 1/\|\mathbf{X}\|_2^2 for 10610^6 steps, which takes seconds in vectorized NumPy. Plot, against kk on a logarithmic axis, the norm ∥wk∥\|\mathbf{w}_k\|, the training loss, the angle between wk\mathbf{w}_k and w^\hat{\mathbf{w}}, and the margin gap γ−min⁡iyiwk⊤xi/∥wk∥\gamma - \min_i y_i \mathbf{w}_k^\top \mathbf{x}_i / \|\mathbf{w}_k\|. Compare the slope of ∥wk∥\|\mathbf{w}_k\| against log⁡k\log k with (b).
  4. The training error reaches zero within the first few steps. By what factor do the margin gap and the training loss change between k=103k = 10^3 and k=106k = 10^6? What does the comparison imply for stopping training as soon as the training error reaches zero?
  1. Convexity of the log-partition function. This exercise generalizes the log-sum-exp proposition to the log-partition functions that Section 24.4 builds on. For a finite set X\mathcal{X}, weights h(x)>0h(x) > 0, statistics T(x)∈Rp\mathbf{T}(x) \in \mathbb{R}^p, and natural parameters η∈Rp\boldsymbol{\eta} \in \mathbb{R}^p (not a step size here), let A(η)=log⁡∑x∈Xh(x)exp⁡(η⊤T(x))A(\boldsymbol{\eta}) = \log\sum_{x \in \mathcal{X}} h(x)\exp(\boldsymbol{\eta}^\top\mathbf{T}(x)) and pη(x)=h(x)exp⁡(η⊤T(x)−A(η))p_{\boldsymbol{\eta}}(x) = h(x)\exp(\boldsymbol{\eta}^\top\mathbf{T}(x) - A(\boldsymbol{\eta})).
    1. Show that ∇A(η)=Eη[T]\nabla A(\boldsymbol{\eta}) = \mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}] and ∇2A(η)=Covη[T]\nabla^2 A(\boldsymbol{\eta}) = \textrm{Cov}_{\boldsymbol{\eta}}[\mathbf{T}], with expectation and covariance under pηp_{\boldsymbol{\eta}}.
    2. Conclude that AA is convex, and that it is strictly convex if and only if no nonzero v\mathbf{v} makes v⊤T(x)\mathbf{v}^\top\mathbf{T}(x) constant on X\mathcal{X}.
    3. Recover (23.3.11) with X={1,…,d}\mathcal{X} = \{1, \ldots, d\}, T(x)=ex\mathbf{T}(x) = \mathbf{e}_x, and h≡1h \equiv 1, and name the direction in which AA is flat.
    4. For observations x1,…,xnx_1, \ldots, x_n with average statistic Tˉ=1n∑iT(xi)\bar{\mathbf{T}} = \tfrac1n\sum_i \mathbf{T}(x_i), show that the average negative log-likelihood A(η)−η⊤Tˉ−1n∑ilog⁡h(xi)A(\boldsymbol{\eta}) - \boldsymbol{\eta}^\top\bar{\mathbf{T}} - \tfrac1n\sum_i \log h(x_i) is convex in η\boldsymbol{\eta}, and that a minimizer satisfies Eη[T]=Tˉ\mathbb{E}_{\boldsymbol{\eta}}[\mathbf{T}] = \bar{\mathbf{T}} (moment matching). For the softmax case of (c), why does no minimizer exist when one class is never observed?

Discussions