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 random starting points, first on the bowl and then on the tilted double well . 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 for measuring convergence rates, and the double well , 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 of -dimensional points is convex if
As moves from to , the combination sweeps out the line segment from to . 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.
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 and a half-space , both convex.
To see what the definition rules out, consider the annulus . It contains both and , 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 and any half-space are convex because is linear: a weighted average of two numbers equal to (or at most ) is again equal to (or at most ). Second, any norm ball is convex by the triangle inequality and homogeneity, . This single check covers both the balls of weight decay and gradient clipping and the balls of sparsity-inducing regularization. Third is the probability simplex , where means every entry is nonnegative. Attention weights, class probabilities, and mixture weights all live on , 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: is a union of two convex intervals, yet the segment from to leaves the set.
This single intersection rule certifies two central sets at once. The probability simplex is the intersection of one hyperplane () with half-spaces (), 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 , the constraint is a single linear inequality in the entries of .
We can also build a convex set from the inside out. The convex hull of a set is the collection of all weighted averages of points with and . It is convex, and in fact it is the smallest convex set containing (Exercise 2). Seen this way, the probability simplex is simply the convex hull of the standard basis vectors : 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 on a convex domain is convex if its graph lies on or below every chord joining two of its points:
Here the left side evaluates at a point on the segment between and , while the right side gives the height of the straight chord joining to directly above that point. Let us check a concrete case: for with , , and , the graph sits at while the chord sits at , and indeed . For arbitrary , , and , expanding the squares shows that the height gap between chord and graph is
Thus 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 and , we call strictly convex; if is convex, we call concave. Notice that a linear function is convex (and concave) but not strictly convex, because every chord lies directly on its graph. Notice also why the domain must be convex: without that requirement, the intermediate point might not even belong to the domain where is defined.
Convex functions and convex sets are two sides of the same geometric coin. The epigraph of is the region on and above its graph, . A function 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 : if and , the chord inequality immediately gives . This is why any inequality constraint with a convex automatically carves out a convex feasible region. Figure 23.3.2(a) shows both sets for a parabola.
Epigraphs and sublevel sets. (a) The epigraph of the convex function (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 and projecting onto the -axis gives the sublevel set . (b) Every sublevel set of 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 is a convex interval , yet itself is not convex. At , , and , the graph sits at while the chord sits below it at (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.
(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 is convex on a convex set , every local minimizer of on is a global minimizer.
Proof. Let be a local minimizer and let be any other point. For sufficiently small , the point along the segment toward falls inside the neighborhood where is minimal. Combining local minimality with the chord inequality gives
Subtract from both sides and divide by to obtain .
The geometric picture is just as crisp: if any strictly better point existed anywhere in , the chord from toward would slope downward immediately, forcing the graph below arbitrarily close to 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 , steps) to both the bowl and the double well , starting from the same points drawn uniformly on . Because the step is small, each iterate rolls downhill without hopping over the central hump, so a run on should land in whichever well lies on its own side of the local maximum. We compute that local maximum as a root of 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 runs converge to to within numerical rounding. On the double well, the runs split cleanly into two camps: one at with , and another at with —nearly a full unit worse. The local maximum separating the two basins sits at , so a fraction of uniform starts fall to its right. Across random draws, the observed share hovers within a few percentage points of , matching the prediction up to the sampling noise of 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 is differentiable, convexity takes an equivalent first-order form: the tangent hyperplane at any point is a global under-estimator of the function,
Check this on at : the tangent line is , and the vertical gap between graph and tangent is for every . Pause to appreciate how strong a statement (23.3.3) is: a single gradient, computed at a single point , bounds 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.
Two equivalent conditions. (a) The chord joining two points of the graph lies above the graph: . (b) The tangent at any point lies below the graph: .
23.3.2.4 The Second-Order Condition#
For smooth objectives, the quickest way to verify convexity is usually a matrix test. When is twice differentiable on an open convex domain , is convex if and only if its Hessian is positive semidefinite everywhere:
In one dimension this reduces to the familiar calculus rule : the curve bends upward. In dimensions it says that every one-dimensional slice through bends upward, since is the second derivative of along the line in direction (Section 22.2).
This matrix test settles three workhorse examples immediately. First, a quadratic with symmetric has constant Hessian , so it is convex if and only if . Second, the least-squares loss for a design matrix ( examples, weights) has Hessian ; because for every , least squares is always convex (Section 21.3.2.2). Third, the scalar functions , , and are all convex on their domains, since their second derivatives , , and are positive everywhere.
Why did we insist that the domain be open? On a lower-dimensional domain, only directions that stay inside matter: for instance, is convex when restricted to the line , 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 be differentiable on an open convex domain . Then the chord condition (23.3.2) and the first-order condition (23.3.3) are equivalent. If is twice differentiable, both are equivalent to on .
Proof. (Chord first-order.) Fix and . Apply the chord inequality at the intermediate point , subtract from both sides, and divide by :
Letting , the left side approaches the directional derivative , yielding (23.3.3).
(First-order chord.) Set and apply the tangent lower bound at twice, once toward each endpoint:
Multiply the first inequality by , the second by , and add. The linear terms combine to , leaving (23.3.2).
(Second-order first-order.) Restrict to the line segment between and by defining . Its second derivative is . By Taylor's theorem with the Lagrange remainder (Section 22.1), for some . Dropping the nonnegative remainder yields (23.3.3).
(First-order second-order.) Suppose for contradiction that for some and direction . Expanding along gives
For sufficiently small , the negative quadratic term dominates the remainder, so drops strictly below the tangent value , contradicting (23.3.3).
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 with random examples and weights, and the double well from our opening experiment. For least squares we already know the exact formulas for the violations: expanding the squares as we did for gives the chord gap (graph minus chord) as and the tangent gap (tangent minus graph) as , both nonpositive. For each loss, the code below samples random chords and tangents in , 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 at the central hump, where . Notice, however, an asymmetry between the tests. Random sampling can refute convexity—a single bad chord is a complete counterexample for —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 is the same PSD matrix at every .
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 is convex but not strictly convex, because its chords sit right on its graph. The quartic is strictly convex—its second derivative vanishes only at , so its slope increases strictly everywhere—yet leaves it completely flat at the minimizer. The quadratic , by contrast, has constant curvature at every point.
Strong convexity turns this observation into a quantitative bound. For , a function is -strongly convex if subtracting a quadratic of curvature leaves a convex function—that is, if is convex. When is differentiable, applying the first-order condition to (whose gradient is ) and using the identity yields the equivalent inequality
Geometrically, the graph of must sit not merely above its tangent line at , but above a parabola of curvature tangent to it there. Applying the second-order condition to gives the matrix test: a twice-differentiable is -strongly convex if and only if everywhere, where is the identity matrix. Thus is -strongly convex, whereas fails to be strongly convex on any neighborhood of because for every . Notice also a practical bonus: adding the ridge penalty to any convex loss immediately makes the sum -strongly convex, because subtracting recovers the original convex loss. Weight decay does not just shrink parameters; it guarantees strong convexity.
(a) Convex, strictly convex, strongly convex: has chords on its graph, is flat at the origin, curves everywhere. (b) A -strongly convex, -smooth function, here , lies between two parabolas tangent at , with curvatures and ; their ratio is .
Strong convexity is the natural counterpart to smoothness. Recall from Section 23.1.1 that is -smooth when its gradient is -Lipschitz, ; for a convex twice-differentiable function, this means . Smoothness places a quadratic ceiling above the graph, , while strong convexity places a quadratic floor (23.3.4) beneath it. Together they sandwich between two tangent parabolas of curvatures and , as illustrated in Figure 23.3.5(b) for , whose second derivative ranges between and .
The ratio is the condition number, generalizing the eigenvalue ratio we encountered for quadratics in Section 23.1.2. On our running quadratic , the extreme curvatures are and , giving .
23.3.2.7 Subgradients#
Important losses such as the norm and the hinge loss 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 is a subgradient of at if
The set of all subgradients at is called the subdifferential, written . Wherever a convex function is differentiable, the subdifferential collapses to a single vector, . At a corner, however, it fans out into a whole set of supporting slopes (Figure 23.3.6). For at , every slope satisfies for all , so ; similarly, for the hinge loss at the kink , we get .
At the kink of the gradient does not exist, but the subdifferential is a set: every slope defines a supporting line below the V, and the two extreme slopes lie along the branches themselves, so is the whole interval from to . The zero-slope member (orange) is the optimality certificate : the corner is a minimum certified without differentiability.
This immediately gives a derivative-free optimality test: minimizes if and only if . The proof is a one-line tautology: setting in (23.3.5) reads for all , 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 in an open interval where is convex, rearranging the chord inequality at gives
meaning that chord slopes are nondecreasing from left to right. Consequently, the difference quotient at any interior point is nondecreasing in , so its one-sided limits—the left and right derivatives —both exist and are finite. Every slope is a subgradient: for we have , which rearranges to , and the case is symmetric.
The same guarantee extends to 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 need not decrease at all (at the minimum of , the valid subgradient steps to , raising the loss). For that reason, the subgradient method requires diminishing step sizes and converges slowly, with error falling only as .
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 take the values and with probability each, and let . Evaluating at the mean gives , whereas averaging over the outcomes gives . The gap of is simply the variance of ; in fact, for the difference 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 and , and the gap we computed earlier for 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
Because nonnegative weights summing to one define a discrete probability distribution on the points , the natural generalization replaces the finite average with an arbitrary expectation.
Proposition (Jensen's inequality). Let be convex on a convex set , and let be a random vector taking values in , with and mean in the interior of . Then
If is strictly convex, equality holds if and only if with probability one.
Proof. Because lies in the interior of , has at least one subgradient . The supporting hyperplane at bounds for every outcome at once: by (23.3.5),
Now take expectations of both sides. Because , the linear term vanishes, leaving . When is strictly convex, this supporting hyperplane touches the graph only at : if it also touched at some , strict convexity would force , placing the graph strictly below the supporting hyperplane at the midpoint, a contradiction. Hence the pointwise inequality is strict whenever , so equality in expectation forces with probability one.
As a bonus, the same pointwise bound shows that is bounded below by an integrable random variable, so is always well-defined (possibly , 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 , the inequality reverses: .
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 and on a common finite alphabet, with wherever ,
with equality if and only if .
Proof. Draw and apply Jensen's inequality to the strictly convex function and the positive random variable :
where the last step uses . By the equality condition of Jensen's inequality, equality holds if and only if is constant with probability one and places no mass outside the support of —that is, with .
Applying the same idea to the concave function yields the classical arithmetic–geometric mean inequality: for any positive numbers , concavity gives , and exponentiating both sides produces
with equality if and only if all are equal, since 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 .
Let us test both Jensen's gap and the KL equality case numerically. First, for and , we can compute both sides in closed form— versus —and see how closely Monte Carlo matches them. Second, as we blend into via , how quickly does the KL divergence vanish: linearly in , 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 versus ; drawing more samples shrinks the estimation noise, but the structural Jensen gap remains fixed. In the KL experiment, the divergence vanishes much faster than : every tenfold reduction in cuts the median divergence roughly a hundredfold. Expanding the logarithm explains why: once is small for every . (Pairs where 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 .
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 and attain the minimum value , the chord inequality forces every point between them to lie at or below . Second, for a differentiable convex on an open set, immediately implies , because the first-order condition with a zero gradient reads for all . Third, a small gradient guarantees a small suboptimality gap: pointing the first-order condition at a minimizer gives . Thus the stationarity result of Section 23.1.1—that gradient descent with 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 . 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 ( approaches as without ever attaining it). Strict convexity rules out multiple minimizers, and strong convexity guarantees both existence and uniqueness.
Proposition (uniqueness). A strictly convex has at most one minimizer. A continuous -strongly convex on a nonempty closed convex set with nonempty interior has exactly one.
Proof. Suppose were both global minimizers with value . By the strict chord inequality at , their midpoint would satisfy , a contradiction. Because strong convexity implies strict convexity, it remains only to prove existence. We prove it for a differentiable on , which covers the unconstrained losses in this book; the general case follows the same steps using a subgradient of at an interior point of . Fix any starting point . In (23.3.4), the linear term is at least , so whenever . Hence the sublevel set is bounded, and continuity of 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 .
The technical hypotheses on 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 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 and : both are strictly convex with unique minimizer , yet only is strongly convex. Let us run the exact same gradient-descent loop (, starting from ) on both functions for 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 , every step multiplies the iterate by a constant factor , driving it below in just steps; the loss drops off the bottom of the plot almost immediately. On , by contrast, each step multiplies by , a contraction factor that creeps closer and closer to as the iterate approaches the flat valley at . The printed products settle near , showing that decays only like and still sits at after steps. On a log–log plot, the loss gap therefore traces a straight line of slope . Strict convexity rules out multiple minimizers, but it cannot guarantee fast convergence; a geometric rate requires .
The next two propositions make this contrast completely general: every smooth strongly convex function converges geometrically like , whereas without we can guarantee only an decay. Both proofs begin with the descent lemma from Section 23.1.1: for an -smooth function and the gradient step ,
Each step reduces the objective by at least . 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 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 be convex and -smooth with a minimizer . Gradient descent with satisfies, for every ,
Thus the loss gap decays at least as fast as , scaled by the smoothness constant and the squared initial distance to the minimizer. To put numbers on it, if and , the bound is , guaranteeing a gap below within steps.
Proof. Combine the descent lemma with the first-order condition (23.3.3) evaluated at toward the optimum, :
Now comes the clever step: complete the square so that the right side turns into a difference of two squared distances to ,
Notice that the second norm is simply . Summing over , the right side telescopes cleanly:
Because the descent lemma ensures that never increases, the final term is the smallest term in the sum, so is bounded by the total sum. Dividing by gives (23.3.8).
Two features of this proof are worth noting. First, the dimension never appears: a model with a billion weights and the same and initial distance enjoys the exact same worst-case guarantee. Second, before summing, the per-step inequality has a nonnegative left side , which forces : every single step moves monotonically closer to every minimizer.
Adding strong convexity transforms this decay into a geometric rate.
Proposition (linear rate under strong convexity). Let be -strongly convex and -smooth, with minimizer . Gradient descent with satisfies
In words, every iteration shaves off at least a fraction 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 : the left side attains its minimum , while the right side is a simple quadratic in minimized at , where its value is . Rearranging gives
Second, substitute (23.3.10) directly into the descent lemma:
Applying this contraction times completes the proof.
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 now takes roughly steps instead of . On our running quadratic with , gaining six digits of accuracy, , takes about steps by this bound.
How tight is (23.3.9) in practice? Let us measure it on a least-squares problem whose Hessian has eigenvalues and by construction (, , ). We run gradient descent with and track the actual per-step ratio of successive loss gaps, .
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 per step, yet from the second step onward the measured ratio is —which is . (The very first ratio depends on the random starting direction and varies from run to run.) Viewing the update in the eigenvector coordinates of explains what happened. With , the first step multiplies the stiff eigen-component of by , wiping it out completely. In two dimensions, only the slow component remains; its distance to shrinks by per step, so the loss gap—which is quadratic in that distance—shrinks by . In higher dimensions, the ratio climbs toward 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 in fact contracts by per step on every -smooth -strongly convex function (Taylor et al., 2018), with quadratics achieving equality; Exercise 5 proves the closely related bound . Returning to our running quadratic, six digits of accuracy in the loss gap (three digits in the distance to the minimizer) cost roughly steps by our simple bound, about steps at the true rate, and half as many, steps, at the optimal fixed step . This is half of the 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.
- Nonnegative weighted sums. If are convex and , then is convex: simply multiply the chord inequality for each by and add. In particular, averaging a convex per-example loss over a training set always yields a convex objective.
- Affine pre-composition. If is convex, then so is : an affine map carries the line segment between and onto the segment between their images with the exact same weight , 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.
- Pointwise maximum and supremum. If every is convex, then so is . 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.
- Monotone composition. If is convex and is both convex and nondecreasing, then the composition is convex. Two lines prove it:
where the first inequality uses convexity of together with monotonicity of , and the second uses convexity of . Do not forget the monotonicity requirement on : is convex but not nondecreasing, and composing it with the convex function produces the nonconvex double well (which becomes after adding ).
These four rules certify nearly all the standard convex losses in one sweep. The hinge loss is the maximum of two affine functions of (rules 3 and 2). The norm is a sum of maxima of affine functions (rules 1, 3, and 2). The logistic loss starts from the scalar function —convex because its second derivative is strictly positive—pre-composed with an affine map (rule 2) and summed over training examples (rule 1). Adding the ridge penalty to any of these produces a strongly convex objective. Notice, however, that convexity does not automatically upgrade to strong convexity under rule 3: is convex, yet it equals the flat affine line across the entire interval between the two roots of , 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 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 at the heart of every softmax cross-entropy loss. Geometrically, is a smooth upper approximation to that never overshoots it by more than . 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 at is
which is the covariance matrix of the one-hot encoding of a class drawn from . Since every covariance matrix is PSD, is convex.
Proof. Differentiating once gives , so the gradient of is simply the softmax vector . Differentiating a second time by the quotient rule yields
which is the entry of (the same softmax Jacobian derived in Section 22.4). Now let be a random class index drawn with probabilities , and let be its one-hot vector. Then and , so the Hessian is literally . Every covariance matrix is PSD; explicitly, for any direction ,
In other words, the curvature of log-sum-exp along a direction is nothing more than the variance of the coordinate under the softmax distribution.
Three practical consequences follow immediately from this formula. First, the cross-entropy loss as a function of the logits, for true class , is log-sum-exp minus a linear term, hence convex. Second, softmax regression (Section 3.1) feeds affine logits into , 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 , because whenever all entries are equal. That flat direction reflects the shift invariance that makes the numerically stable softmax possible. The very same Jacobian 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 , regardless of the logits, so is a global smoothness constant. Where is that ceiling approached, and how curved is the loss at typical logits? Below, we draw random six-class logit vectors, rescale them by a temperature multiplier , 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 , confirming that softmax cross-entropy is -smooth in the logits at every temperature. When the logits are small (), the softmax is nearly uniform across the six classes and the curvature hovers just above . At moderate scales, the typical curvature peaks with a median near . Push 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 draws climbs toward , 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 : 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 . 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 and is the origin , where sits well above the minimum value . The origin is a stationary point, not a minimum—its Hessian has eigenvalues , making it a saddle point.
The two-weight model . Its minimizers form the hyperbola , which is not convex: the midpoint of and is the origin, where and the Hessian has eigenvalues .
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 and 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 in computes , and swapping the two units computes 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 with infimum satisfies the Polyak–Łojasiewicz (PL) inequality with constant if for all , 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 be -smooth, bounded below with , and satisfy the PL inequality with constant . Then gradient descent with satisfies .
Proof. Repeat the second half of the strong-convexity proof verbatim: combining the descent lemma with the PL inequality yields (Karimi et al., 2016), and iterating times finishes the proof.
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 forces ), and must grow at least quadratically away from the minimizer set. The quartic shows why the second requirement matters: it has only one stationary point, its global minimum, yet it fails PL because cannot stay above as for any . That failure is precisely why gradient descent crawled on 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 , whose second derivative dips all the way to and peaks at . Let us estimate its PL constant numerically on and run gradient descent from using step size . (We choose rather than because at the local contraction factor vanishes at the origin, hiding the asymptotic rate.) At , the quadratic ceiling guarantees a per-step decrease of , which the PL inequality turns into the contraction factor .
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 is , and the minimum of is : the function is nonconvex yet PL. The window suffices, because outside it the ratio stays well above this value and tends to as ; Exercise 4 proves the bound.
With this the guaranteed factor is about per step. The largest measured ratio, about , comes from , where attains its minimum , so there the guarantee is nearly tight. Near the minimizer the ratio settles at . That limit comes from the local quadratic: near , with , each step multiplies by , and the gap, quadratic in , by .
PL can also hold on part of the space. For the gradient satisfies , so PL holds with constant on the region 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 of full row rank. Every gradient lies in the row space of , so iterates started from 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 , for instance, leads to the interpolant that minimizes instead of (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 . 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: for smooth convex , and a factor per step with strong convexity, hence about steps. Jensen's inequality is the chord inequality for expectations and gives . Four closure rules certify the hinge, , 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#
-
Subdifferentials of norms and maxima. Compute each subdifferential from the definition (23.3.5).
- Compute at every , including .
- Let , and let be its set of active coordinates. Show that is the convex hull of . Backpropagation through max pooling passes the incoming gradient to a single maximal input, so it uses one vertex of this hull. Suppose that two or more inputs tie. Show that a small step along does not decrease . For which is a descent direction, and which of them makes the directional derivative of along most negative?
- Use (a) and the optimality criterion to minimize over , which gives the proximal operator of . Compare the zero pattern of the solution with that of coordinatewise soft-thresholding, . What does this penalty do when collects the outgoing weights of one hidden unit?
-
Convex combinations and Jensen's inequality. Write with and for a convex combination of points.
- Show by induction on that a convex set contains every convex combination of points of . This is the inclusion that completes the description of the convex hull in Section 23.3.1.
- Apply (a) to the epigraph of a convex function to derive the finite form (23.3.6) of Jensen's inequality.
- Let be twice differentiable with on an interval that contains the values of a random variable with mean and variance . Show that the Jensen gap lies between and . Check the bounds on the two-point example of the text, with , where . Then apply the result to to bound for with values in .
-
Existence of minimizers. Let be the logistic loss of labels , and let be the matrix with rows . 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.
- Suppose that some satisfies for every , that is, the data are linearly separable by a hyperplane through the origin. Show that and that has no minimizer.
- Show that is strictly convex whenever has full column rank. Why does this not contradict (a)?
- Show that has exactly one minimizer for every and every dataset. Which hypothesis of the uniqueness proposition does the penalty supply?
-
The PL condition beyond convexity. The cell that studies measures its PL constant on the window .
- Bound from below and from above for . Conclude that the PL inequality (23.3.10) holds on all of with the constant measured on the window.
- Let with have full row rank, and let . Show that is not strongly convex and has infinitely many minimizers, but satisfies the PL inequality with , the smallest eigenvalue of . Which linear rate does gradient descent with then achieve, and how is related to ?
-
[code] Contraction of the distance. ● The rate (23.3.9) guarantees the per-step factor for , but the rate-check cell measures . Let be twice continuously differentiable with , and let . Two facts from Section 23.1 are used: the quadratic ceiling and the step , the best fixed step on a quadratic.
- Write with . Show that
- Set and . Combine (a) with the lower bound (23.3.4) and the quadratic ceiling, both taken at , to show that . From which on is this bound stronger than (23.3.9)?
- Predict the per-step contraction of on the design of the rate-check cell at . (Hint: both eigen-components are multiplied by numbers of absolute value .) Verify the prediction by changing the step in that cell, and explain why, unlike at , the first ratio is no longer special.
- 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 , let
for
. This smoothing technique is due to
Nesterov (2005).
- Show that , and conclude that .
- Use (23.3.11) to show that the largest eigenvalue of is at most , by bounding by for a well-chosen constant . Is the bound attained?
- Let and , and assume that has a minimizer within distance of . Show with (b) that is -smooth for , and that steps of gradient descent on with give
Choose to minimize this bound, and give the number of steps that guarantees accuracy . How does the count change when an accelerated method with error replaces gradient descent?
-
[code] Implicit bias and the optimizer. ● Exercise 4 of Section 21.5 shows on paper that gradient descent on , for with and full row rank, started at , stays in the row space of and converges to the minimum-norm interpolant . Here the start stays at and the algorithm changes. Take a random system, and compare the limit of each method and its norm with
np.linalg.pinv(X) @ y.- Run gradient descent with , and track the norm of the component of orthogonal to the row space, computed with the projector .
- Heavy-ball momentum updates . Show that its iterates stay in the row space, and predict their limit. Verify the prediction with the step of (a) and .
- Replace the update by the diagonally preconditioned step , where is a fixed diagonal matrix with entries drawn uniformly from and . Use the substitution 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 ?
- Run exact cyclic coordinate descent for 1000 sweeps, with , , and the update for 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?
-
[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 , with bounded for almost every dataset, where
is the hard-margin SVM solution, with margin . The vector is characterized by with , where unless ; the points with equality are the support vectors.
- Derive the direction heuristically. Replace the logistic loss by its tail in the margin , and suppose that with and . Show that the negative gradient is asymptotically a nonnegative combination of the points of smallest margin . Conclude that is proportional to .
- Derive the growth rate. Keep only the support vectors in the gradient flow , show that for a constant , and conclude that .
- Take the support vectors and with label , their negatives with label , and 12 random points, 6 per class, with for . Let be the matrix with rows . Run gradient descent on the summed logistic loss from with for steps, which takes seconds in vectorized NumPy. Plot, against on a logarithmic axis, the norm , the training loss, the angle between and , and the margin gap . Compare the slope of against with (b).
- The training error reaches zero within the first few steps. By what factor do the margin gap and the training loss change between and ? What does the comparison imply for stopping training as soon as the training error reaches zero?
- 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
, weights , statistics
, and natural parameters
(not a step size here), let
and .
- Show that and , with expectation and covariance under .
- Conclude that is convex, and that it is strictly convex if and only if no nonzero makes constant on .
- Recover (23.3.11) with , , and , and name the direction in which is flat.
- For observations with average statistic , show that the average negative log-likelihood is convex in , and that a minimizer satisfies (moment matching). For the softmax case of (c), why does no minimizer exist when one class is never observed?