22.1 Single Variable Calculus

Every model in the Basics part was trained by gradient descent. At each step, the optimizer evaluates the loss and its slope at the current weights, nudges the weights a little downhill, and repeats. Because it never inspects the loss anywhere else, every step rests on a local prediction: the slope at the current point is assumed to describe the loss a short distance away. How accurate is that prediction, and how large a step can it safely support?

A single weight already shows what the answer looks like. Consider one training example, one scalar weight ww, and the logistic loss ℓ(w)=log⁡(1+e−w)\ell(w)=\log(1+e^{-w}). At w=0w=0, the loss is 0.6931470.693147 and its slope is −12-\tfrac12. If we move the weight to w=0.1w=0.1, a straight line through w=0w=0 with that slope predicts a loss of 0.693147−0.05=0.6431470.693147-0.05=0.643147. The actual loss is 0.6443970.644397, so the linear prediction is off by only 0.001250.00125. Remarkably, that small gap has a simple structure: to the digits shown, it equals 12⋅14⋅0.12\tfrac12\cdot\tfrac14\cdot0.1^2, where the factor 14\tfrac14 measures how sharply the graph of ℓ\ell bends at w=0w=0. The slope makes the prediction, and the bend tells us how quickly that prediction drifts off as the step grows. We will derive both constants shortly, once we have the rules of differentiation in hand.

This section develops the local straight-line model from the first derivative and extends it, using the second derivative, to a parabola that also captures the bend. Three results anchor the development: the Mean Value Theorem, which connects slopes at points to changes over intervals; the Lagrange remainder, which bounds the error of both the line and the parabola; and the descent lemma, which turns a bound on curvature into a guaranteed safe step size for gradient descent. We also meet Newton's method and the corner of ReLU\mathrm{ReLU}, where no tangent line exists yet backpropagation must still return a number. Here we study all of these ideas in one variable; their multivariable optimization theory belongs to Chapter 23.

Earlier, Section 1.4 introduced the derivative, listed the rules of differentiation, and used automatic differentiation as a practical tool. Here we review those rules briefly and focus on the proofs, geometric intuition, and error bounds. If you are already comfortable with the differentiation rules, you can jump straight to Section 22.1.3. One variable is the natural starting point because every multivariable loss contains it: holding all weights of ℓ(w1,…,wn)\ell(w_1,\ldots,w_n) fixed except wiw_i yields a one-dimensional slice, and single-variable calculus is the study of such slices.

Our running example throughout this section is the softplus function, s(x)=log⁡(1+ex)s(x)=\log(1+e^{x}). It is the one-variable slice log⁡(e0+ex)\log(e^0+e^x) of the log-sum-exp function used across this chapter, and the logistic loss above is simply ℓ(w)=s(−w)\ell(w)=s(-w).

22.1.1 The Derivative#

22.1.1.1 The Difference Quotient#

Zoom in far enough on the graph of a smooth function ff near a point xx, and the curve becomes indistinguishable from a straight line (Figure 22.1.1). The slope of that line is the derivative.

Figure 22.1.1:

The curve sin⁡(xx)\sin(x^x) near x0=2x_0=2, shown in windows of half-width 0.60.6, 0.060.06, and 0.0060.006. As the window shrinks, the curve (solid) becomes indistinguishable from its tangent line (dashed).

To capture that slope algebraically, we follow Section 1.4 and start with the secant line through (x,f(x))(x, f(x)) and (x+ϵ,f(x+ϵ))(x+\epsilon, f(x+\epsilon)). Its slope is the difference quotient (f(x+ϵ)−f(x))/ϵ\bigl(f(x+\epsilon)-f(x)\bigr)/\epsilon. As ϵ\epsilon shrinks toward zero, the secant rotates toward the tangent line (Figure 22.1.2).

Figure 22.1.2:

The difference quotient is the slope of the secant through (x,f(x))(x, f(x)) and (x+ϵ,f(x+ϵ))(x+\epsilon, f(x+\epsilon)). As ϵ→0\epsilon \to 0, this slope approaches the tangent slope f′(x)f'(x).

How small must ϵ\epsilon be before the secant slope is a trustworthy stand-in for the tangent slope? Unfortunately, there is no universal threshold: it depends entirely on the function. Consider the polynomial f(x)=x2+1701(x−4)3f(x) = x^2 + 1701(x-4)^3, whose true slope at x=4x=4 is 88, and observe how slowly the secant slope settles as ϵ\epsilon shrinks.

def f(x):
    return x**2 + 1701*(x-4)**3

# Slope of the secant through x=4, for shrinking epsilon
for epsilon in [0.1, 0.001, 0.0001, 0.00001]:
    print(f'epsilon = {epsilon:.5f} -> {(f(4+epsilon) - f(4)) / epsilon:.5f}')
epsilon = 0.10000 -> 25.11000
epsilon = 0.00100 -> 8.00270
epsilon = 0.00010 -> 8.00012
epsilon = 0.00001 -> 8.00001

At ϵ=0.1\epsilon=0.1, the secant slope is 25.1125.11, more than three times the true limit, and the printed values only settle near 88 once ϵ\epsilon reaches 0.0010.001. Expanding f(4+ϵ)−f(4)=8ϵ+ϵ2+1701ϵ3f(4+\epsilon)-f(4)=8\epsilon+\epsilon^2+1701\epsilon^3 shows why: the difference quotient equals 8+ϵ+1701ϵ28+\epsilon+1701\epsilon^2, so the cubic term adds 1717 at ϵ=0.1\epsilon=0.1 but only 1.7×10−71.7\times10^{-7} at ϵ=10−5\epsilon=10^{-5}. The large coefficient delays the approach to the limit without changing it. Automatic differentiation sidesteps this problem altogether: it never chooses an ϵ\epsilon, instead applying the rules of differentiation directly (Section 22.5).

22.1.1.2 The Derivative and the Linear Approximation#

The derivative of ff at xx is the limit of the secant slopes,

f′(x)=dfdx(x)=lim⁡ϵ→0f(x+ϵ)−f(x)ϵ,(22.1.1)f'(x) = \frac{df}{dx}(x) = \lim_{\epsilon \rightarrow 0}\frac{f(x+\epsilon) - f(x)}{\epsilon}, \tag{22.1.1}

whenever this limit exists, in which case we say ff is differentiable at xx. For the cubic above, f′(4)=8f'(4)=8. We write f′f' or dfdx\frac{df}{dx}, and ddx[…]\frac{d}{dx}[\ldots] when differentiating a bulky expression. The limit can also fail to exist, as it does for ∣x∣|x| at 00; we return to such corners in Section 22.1.6.

It is instructive to rearrange this definition. Let r(ϵ)=f(x+ϵ)−f(x)−ϵf′(x)r(\epsilon)=f(x+\epsilon)-f(x)-\epsilon f'(x) denote the error of the straight-line prediction; the limit (22.1.1) says that r(ϵ)/ϵ→0r(\epsilon)/\epsilon\to0. Writing o(ϵ)o(\epsilon) for any quantity r(ϵ)r(\epsilon) satisfying r(ϵ)/ϵ→0r(\epsilon)/\epsilon\to0 as ϵ→0\epsilon\to0, we obtain the linear approximation

f(x+ϵ)=f(x)+ϵf′(x)+o(ϵ).(22.1.2)f(x+\epsilon) = f(x) + \epsilon f'(x) + o(\epsilon). \tag{22.1.2}

In plain words, a small step ϵ\epsilon changes the output by ϵf′(x)\epsilon f'(x), up to an error that vanishes faster than ϵ\epsilon. The converse holds too: if f(x+ϵ)=f(x)+aϵ+o(ϵ)f(x+\epsilon)=f(x)+a\epsilon+o(\epsilon) for some constant aa, then dividing by ϵ\epsilon and letting ϵ→0\epsilon\to0 proves that ff is differentiable at xx with f′(x)=af'(x)=a. The expansion (22.1.2) and the limit (22.1.1) therefore carry the same information, and our proofs of the sum and chain rules will lean on this equivalence.

Plotted as a function of x+ϵx+\epsilon, the line f(x)+ϵf′(x)f(x)+\epsilon f'(x) is the tangent to the graph at xx, the limit of the rotating secants. This is the line that predicted the logistic loss at w=0.1w=0.1, and the gap of 0.001250.00125 was its o(ϵ)o(\epsilon) remainder. By itself, o(ϵ)o(\epsilon) promises very little: an error of order o(ϵ)o(\epsilon) could shrink only slightly faster than ϵ\epsilon. Here, however, the gap shrank as ϵ2\epsilon^2, and as we will see in Section 22.1.5.2, quadratic error decay is the rule for every twice differentiable function.

22.1.2 Computing Derivatives#

In practice, nobody computes derivatives by taking limits. Instead, as in Section 1.4, we combine a short table of elementary derivatives with rules for sums, products, and compositions. Here we prove each rule directly from the linear approximation. Among the table entries, we derive the exponential, the logarithm, and the power rule; we take the sine and cosine entries, along with the existence of a base whose exponential has slope 11 at 00, as known from a first calculus course.

22.1.2.1 A Table of Common Derivatives#

The following formulas hold wherever the right-hand sides are defined: the power rule for every real nn when x>0x>0 and for integer nn wherever xnx^n is defined, and the logarithm for x>0x>0.

  • Derivative of constants. ddxc=0\frac{d}{dx}c = 0.
  • Derivative of linear functions. ddx(ax)=a\frac{d}{dx}(ax) = a.
  • Power rule. ddxxn=nxn−1\frac{d}{dx}x^n = nx^{n-1}.
  • Derivative of exponentials. ddxex=ex\frac{d}{dx}e^x = e^x.
  • Derivative of the logarithm. ddxlog⁡(x)=1x\frac{d}{dx}\log(x) = \frac{1}{x}.
  • Derivative of sine. ddxsin⁡(x)=cos⁡(x)\frac{d}{dx}\sin(x) = \cos(x).
  • Derivative of cosine. ddxcos⁡(x)=−sin⁡(x)\frac{d}{dx}\cos(x) = -\sin(x).

The exponential entry rests on a one-line observation that also reveals what makes the base ee special. For any a>0a>0, the difference quotient of axa^x factors cleanly as

ax+ϵ−axϵ=ax aϵ−1ϵ,\frac{a^{x+\epsilon}-a^x}{\epsilon} = a^x\,\frac{a^\epsilon-1}{\epsilon},

