7.1 Derivatives and Finite Differences
Training a model by gradient descent needs the derivative of a loss with respect to every weight. The autograd engine built in Tensor, broadcasting backward, and no_grad and The op library and gradcheck_all in AI Engineering computes those derivatives by the chain rule, and every backward rule there could be wrong in ways that still train a little: a transposed gradient, a missing factor of 2, a flipped sign. The only independent check is the definition of the derivative itself, evaluated numerically: nudge one input, watch the output move, divide. That check is gradcheck, built in Gradients and gradcheck, and it rests on the functions you build in this section.
Concepts from other sections (8)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- chain rule: . Read more: 7.5 Calculus 1 Problem Set
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all in AI Engineering
- Taylor series: the power series built from the derivatives of at ; truncating it gives the polynomials that libraries use to compute , , and . Read more: Chapter 8: Calculus 2
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- Gradient check: a comparison of an analytic gradient against the numerical one that reports pass or fail and the element furthest past its allowance. Read more: 10.1 Partial derivatives, gradients, and gradcheck
- Automatic differentiation / autodiff: computing exact derivatives of a program by applying the chain rule to each primitive operation it executes, in forward mode (Jacobian-vector products) or reverse mode (vector-Jacobian products); it is how neural networks get their gradients, with no step size and no symbolic formula. Read more: Chapter 14: Matrix Calculus and Autodiff
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- dual numbers: forward-mode autodiff values that carry an exact derivative alongside each number. Read more: 6.3 The op library and gradcheck_all in AI Engineering
A numerical derivative is only as trustworthy as its step size. Too large, and the formula is inaccurate; too small, and floating-point rounding swamps the answer. This section derives the right step from first principles, then implements the three difference formulas the rest of the book uses: the forward difference, the central difference, and Richardson extrapolation. The finished code lives in course/solutions/python/tinyllm/num/diff.py (functions forward_diff, central_diff, and richardson), and its contract is course/contracts/py/tinyllm/num/diff.pyi.
There is nothing to call from earlier sections, but the arguments lean on Exponents, logs, and units of information for and on Polynomials, Horner, and stable roots for the shape of a truncated polynomial expansion. As you read the implementation, try to predict each step before you see it.
Learning objectives
- Derive the truncation error of the forward and central differences from Taylor’s formula and state their orders.
- Explain why rounding error grows as the step shrinks, and compute the step that balances the two errors for each formula.
- Scale a default step with the size of and divide by the step the hardware actually took.
- Build a Richardson extrapolation table and explain why it uses weights .
- Implement
forward_diff,central_diff, andrichardsonwith the validation the gradient checker relies on.
The derivative is a limit
Section titled “The derivative is a limit”Throughout this section, is a function of one real variable evaluated in float64 (a Callable[[float], float]), is the point where you want the derivative, and is the step. The slope of the straight line through and is the difference quotient : rise over run. As shrinks, the second point slides toward the first, and if the slopes settle on one number, that number is the derivative , the slope of the tangent line:
“Settles on” has a precise meaning, the limit: for every tolerance you name, there is a step size below which every quotient is within that tolerance of . For you get , which tends to . The usual rules follow from the definition the same way: , (the property that defines ), , and the chain rule , which Jacobians and the chain rule generalizes and every backward pass applies.
A computer cannot take a limit
Section titled “A computer cannot take a limit”A program picks one and computes one quotient. Two questions follow: how wrong is the quotient for a given , and which makes it least wrong? Both answers come from comparing near with a polynomial. If is smooth (has enough continuous derivatives), then for small
This is Taylor’s formula; Taylor series proves it and bounds the dots. Here only the first few terms matter, and you can check them on : , and indeed , , .
With Taylor’s formula in hand, you can measure exactly how far each difference quotient sits from the true derivative.
Truncation error
Section titled “Truncation error”Write for the forward difference and for the central difference, and use to mean “at most a constant times ” as . Subtract from Taylor’s formula and divide by :
The forward difference is off by about : it is first order, with error proportional to . Halve and the error halves. Now write the expansion at as well,
and subtract it from the one at . The even powers cancel:
The central difference is second order: halve and the error drops by a factor of 4. On a log-log plot of error against , the forward difference is a line of slope 1 and the central difference a line of slope 2; that slope is the signature of each formula’s order. The error from the dropped terms is called truncation error, because it comes from truncating the Taylor series. The central difference is exact on quadratics (), while the forward difference is exact only on straight lines.
If truncation were the whole story, you would simply take as small as possible. Floating point says otherwise.
Rounding error
Section titled “Rounding error”Every float64 operation rounds its exact result to the nearest representable number, with relative error at most , where is float64 machine epsilon, the gap between 1 and the next float. So a computed is off by about , more if itself is a long computation. When is small, the numerator is a difference of two nearly equal numbers: their leading digits cancel and their rounding errors do not. That error, about , is then divided by . The total error of the central difference is
The first term falls as shrinks, and the second rises. The following table shows the measured error of on at , where :
| error of |
Down to the error falls by a factor of 100 per decade (slope 2); below about rounding takes over and the error rises again. A step of is worse than a step of .
Choosing the step
Section titled “Choosing the step”Since one error falls and the other rises, there is a best step in between. Minimize with and : the derivative is zero at . When and its derivatives are of size 1, that is , and the error there is about : two thirds of the 16 digits survive. The same argument for the forward difference, , gives and an error of about , half the digits.
The step must also follow the scale of . Floats near are about apart, so at a step of moves by only relative, and the quotient is mostly rounding. A step proportional to keeps the relative perturbation fixed, and using instead of keeps it from vanishing at . The contract’s defaults are therefore
One more floating-point detail matters. is itself rounded, so the step the hardware took is , not . Dividing by the step actually taken makes come out as exactly 1. With and , dividing by gives instead.
Richardson extrapolation
Section titled “Richardson extrapolation”The best single central difference keeps about 11 digits. You can do better by removing truncation error with algebra instead of a smaller step. The central difference has an error series with only even powers, , where the ‘s do not depend on . Then , and the combination
cancels the term exactly. Repeating with weight at level cancels . Writing and
the value after levels has error and is exact on polynomials of degree up to . Because the truncation error shrinks so fast, Richardson can use a large (like 0.1), where rounding is negligible, and still reach about 12 digits. This is the method behind adaptive differentiation libraries.
Working it by hand
Section titled “Working it by hand”Before writing code, check every formula on an example small enough to compute by hand. Take at , so , with . The function values are , , , , and . The table collects the four estimates:
| Quantity | Computation | Value | Error |
|---|---|---|---|
| 12.61 | |||
| 12.01 | (here ) | ||
| 12.0025 | |||
| 12 | 0 |
The forward error is the predicted by the truncation analysis, plus the next term . The central error is exactly because has no terms beyond , and quartering it at is what lets Richardson remove it completely.
Designing the interface
Section titled “Designing the interface”The three functions share one shape:
def forward_diff(f: Callable[[float], float], x: float, h: Optional[float] = None) -> float: ...def central_diff(f: Callable[[float], float], x: float, h: Optional[float] = None) -> float: ...def richardson(f: Callable[[float], float], x: float, h: float, levels: int = 2) -> float: ...h = None means the default step derived above; a given h is used as is, because the gradient checker passes its own. Each function returns a Python float, divides by the step actually taken, and raises ValueError for a non-finite x, a step that is not finite and positive, or levels < 0. Richardson’s default is two levels.
Building it step by step
Section titled “Building it step by step”The design follows from the analysis in seven decisions.
- Pick the formula by its truncation order. The forward difference errs by , the central one by . Both are provided because callers differ (an optimizer that already has saves one evaluation with the forward one), but gradcheck uses the central one.
- Pick the default step by balancing errors. Minimizing gives , so for the forward difference () and for the central one (). These are separate constants because each is wrong for the other formula.
- Scale the step with , but never to zero. The spacing of floats near is about , so a fixed relative step means . Multiplying by instead of keeps from vanishing at .
- Treat a caller’s step as sacred. gradcheck chooses
epsdeliberately, so an explicithis validated (finite and positive) and used unchanged; onlyNonetriggers the default. - Divide by the step the hardware took. is rounded, so the true run of the secant is
xp - x(orxp - xm), not (or ). Dividing by it makes the quotient the exact slope of the secant through the two evaluated points, which is why gives exactly 1. - Build Richardson as a table, column by column. Column 0 holds for . Each later column applies , which shortens the column by one, so after rounds a single value remains. Only the current column needs to be kept.
- Validate at the boundary. NaN or infinite , a bad step, or a negative or fractional
levelsraises immediately, so a NaN never travels silently into a gradient check.
The code starts with the validators and the machine epsilon constant:
EPS = 2.0**-52 # float64 machine epsilon: the gap between 1 and the next float
def _check_x(x: float) -> float: x = float(x) if not math.isfinite(x): # nan and +-inf have no derivative to estimate raise ValueError(f"x must be finite, got {x}") return x
def _check_h(h: float) -> float: h = float(h) if not math.isfinite(h) or h <= 0: # "not isfinite" first, so nan is rejected too raise ValueError(f"h must be finite and > 0, got {h}") return hThe two difference formulas differ only in their default step and their second point:
def forward_diff( f: Callable[[float], float], x: float, h: Optional[float] = None) -> float: x = _check_x(x) # Default: sqrt(eps), the balance point for an O(h) formula, relative to |x|. h = math.sqrt(EPS) * max(1.0, abs(x)) if h is None else _check_h(h) xp = x + h # Divide by the step the hardware actually took: x + h is rounded, so # (x + h) - x is usually not h. Using it makes f(x) = x exact. return (float(f(xp)) - float(f(x))) / (xp - x)
def central_diff( f: Callable[[float], float], x: float, h: Optional[float] = None) -> float: x = _check_x(x) # Default: cbrt(eps), the balance point for an O(h^2) formula. h = math.cbrt(EPS) * max(1.0, abs(x)) if h is None else _check_h(h) xp, xm = x + h, x - h # xp - xm is the run actually taken, not 2h. return (float(f(xp)) - float(f(xm))) / (xp - xm)float(f(...)) turns a numpy scalar returned by f into a Python float before the subtraction, so the result is always a plain float. At the default central step is , which perturbs by the same relative amount as perturbs 1.
Richardson builds on central_diff with explicit steps:
def richardson( f: Callable[[float], float], x: float, h: float, levels: int = 2) -> float: x = _check_x(x) h = _check_h(h) # no default: Richardson wants a large h if int(levels) != levels or levels < 0: raise ValueError(f"levels must be an integer >= 0, got {levels}") levels = int(levels) # Column 0: central differences at h, h/2, h/4, ... Each later column # cancels the next even power of h: D(h) = f' + c2 h^2 + c4 h^4 + ..., # so (4^k D(h/2) - D(h)) / (4^k - 1) removes the h^(2k) term. col = [central_diff(f, x, h / 2.0**j) for j in range(levels + 1)] for k in range(1, levels + 1): p = 4.0**k # Combine neighbours: entry j uses steps h/2^j and h/2^(j+1). col = [(p * col[j + 1] - col[j]) / (p - 1.0) for j in range(len(col) - 1)] return col[0] # the single value of the last columnOn the hand-worked example with levels=1, col starts as ; with the next column is , exact. levels=0 returns the plain central difference . The full solution is in diff.py.
Why this design
Section titled “Why this design”Consider cost first. forward_diff evaluates twice, central_diff twice, and richardson times, plus arithmetic for the table. For gradcheck on parameters that is evaluations of the loss, which is why gradcheck runs on small models only.
The central difference beats the forward one for checking gradients. At its best step it keeps about (11 digits), against (8 digits) for the forward one, for the same two evaluations. gradcheck compares against an analytic gradient with a tolerance, so the extra digits decide whether real bugs stand out from noise.
Richardson beats a smaller step. A smaller eventually makes rounding dominate, as the error table for showed. Richardson reduces truncation error by algebra instead, so it can keep large where rounding is negligible and reach about 12 digits with three pairs of evaluations.
Two alternatives were not taken. Complex-step differentiation has no subtraction and is exact to rounding, but it needs to accept complex input, which most of the book’s code does not. Automatic differentiation is exact, but it is precisely what these functions exist to check, so it cannot be its own referee.
The design also accepts two tradeoffs. The default step assumes and its derivatives have size near 1 relative to ; a badly scaled (huge ) would want a different step, and callers that know better pass h. And richardson divides each column by the step actually taken too, so its steps are only approximately in ratio 2; the difference is of rounding size and does not affect the cancellation.
What can go wrong
Section titled “What can go wrong”A correct implementation must reproduce the hand-worked values 12.61, 12.01, and 12, so that everyone agrees on the definitions, and it must return a Python float even when f returns numpy scalars, because gradcheck stores results in float64 arrays. Its error behavior is tested as properties: the log-log slope of the central error must be 2 and that of the forward error 1, confirming the truncation orders. At the default steps, the central error must be at most on five smooth functions at 26 points (the tolerance in Gradients and gradcheck assumes this accuracy), and the forward error at most , the rule at work.
The boundaries matter just as much. The default step must scale with : at must come out to 7 digits, because weights and logits are not all near 1. The default step at must be nonzero, because activations are checked at their kink. must give exactly 1, which only dividing by the step actually taken achieves. A given step must be used as is: the central difference of with h = 0.5 at gives , not the default-step answer, so gradcheck’s eps means what it says. For Richardson, on at 0.5 with , the errors for levels 0 to 3 must fall as , , , and ; it must be exact on a quartic with one level and a sextic with two, confirming the claim. Finally, , a negative , NaN, or infinity must raise ValueError, as must a NaN or infinite or negative levels, so bugs surface at the call and NaN never travels into a gradient check.
The common mistakes each have a recognizable symptom, and the table maps them to the line of the solution that prevents them:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| a one-sided difference where the central one was meant | error instead of ; slope 1 on the log-log plot | central_diff evaluates at x + h and x - h |
| an absolute step, ignoring the size of | the derivative of at is off by 3 percent | default step multiplied by max(1.0, abs(x)) |
| a step proportional to alone | at : division by zero | the max(1.0, ...) floor |
| dividing by instead of the step actually taken | differentiates to | divides by xp - xm (or xp - x) |
| the wrong step rule for the formula ( for central, for forward) | central error instead of ; forward error instead of | math.sqrt(EPS) in forward_diff, math.cbrt(EPS) in central_diff |
| Richardson weights instead of | the extrapolation removes nothing; worse than level 0 | p = 4.0**k |
| Richardson steps that grow () instead of shrink | the hand example gives 12.05 | column 0 uses h / 2.0**j |
| rescaling a step the caller gave | gradcheck’s eps silently becomes eps at | the default applies only when h is None |
| accepting a NaN or infinite step | a NaN derivative instead of an error | _check_h rejects non-finite and non-positive steps |
Warning: The most damaging of these is silent: rescaling a caller’s step. Nothing crashes, but gradcheck’s tolerance stops meaning what its author intended.
Where this leads
Section titled “Where this leads”These functions are used throughout the book. Gradients and gradcheck builds numerical_grad by calling central_diff(along, x_i, eps) once per coordinate of every input: the frozen-step gradient behind gradcheck. The next section, Newton’s Method, uses central_diff as its slope when it is given no derivative. Taylor series proves Taylor’s formula with a remainder, making the truncation errors here rigorous, and Error analysis, condition numbers, and tolerance budgets generalizes the rounding analysis. In AI Engineering, F.gradcheck_all() in The op library and gradcheck_all checks every op of the autograd library through gradcheck, and so through this file. Exact derivatives with no step at all come from automatic differentiation: the autograd engine and the dual numbers of Dual numbers and forward-mode autodiff.
Further reading
Section titled “Further reading”- OpenStax, Calculus Volume 1 (free), sections 2.2 and 3.1 to 3.2: limits and the derivative.
- Sauer, Numerical Analysis, section 5.1: numerical differentiation and its rounding error.
- Nocedal and Wright, Numerical Optimization, section 8.1: finite-difference gradients.
- PyTorch
torch.autograd.gradcheck(torch/autograd/gradcheck.py,_compute_numerical_gradient): the same central difference per element in float64 with eps , plus checks of complex inputs and forward-mode gradients. - SciPy
scipy.optimize.approx_fprimeandscipy.differentiate.derivative(scipy/optimize/_numdiff.py): forward steps for optimizers, with adaptive step and order selection. - numdifftools (
numdifftools/limits.py): Richardson tables with automatic step search and error estimates. - Martins, Sturdza, and Alonso, “The complex-step derivative approximation” (2003): has no subtraction, so works and the result is exact to rounding.
Key terms
Section titled “Key terms”- derivative: the limit of the difference quotient as ; the slope of the tangent line.
- forward difference: , a first-order approximation of .
- central difference: , a second-order approximation of .
- truncation error: the error from dropping the higher terms of the Taylor series.
- rounding error: the error from floating-point rounding, about in a difference quotient.
- machine epsilon: , the gap between 1 and the next float64.
- Richardson extrapolation: combining differences at with weights to cancel successive even powers of .
Summary
Section titled “Summary”- The derivative is a limit; a computer evaluates the quotient at one , and the result is an approximation whose error you can predict.
- The forward difference has truncation error proportional to ; the central difference cancels the term and has error proportional to .
- Rounding adds an error of about that grows as shrinks, so the best step balances the two: for forward, for central, times .
- Divide by the step actually taken, , not by , because is rounded.
- Richardson extrapolation combines central differences at to cancel in turn, reaching about 12 digits from a large step.
Review questions
Section titled “Review questions”-
Why is the default step for the central difference but for the forward one?
Answer
Each step minimizes truncation plus rounding, . Setting the derivative to zero gives . The central difference has , so ; the forward one has , so . Using the other formula’s step leaves either too much truncation or too much rounding.
-
What happens to
central_diff(math.log, 1e8)if the step is without the factor?Answer
near moves by less than one part in , a handful of float spacings (about each). The numerator is then mostly rounding, and the derivative comes out several percent wrong. Scaling the step to restores the relative perturbation of the case.
-
Why divide by
xp - xmrather than2 * h?Answer
xpandxmare rounded, so the points where was evaluated are not exactly apart. The quotient is meant to be the slope of the secant through the two points actually used; dividing by their actual distance makes it so, which is why gives exactly 1. Dividing by adds a relative error of up to about ; at , it gives instead of 1. -
Why does Richardson combine levels with and not ?
Answer
The central difference’s error series has only even powers, . Halving the step divides the term by , so cancels it exactly. With the leading term does not cancel and the extrapolation is worse than not extrapolating.
-
Why does
richardsonrequirehwhile the other two functions default it?Answer
The defaults are tuned to make a single difference quotient as accurate as possible, which puts where rounding and truncation are equal. Richardson’s point is the opposite regime: a large (like 0.1) where rounding is negligible, letting extrapolation remove the truncation. Its later columns also amplify rounding by the weights , so starting from a tiny default step would undo its advantage.