1.4 Calculus
In Ancient Greece, Archimedes calculated the area of a circle by inscribing regular polygons with increasing numbers of sides (Figure 1.4.1): as the triangles become thinner, their height approaches and their combined bases approach the circumference , giving area . Approximating curved quantities by simple linear pieces in the limit of small steps lies at the root of both integral calculus and differential calculus.
Regular polygons with 4, 5, 6, and 8 sides inscribed in a circle. As the number of sides grows, the area of the polygon approaches the area of the circle.
In deep learning, differential calculus is the engine of optimization. Training a model means adjusting its parameters to minimize a scalar loss function measuring how poorly the model fits its training examples. With millions or billions of parameters, probing each parameter by trial and error would require millions of forward passes per update. Instead, the derivative gives the instantaneous rate at which the loss changes with respect to each parameter; collecting all partial derivatives into the gradient vector identifies the direction of steepest ascent, and the chain rule assembles gradients across nested layers in a single backward pass.
In this section, we develop derivatives, gradients, and the chain rule on a running linear-regression example small enough that every number can be verified by hand. In Section 1.5, we will see how deep learning frameworks automate these calculations for arbitrary programs.
1.4.1 Derivatives#
1.4.1.1 The Derivative as a Limit#
Suppose a single-parameter model predicts the constant value for every example, and we evaluate it on three training examples with labels , , and . Summing the squared errors gives
At , the loss is :
def loss(w):
return 3 * w ** 2 - 4 * w + 2
To see how responds to a small perturbation , we evaluate the difference quotient as shrinks from to :
for h in 10.0 ** -np.arange(1, 6):
print(f'h = {h:.0e} ratio = {(loss(1 + h) - loss(1)) / h:.5f}')
h = 1e-01 ratio = 2.30000
h = 1e-02 ratio = 2.03000
h = 1e-03 ratio = 2.00300
h = 1e-04 ratio = 2.00030
h = 1e-05 ratio = 2.00003
Expanding shows that as . Formally, for , the derivative of at is the limit
Geometrically, the difference quotient is the slope of the secant line through and ; as , the secant rotates into the tangent line at with slope (Figure 1.4.2).
The difference quotient is the slope of the secant through and . As , slides toward and the secant turns into the tangent at , whose slope is .
Not every function is differentiable everywhere: has a corner at (slope from the left, from the right). Even worse, discrete classification accuracy is flat () almost everywhere and jumps discontinuously where a prediction flips, providing no gradient signal. That is why classifiers are trained by minimizing smooth surrogate losses such as cross-entropy (Figure 1.4.3).
The 0--1 error ( for a wrong prediction, for a correct one) and a smooth surrogate loss, plotted against a score that is positive when the classifier is right. The 0--1 error is flat on either side of its jump, so its slope says nothing. The surrogate slopes downward everywhere and tells the parameters which way to move.
1.4.1.2 Rules of Differentiation#
Given , we write . Common elementary derivatives are
and combinations of differentiable functions obey
Figure 1.4.4 illustrates the product rule geometrically via the area of a rectangle (full proofs appear in Section 22.1). Applying these rules to immediately gives , so .
The product rule as the area of a rectangle. When grows by , the sides and grow by about and , and the area grows by two thin strips and a corner of area , which is negligible for small .
1.4.1.3 First-Order Linear Approximation and Minima#
Multiplying by gives the first-order linear approximation
Because , decreasing lowers the loss. Stepping opposite the derivative via with step size moves from to and drops from to , close to the tangent prediction (the gap is the neglected quadratic curvature ). At any smooth local minimum, the tangent must be horizontal (); setting gives the unique global minimizer , the sample mean of the three labels .
w = np.linspace(0, 2, 101)
d2l.plot(w, [loss(w), 2 * w - 1], 'w', 'L(w)',
legend=['L(w)', 'tangent at w = 1'])1.4.2 Partial Derivatives and Gradients#
1.4.2.1 Partial Derivatives#
Now give our three-example problem scalar inputs , , and paired with labels , , and , and fit an affine line :
For a multivariate function , the partial derivative with respect to perturbs only coordinate while holding all other variables fixed:
At , holding fixed gives , so ; holding fixed gives , with derivative , so (Figure 1.4.5).
The loss of the line model near (black dot). Holding cuts out the orange curve, the loss of the constant model; holding cuts out the green curve. Their tangents at the dot (dashed) have slopes and .
In matrix--vector form (Section 1.3), writing each example as a row of gives
We can check these partial derivatives numerically by defining line_loss(w) and a finite-difference helper numerical_gradient(f, w, h=1e-6) that perturbs one coordinate of w at a time by in float64:
X = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]]) # rows [1, input]
y = np.array([1.0, 1.0, 0.0])
def line_loss(w):
return np.sum((X @ w - y) ** 2)
def numerical_gradient(f, w, h=1e-6):
"""Finite differences of f at w, moving one coordinate at a time."""
grad = np.zeros_like(w)
for i in range(len(w)):
step = np.zeros_like(w)
step[i] = h
grad[i] = (f(w + step) - f(w)) / h
return grad
Evaluating numerical_gradient(line_loss, w) at reproduces our analytical partial derivatives to within the truncation error:
w = np.array([1.0, 0.0])
numerical_gradient(line_loss, w)
array([2.000003, 4.000005])
Note that numerical_gradient requires extra evaluations of for parameters, which becomes prohibitive when .
1.4.2.2 Numerical Precision Limits of Finite Differences#
Finite differences also suffer from floating-point cancellation when is too small. In finite precision (machine epsilon in float64, in float32), subtracting nearly equal numbers cancels leading digits (catastrophic cancellation) and divides the rounding residual by . Thus truncation error () and rounding error () compete:
def quotient_error(f, x, df, h):
"""Error of (f(x + h) - f(x)) / h as an estimate of f'(x) = df."""
return abs((f(x + h) - f(x)) / h - df)
h = np.logspace(-1, -16, 61) # 61 values of h, evenly spaced on a log scale
To compare 64-bit NumPy arithmetic against the 32-bit floating-point format used by default in deep learning, we cast the step grid h to a float32 framework tensor h32:
h32 = torch.tensor(h, dtype=torch.float32)We now evaluate quotient_error(loss, 1, 2, ...) at (where the exact derivative is ) across all step sizes in both float64 (h) and float32 (h32), overlaying the truncation error line and the float32 rounding asymptote :
eps32 = np.finfo(np.float32).eps
d2l.plot(h, [quotient_error(loss, 1, 2, h), quotient_error(loss, 1, 2, h32),
3 * h, eps32 / h], 'h', 'error', xscale='log', yscale='log',
ylim=(1e-10, 1e1), legend=['float64', 'float32', '3h', 'ε/h'],
figsize=(5, 3.5))Balancing puts the optimal step at , losing half the format's digits (best error at in float64, and at in float32). Analytical differentiation via the chain rule avoids both the cost and the precision loss, leaving float64 finite differences for unit-test gradient checking.
1.4.2.3 The Gradient and Steepest Descent#
Concatenating all partial derivatives of forms the gradient vector (matching the shape of ), which generalizes (1.4.3) to simultaneous perturbations :
For a step of length along unit vector (), (1.3.7) gives . Thus points in the direction of steepest ascent (), points in the direction of steepest descent (), and is perpendicular to the level set passing through () (Figure 1.4.6).
Level sets of the loss of the line model. The gradients (red) are perpendicular to the level set through their base points and point uphill. From (black dot), gradient descent with (orange) starts along , which does not point at the minimum, and zigzags toward it.
This motivates gradient descent, : from with learning rate , one step moves to , cutting the loss from to . Why does steepest descent zigzag across the valley in Figure 1.4.6 instead of pointing straight at the global minimum ? Because "steepest" is measured per unit of Euclidean step length , which depends on the units of each coordinate: stretching one feature axis flattens its contours and tilts away from the minimum, which is why standardizing features (Section 1.2) and preconditioning curvature (Chapter 9) matter so much in practice.
1.4.2.4 Matrix Calculus Identities#
Three vector gradient identities (Section 22.4) allow us to differentiate vector expressions without writing out coordinates:
Expanding and applying these rules gives
In words, each component of the gradient is twice the dot product of the corresponding feature column of with the residual vector ; at the optimum , the prediction errors are orthogonal to every feature.
1.4.3 The Chain Rule#
Deep networks compose many nested layers ; differentiating compositions without expanding them relies on the chain rule.
For scalar functions and , rates of change multiply: . More generally, if where each , rates multiply along each path and sum across all parallel paths:
where is the Jacobian matrix of with respect to , with entries . For an affine map , the Jacobian is simply .
A small case is worth working by hand. Let with and , evaluated at . The input reaches along two paths, one through and one through (Figure 1.4.7). Each path contributes the product of its local derivatives, and the two contributions add: .
The chain rule for with and at . Each box shows the value of a variable (black) and the derivative of with respect to it (red), and each red arrow carries a local derivative. Derivatives multiply along a path and add where two paths meet, as they do at .
Decomposing our line loss into two stages, namely (1) inner residuals with Jacobian and (2) outer squared norm with gradient , the multivariate chain rule recovers in two passes:
r = X @ w - y # forward: errors, from which the loss is r @ r
grad_r = 2 * r # backward: gradient of the loss with respect to r
X.T @ grad_r # backward: gradient with respect to w
array([2., 4.])
The forward pass computes and ; the backward pass (backpropagation) multiplies by , computing the exact gradient with respect to all parameters at roughly the cost of one forward evaluation. In Section 1.5, we hand this mechanical backward pass over to the framework's automatic differentiation engine.
1.4.4 Summary#
The derivative gives the slope of the tangent line and the local linear approximation . For , the gradient collects all partial derivatives, satisfies , and points in the direction of steepest ascent (perpendicular to level sets), motivating gradient descent . Unlike finite differences, which cost evaluations and lose precision to catastrophic cancellation (), the multivariate chain rule propagates exact gradients backward from the loss to all parameters in a single backward pass (backpropagation).
1.4.5 Exercises#
-
Differentiating when both base and exponent vary. For , consider the function , in which appears in both the base and the exponent.
- Explain why applying the power rule alone (treating the exponent as constant to get ) and applying the exponential rule alone (treating the base as constant to get ) are both incorrect.
- Rewrite and apply the chain rule and product rule to find . Notice that the true derivative is the sum of the two naive answers from Part 1; explain why this happens using the two-variable chain rule applied to along .
-
Why squared error yields the mean and absolute error yields the median. Suppose a single-parameter model predicts the constant value for training examples with scalar labels .
- Differentiate the sum of squared errors with respect to , set the derivative to zero, and prove that the unique minimizer is the sample mean .
- Now consider the sum of absolute errors . Show that at any point not equal to one of the labels , the derivative equals the number of labels strictly less than minus the number of labels strictly greater than . At which values of does fail to exist? Conclude that is minimized by any sample median of .
- For the four labels , compute the minimizer (mean) and the minimizer (median). What happens to each minimizer if the outlier label is corrupted to ?
-
Gradient of the Euclidean norm. Compute the gradient of the unsquared Euclidean norm for any nonzero vector , and verify that everywhere it exists. What happens to the gradient at the origin , and why?
-
Step-size stability of gradient descent. Consider minimizing the isotropic quadratic bowl via the gradient descent update with learning rate .
- Starting from , compute and the new objective value after a single step for three choices of learning rate: , , and .
- Write in closed form in terms of and . For what range of learning rates does a gradient descent step strictly decrease from any nonzero starting point ? Which special value of jumps directly to the global minimum in a single step, and what happens when ?
- Characterize the stationary points at which a gradient descent step leaves the parameter vector unchanged (), both for and for a general differentiable objective .
-
[code] Central differences versus forward differences. ● The one-sided forward difference analyzed in this section has truncation error . The symmetric central difference
evaluates at and so that the quadratic terms cancel out. Write a central-difference version of quotient_error and evaluate it across our logarithmic grid of values in float64:
-
For the quadratic loss at , plot the forward-difference and central-difference error curves on the same log--log axes. Why does the central-difference error drop straight to machine epsilon () even at large on a quadratic function?
-
Now repeat the comparison on a non-quadratic function, at (where ). Compare the slope of the large- truncation branch of the central-difference curve against the slope- forward-difference branch, identify the optimal step size and minimum achievable error for each method, and explain both using the Taylor expansion .
-
[code] Gradient checking in
float64versusfloat32. ● Although finite differences are far too slow for training, central finite differences are the gold standard for unit-testing hand-derived or custom-kernel gradients.- Write a function
central_gradient(f, x, h=1e-5)that estimates for via central differences. Use it infloat64to test the quadratic-form gradient identity on a random non-symmetric matrix at a random vector , and report the maximum relative error across the five coordinates. - Now run the same check against the buggy formula (a common mistake made when forgetting that is not symmetric). How large is the relative error now?
- Finally, repeat the check of the correct formula in 32-bit
float32using framework tensors across . Which achieves the smallest relative error infloat32, why does it differ from the forward-difference optimum , and what relative-error threshold cleanly separates a correct gradient implementation from a buggy one infloat32?
- Write a function