where the second factor is simply the difference quotient at 00. Thus, if axa^x is differentiable at 00 with slope cac_a, then ddxax=ca ax\frac{d}{dx}a^x=c_a\,a^x for every xx: the slope of an exponential is always proportional to its height, with a single proportionality constant per base. Numerically, at ϵ=10−6\epsilon=10^{-6} we find (2ϵ−1)/ϵ=0.69315(2^\epsilon-1)/\epsilon=0.69315 for base 22 and (10ϵ−1)/ϵ=2.30259(10^\epsilon-1)/\epsilon=2.30259 for base 1010. The number ee is defined as the unique base whose constant is 11, which immediately yields ddxex=ex\frac{d}{dx}e^x=e^x. Once we have the derivative of the logarithm, the chain rule will identify cac_a for every other base.

22.1.2.2 Rules for Combining Derivatives#

A loss function builds on the table above using sums, products, quotients, and compositions. Let gg and hh be differentiable at xx (for the chain rule, assume hh is differentiable at xx and gg is differentiable at h(x)h(x)). Then:

  • Sum rule. ddx(g(x)+h(x))=g′(x)+h′(x)\frac{d}{dx}\bigl(g(x) + h(x)\bigr) = g'(x) + h'(x).
  • Product rule. ddx(g(x) h(x))=g(x)h′(x)+g′(x)h(x)\frac{d}{dx}\bigl(g(x)\, h(x)\bigr) = g(x)h'(x) + g'(x)h(x).
  • Quotient rule. ddxg(x)h(x)=g′(x)h(x)−g(x)h′(x)h(x)2\frac{d}{dx}\frac{g(x)}{h(x)} = \frac{g'(x)h(x) - g(x)h'(x)}{h(x)^2}, where h(x)≠0h(x)\neq 0.
  • Chain rule. ddxg(h(x))=g′(h(x)) h′(x)\frac{d}{dx}g(h(x)) = g'(h(x))\, h'(x).

The sum and product rules are routine; only the chain rule requires real care, because the naive argument divides by h(x+ϵ)−h(x)h(x+\epsilon)-h(x), which can vanish even when ϵ≠0\epsilon\neq 0. The proofs all rely on one basic fact: a function differentiable at xx is continuous at xx, because g(x+ϵ)−g(x)=ϵ⋅g(x+ϵ)−g(x)ϵg(x+\epsilon)-g(x)=\epsilon\cdot\frac{g(x+\epsilon)-g(x)}{\epsilon} tends to 0⋅g′(x)=00\cdot g'(x)=0 as ϵ→0\epsilon\to 0.

Sum rule. Adding the linear approximations for gg and hh gives

g(x+ϵ)+h(x+ϵ)=g(x)+h(x)+ϵ(g′(x)+h′(x))+o(ϵ),g(x+\epsilon) + h(x+\epsilon) = g(x) + h(x) + \epsilon\bigl(g'(x) + h'(x)\bigr) + o(\epsilon),

since the sum of two quantities that vanish faster than ϵ\epsilon also vanishes faster than ϵ\epsilon. By the converse of the linear approximation, the coefficient of ϵ\epsilon is the derivative: first-order changes simply add. ■\blacksquare

Product rule. Adding and subtracting g(x+ϵ)h(x)g(x+\epsilon)h(x) in the numerator splits the difference quotient of the product into two quotients we already know:

g(x+ϵ)h(x+ϵ)−g(x)h(x)ϵ=g(x+ϵ) h(x+ϵ)−h(x)ϵ+h(x) g(x+ϵ)−g(x)ϵ.\frac{g(x+\epsilon)h(x+\epsilon)-g(x)h(x)}{\epsilon} = g(x+\epsilon)\,\frac{h(x+\epsilon)-h(x)}{\epsilon} + h(x)\,\frac{g(x+\epsilon)-g(x)}{\epsilon}.

As ϵ→0\epsilon\to0, continuity gives g(x+ϵ)→g(x)g(x+\epsilon)\to g(x), so the right-hand side converges to g(x)h′(x)+h(x)g′(x)g(x)h'(x)+h(x)g'(x). ■\blacksquare

Chain rule. Rather than dividing by h(x+ϵ)−h(x)h(x+\epsilon)-h(x), we feed the change of the inner function directly into the linear approximation of the outer function. Because gg is differentiable at h(x)h(x), the error ratio ρ(t)=g(h(x)+t)−g(h(x))t−g′(h(x))\rho(t)=\frac{g(h(x)+t)-g(h(x))}{t}-g'(h(x)) for t≠0t\neq0, extended by ρ(0)=0\rho(0)=0, tends to 00 as t→0t\to0. For every tt, including t=0t=0, we can therefore write

g(h(x)+t)=g(h(x))+(g′(h(x))+ρ(t)) t.g(h(x)+t) = g(h(x)) + \bigl(g'(h(x)) + \rho(t)\bigr)\,t.

Now set t=h(x+ϵ)−h(x)=ϵh′(x)+o(ϵ)t=h(x+\epsilon)-h(x)=\epsilon h'(x)+o(\epsilon). By continuity of hh, t→0t\to0 as ϵ→0\epsilon\to0, so ρ(t)→0\rho(t)\to0 as well. Substituting this tt yields

g(h(x+ϵ))−g(h(x))=(g′(h(x))+ρ(t))(ϵh′(x)+o(ϵ))=ϵ g′(h(x)) h′(x)+o(ϵ),\begin{aligned} g(h(x+\epsilon)) - g(h(x)) &= \bigl(g'(h(x)) + \rho(t)\bigr)\bigl(\epsilon h'(x) + o(\epsilon)\bigr) \\ &= \epsilon\, g'(h(x))\, h'(x) + o(\epsilon), \end{aligned}

because every term other than g′(h(x)) ϵh′(x)g'(h(x))\,\epsilon h'(x) contains a factor that vanishes faster than ϵ\epsilon. Applying the converse of the linear approximation finishes the proof. ■\blacksquare

Rates multiply along a composition. Applied layer by layer to a neural network, the chain rule produces a product of local slopes, and evaluating that product efficiently is precisely what backpropagation does. The quotient rule follows immediately by applying the product and chain rules to g⋅h−1g\cdot h^{-1}.

22.1.2.3 Inverse Functions#

The chain rule also differentiates a function that undoes another. A function gg satisfying g(f(x))=xg(f(x))=x for all xx near a point is an inverse of ff there. Suppose such a gg exists and is differentiable at f(x)f(x); by the inverse function theorem (Rudin, 1976), which we use without proof, both hold whenever f′f' is continuous and nonzero near xx. Differentiating both sides of g(f(x))=xg(f(x))=x with the chain rule gives

g′(f(x)) f′(x)=1,sog′(y)=1f′(g(y))at y=f(x).g'(f(x))\,f'(x) = 1, \qquad\text{so}\qquad g'(y) = \frac{1}{f'(g(y))} \quad\text{at } y = f(x).

In other words, the slope of the inverse is the reciprocal of the slope of ff, evaluated at the matching point. Geometrically, the graph of gg is the graph of ff reflected across the diagonal, and reflecting a line across the diagonal turns rise over run upside down.

Since the logarithm undoes exe^x, this rule gives log⁡′(y)=1/elog⁡y=1/y\log'(y)=1/e^{\log y}=1/y, the fifth entry in our table. Notice that the condition f′(x)≠0f'(x)\neq0 is strictly necessary. For f(x)=x3f(x)=x^3 we have f′(0)=0f'(0)=0, so the formula breaks down at y=0y=0; indeed, its inverse x1/3x^{1/3} is not differentiable at 00, because the difference quotient ϵ1/3/ϵ=ϵ−2/3\epsilon^{1/3}/\epsilon=\epsilon^{-2/3} grows without bound and the graph has a vertical tangent there.

With the logarithm in hand, the chain rule settles the remaining two entries of the table. Writing ax=exlog⁡aa^x=e^{x\log a} gives ddxax=(log⁡a) ax\frac{d}{dx}a^x=(\log a)\,a^x, identifying the constant ca=log⁡ac_a=\log a; indeed, log⁡2=0.69315\log 2=0.69315 and log⁡10=2.30259\log 10=2.30259 are the constants we measured numerically above. Similarly, writing xn=enlog⁡xx^n=e^{n\log x} for x>0x>0 yields ddxxn=enlog⁡x⋅nx=nxn−1\frac{d}{dx}x^n=e^{n\log x}\cdot\frac{n}{x}=nx^{n-1} for every real nn.

22.1.2.4 The Softplus, the Sigmoid, and the Logit#

We can now apply these rules to our running function, s(x)=log⁡(1+ex)s(x)=\log(1+e^x). Using the chain rule with outer function log⁡\log and inner function 1+ex1+e^x gives

s′(x)=ex1+ex=11+e−x=σ(x),s'(x) = \frac{e^x}{1+e^x} = \frac{1}{1+e^{-x}} = \sigma(x),

so the derivative of the softplus is the sigmoid σ\sigma. Applying the chain rule a second time to σ(x)=(1+e−x)−1\sigma(x)=(1+e^{-x})^{-1}, with outer function u−1u^{-1} and inner function 1+e−x1+e^{-x} of slope −e−x-e^{-x}, yields

σ′(x)=e−x(1+e−x)2=σ(x)(1−σ(x)),\sigma'(x) = \frac{e^{-x}}{(1+e^{-x})^2} = \sigma(x)\bigl(1-\sigma(x)\bigr),

since 1−σ(x)=e−x/(1+e−x)1-\sigma(x)=e^{-x}/(1+e^{-x}). Because a product p(1−p)p(1-p) is maximized at p=12p=\tfrac12, the sigmoid is steepest at the origin, where σ(0)=12\sigma(0)=\tfrac12 and σ′(0)=14\sigma'(0)=\tfrac14. The inverse of σ\sigma is the logit function logit(p)=log⁡p1−p\mathrm{logit}(p)=\log\frac{p}{1-p}, and the inverse-function rule immediately gives logit′(p)=1/σ′(logit p)=1p(1−p)\mathrm{logit}'(p)=1/\sigma'(\mathrm{logit}\,p)=\frac{1}{p(1-p)}. At p=12p=\tfrac12, this equals 4=1/144=1/\tfrac14, matching the reciprocal of the sigmoid's slope.

