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 , and the logistic loss . At , the loss is and its slope is . If we move the weight to , a straight line through with that slope predicts a loss of . The actual loss is , so the linear prediction is off by only . Remarkably, that small gap has a simple structure: to the digits shown, it equals , where the factor measures how sharply the graph of bends at . 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 , 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 fixed except 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, . It is the one-variable slice of the log-sum-exp function used across this chapter, and the logistic loss above is simply .
22.1.1 The Derivative#
22.1.1.1 The Difference Quotient#
Zoom in far enough on the graph of a smooth function near a point , and the curve becomes indistinguishable from a straight line (Figure 22.1.1). The slope of that line is the derivative.
The curve near , shown in windows of half-width , , and . 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 and . Its slope is the difference quotient . As shrinks toward zero, the secant rotates toward the tangent line (Figure 22.1.2).
The difference quotient is the slope of the secant through and . As , this slope approaches the tangent slope .
How small must 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 , whose true slope at is , and observe how slowly the secant slope settles as 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 , the secant slope is , more than three times the true limit, and the printed values only settle near once reaches . Expanding shows why: the difference quotient equals , so the cubic term adds at but only at . The large coefficient delays the approach to the limit without changing it. Automatic differentiation sidesteps this problem altogether: it never chooses an , instead applying the rules of differentiation directly (Section 22.5).
22.1.1.2 The Derivative and the Linear Approximation#
The derivative of at is the limit of the secant slopes,
whenever this limit exists, in which case we say is differentiable at . For the cubic above, . We write or , and when differentiating a bulky expression. The limit can also fail to exist, as it does for at ; we return to such corners in Section 22.1.6.
It is instructive to rearrange this definition. Let denote the error of the straight-line prediction; the limit (22.1.1) says that . Writing for any quantity satisfying as , we obtain the linear approximation
In plain words, a small step changes the output by , up to an error that vanishes faster than . The converse holds too: if for some constant , then dividing by and letting proves that is differentiable at with . 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 , the line is the tangent to the graph at , the limit of the rotating secants. This is the line that predicted the logistic loss at , and the gap of was its remainder. By itself, promises very little: an error of order could shrink only slightly faster than . Here, however, the gap shrank as , 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 at , 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 when and for integer wherever is defined, and the logarithm for .
- Derivative of constants. .
- Derivative of linear functions. .
- Power rule. .
- Derivative of exponentials. .
- Derivative of the logarithm. .
- Derivative of sine. .
- Derivative of cosine. .
The exponential entry rests on a one-line observation that also reveals what makes the base special. For any , the difference quotient of factors cleanly as
where the second factor is simply the difference quotient at . Thus, if is differentiable at with slope , then for every : the slope of an exponential is always proportional to its height, with a single proportionality constant per base. Numerically, at we find for base and for base . The number is defined as the unique base whose constant is , which immediately yields . Once we have the derivative of the logarithm, the chain rule will identify 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 and be differentiable at (for the chain rule, assume is differentiable at and is differentiable at ). Then:
- Sum rule. .
- Product rule. .
- Quotient rule. , where .
- Chain rule. .
The sum and product rules are routine; only the chain rule requires real care, because the naive argument divides by , which can vanish even when . The proofs all rely on one basic fact: a function differentiable at is continuous at , because tends to as .
Sum rule. Adding the linear approximations for and gives
since the sum of two quantities that vanish faster than also vanishes faster than . By the converse of the linear approximation, the coefficient of is the derivative: first-order changes simply add.
Product rule. Adding and subtracting in the numerator splits the difference quotient of the product into two quotients we already know:
As , continuity gives , so the right-hand side converges to .
Chain rule. Rather than dividing by , we feed the change of the inner function directly into the linear approximation of the outer function. Because is differentiable at , the error ratio for , extended by , tends to as . For every , including , we can therefore write
Now set . By continuity of , as , so as well. Substituting this yields
because every term other than contains a factor that vanishes faster than . Applying the converse of the linear approximation finishes the proof.
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 .
22.1.2.3 Inverse Functions#
The chain rule also differentiates a function that undoes another. A function satisfying for all near a point is an inverse of there. Suppose such a exists and is differentiable at ; by the inverse function theorem (Rudin, 1976), which we use without proof, both hold whenever is continuous and nonzero near . Differentiating both sides of with the chain rule gives
In other words, the slope of the inverse is the reciprocal of the slope of , evaluated at the matching point. Geometrically, the graph of is the graph of reflected across the diagonal, and reflecting a line across the diagonal turns rise over run upside down.
Since the logarithm undoes , this rule gives , the fifth entry in our table. Notice that the condition is strictly necessary. For we have , so the formula breaks down at ; indeed, its inverse is not differentiable at , because the difference quotient 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 gives , identifying the constant ; indeed, and are the constants we measured numerically above. Similarly, writing for yields for every real .
22.1.2.4 The Softplus, the Sigmoid, and the Logit#
We can now apply these rules to our running function, . Using the chain rule with outer function and inner function gives
so the derivative of the softplus is the sigmoid . Applying the chain rule a second time to , with outer function and inner function of slope , yields
since . Because a product is maximized at , the sigmoid is steepest at the origin, where and . The inverse of is the logit function , and the inverse-function rule immediately gives . At , this equals , matching the reciprocal of the sigmoid's slope.
We can now verify the two constants from the opening logistic-loss example. Since , the chain rule gives , so . Differentiating once more gives and thus , the curvature at the origin. Let us check numerically whether the gap between and its linear approximation indeed shrinks like with leading constant .
# 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 by a factor of ten, and settles to . 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 rather than : the gap is not quite , 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 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 attains a local maximum or a local minimum at an interior point of an interval and is differentiable at , then .
Proof. At a local maximum, for all sufficiently small of either sign. The difference quotient is therefore for and for . Because is differentiable at , both one-sided limits must equal , and the only number that is simultaneously and is zero. A local minimum follows by the same argument with inequalities reversed.
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 is parallel to the tangent line at some interior point.
Over the interval from to , the secant chord through the endpoints has slope equal to the average rate of change; the Mean Value Theorem guarantees that some interior point has a tangent of that same slope, parallel to the chord.
On a simple example like over , the chord has slope , and the tangent slope matches it at the midpoint . Notice, however, that the theorem truly requires differentiability at every interior point. The absolute value on satisfies , so its chord is horizontal, yet no interior point has slope : the slope is on the left, on the right, and undefined at .
Proposition (Mean Value Theorem). If is continuous on and differentiable on , then there exists a point such that
Proof. Consider first the flat case , 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 is constant and everywhere inside. Otherwise, at least one extremum occurs at an interior point , where by Fermat's lemma.
For the general case, we subtract the chord to flatten the endpoints. Define the tilted function . Since , Rolle's theorem provides an interior point with , which rearranges directly to (22.1.3).
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:
- If on an interval, then is strictly increasing there. For any in the interval, (22.1.3) gives for some between them. By the same token, implies is strictly decreasing, and implies is constant.
- If on and on for some , and is continuous at , then is a strict local minimum. Applying the first consequence on each side shows that falls into from the left and rises out of it to the right.
Returning to our running function, everywhere, so the softplus is strictly increasing on all of .
22.1.4 Gradient Descent in One Variable#
22.1.4.1 The Gradient-Descent Step#
The linear approximation predicts how responds to any small step : . To decrease , we should choose with the sign opposite to the slope. Setting for a positive step size , the linear model predicts the change
which is strictly negative whenever . 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).
One gradient-descent step on a 1-D bowl. At the tangent line has slope ; the step moves opposite the slope and lands at , lower on the curve, with the drop equal to to first order.
Iterating this update gives one-dimensional gradient descent:
Each step moves against the local slope, and the iteration comes to rest at a stationary point, where . In a neural network, every coordinate of the weight update takes this form, with all coordinates updated simultaneously. On our logistic loss starting at , the slope is , so a step of size moves the weight by and predicts a loss drop of .
Notice a glaring limitation of the linear model: its predicted change is negative for every , 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, , already reveals where the linear prediction breaks down.
22.1.4.2 The Quadratic Case#
For , the slope is , so the gradient-descent update simplifies to
Every step multiplies the current iterate by the same factor , giving the closed form . The iterates therefore converge to the minimum if and only if , which is . Within this convergent range, a small creeps monotonically toward , lands on the minimum in a single step, and overshoots and oscillates inward. Right at the boundary , the iterates bounce forever between and , and for they blow up.
Let us run ten steps from 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 : the cautious step has only crawled down to , has zig-zagged down to , is right back at , and has already diverged to . Notice that the stability threshold equals , because for . As we will see in Section 22.1.5.4, this is no coincidence: any bound on the curvature gives the safe step-size threshold 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 is itself a function of , we can differentiate it again. The result is the second derivative, , which measures the rate of change of the slope. Repeating this process times yields the -th derivative,
Geometrically, means the slope is increasing, so the graph curves upward like a bowl; 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 and suppose exists. If , then is a strict local minimum; if , it is a strict local maximum.
Proof. Because , the definition of simplifies to . If this limit is positive, then the quotient must be positive for all sufficiently small . Hence shares the sign of : negative just to the left of and positive just to the right. By the second consequence of the Mean Value Theorem, is a strict local minimum. The case follows identically with all signs reversed.
Notice where the real work happened in that proof: turning a local sign pattern of into a minimum over an interval requires the Mean Value Theorem. Note also that the test certifies only a neighborhood of , 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.
The second-derivative test. Rows: (a bowl, minimum), (a dome, maximum), and , where , , and share yet have an inflection point, a minimum, and a maximum at . Columns: , , .
When at a stationary point, the test is silent (Figure 22.1.5, bottom row): , , and all satisfy , yet 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 at a base point . To capture the bend as well, we can fit a parabola. A general quadratic has derivatives
so its curvature is the constant . Matching the curvature of at fixes , and matching the value and slope fixes and . For , where and , the best-fitting parabola at is
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 so the parabola has nonzero curvature).
The sine curve with its two local models at : 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 , the values , , and produce the best parabola . Its quadratic coefficient is the exact constant to which converged for the logistic loss .
The same idea extends to any degree . The degree- Taylor polynomial of at is
which is the unique polynomial of degree at most whose value and first derivatives agree with those of at . The factorials appear because differentiating exactly times at produces , while every other term vanishes. In this notation, is the tangent line and is the best parabola. For at , where every derivative equals , we obtain , 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 , 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 , 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 case.
Proposition (Lagrange remainder). If is -times differentiable on an open interval containing and , with , then
for some strictly between and . Note that the case recovers the Mean Value Theorem, .
Proof. The one clever step is choosing the right auxiliary function; everything after that is straightforward differentiation. Fix and treat the base point as the variable: for between and , define
which is the error at of the Taylor polynomial centered at , minus a term of the form we expect that error to take. Choose the constant so that . The proof now finishes in three steps.
First, vanishes at both endpoints. Our choice of ensures , while because every positive power of vanishes at and the term leaves . Rolle's theorem therefore guarantees a point strictly between and where .
Second, differentiate with respect to . By the product rule, each summand with contributes
to , while the term contributes . Adjacent terms cancel in pairs (the sum telescopes), leaving only the highest-order derivative and the derivative of the term:
Third, evaluate at . Because lies strictly between and , we have , so forces . Plugging this back into yields (22.1.5).
The remainder looks just like the next term of the Taylor polynomial, except that the -st derivative is evaluated at an unknown interior point rather than at . Whenever stays bounded near , the error therefore scales as : each additional matched derivative raises the order of accuracy by one.
Let us test this on our running function. For the softplus, vanishes at and , giving the fourth-degree polynomial
At , this evaluates to against the true value , an error of only . In fact, the error is even smaller than an estimate would suggest, because 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 instead of at : we were seeing .
We can check the scaling directly in code. If the worst-case error of on the window behaves like , then halving should divide the maximum error by : by for the tangent line, for the parabola, and for the cubic. Let us verify this prediction on at .
# 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 , , and , and on the log–log plot the three error curves appear as straight lines with slopes , , and , matching . The ratios slightly exceed the theoretical values on the wider windows because the factor in the remainder is larger there.
The Lagrange remainder also answers when the infinite Taylor series reproduces the function itself. For , every derivative equals , so (22.1.5) around gives
For any fixed , the right-hand side vanishes as because factorials eventually outgrow powers. Hence
on all of . Be careful, though: having infinitely many derivatives does not guarantee that a function equals its Taylor series. For (extended by ), every single derivative vanishes at , so its Taylor series at the origin is identically zero and agrees with only at (Figure 22.1.7). Luckily, nothing we do later depends on infinite series: we work exclusively with finite Taylor polynomials , whose error (22.1.5) bounds directly.
The smooth function has every derivative equal to zero at the origin, so its Taylor series there is identically zero. The series converges everywhere yet agrees with only at : 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 ? The Lagrange remainder with answers yes. Among all results in this section, this is the one optimization theory uses most.
Proposition (descent lemma). Let be twice differentiable on an open interval containing and , with on . Then
In particular, strictly decreases whenever and , and the guaranteed decrease is maximized at , where it equals .
Proof. For any step , the Lagrange remainder with gives . Setting turns the right-hand side into . The factor is positive whenever , and the quadratic attains its maximum at .
Geometrically, the lemma replaces the unknown local curvature with its worst-case bound . The resulting quadratic acts as an upper-bounding parabola that touches at and stays above it throughout . The step 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 is -Lipschitz, meaning that slopes at any two points differ by at most times their distance, . That is the form used in multivariable optimization (Section 23.1), and exercise 1 proves it in one variable.
For , is a quadratic upper bound in the step that equals at the base point. The gradient step with minimizes this bound and guarantees a decrease of at least . Here with , and the actual decrease exceeds the worst-case guarantee.
Let us check the lemma on two familiar functions. For , we have , so recovers the exact stability threshold we found from the closed form. For the logistic loss, with equality at , so and every step size is guaranteed to decrease from any starting weight. Starting from with moves to : the bound guarantees a loss at most , and the actual value is . The bound is nearly tight here because the curvature stays close to its maximum over that short step. With the larger step , the bound promises while the actual loss drops all the way to : 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 . If instead we use the actual local curvature at the current iterate, we obtain a step that minimizes any quadratic function in a single leap. The local model at is the second-order Taylor polynomial ,
Whenever , this parabola opens upward and has a unique minimizer. Setting and solving for yields the update of Newton's method:
This is a gradient step with an adaptive local step size , and on any upward-opening parabola it lands on the exact minimizer in one step. Figure 22.1.9 illustrates one step on , whose minimizer is . At , we have , , and , so the parabola's minimizer lies at .
One Newton step on from . The parabola matches the value, slope, and curvature of at ; its minimizer is the next iterate , closer to the minimizer .
Let us see how quickly Newton's method converges on from , and also test what happens on a second function, , starting from and . 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 , the errors plummet through , , , , , and : once close to the minimum, each step squares the previous error and roughly doubles the number of correct digits. By contrast, gradient descent on shrank the error by a constant factor per step, gaining only a fixed number of digits at each iteration.
The Lagrange remainder explains why the error squares. Let be a stationary point and let denote the error at step . Applying (22.1.5) with to around the base point and evaluating at gives . Dividing through by and substituting Newton's update (22.1.7) leaves
for some between and , provided is three times differentiable. For , the prefactor converges to , and the printed errors indeed yield , , , and . 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 , which has and , so it is strictly convex with a unique global minimum at . Starting from , the second loop above prints : Newton's method diverges wildly. Starting slightly closer at , it converges smoothly (, , , , …), with the threshold between convergence and divergence sitting near .
The local parabola explains what went wrong. Far from the origin, the curvature becomes tiny, so the approximating parabola is nearly flat and places its minimizer far past . The standard fix is to scale back the step by a factor chosen to ensure 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 network is full of corners: has no derivative at . 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 at ,
The quotient is constant on either side of , but the two constants disagree. Approaching from the right, the graph rises with slope ; approaching from the left, it falls with slope . These limits are the one-sided derivatives, and , and an ordinary derivative exists only when the two match. The same calculation for at gives on the flat left side and 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 , autograd returns , the left-hand slope. For at , it returns a fixed value chosen by convention.
Here it returns , following the convention .
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 is called a subgradient of a convex function at if
meaning that the line through with slope lies everywhere on or below the graph of . The set of all subgradients at is the subdifferential (Rockafellar, 1970). At any point where is differentiable, contains only the single number . 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:
Every value returned by autograd above lies inside the corresponding interval.
Two corners and their subdifferentials: the fan of supporting lines through the origin of (left) and of (right), with slopes running over and 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 converges to as , and its derivative is (Figure 22.1.11). At , the slopes are and when , and sharpen to and when . The subdifferential is precisely the set of slopes that these smooth approximations approach as and together.
Smoothing the corner. Left: approaches as grows. Right: its slope steepens into the step from to ; near the slopes of the smooth neighbors fill the interval , the subdifferential of at the corner.
Subgradients also yield a clean optimality test. Setting in (22.1.9) gives for all , so a point is a global minimizer of a convex function if and only if
Both directions of the equivalence are immediate from that one line. For , the membership certifies the origin as the global minimum even though no derivative exists there. Without convexity, by contrast, is only necessary (Fermat's lemma): satisfies 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 , the number is a valid subgradient, yet stepping to actually increases . 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 , , or the hinge loss. At the kink, autograd picks one fixed element from that block's subdifferential (for example, ) 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:
Because everywhere, its only true slope at is . Yet applying the chain rule mechanically gives , which equals everywhere except at , where the convention yields . 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 for the identity function.
Triggering such an error requires a pre-activation to land on 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 and with 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 . In the corrected experiments, any choice of in yields virtually identical training loss and test accuracy; training degrades only for extreme choices such as , 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 is the slope of the linear approximation . 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 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- Taylor polynomial by a multiple of whenever is bounded.
Applied at order , the Lagrange remainder gives the descent lemma: if on the step interval and , every gradient step with strictly lowers . Replacing the global bound with the local curvature gives Newton's step , which squares the error near a minimizer with but can diverge far from it, even on a strictly convex function. Finally, at nondifferentiable corners of a convex function, the subdifferential replaces the derivative and 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#
- Smoothness of the logistic loss. The descent lemma (22.1.6) requires a bound on the curvature.
Express in terms of . Find the smallest for which is -Lipschitz on all of , and the step sizes for which (22.1.6) guarantees a decrease from every starting point.
- Prove the descent lemma when is only differentiable and is -Lipschitz on the interval of the step. For let . Show that and for , and conclude from the Mean Value Theorem. This is the form of the lemma that optimization uses for functions of many variables.
- Entropy extremes. The binary entropy of a coin that shows heads with probability is
-
Find the minimum of on , where is the limiting value. Why does the minimum not lie at the boundary ?
-
Show that , the negative logit of . Locate the stationary point of and classify it with the second-derivative test.
-
Find the limit of as . Then parameterize the coin by its logit , so that , and compute . In which of the two parameterizations is the slope of Lipschitz on the whole domain, so that (22.1.6) certifies one step size of gradient descent on for every starting point?
-
Newton at degenerate minima. For , the function is convex with its unique minimum at .
- Show that is differentiable everywhere, including at , with , and compute for . For which does exist, and what is its value?
- Show that Newton's method (22.1.7) maps every to . For which does the iteration converge? How fast does it converge for ?
- Which hypothesis of the local convergence statement in Section 22.1.5.5 fails for , and which fails for ?
- For , the damped update shortens the Newton step by a factor . For which does it converge from every , and at what rate?
Adapted from MIT 18.01SC, Session 33 problems, "Cube Root of x".
-
[code] Minimizers at kinks. A support vector machine with one weight , weight decay , and a single training example whose label times input equals minimizes
- Compute the subdifferential of the hinge loss at every from (22.1.9).
- Take as given that adding a differentiable convex function to a convex function adds to every subgradient, . Use the optimality condition (22.1.10) to find the minimizer of for every . For which does it sit at the kink?
- Take and run the subgradient method from for steps, where is the value that autograd returns for when the hinge is written as . Compare the constant steps and with the decaying steps . How does the final distance to the minimizer depend on the schedule?
- The kink 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?
- [code] Chained subgradients. Autograd returns
and chains this value through every expression, as
in Section 22.1.6.3.
- Let and be convex, , , and . Show from (22.1.9) that . Why does this argument not cover ?
- Show that for every real ,
Predict the value that autograd returns for , and check the prediction for , , and . For which is the returned value a subgradient of at ?
- Run gradient descent with the derivative from autograd on for steps from , once with and once with . 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?
-
Quartic descent. ● The minimum of is flat, since . Gradient descent (22.1.4) on reads .
- Using problem 1a, find the smallest for which is -Lipschitz on . Which starting points does the descent lemma (22.1.6) cover for a given ? Why does no fixed cover all of them?
- Show that the iterates converge to if and diverge if . What happens at ? Compare this threshold with the starting points covered in (a).
- Show that , and conclude that . Check the prediction for and at , , and . How does this rate compare with gradient descent on , and with Newton's method on in problem 3b?
-
[code] Central differences. ● The forward difference and the central difference both approximate .
- Use the Lagrange remainder (22.1.5) to show and for some , near , where is three times continuously differentiable (the continuity of merges two remainder points into one). Expand to the needed order and subtract.
- For at , show that the two errors are and . At they are and , nearly equal. The central difference raises the order of the error, which helps only once is small. At which is the central error a hundred times smaller than the forward one?
In floating point, rounding puts a floor under . The gradient-check exercise of Section 22.3 balances it against the truncation error of (a).
-
[code] Gradient descent past . ●● On , every step size 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 be a local minimizer of a four times continuously differentiable with , and write for one step of (22.1.4).
- Use (22.1.3) to show that iterates that start close enough to converge to it if . Show that if , every iterate in some neighborhood of , other than itself, is followed by one farther from .
- A period-2 orbit is a pair with and . Show that for every period-2 orbit there is a point strictly between and with .
- Let with a small . Expand around to third order, and show that a period-2 orbit near exists and attracts nearby iterates if
Derive the half-width of the orbit to leading order in .
- Run gradient descent on the double well from for steps for each step size , and plot the last iterates against . Compare the half-width of the orbit near with (c). Compare the range of with a stable period-2 orbit with the range in which Chen and Bruna (2023) prove convergence to the orbit from almost every .
- Predict from (c) what gradient descent with does on and on , both of which have and . Confirm the predictions by running both from for steps.