We can now verify the two constants from the opening logistic-loss example. Since ℓ(w)=s(−w)\ell(w)=s(-w), the chain rule gives ℓ′(w)=−σ(−w)\ell'(w)=-\sigma(-w), so ℓ′(0)=−12\ell'(0)=-\tfrac12. Differentiating once more gives ℓ′′(w)=σ(−w)(1−σ(−w))\ell''(w)=\sigma(-w)\bigl(1-\sigma(-w)\bigr) and thus ℓ′′(0)=14\ell''(0)=\tfrac14, the curvature at the origin. Let us check numerically whether the gap between ℓ(ϵ)\ell(\epsilon) and its linear approximation ℓ(0)−12ϵ\ell(0)-\tfrac12\epsilon indeed shrinks like ϵ2\epsilon^2 with leading constant 12ℓ′′(0)=18\tfrac12\ell''(0)=\tfrac18.

# The logistic loss l(w) = log(1 + e^{-w}) near w = 0, where l'(0) = -1/2
def ell(w):
    return np.log(1 + np.exp(-w))

for eps in [0.1, 0.01, 0.001]:
    line = ell(0) - 0.5 * eps          # the linear approximation
    gap = ell(eps) - line
    print(f'eps = {eps:<5}: l = {ell(eps):.6f}, line = {line:.6f}, '
          f'gap = {gap:.2e}, gap / eps^2 = {gap / eps**2:.4f}')
eps = 0.1  : l = 0.644397, line = 0.643147, gap = 1.25e-03, gap / eps^2 = 0.1249
eps = 0.01 : l = 0.688160, line = 0.688147, gap = 1.25e-05, gap / eps^2 = 0.1250
eps = 0.001: l = 0.692647, line = 0.692647, gap = 1.25e-07, gap / eps^2 = 0.1250

Sure enough, the gap drops a hundredfold every time we cut ϵ\epsilon by a factor of ten, and gap/ϵ2\text{gap}/\epsilon^2 settles to 0.125=12ℓ′′(0)0.125=\tfrac12\ell''(0). The error of the linear approximation is indeed of second order, with a leading constant governed by the curvature. Notice also that the first line prints 0.12490.1249 rather than 0.12500.1250: the gap is not quite ϵ2/8\epsilon^2/8, and Section 22.1.5.2 will identify the higher-order term responsible for that small difference.

So far, every calculation has lived in an infinitesimal neighborhood of a single point. Asking what the slope tells us about a function across an entire interval is a different kind of question.

22.1.3 The Mean Value Theorem#

In optimization, we routinely act on two intuitions: a positive slope means the function is climbing, and a point where the slope vanishes is a candidate minimum. Gradient descent relies on both. Yet each claim infers the behavior of ff over an interval from its derivative at individual points, and neither is built into the definition of the derivative. We prove the second claim first, as it is the simpler one.

Lemma (Fermat). If ff attains a local maximum or a local minimum at an interior point ξ\xi of an interval and is differentiable at ξ\xi, then f′(ξ)=0f'(\xi)=0.

Proof. At a local maximum, f(ξ+ϵ)−f(ξ)≤0f(\xi + \epsilon) - f(\xi) \le 0 for all sufficiently small ϵ\epsilon of either sign. The difference quotient is therefore ≤0\le 0 for ϵ>0\epsilon > 0 and ≥0\ge 0 for ϵ<0\epsilon \lt 0. Because ff is differentiable at ξ\xi, both one-sided limits must equal f′(ξ)f'(\xi), and the only number that is simultaneously ≤0\le 0 and ≥0\ge 0 is zero. A local minimum follows by the same argument with inequalities reversed. ■\blacksquare

The first intuition requires a deeper tool: the Mean Value Theorem. Every error bound in the remainder of this section is obtained by applying this theorem to a well-chosen auxiliary function. Geometrically (Figure 22.1.3), it states that the chord joining the endpoints of the graph over [a,b][a,b] is parallel to the tangent line at some interior point.

Figure 22.1.3:

Over the interval from aa to bb, the secant chord through the endpoints has slope equal to the average rate of change; the Mean Value Theorem guarantees that some interior point ξ\xi has a tangent of that same slope, parallel to the chord.

On a simple example like f(x)=x2f(x)=x^2 over [0,2][0,2], the chord has slope (4−0)/2=2(4-0)/2=2, and the tangent slope f′(ξ)=2ξf'(\xi)=2\xi matches it at the midpoint ξ=1\xi=1. Notice, however, that the theorem truly requires differentiability at every interior point. The absolute value ∣x∣|x| on [−1,1][-1,1] satisfies f(−1)=f(1)f(-1)=f(1), so its chord is horizontal, yet no interior point has slope 00: the slope is −1-1 on the left, +1+1 on the right, and undefined at 00.

Proposition (Mean Value Theorem). If ff is continuous on [a,b][a,b] and differentiable on (a,b)(a,b), then there exists a point ξ∈(a,b)\xi \in (a,b) such that

f′(ξ)=f(b)−f(a)b−a.(22.1.3)f'(\xi) = \frac{f(b) - f(a)}{b - a}. \tag{22.1.3}

Proof. Consider first the flat case f(a)=f(b)f(a) = f(b), known as Rolle's theorem. We invoke one foundational result from real analysis, the extreme value theorem: a continuous function on a closed interval attains both a maximum and a minimum (Rudin, 1976). If both extrema occur at the endpoints, then ff is constant and f′≡0f' \equiv 0 everywhere inside. Otherwise, at least one extremum occurs at an interior point ξ\xi, where f′(ξ)=0f'(\xi)=0 by Fermat's lemma.

For the general case, we subtract the chord to flatten the endpoints. Define the tilted function f~(x)=f(x)−f(b)−f(a)b−a(x−a)\tilde f(x) = f(x) - \frac{f(b)-f(a)}{b-a}(x - a). Since f~(a)=f~(b)=f(a)\tilde f(a) = \tilde f(b) = f(a), Rolle's theorem provides an interior point ξ\xi with f~′(ξ)=0\tilde f'(\xi) = 0, which rearranges directly to (22.1.3). ■\blacksquare

In words, the average rate of change over an interval is always realized as an instantaneous rate of change at some point inside it. Two consequences will appear repeatedly throughout the chapter:

  1. If f′>0f'>0 on an interval, then ff is strictly increasing there. For any x1<x2x_1\lt x_2 in the interval, (22.1.3) gives f(x2)−f(x1)=f′(ξ)(x2−x1)>0f(x_2)-f(x_1)=f'(\xi)(x_2-x_1)>0 for some ξ\xi between them. By the same token, f′<0f'\lt 0 implies ff is strictly decreasing, and f′=0f'=0 implies ff is constant.
  2. If f′<0f'\lt 0 on (x0−δ,x0)(x_0-\delta,x_0) and f′>0f'>0 on (x0,x0+δ)(x_0,x_0+\delta) for some δ>0\delta>0, and ff is continuous at x0x_0, then x0x_0 is a strict local minimum. Applying the first consequence on each side shows that ff falls into x0x_0 from the left and rises out of it to the right.

Returning to our running function, s′=σ>0s'=\sigma>0 everywhere, so the softplus is strictly increasing on all of R\mathbb R.

22.1.4 Gradient Descent in One Variable#

22.1.4.1 The Gradient-Descent Step#

The linear approximation predicts how ff responds to any small step ϵ\epsilon: f(x+ϵ)≈f(x)+ϵf′(x)f(x+\epsilon)\approx f(x)+\epsilon f'(x). To decrease ff, we should choose ϵ\epsilon with the sign opposite to the slope. Setting ϵ=−ηf′(x)\epsilon=-\eta f'(x) for a positive step size η>0\eta>0, the linear model predicts the change

f(x−ηf′(x))−f(x)≈−η f′(x)2,f\bigl(x-\eta f'(x)\bigr) - f(x) \approx -\eta\, f'(x)^2,

which is strictly negative whenever f′(x)≠0f'(x)\neq0. Regardless of whether the slope is positive or negative, stepping opposite to it lowers the linear model by an amount proportional to the squared slope (Figure 22.1.4).

Figure 22.1.4:

One gradient-descent step on a 1-D bowl. At xx the tangent line has slope f′(x)f'(x); the step −ηf′(x)-\eta f'(x) moves opposite the slope and lands at x−ηf′(x)x - \eta f'(x), lower on the curve, with the drop equal to ηf′(x)2\eta f'(x)^2 to first order.

Iterating this update gives one-dimensional gradient descent:

xt+1=xt−η f′(xt).(22.1.4)x_{t+1} = x_t - \eta\, f'(x_t). \tag{22.1.4}

Each step moves against the local slope, and the iteration comes to rest at a stationary point, where f′(xt)=0f'(x_t)=0. In a neural network, every coordinate of the weight update wi←wi−η ∂ℓ/∂wiw_i\leftarrow w_i-\eta\,\partial\ell/\partial w_i takes this form, with all coordinates updated simultaneously. On our logistic loss starting at w=0w=0, the slope is ℓ′(0)=−12\ell'(0)=-\tfrac12, so a step of size η\eta moves the weight by ϵ=η/2\epsilon=\eta/2 and predicts a loss drop of η/4\eta/4.

Notice a glaring limitation of the linear model: its predicted change −ηf′(x)2-\eta f'(x)^2 is negative for every η>0\eta > 0, no matter how huge. In reality, too large a step can overshoot the minimum and land higher than where it began. The tangent line cannot warn us of this danger because it knows nothing about how the curve bends. The simplest bowl, f(x)=x2f(x)=x^2, already reveals where the linear prediction breaks down.

22.1.4.2 The Quadratic Case#

For f(x)=x2f(x)=x^2, the slope is f′(x)=2xf'(x)=2x, so the gradient-descent update simplifies to

xt+1=xt−η (2xt)=(1−2η) xt.x_{t+1} = x_t - \eta\,(2x_t) = (1 - 2\eta)\, x_t.

Every step multiplies the current iterate by the same factor 1−2η1-2\eta, giving the closed form xt=(1−2η)tx0x_t=(1-2\eta)^t x_0. The iterates therefore converge to the minimum x=0x = 0 if and only if ∣1−2η∣<1|1 - 2\eta| \lt 1, which is 0<η<10 \lt \eta \lt 1. Within this convergent range, a small η\eta creeps monotonically toward 00, η=12\eta = \tfrac12 lands on the minimum in a single step, and 12<η<1\tfrac12 \lt \eta \lt 1 overshoots and oscillates inward. Right at the boundary η=1\eta = 1, the iterates bounce forever between +x0+x_0 and −x0-x_0, and for η>1\eta > 1 they blow up.

Let us run ten steps from x0=1x_0=1 across five step sizes, one from each regime, to see these trajectories side by side.

# Gradient descent on f(x) = x^2 from x0 = 1, for several step sizes
def gd(eta, steps=10, x0=1.0):
    xs = [x0]
    for _ in range(steps):
        xs.append(xs[-1] - eta * (2 * xs[-1]))  # x <- x - eta * f'(x)
    return xs

etas = [0.05, 0.5, 0.9, 1.0, 1.1]
trajectories = [gd(eta) for eta in etas]
for eta, xs in zip(etas, trajectories):
    print(f'eta = {eta:.2f} -> x_10 = {xs[-1]:+.5f}')
d2l.plot(list(range(11)), trajectories, 'step t', 'x_t', ylim=[-2.5, 2.5],
         legend=[f'eta = {eta}' for eta in etas],
         fmts=('-', 'm--', 'g-.', 'r:', 'c-'))
eta = 0.05 -> x_10 = +0.34868
eta = 0.50 -> x_10 = +0.00000
eta = 0.90 -> x_10 = +0.10737
eta = 1.00 -> x_10 = +1.00000
eta = 1.10 -> x_10 = +6.19174

The printed values match the closed-form powers (1−2η)10(1-2\eta)^{10}: the cautious step η=0.05\eta=0.05 has only crawled down to 0.3490.349, η=0.9\eta=0.9 has zig-zagged down to 0.1070.107, η=1\eta=1 is right back at 11, and η=1.1\eta=1.1 has already diverged to 6.196.19. Notice that the stability threshold η=1\eta=1 equals 2/f′′2/f'', because f′′≡2f''\equiv2 for x2x^2. As we will see in Section 22.1.5.4, this is no coincidence: any bound LL on the curvature gives the safe step-size threshold 2/L2/L for every smooth function.

22.1.5 Curvature and Taylor Series#

How far can we trust the linear approximation, and how large a step size is safe? Both questions depend on how fast the slope itself changes.

22.1.5.1 The Second Derivative#

Because f′f' is itself a function of xx, we can differentiate it again. The result is the second derivative, f′′=d2fdx2=ddx(dfdx)f''=\frac{d^2f}{dx^2}=\frac{d}{dx}\bigl(\frac{df}{dx}\bigr), which measures the rate of change of the slope. Repeating this process nn times yields the nn-th derivative,

f(n)(x)=dnfdxn=(ddx)nf.f^{(n)}(x) = \frac{d^{n}f}{dx^{n}} = \left(\frac{d}{dx}\right)^{n} f.

Geometrically, f′′>0f''>0 means the slope is increasing, so the graph curves upward like a bowl; f′′<0f''\lt 0 means the slope is decreasing, so the graph curves downward like a dome. At a stationary point, this sign tells a local minimum apart from a local maximum.

Proposition (second-derivative test). Let f′(x0)=0f'(x_0)=0 and suppose f′′(x0)f''(x_0) exists. If f′′(x0)>0f''(x_0)>0, then x0x_0 is a strict local minimum; if f′′(x0)<0f''(x_0)\lt 0, it is a strict local maximum.

Proof. Because f′(x0)=0f'(x_0)=0, the definition of f′′(x0)f''(x_0) simplifies to f′′(x0)=lim⁡ϵ→0f′(x0+ϵ)/ϵf''(x_0)=\lim_{\epsilon\to0}f'(x_0+\epsilon)/\epsilon. If this limit is positive, then the quotient f′(x0+ϵ)/ϵf'(x_0+\epsilon)/\epsilon must be positive for all sufficiently small ϵ≠0\epsilon\neq0. Hence f′(x0+ϵ)f'(x_0+\epsilon) shares the sign of ϵ\epsilon: negative just to the left of x0x_0 and positive just to the right. By the second consequence of the Mean Value Theorem, x0x_0 is a strict local minimum. The case f′′(x0)<0f''(x_0)\lt 0 follows identically with all signs reversed. ■\blacksquare

Notice where the real work happened in that proof: turning a local sign pattern of f′f' into a minimum over an interval requires the Mean Value Theorem. Note also that the test certifies only a neighborhood of x0x_0, not the entire domain. When we move to many variables, the signs of the eigenvalues of the matrix of second derivatives will play this same role.

Figure 22.1.5:

The second-derivative test. Rows: f′′(0)>0f''(0)>0 (a bowl, minimum), f′′(0)<0f''(0)\lt 0 (a dome, maximum), and f′′(0)=0f''(0)=0, where x3x^3, x4x^4, and −x4-x^4 share f′(0)=f′′(0)=0f'(0)=f''(0)=0 yet have an inflection point, a minimum, and a maximum at 00. Columns: f′′f'', f′f', ff.

When f′′(x0)=0f''(x_0)=0 at a stationary point, the test is silent (Figure 22.1.5, bottom row): x3x^3, x4x^4, and −x4-x^4 all satisfy f′(0)=f′′(0)=0f'(0)=f''(0)=0, yet 00 is an inflection point for the first, a minimum for the second, and a maximum for the third; higher-order derivatives decide such flat stationary points.

22.1.5.2 The Taylor Polynomial#

The tangent line matches the value and the slope of ff at a base point x0x_0. To capture the bend as well, we can fit a parabola. A general quadratic q(x)=ax2+bx+cq(x)=ax^2+bx+c has derivatives

q′(x)=2ax+b,q′′(x)=2a,q'(x) = 2ax + b, \qquad q''(x) = 2a,

so its curvature is the constant 2a2a. Matching the curvature of ff at x0x_0 fixes a=f′′(x0)/2a=f''(x_0)/2, and matching the value and slope fixes bb and cc. For f(x)=sin⁡(x)f(x) = \sin(x), where sin⁡′=cos⁡\sin'=\cos and sin⁡′′=−sin⁡\sin''=-\sin, the best-fitting parabola at x0x_0 is

q(x)=sin⁡(x0)+cos⁡(x0) (x−x0)−12sin⁡(x0) (x−x0)2.q(x) = \sin(x_0) + \cos(x_0)\,(x - x_0) - \tfrac{1}{2}\sin(x_0)\,(x-x_0)^2.

Because this parabola follows the bend of the sine curve, it stays accurate over a noticeably wider interval than the tangent line (Figure 22.1.6, drawn at a base point where sin⁡x0≠0\sin x_0\neq0 so the parabola has nonzero curvature).

Figure 22.1.6:

The sine curve with its two local models at x0x_0: the tangent line matches value and slope, while the best parabola also matches curvature and remains accurate over a wider interval.

For our running function at x0=0x_0=0, the values s(0)=log⁡2s(0)=\log2, s′(0)=12s'(0)=\tfrac12, and s′′(0)=14s''(0)=\tfrac14 produce the best parabola log⁡2+x2+x28\log2+\tfrac{x}{2}+\tfrac{x^2}{8}. Its quadratic coefficient 18\tfrac18 is the exact constant to which gap/ϵ2\text{gap}/\epsilon^2 converged for the logistic loss ℓ(w)=s(−w)\ell(w)=s(-w).

The same idea extends to any degree nn. The degree-nn Taylor polynomial of ff at x0x_0 is

Pn(x)=∑i=0nf(i)(x0)i!(x−x0)i,P_n(x) = \sum_{i = 0}^{n} \frac{f^{(i)}(x_0)}{i!}(x-x_0)^{i},

which is the unique polynomial of degree at most nn whose value and first nn derivatives agree with those of ff at x0x_0. The factorials appear because differentiating (x−x0)i(x-x_0)^i exactly ii times at x0x_0 produces i!i!, while every other term vanishes. In this notation, P1P_1 is the tangent line and P2P_2 is the best parabola. For exe^x at x0=0x_0=0, where every derivative equals 11, we obtain Pn(x)=∑i=0nxi/i!P_n(x)=\sum_{i=0}^n x^i/i!, and each new term lets the polynomial hug the exponential curve a little farther from the origin. To know just how far we can trust PnP_n, and how rapidly its error grows beyond that range, we need an explicit formula for the remainder.

22.1.5.3 The Lagrange Remainder#

The Mean Value Theorem yields an exact formula for the error of PnP_n, expressed in terms of a single unknown interior point. This is the centerpiece of the section: both the descent lemma and Newton's quadratic convergence rate fall out of its n=1n=1 case.

Proposition (Lagrange remainder). If ff is (n+1)(n+1)-times differentiable on an open interval containing x0x_0 and xx, with x≠x0x\neq x_0, then

f(x)=Pn(x)+Rn(x),Rn(x)=f(n+1)(ξ)(n+1)! (x−x0)n+1,(22.1.5)f(x) = P_n(x) + R_n(x), \qquad R_n(x) = \frac{f^{(n+1)}(\xi)}{(n+1)!}\,(x - x_0)^{n+1}, \tag{22.1.5}

for some ξ\xi strictly between x0x_0 and xx. Note that the case n=0n = 0 recovers the Mean Value Theorem, f(x)=f(x0)+f′(ξ)(x−x0)f(x) = f(x_0) + f'(\xi)(x - x_0).

Proof. The one clever step is choosing the right auxiliary function; everything after that is straightforward differentiation. Fix xx and treat the base point tt as the variable: for tt between x0x_0 and xx, define

G(t)=f(x)−∑k=0nf(k)(t)k! (x−t)k−M (x−t)n+1(n+1)!,G(t) = f(x) - \sum_{k=0}^{n} \frac{f^{(k)}(t)}{k!}\,(x-t)^k - M\,\frac{(x-t)^{n+1}}{(n+1)!},

which is the error at xx of the Taylor polynomial centered at tt, minus a term of the form we expect that error to take. Choose the constant MM so that G(x0)=0G(x_0)=0. The proof now finishes in three steps.

First, GG vanishes at both endpoints. Our choice of MM ensures G(x0)=0G(x_0)=0, while G(x)=0G(x)=0 because every positive power of (x−t)(x-t) vanishes at t=xt=x and the k=0k=0 term leaves f(x)−f(x)=0f(x)-f(x)=0. Rolle's theorem therefore guarantees a point ξ\xi strictly between x0x_0 and xx where G′(ξ)=0G'(\xi)=0.

Second, differentiate G(t)G(t) with respect to tt. By the product rule, each summand with k≥1k\geq1 contributes

−f(k+1)(t)k!(x−t)k+f(k)(t)(k−1)!(x−t)k−1-\frac{f^{(k+1)}(t)}{k!}(x-t)^k + \frac{f^{(k)}(t)}{(k-1)!}(x-t)^{k-1}

to G′(t)G'(t), while the k=0k=0 term contributes −f′(t)-f'(t). Adjacent terms cancel in pairs (the sum telescopes), leaving only the highest-order derivative and the derivative of the MM term:

G′(t)=−f(n+1)(t)n! (x−t)n+M (x−t)nn!.G'(t) = -\frac{f^{(n+1)}(t)}{n!}\,(x-t)^n + M\,\frac{(x-t)^n}{n!}.

Third, evaluate at t=ξt=\xi. Because ξ\xi lies strictly between x0x_0 and xx, we have (x−ξ)n≠0(x-\xi)^n\neq0, so G′(ξ)=0G'(\xi)=0 forces M=f(n+1)(ξ)M=f^{(n+1)}(\xi). Plugging this back into G(x0)=0G(x_0)=0 yields (22.1.5). ■\blacksquare

The remainder looks just like the next term of the Taylor polynomial, except that the (n+1)(n+1)-st derivative is evaluated at an unknown interior point ξ\xi rather than at x0x_0. Whenever f(n+1)f^{(n+1)} stays bounded near x0x_0, the error therefore scales as ∣x−x0∣n+1|x-x_0|^{n+1}: each additional matched derivative raises the order of accuracy by one.

Let us test this on our running function. For the softplus, s′′′=σ(1−σ)(1−2σ)s'''=\sigma(1-\sigma)(1-2\sigma) vanishes at 00 and s′′′′(0)=−18s''''(0)=-\tfrac18, giving the fourth-degree polynomial

P4(x)=log⁡2+x2+x28−x4192.P_4(x) = \log 2 + \frac{x}{2} + \frac{x^2}{8} - \frac{x^4}{192}.

At x=0.5x=0.5, this evaluates to 0.9740720.974072 against the true value s(0.5)=0.974077s(0.5)=0.974077, an error of only 5×10−65\times10^{-6}. In fact, the error is even smaller than an x5x^5 estimate would suggest, because s(x)−x2=log⁡(2cosh⁡x2)s(x)-\tfrac{x}{2}=\log\bigl(2\cosh\tfrac{x}{2}\bigr) is an even function, so all higher odd terms vanish and the next nonzero term is sixth order. That quartic term also explains why our earlier script printed 0.12490.1249 instead of 0.12500.1250 at ϵ=0.1\epsilon=0.1: we were seeing 18−ϵ2192=0.12495\tfrac18-\tfrac{\epsilon^2}{192}=0.12495.

We can check the hn+1h^{n+1} scaling directly in code. If the worst-case error of PnP_n on the window ∣x∣≤h|x|\le h behaves like hn+1h^{n+1}, then halving hh should divide the maximum error by 2n+12^{n+1}: by 44 for the tangent line, 88 for the parabola, and 1616 for the cubic. Let us verify this prediction on exe^x at x0=0x_0=0.

# Max error of P_n for e^x on |x| <= h. Lagrange predicts error ~ h^(n+1),
# so halving h should divide it by 2^(n+1)
def taylor_error(n, h, m=1000):
    x = h * np.arange(-m, m + 1) / m
    P = sum(x**k / math.factorial(k) for k in range(n + 1))
    return np.max(np.abs(np.exp(x) - P))

hs = [0.4, 0.2, 0.1, 0.05]
errs = [[taylor_error(n, h) for h in hs] for n in (1, 2, 3)]
for n, e in zip((1, 2, 3), errs):
    ratios = ' '.join(f'{a / b:.1f}' for a, b in zip(e, e[1:]))
    print(f'n = {n}: ratios between successive windows {ratios}, '
          f'predicted {2**(n + 1)}')
d2l.plot(hs, errs, 'window h', 'max error', xscale='log', yscale='log',
         legend=['n = 1', 'n = 2', 'n = 3'])
n = 1: ratios between successive windows 4.3 4.1 4.1, predicted 4
n = 2: ratios between successive windows 8.4 8.2 8.1, predicted 8
n = 3: ratios between successive windows 16.7 16.3 16.2, predicted 16

The measured ratios indeed sit near 44, 88, and 1616, and on the log–log plot the three error curves appear as straight lines with slopes 22, 33, and 44, matching n+1n+1. The ratios slightly exceed the theoretical values on the wider windows because the factor eξe^{\xi} in the remainder is larger there.

The Lagrange remainder also answers when the infinite Taylor series reproduces the function itself. For exe^x, every derivative equals exe^x, so (22.1.5) around x0=0x_0=0 gives

∣ex−Pn(x)∣=eξ ∣x∣n+1(n+1)!≤e∣x∣ ∣x∣n+1(n+1)!.\bigl|e^x - P_n(x)\bigr| = \frac{e^{\xi}\,|x|^{n+1}}{(n+1)!} \le \frac{e^{|x|}\,|x|^{n+1}}{(n+1)!}.

For any fixed xx, the right-hand side vanishes as n→∞n\to\infty because factorials eventually outgrow powers. Hence

ex=∑n=0∞xnn!=1+x+x22+x36+⋯e^{x} = \sum_{n = 0}^\infty \frac{x^{n}}{n!} = 1 + x + \frac{x^2}{2} + \frac{x^3}{6} + \cdots

on all of R\mathbb R. Be careful, though: having infinitely many derivatives does not guarantee that a function equals its Taylor series. For f(x)=e−1/x2f(x) = e^{-1/x^2} (extended by f(0)=0f(0) = 0), every single derivative vanishes at 00, so its Taylor series at the origin is identically zero and agrees with ff only at x=0x=0 (Figure 22.1.7). Luckily, nothing we do later depends on infinite series: we work exclusively with finite Taylor polynomials PnP_n, whose error (22.1.5) bounds directly.

Figure 22.1.7:

The smooth function f(x)=e−1/x2f(x) = e^{-1/x^2} has every derivative equal to zero at the origin, so its Taylor series there is identically zero. The series converges everywhere yet agrees with ff only at x=0x = 0: smooth does not imply analytic.

22.1.5.4 The Descent Lemma#

Does a bound on curvature guarantee that gradient descent lowers any smooth function, just as it did for x2x^2? The Lagrange remainder with n=1n=1 answers yes. Among all results in this section, this is the one optimization theory uses most.

Proposition (descent lemma). Let ff be twice differentiable on an open interval II containing xx and x−ηf′(x)x-\eta f'(x), with ∣f′′∣≤L|f''|\le L on II. Then

f(x−η f′(x))  ≤  f(x)−η(1−Lη2)f′(x)2.(22.1.6)f\bigl(x - \eta\, f'(x)\bigr) \;\le\; f(x) - \eta\Bigl(1 - \frac{L\eta}{2}\Bigr)f'(x)^2. \tag{22.1.6}

In particular, ff strictly decreases whenever 0<η<2/L0 \lt \eta \lt 2/L and f′(x)≠0f'(x) \neq 0, and the guaranteed decrease is maximized at η=1/L\eta = 1/L, where it equals f′(x)2/(2L)f'(x)^2/(2L).

Proof. For any step uu, the Lagrange remainder with n=1n=1 gives f(x+u)=f(x)+f′(x)u+12f′′(ξ)u2≤f(x)+f′(x)u+L2u2f(x+u)=f(x)+f'(x)u+\tfrac12f''(\xi)u^2\le f(x)+f'(x)u+\tfrac L2u^2. Setting u=−ηf′(x)u=-\eta f'(x) turns the right-hand side into f(x)−η(1−Lη/2)f′(x)2f(x)-\eta(1-L\eta/2)f'(x)^2. The factor 1−Lη/21-L\eta/2 is positive whenever η<2/L\eta\lt 2/L, and the quadratic η(1−Lη/2)\eta(1-L\eta/2) attains its maximum at η=1/L\eta=1/L. ■\blacksquare

Geometrically, the lemma replaces the unknown local curvature f′′(ξ)f''(\xi) with its worst-case bound LL. The resulting quadratic f(x)+f′(x)u+L2u2f(x)+f'(x)u+\tfrac L2u^2 acts as an upper-bounding parabola that touches ff at xx and stays above it throughout II. The step η=1/L\eta=1/L simply jumps to the exact minimizer of this ceiling parabola (Figure 22.1.8). This bound is the workhorse of smooth optimization (Nesterov, 2018). In fact, it does not even require a second derivative: it holds whenever f′f' is LL-Lipschitz, meaning that slopes at any two points differ by at most LL times their distance, ∣f′(u)−f′(v)∣≤L∣u−v∣|f'(u)-f'(v)|\le L|u-v|. That is the form used in multivariable optimization (Section 23.1), and exercise 1 proves it in one variable.

Figure 22.1.8:

For ∣f′′∣≤L|f''|\le L, f(x)+f′(x)u+L2u2f(x) + f'(x)u + \frac{L}{2}u^2 is a quadratic upper bound in the step uu that equals ff at the base point. The gradient step with η=1/L\eta = 1/L minimizes this bound and guarantees a decrease of at least 12Lf′(x)2\frac{1}{2L}f'(x)^2. Here f(x)=sin⁡(2x)f(x) = \sin(2x) with L=4L = 4, and the actual decrease exceeds the worst-case guarantee.

Let us check the lemma on two familiar functions. For x2x^2, we have L=2L=2, so 2/L=12/L=1 recovers the exact stability threshold we found from the closed form. For the logistic loss, ℓ′′(w)=σ(−w)(1−σ(−w))≤14\ell''(w)=\sigma(-w)\bigl(1-\sigma(-w)\bigr)\le\tfrac14 with equality at w=0w=0, so L=14L=\tfrac14 and every step size η<8\eta\lt 8 is guaranteed to decrease ℓ\ell from any starting weight. Starting from w=0w=0 with η=1\eta=1 moves to w1=0.5w_1=0.5: the bound guarantees a loss at most 0.693147−(1−18)⋅14=0.47440.693147-(1-\tfrac18)\cdot\tfrac14=0.4744, and the actual value is ℓ(0.5)=0.4741\ell(0.5)=0.4741. The bound is nearly tight here because the curvature stays close to its maximum LL over that short step. With the larger step η=4=1/L\eta=4=1/L, the bound promises 0.19310.1931 while the actual loss drops all the way to ℓ(2)=0.1269\ell(2)=0.1269: away from the origin, the curvature flattens out, so the curve descends even further than the worst-case ceiling predicts.

22.1.5.5 Newton's Method#

The descent lemma builds its quadratic model using the global worst-case curvature LL. If instead we use the actual local curvature f′′(xt)f''(x_t) at the current iterate, we obtain a step that minimizes any quadratic function in a single leap. The local model at xtx_t is the second-order Taylor polynomial P2P_2,

q(x)=f(xt)+f′(xt) (x−xt)+12f′′(xt) (x−xt)2.q(x) = f(x_t) + f'(x_t)\,(x - x_t) + \tfrac{1}{2}f''(x_t)\,(x - x_t)^2.

Whenever f′′(xt)>0f''(x_t)>0, this parabola opens upward and has a unique minimizer. Setting q′(x)=f′(xt)+f′′(xt)(x−xt)=0q'(x) = f'(x_t) + f''(x_t)(x - x_t) = 0 and solving for xx yields the update of Newton's method:

xt+1=xt−f′(xt)f′′(xt).(22.1.7)x_{t+1} = x_t - \frac{f'(x_t)}{f''(x_t)}. \tag{22.1.7}

This is a gradient step with an adaptive local step size 1/f′′(xt)1/f''(x_t), and on any upward-opening parabola it lands on the exact minimizer in one step. Figure 22.1.9 illustrates one step on f(x)=x4/4−xf(x)=x^4/4-x, whose minimizer is x⋆=1x^\star=1. At xt=2x_t=2, we have f(2)=2f(2)=2, f′(2)=7f'(2)=7, and f′′(2)=12f''(2)=12, so the parabola's minimizer lies at xt+1=2−7/12=1.4167x_{t+1}=2-7/12=1.4167.

Figure 22.1.9:

One Newton step on f(x)=x4/4−xf(x)=x^4/4-x from xt=2x_t=2. The parabola qq matches the value, slope, and curvature of ff at xtx_t; its minimizer is the next iterate xt+1=xt−f′(xt)/f′′(xt)=2−7/12x_{t+1}=x_t-f'(x_t)/f''(x_t)=2-7/12, closer to the minimizer x⋆=1x^\star=1.

Let us see how quickly Newton's method converges on x4/4−xx^4/4-x from x0=2x_0=2, and also test what happens on a second function, xarctan⁡x−12log⁡(1+x2)x\arctan x-\tfrac12\log(1+x^2), starting from x0=1.4x_0=1.4 and x0=1.3x_0=1.3. We will analyze that second example right after inspecting the numbers.

# Newton on f(x) = x^4/4 - x: solve f'(x) = x^3 - 1 = 0, root x* = 1
x = 2.0
for t in range(6):
    print(f't = {t}: x = {x:.12f}, error = {abs(x - 1):.1e}')
    x = x - (x**3 - 1) / (3 * x**2)  # x - f'(x) / f''(x)

# Newton on the convex f(x) = x arctan(x) - log(1 + x^2)/2,
# with f' = arctan(x) and f'' = 1/(1 + x^2)
for x0 in [1.4, 1.3]:
    x, xs = x0, []
    for t in range(6):
        x = x - math.atan(x) * (1 + x**2)
        xs.append(x)
    print(f'from x0 = {x0}:', ', '.join(f'{v:.2f}' for v in xs))
t = 0: x = 2.000000000000, error = 1.0e+00
t = 1: x = 1.416666666667, error = 4.2e-01
t = 2: x = 1.110534409842, error = 1.1e-01
t = 3: x = 1.010636768405, error = 1.1e-02
t = 4: x = 1.000111557304, error = 1.1e-04
t = 5: x = 1.000000012443, error = 1.2e-08
from x0 = 1.4: -1.41, 1.45, -1.55, 1.85, -2.89, 8.71
from x0 = 1.3: -1.16, 0.86, -0.37, 0.03, -0.00, 0.00

On x4/4−xx^4/4-x, the errors plummet through 1.01.0, 0.420.42, 0.110.11, 1.1×10−21.1\times10^{-2}, 1.1×10−41.1\times10^{-4}, and 1.2×10−81.2\times10^{-8}: once close to the minimum, each step squares the previous error and roughly doubles the number of correct digits. By contrast, gradient descent on x2x^2 shrank the error by a constant factor ∣1−2η∣|1-2\eta| per step, gaining only a fixed number of digits at each iteration.

The Lagrange remainder explains why the error squares. Let x⋆x^\star be a stationary point and let et=xt−x⋆e_t=x_t-x^\star denote the error at step tt. Applying (22.1.5) with n=1n=1 to f′f' around the base point xtx_t and evaluating at x⋆x^\star gives 0=f′(xt)−f′′(xt) et+12f′′′(ξt) et20=f'(x_t)-f''(x_t)\,e_t+\tfrac12f'''(\xi_t)\,e_t^2. Dividing through by f′′(xt)≠0f''(x_t)\neq0 and substituting Newton's update (22.1.7) leaves

et+1=f′′′(ξt)2f′′(xt) et2(22.1.8)e_{t+1} = \frac{f'''(\xi_t)}{2f''(x_t)}\,e_t^2 \tag{22.1.8}

for some ξt\xi_t between xtx_t and x⋆x^\star, provided ff is three times differentiable. For x4/4−xx^4/4-x, the prefactor converges to f′′′(1)/(2f′′(1))=6/(2⋅3)=1f'''(1)/(2f''(1))=6/(2\cdot3)=1, and the printed errors indeed yield et+1/et2≈0.42e_{t+1}/e_t^2\approx0.42, 0.640.64, 0.870.87, and 0.990.99. The general multivariable theorem, giving quadratic convergence from any starting point close enough to a minimizer with positive curvature, appears in Section 23.2.

That qualification "close enough" is essential, even for a strictly convex function. Consider f(x)=xarctan⁡x−12log⁡(1+x2)f(x)=x\arctan x-\tfrac12\log(1+x^2), which has f′(x)=arctan⁡xf'(x)=\arctan x and f′′(x)=1/(1+x2)>0f''(x)=1/(1+x^2)>0, so it is strictly convex with a unique global minimum at 00. Starting from x0=1.4x_0=1.4, the second loop above prints −1.41,1.45,−1.55,1.85,−2.89,8.71-1.41, 1.45, -1.55, 1.85, -2.89, 8.71: Newton's method diverges wildly. Starting slightly closer at x0=1.3x_0=1.3, it converges smoothly (−1.16-1.16, 0.860.86, −0.37-0.37, 0.030.03, …), with the threshold between convergence and divergence sitting near x0≈1.39x_0\approx1.39.

The local parabola explains what went wrong. Far from the origin, the curvature 1/(1+x2)1/(1+x^2) becomes tiny, so the approximating parabola qq is nearly flat and places its minimizer far past x⋆x^\star. The standard fix is to scale back the step by a factor chosen to ensure ff actually decreases, a technique called damping. We develop damped Newton steps, and examine the cost of computing them in high dimensions, in Section 23.2.1.

22.1.6 Nondifferentiable Points#

Every ReLU\mathrm{ReLU} network is full of corners: ReLU(x)=max⁡(0,x)\mathrm{ReLU}(x)=\max(0,x) has no derivative at 00. Yet backpropagation still returns a number there. Which number does it pick, and in what sense is that number a valid slope?

22.1.6.1 One-Sided Derivatives#

The difference quotient (22.1.1) exposes the problem immediately. For f(x)=∣x∣f(x) = |x| at x=0x = 0,

∣0+ϵ∣−∣0∣ϵ=∣ϵ∣ϵ={+1ϵ>0,−1ϵ<0.\frac{|0+\epsilon| - |0|}{\epsilon} = \frac{|\epsilon|}{\epsilon} = \begin{cases} +1 & \epsilon > 0, \\ -1 & \epsilon \lt 0. \end{cases}

The quotient is constant on either side of 00, but the two constants disagree. Approaching from the right, the graph rises with slope +1+1; approaching from the left, it falls with slope −1-1. These limits are the one-sided derivatives, f+′(0)=+1f'_+(0) = +1 and f−′(0)=−1f'_-(0) = -1, and an ordinary derivative exists only when the two match. The same calculation for ReLU\mathrm{ReLU} at 00 gives f−′(0)=0f'_-(0) = 0 on the flat left side and f+′(0)=1f'_+(0) = 1 on the right. No tangent slope exists at these corners, yet an automatic differentiation engine must still return a number. Let us check what automatic differentiation actually returns.

# What autograd returns at the corner, where no derivative exists
for name, fn in [('d|x|/dx', torch.abs), ("ReLU'", torch.relu)]:
    x = torch.tensor(0.0, requires_grad=True)
    fn(x).backward()
    print(f"{name} at 0: autograd returns {x.grad.item():.1f}")
d|x|/dx at 0: autograd returns 0.0
ReLU' at 0: autograd returns 0.0

For ReLU′(0)\mathrm{ReLU}'(0), autograd returns 00, the left-hand slope. For ddx∣x∣\frac{d}{dx}|x| at 00, it returns a fixed value chosen by convention.

Here it returns 00, following the convention sign⁡(0)=0\operatorname{sign}(0)=0.

22.1.6.2 Subgradients and Optimality#

Although a corner has no single tangent line, it has an entire family of lines that touch the graph at the corner without ever rising above it. For a convex function, one whose chords all lie on or above its graph (Section 23.3), these supporting lines step into the role of the tangent. A number gg is called a subgradient of a convex function ff at xx if

f(y)≥f(x)+g (y−x)for all y,(22.1.9)f(y) \ge f(x) + g\,(y - x) \quad \textrm{for all } y, \tag{22.1.9}

meaning that the line through (x,f(x))(x, f(x)) with slope gg lies everywhere on or below the graph of ff. The set of all subgradients at xx is the subdifferential ∂f(x)\partial f(x) (Rockafellar, 1970). At any point where ff is differentiable, ∂f(x)\partial f(x) contains only the single number f′(x)f'(x). At a corner, it expands into the closed interval between the one-sided derivatives, corresponding to the fan of supporting lines in Figure 22.1.10:

∂∣x∣(0)=[−1,1],∂ ReLU(0)=[0,1].\partial |x|(0) = [-1, 1], \qquad \partial\, \mathrm{ReLU}(0) = [0, 1].

Every value returned by autograd above lies inside the corresponding interval.

Figure 22.1.10:

Two corners and their subdifferentials: the fan of supporting lines through the origin of ∣x∣|x| (left) and of ReLU\mathrm{ReLU} (right), with slopes running over ∂∣x∣(0)\partial|x|(0) and ∂ ReLU(0)\partial\,\mathrm{ReLU}(0) respectively. Off each corner there is a single tangent and the subdifferential collapses to the ordinary derivative.

Our running function shows intuitively where this interval comes from. The sharpened softplus softplusβ(x)=1βs(βx)\mathrm{softplus}_\beta(x)=\tfrac1\beta s(\beta x) converges to ReLU(x)\mathrm{ReLU}(x) as β→∞\beta\to\infty, and its derivative is σ(βx)\sigma(\beta x) (Figure 22.1.11). At x=±0.1x=\pm0.1, the slopes are 0.400.40 and 0.600.60 when β=4\beta=4, and sharpen to 0.170.17 and 0.830.83 when β=16\beta=16. The subdifferential [0,1][0,1] is precisely the set of slopes that these smooth approximations approach as β→∞\beta\to\infty and x→0x\to0 together.

Figure 22.1.11:

Smoothing the corner. Left: softplusβ(x)=1βlog⁡(1+eβx)\mathrm{softplus}_\beta(x)=\frac1\beta\log(1+e^{\beta x}) approaches ReLU\mathrm{ReLU} as β\beta grows. Right: its slope σ(βx)\sigma(\beta x) steepens into the step from 00 to 11; near x=0x=0 the slopes of the smooth neighbors fill the interval [0,1][0,1], the subdifferential of ReLU\mathrm{ReLU} at the corner.

Subgradients also yield a clean optimality test. Setting g=0g=0 in (22.1.9) gives f(y)≥f(x)f(y)\ge f(x) for all yy, so a point xx is a global minimizer of a convex function ff if and only if

0∈∂f(x).(22.1.10)0 \in \partial f(x). \tag{22.1.10}

Both directions of the equivalence are immediate from that one line. For ∣x∣|x|, the membership 0∈[−1,1]0 \in [-1,1] certifies the origin as the global minimum even though no derivative exists there. Without convexity, by contrast, f′(x)=0f'(x)=0 is only necessary (Fermat's lemma): x3x^3 satisfies f′(0)=0f'(0)=0 yet has no minimum at all.

We extend subgradients to many variables in Section 23.3, but one caution belongs right here: unlike a true gradient step, a subgradient step is not guaranteed to descend. Right at the minimum of ∣x∣|x|, the number g=12g = \tfrac12 is a valid subgradient, yet stepping to x=−η/2x=-\eta/2 actually increases ∣x∣|x|. Subgradient methods therefore converge by gradually shrinking their step sizes rather than by guaranteeing progress on every step (Nesterov, 2018).

22.1.6.3 Kinks in a Network#

Each kink in a neural network originates in a simple convex building block such as ∣x∣|x|, ReLU\mathrm{ReLU}, or the hinge loss. At the kink, autograd picks one fixed element from that block's subdifferential (for example, ReLU′(0)=0\mathrm{ReLU}'(0)=0) and propagates it through the surrounding composition using the chain rule. Unfortunately, chaining valid subgradients of individual pieces can produce a number that is not a subgradient of the composite function at all. The simplest counterexample is the identity function written in a roundabout way:

φ(x)=ReLU(x)−ReLU(−x)=xfor all x.\varphi(x) = \mathrm{ReLU}(x) - \mathrm{ReLU}(-x) = x \quad \textrm{for all } x.

Because φ(x)=x\varphi(x)=x everywhere, its only true slope at 00 is 11. Yet applying the chain rule mechanically gives φ′(x)=ReLU′(x)+ReLU′(−x)\varphi'(x) = \mathrm{ReLU}'(x) + \mathrm{ReLU}'(-x), which equals 11 everywhere except at x=0x=0, where the convention ReLU′(0)=0\mathrm{ReLU}'(0)=0 yields 0+0=00 + 0 = 0. Let us verify that automatic differentiation indeed does this.

# phi(x) = relu(x) - relu(-x) is the identity, so the true slope at 0 is 1
x = torch.tensor(0.0, requires_grad=True)
phi = torch.relu(x) - torch.relu(-x)
phi.backward()
print(f"autograd: phi'(0) = {x.grad.item():.1f}  (true slope: 1.0)")
autograd: phi'(0) = 0.0  (true slope: 1.0)

As predicted, autograd reports slope 00 for the identity function.

Triggering such an error requires a pre-activation to land on 00 exactly. In exact real arithmetic, when data and initial weights are drawn from continuous distributions, this occurs with probability zero at any fixed step. In finite floating-point arithmetic, however, exact zeros do occur. Bertoin et al. (2021) measured how often on a small fully connected network. We quote the figures of the authors' 2023 erratum (the revised arXiv version of the paper), which repairs a bug in the published experiments and reverses some of their conclusions. Backpropagation with ReLU′(0)=0\mathrm{ReLU}'(0)=0 and with ReLU′(0)=1\mathrm{ReLU}'(0)=1 produced different gradients on at least one minibatch for every initialization in 16-bit precision, for a little under half of all initializations in 32-bit precision, and for none in 64-bit precision.

Whether those discrepancies affect training is a separate question, and the answer is reassuring: practically not at all. In 32-bit arithmetic, only a few minibatches in a million are affected, and even on those the two gradients differ by a relative amount of only about 10−310^{-3}. In the corrected experiments, any choice of ReLU′(0)\mathrm{ReLU}'(0) in [0,1][0,1] yields virtually identical training loss and test accuracy; training degrades only for extreme choices such as ReLU′(0)=104\mathrm{ReLU}'(0)=10^4, and batch normalization and Adam tame even those. The convention is therefore a real source of minor numerical differences between runs, yet a harmless one. Exercise 5 examines this behavior on a small scale.

Everything in this section concerned a single scalar weight. A neural network has millions of weights moving together: which joint direction lowers the loss, and what curvature means in many dimensions, are the subjects of Section 22.2.

22.1.7 Summary#

The derivative f′(x)f'(x) is the slope of the linear approximation f(x+ϵ)=f(x)+ϵf′(x)+o(ϵ)f(x+\epsilon)=f(x)+\epsilon f'(x)+o(\epsilon). Proved from this approximation, the sum, product, and chain rules let us differentiate any composition built from a short table of elementary functions, such as s′=σs'=\sigma for the softplus. To go from slopes at single points to guarantees over intervals, we rely on the Mean Value Theorem and its higher-order extension, the Lagrange remainder, which bounds the error of the degree-nn Taylor polynomial by a multiple of ∣x−x0∣n+1|x-x_0|^{n+1} whenever f(n+1)f^{(n+1)} is bounded.

Applied at order n=1n=1, the Lagrange remainder gives the descent lemma: if ∣f′′∣≤L|f''|\le L on the step interval and f′(x)≠0f'(x)\neq0, every gradient step with 0<η<2/L0\lt \eta\lt 2/L strictly lowers ff. Replacing the global bound LL with the local curvature f′′(xt)f''(x_t) gives Newton's step −f′/f′′-f'/f'', which squares the error near a minimizer with f′′>0f''>0 but can diverge far from it, even on a strictly convex function. Finally, at nondifferentiable corners of a convex function, the subdifferential ∂f(x)\partial f(x) replaces the derivative and 0∈∂f(x)0\in\partial f(x) characterizes global minima; autograd selects one element per kink, and although chaining those choices can fail to produce a true subgradient in floating point, the effect on training is negligible.

22.1.8 Exercises#

  1. Smoothness of the logistic loss. The descent lemma (22.1.6) requires a bound LL on the curvature.
    1. Use the Mean Value Theorem (22.1.3) to show that if ∣f′′∣≤L|f''| \le L on an interval, then f′f' is LL-Lipschitz there. Conversely, show from the definition (22.1.1) that a twice differentiable ff with an LL-Lipschitz f′f' satisfies ∣f′′∣≤L|f''| \le L.
    2. Logistic regression with one weight ww, inputs ai∈Ra_i \in \mathbb{R}, and labels yi∈{−1,1}y_i \in \{-1, 1\} minimizes
ℓ(w)=1n∑i=1nlog⁡(1+e−yiaiw).(22.1.11)\ell(w) = \frac{1}{n}\sum_{i=1}^{n} \log\bigl(1 + e^{-y_i a_i w}\bigr). \tag{22.1.11}

Express ℓ′′\ell'' in terms of σ\sigma. Find the smallest LL for which ℓ′\ell' is LL-Lipschitz on all of R\mathbb{R}, and the step sizes for which (22.1.6) guarantees a decrease from every starting point.

  1. Prove the descent lemma when ff is only differentiable and f′f' is LL-Lipschitz on the interval of the step. For u=−ηf′(x)u=-\eta f'(x) let ψ(t)=f(x+tu)−f(x)−tf′(x)u−L2t2u2\psi(t)=f(x+tu)-f(x)-tf'(x)u-\tfrac L2t^2u^2. Show that ψ(0)=0\psi(0)=0 and ψ′(t)=u (f′(x+tu)−f′(x))−Ltu2≤0\psi'(t)=u\,\bigl(f'(x+tu)-f'(x)\bigr)-Ltu^2\le0 for t∈[0,1]t\in[0,1], and conclude ψ(1)≤0\psi(1)\le0 from the Mean Value Theorem. This is the form of the lemma that optimization uses for functions of many variables.
  1. Entropy extremes. The binary entropy of a coin that shows heads with probability pp is
H(p)=−plog⁡p−(1−p)log⁡(1−p),0<p<1.(22.1.12)H(p) = -p\log p - (1-p)\log(1-p), \qquad 0 \lt p \lt 1. \tag{22.1.12}
  1. Find the minimum of f(x)=xlog⁡xf(x) = x\log x on x≥0x \ge 0, where f(0)=0f(0) = 0 is the limiting value. Why does the minimum not lie at the boundary x=0x = 0?

  2. Show that H′(p)=−log⁡p1−pH'(p) = -\log\frac{p}{1-p}, the negative logit of pp. Locate the stationary point of HH and classify it with the second-derivative test.

  3. Find the limit of H′(p)H'(p) as p→0p \to 0. Then parameterize the coin by its logit zz, so that p=σ(z)p = \sigma(z), and compute ddzH(σ(z))\frac{d}{dz}H(\sigma(z)). In which of the two parameterizations is the slope of HH Lipschitz on the whole domain, so that (22.1.6) certifies one step size of gradient descent on −H-H for every starting point?

  4. Newton at degenerate minima. For p>1p > 1, the function fp(x)=∣x∣p/pf_p(x) = |x|^p/p is convex with its unique minimum at x=0x = 0.

    1. Show that fpf_p is differentiable everywhere, including at 00, with fp′(x)=sign⁡(x) ∣x∣p−1f_p'(x) = \operatorname{sign}(x)\,|x|^{p-1}, and compute fp′′(x)f_p''(x) for x≠0x \neq 0. For which pp does fp′′(0)f_p''(0) exist, and what is its value?
    2. Show that Newton's method (22.1.7) maps every xt≠0x_t \neq 0 to xt+1=p−2p−1 xtx_{t+1} = \frac{p-2}{p-1}\,x_t. For which pp does the iteration converge? How fast does it converge for p=4p = 4?
    3. Which hypothesis of the local convergence statement in Section 22.1.5.5 fails for p=4/3p = 4/3, and which fails for p=4p = 4?
    4. For p=4/3p = 4/3, the damped update xt+1=xt−αfp′(xt)/fp′′(xt)x_{t+1} = x_t - \alpha f_p'(x_t)/f_p''(x_t) shortens the Newton step by a factor α>0\alpha > 0. For which α\alpha does it converge from every x0x_0, and at what rate?

    Adapted from MIT 18.01SC, Session 33 problems, "Cube Root of x".

  5. [code] Minimizers at kinks. A support vector machine with one weight xx, weight decay λ>0\lambda > 0, and a single training example whose label times input equals 11 minimizes

F(x)=max⁡(0,1−x)+λ2x2.(22.1.13)F(x) = \max(0, 1 - x) + \frac{\lambda}{2}x^2. \tag{22.1.13}
  1. Compute the subdifferential of the hinge loss max⁡(0,1−x)\max(0, 1-x) at every xx from (22.1.9).
  2. Take as given that adding a differentiable convex function qq to a convex function hh adds q′q' to every subgradient, ∂(q+h)(x)=q′(x)+∂h(x)\partial(q + h)(x) = q'(x) + \partial h(x). Use the optimality condition (22.1.10) to find the minimizer of FF for every λ>0\lambda > 0. For which λ\lambda does it sit at the kink?
  3. Take λ=1/2\lambda = 1/2 and run the subgradient method xt+1=xt−ηtgtx_{t+1} = x_t - \eta_t g_t from x0=0x_0 = 0 for 10410^4 steps, where gtg_t is the value that autograd returns for F′(xt)F'(x_t) when the hinge is written as ReLU(1−x)\mathrm{ReLU}(1-x). Compare the constant steps ηt=0.1\eta_t = 0.1 and ηt=0.01\eta_t = 0.01 with the decaying steps ηt=0.5/t+1\eta_t = 0.5/\sqrt{t+1}. How does the final distance to the minimizer depend on the schedule?
  4. The kink {x=1}\{x = 1\} is a single point, which a draw from a density hits with probability zero. What do (b) and (c) imply for the argument in Section 22.1.6.3 that training rarely meets a kink?
  5. [code] Chained subgradients. Autograd returns ReLU′(0)=0\mathrm{ReLU}'(0) = 0 and chains this value through every expression, as in Section 22.1.6.3.
    1. Let f1f_1 and f2f_2 be convex, g1∈∂f1(x)g_1 \in \partial f_1(x), g2∈∂f2(x)g_2 \in \partial f_2(x), and c1,c2≥0c_1, c_2 \ge 0. Show from (22.1.9) that c1g1+c2g2∈∂(c1f1+c2f2)(x)c_1 g_1 + c_2 g_2 \in \partial (c_1 f_1 + c_2 f_2)(x). Why does this argument not cover ReLU(x)−ReLU(−x)\mathrm{ReLU}(x) - \mathrm{ReLU}(-x)?
    2. Show that for every real cc,
kc(x)=ReLU(x)+ReLU(−x)+c (x−ReLU(x)+ReLU(−x))=∣x∣.(22.1.14)k_c(x) = \mathrm{ReLU}(x) + \mathrm{ReLU}(-x) + c\,\bigl(x - \mathrm{ReLU}(x) + \mathrm{ReLU}(-x)\bigr) = |x|. \tag{22.1.14}

Predict the value that autograd returns for kc′(0)k_c'(0), and check the prediction for c=0c = 0, 11, and 55. For which cc is the returned value a subgradient of ∣x∣|x| at 00?

  1. Run gradient descent with the derivative from autograd on φ(x)=ReLU(x)−ReLU(−x)\varphi(x) = \mathrm{ReLU}(x) - \mathrm{ReLU}(-x) for 1010 steps from x0=0.5x_0 = 0.5, once with η=0.125\eta = 0.125 and once with η=0.1\eta = 0.1. What happens in each run? Why do the two step sizes behave differently? What does the difference imply for the probability-zero argument of Section 22.1.6.3 in floating-point arithmetic?
  1. Quartic descent. ● The minimum of f(x)=x4/4f(x) = x^4/4 is flat, since f′′(0)=0f''(0) = 0. Gradient descent (22.1.4) on ff reads xt+1=xt−ηxt3x_{t+1} = x_t - \eta x_t^3.

    1. Using problem 1a, find the smallest LL for which f′f' is LL-Lipschitz on [−R,R][-R, R]. Which starting points x0x_0 does the descent lemma (22.1.6) cover for a given η\eta? Why does no fixed η\eta cover all of them?
    2. Show that the iterates converge to 00 if ηx02<2\eta x_0^2 \lt 2 and diverge if ηx02>2\eta x_0^2 > 2. What happens at ηx02=2\eta x_0^2 = 2? Compare this threshold with the starting points covered in (a).
    3. Show that 1/xt+12=1/xt2+2η+O(xt2)1/x_{t+1}^2 = 1/x_t^2 + 2\eta + O(x_t^2), and conclude that xt2≈1/(x0−2+2ηt)x_t^2 \approx 1/(x_0^{-2} + 2\eta t). Check the prediction for η=0.1\eta = 0.1 and x0=1x_0 = 1 at t=10t = 10, 100100, and 10001000. How does this rate compare with gradient descent on x2x^2, and with Newton's method on x4/4x^4/4 in problem 3b?
  2. [code] Central differences. ● The forward difference D+f(x)=f(x+ϵ)−f(x)ϵD_+f(x)=\frac{f(x+\epsilon)-f(x)}{\epsilon} and the central difference D0f(x)=f(x+ϵ)−f(x−ϵ)2ϵD_0f(x)=\frac{f(x+\epsilon)-f(x-\epsilon)}{2\epsilon} both approximate f′(x)f'(x).

    1. Use the Lagrange remainder (22.1.5) to show D+f(x)−f′(x)=12f′′(ξ) ϵD_+f(x)-f'(x)=\tfrac12f''(\xi)\,\epsilon and D0f(x)−f′(x)=16f′′′(ξ′) ϵ2D_0f(x)-f'(x)=\tfrac16f'''(\xi')\,\epsilon^2 for some ξ\xi, ξ′\xi' near xx, where ff is three times continuously differentiable (the continuity of f′′′f''' merges two remainder points into one). Expand f(x±ϵ)f(x\pm\epsilon) to the needed order and subtract.
    2. For f(x)=x2+1701(x−4)3f(x)=x^2+1701(x-4)^3 at x=4x=4, show that the two errors are ϵ+1701ϵ2\epsilon+1701\epsilon^2 and 1701ϵ21701\epsilon^2. At ϵ=0.1\epsilon=0.1 they are 17.1117.11 and 17.0117.01, nearly equal. The central difference raises the order of the error, which helps only once ϵ\epsilon is small. At which ϵ\epsilon is the central error a hundred times smaller than the forward one?

    In floating point, rounding puts a floor under ϵ\epsilon. The gradient-check exercise of Section 22.3 balances it against the truncation error of (a).

  3. [code] Gradient descent past 2/L2/L. ●● On f(x)=x2f(x) = x^2, every step size η>2/L\eta > 2/L diverges. On other functions, gradient descent past this threshold can settle into an oscillation instead (Chen and Bruna, 2023), a one-dimensional version of the edge of stability (Cohen et al., 2021). Let x⋆x^\star be a local minimizer of a four times continuously differentiable ff with f′′(x⋆)>0f''(x^\star) > 0, and write T(x)=x−ηf′(x)T(x) = x - \eta f'(x) for one step of (22.1.4).

    1. Use (22.1.3) to show that iterates that start close enough to x⋆x^\star converge to it if η<2/f′′(x⋆)\eta \lt 2/f''(x^\star). Show that if η>2/f′′(x⋆)\eta > 2/f''(x^\star), every iterate in some neighborhood of x⋆x^\star, other than x⋆x^\star itself, is followed by one farther from x⋆x^\star.
    2. A period-2 orbit is a pair a≠ba \neq b with T(a)=bT(a) = b and T(b)=aT(b) = a. Show that for every period-2 orbit there is a point ξ\xi strictly between aa and bb with f′′(ξ)=2/ηf''(\xi) = 2/\eta.
    3. Let η=(1+δ) 2/f′′(x⋆)\eta = (1 + \delta)\,2/f''(x^\star) with a small δ>0\delta > 0. Expand T(T(x))T(T(x)) around x⋆x^\star to third order, and show that a period-2 orbit near x⋆x^\star exists and attracts nearby iterates if
3f′′′(x⋆)2−f′′(x⋆) f′′′′(x⋆)>0.(22.1.15)3 f'''(x^\star)^2 - f''(x^\star)\, f''''(x^\star) > 0. \tag{22.1.15}

Derive the half-width ∣a−b∣/2|a - b|/2 of the orbit to leading order in δ\delta.

  1. Run gradient descent on the double well f(x)=14(x2−1)2f(x) = \tfrac14 (x^2 - 1)^2 from x0=0.5x_0 = 0.5 for 50005000 steps for each step size η∈[0.9,1.5]\eta \in [0.9, 1.5], and plot the last 100100 iterates against η\eta. Compare the half-width of the orbit near η=1\eta = 1 with (c). Compare the range of η\eta with a stable period-2 orbit with the range 1<η<4.5−11 \lt \eta \lt \sqrt{4.5} - 1 in which Chen and Bruna (2023) prove convergence to the orbit from almost every 0<x0<10 \lt x_0 \lt 1.
  2. Predict from (c) what gradient descent with η=2.02\eta = 2.02 does on log⁡cosh⁡x\log\cosh x and on x2/2+x4/4x^2/2 + x^4/4, both of which have x⋆=0x^\star = 0 and f′′(x⋆)=1f''(x^\star) = 1. Confirm the predictions by running both from x0=0.01x_0 = 0.01 for 500500 steps.

Discussions