44.03.08 · optimization-control / unconstrained-optimization

Derivative Computation: Finite Differences and Automatic Differentiation

shipped3 tiersLean: none

Anchor (Master): Griewank & Walther 2008 Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation 2e (SIAM) Ch. 3-4 (forward and reverse accumulation), Ch. 12 (reversal schedules and checkpointing); Nocedal & Wright 2006 Numerical Optimization 2e (Springer) Ch. 8 (finite-difference and automatic derivatives for optimization); Baydin, Pearlmutter, Radul & Siskind 2018 Automatic Differentiation in Machine Learning: a Survey (JMLR 18) for the ML-training context

Intuition Beginner

Almost every fast optimizer needs to know which way is downhill, and how the slope is bending. That information is the derivative: the gradient (the vector of slopes in each direction) and sometimes the second derivatives (how the slopes change). The trouble is that you often have a function only as a piece of code — a long recipe of additions, multiplications, square roots, and so on — with no tidy formula for its slope. So the practical question is: given the code for , how do you get the code for its derivative?

The oldest trick is to nudge and compare. Move the input a tiny amount , see how much the output changes, and divide: the change in output over the change in input is an estimate of the slope. This is the finite-difference idea, and it needs nothing but the ability to run . Its weakness is the size of the nudge. Too big a nudge and the straight-line estimate is crude; too small a nudge and the two outputs are so close that rounding noise in the computer swamps the tiny difference. There is a sweet spot in the middle, and it is not as accurate as you might hope.

The sharper trick is to differentiate the recipe itself. Each basic step — add, multiply, take a sine — has a known derivative rule, and the chain rule stitches those rules together. A computer can apply the chain rule mechanically as it runs the code, producing the exact derivative (up to ordinary rounding), with no nudge and no guessing of . This is automatic differentiation, and it comes in two directions of travel: forward, alongside the computation, and backward, retracing it.

The backward direction holds the prize that powers modern machine learning: it returns the slope in every input direction at once, for a cost close to a single run of — no matter whether there are ten inputs or ten million.

Visual Beginner

Picture the finite-difference estimate first. On the curve , mark your point and a second point a little to the right at distance . Draw the straight line through the two marks: its steepness is the finite-difference slope, a chord standing in for the true tangent. A symmetric version uses one mark on each side, left and right, and the chord through those two hugs the tangent more closely.

The step-size sweet spot is the heart of the method. Shrink and the chord lines up better with the tangent — until gets so small that the two output values agree in almost all their digits, and the subtraction throws away accuracy. The error first falls, bottoms out, then climbs again.

method what it needs cost of a full gradient ( inputs) accuracy
forward difference run only about runs of modest (about half the digits)
central difference run only about runs of better (about two-thirds of the digits)
forward-mode AD the code of about runs' worth full (exact rule, only rounding)
reverse-mode AD the code of a few runs' worth, any full (exact rule, only rounding)

The last row is the surprise: the cost of the whole gradient does not grow with the number of inputs. That single fact is why training a network with millions of parameters is even possible.

Worked example Beginner

Take at the point , where the true slope is . We estimate it three ways.

Forward difference with . Compute and . The chord slope is

The error is — too high, because the chord leans up over the interval.

Central difference with . Compute and . The symmetric chord slope is

The error is only — the two-sided chord cancels most of the lean.

Automatic differentiation. The code for is "multiply by to get , then multiply by again." Differentiating step by step with the product rule and feeding the slope through gives at , exactly, with no at all.

What this tells us: halving the lean by going symmetric turned an error of into , yet both finite-difference numbers are still approximations tied to the choice of . The automatic-differentiation answer is the exact , because it differentiates the recipe rather than sampling the output. The next sections make the step-size sweet spot precise and explain how the backward sweep gets every slope for nearly free.

Check your understanding Beginner

Formal definition Intermediate+

Let be smooth, evaluated in floating-point arithmetic with unit roundoff (the floating-point model of 43.01.01). Write for the -th coordinate vector and for a step.

Finite differences. The forward-difference approximation to a partial derivative is

and the central-difference approximation is

By Taylor's theorem 02.05.05, , while the odd-order terms cancel in the symmetric formula, giving . A Hessian-vector product is obtained by differencing the gradient,

so a Newton-Krylov solver can apply to a vector using only gradient evaluations, never forming the Hessian. A full forward-difference gradient costs evaluations of ; a central-difference gradient costs . The symbols (unit roundoff), (partial derivative), (gradient), (Hessian), (Jacobian), (forward tangent), and (reverse adjoint) are recorded in _meta/NOTATION.md.

The evaluation procedure. Automatic differentiation acts not on a formula but on an evaluation procedure (a Wengert list): the function is a finite straight-line program of intermediate variables , each an elementary operation () of earlier variables, with the inputs and the output . The partial order is the computational graph: a directed acyclic graph with the inputs as sources and as the sink.

Forward (tangent) mode. Fix a direction . Carry with each a tangent and propagate it forward by the chain rule alongside the primal values:

Equivalently, replace each value by the dual number with ; running the unchanged program on duals computes , so one forward sweep yields the Jacobian-vector product (a single directional derivative). For a scalar this is one component of the gradient per sweep, hence sweeps for the full gradient.

Reverse (adjoint) mode. Run the primal forward once, recording the graph (the tape). Then propagate adjoints backward from :

accumulating into each node from its successors. After the backward sweep, are exactly the components of . One forward run plus one backward run yields the entire gradient — the vector-Jacobian product — independent of . Backpropagation is precisely reverse-mode AD applied to a scalar loss.

Counterexamples to common slips Intermediate+

  • "AD is just finite differences done carefully." No nudge is taken and no is chosen; AD applies exact differentiation rules to each elementary operation, so its only error is ordinary floating-point rounding, not truncation. The step-size dilemma below does not apply to AD at all.

  • "AD is symbolic differentiation." Symbolic differentiation manipulates expression trees and suffers expression swell: the derivative of a product of factors expands to terms, and nested compositions blow up combinatorially. AD instead evaluates derivatives numerically at the given point while reusing every shared subexpression through the graph, keeping the work proportional to the original program.

  • "Forward and reverse mode cost the same." For , forward mode costs sweeps (one per input direction) and reverse mode costs sweeps (one per output). For a scalar loss ( and large) reverse mode wins decisively; for (a tall Jacobian) forward mode is cheaper.

  • "Reverse mode is free." It is cheap in time but pays in memory: the tape must store the intermediate values needed by the backward sweep, a cost proportional to the number of operations. Checkpointing trades some of this memory back for recomputation.

Key theorem with proof Intermediate+

The signature result is the error decomposition that fixes the optimal finite-difference step, because it is the single statement that quantifies the truncation-versus-roundoff dilemma and pins the best attainable accuracy to the machine precision of 43.01.01.

Theorem (optimal finite-difference step and accuracy floor). Let be near with on the relevant interval, and suppose each evaluation of is computed with a relative error at most , so the stored value satisfies . Then the computed forward difference satisfies

and the right-hand side is minimised at

The central difference, with , obeys , minimised at with accuracy floor .

Proof. Taylor's theorem 02.05.05 with Lagrange remainder gives for some between and , so the exact forward difference satisfies

the truncation term. The computed numerator replaces by stored values differing from the exact ones by at most each, so the computed quotient differs from the exact quotient by at most , the roundoff term. The triangle inequality adds the two bounds. Let ; then vanishes at , where , so is the minimiser. Substituting, . Since , both and the floor scale as up to the factor . For the central difference the truncation term is (the odd-order Taylor terms cancel) and the roundoff term is ; minimising gives and floor .

Bridge. This decomposition is the foundational reason finite differences can never reach full machine accuracy: the subtraction of two nearby values forfeits about half the available digits for a forward difference and a third for a central difference, so the best a gradient-by-differencing can do is or , and this is exactly the cancellation phenomenon the floating-point model of 43.01.01 predicts. The rule of thumb builds toward the contrast with automatic differentiation, where no subtraction of nearby quantities occurs and the only error is the ordinary rounding of 43.01.01, so AD returns derivatives to nearly full precision. The same Taylor cancellation that costs accuracy is dual to the cancellation that buys the higher order of the central formula: killing the term is the central insight that improves the floor from to . Putting these together, the step-size analysis generalises directly to Hessian-vector products formed by differencing the gradient, where the accuracy floor degrades by another factor, and the dilemma appears again in 44.03.04 wherever a quasi-Newton or Newton-Krylov method must choose between differenced and automatically differentiated curvature information; the bridge is that AD removes the dilemma entirely by differentiating the program rather than sampling its output.

Exercises Intermediate+

Advanced results Master

The finite-difference floor is set by cancellation and the optimal step by a one-dimensional minimisation; the results below place the exact-derivative alternative on its complexity-theoretic footing — the cheap-gradient principle, the duality of the two AD modes, the memory cost of reversal and its checkpointing remedy, and the position of AD between the symbolic and numerical extremes.

Theorem 1 (the cheap-gradient principle). Let be computed by an evaluation procedure whose runtime, measured in a fixed cost model counting additions, multiplications, and library-call evaluations, is . Reverse-mode AD computes the complete gradient in time

independent of . The bound holds because each elementary operation contributes to the backward sweep only its local partials times the incoming adjoint, a constant multiple of the work already done in the forward sweep; summing over all operations gives a constant overhead factor. The contrast with the evaluations of a forward-difference gradient is the entire reason gradient-based training of models with parameters is feasible [Griewank, A. & Walther, A. — Evaluating Derivatives].

Theorem 2 (forward-reverse duality and the Jacobian). For with Jacobian , forward mode evaluates the matrix-free product (a tangent) and reverse mode evaluates (an adjoint/cotangent), each at cost a small constant times . The full Jacobian costs such sweeps up to the optimal-Jacobian-accumulation problem — finding the cheapest order in which to multiply the elementary local Jacobians along the graph — which is NP-hard in general, so practical AD uses the forward or reverse extreme or hand-tuned cross-country schedules. Forward and reverse are formal transposes: reverse mode on is forward mode on the adjoint program, the algorithmic shadow of [Baydin, A. G., Pearlmutter, B. A., Radul, A. A. & Siskind, J. M. — Automatic Differentiation in Machine Learning: a Survey].

Theorem 3 (memory cost of reversal and logarithmic checkpointing). Reverse mode must make the intermediate values of the forward sweep available to the backward sweep. The naive tape stores all intermediates, . For an evaluation that decomposes into a chain of time steps (a deep network, a time-stepping PDE solver), the Revolve checkpointing schedule stores only checkpoints and recomputes intermediate segments on demand, achieving the optimal tradeoff: with checkpoints the chain of length is reversed using at most extra forward recomputations where . Choosing gives memory at the price of an factor in time — the binomial reversal schedule, optimal among all schedules [Griewank, A. & Walther, A. — Evaluating Derivatives].

Theorem 4 (AD versus symbolic and numerical differentiation). Symbolic differentiation returns a closed-form expression but suffers expression swell: the symbolic derivative of a length- program can have size exponential in when common subexpressions are not shared, and evaluating it then costs far more than the cheap-gradient bound. Numerical (finite) differentiation is cheap to implement but caps accuracy at (forward) or (central) by the Key theorem and costs evaluations for a gradient. Automatic differentiation occupies the remaining corner: it evaluates derivatives to full machine precision (no truncation), reuses every shared subexpression (no swell), and computes a scalar gradient at function evaluations (no -fold blowup). The three methods are distinguished not by the chain rule — all three obey it — but by what they carry: symbolic carries expressions, numerical carries perturbed values, AD carries derivative values attached to the live computation [Baydin, A. G., Pearlmutter, B. A., Radul, A. A. & Siskind, J. M. — Automatic Differentiation in Machine Learning: a Survey].

Synthesis. Derivative computation splits into two regimes, and the foundational reason they differ is whether one samples the function or differentiates its program. Finite differences sample: the Key theorem shows this forfeits half the digits to the cancellation of 43.01.01, the floor an irreducible tax on subtracting nearby values, and the cost scales with the input dimension . Automatic differentiation differentiates the program: the cheap-gradient principle is exactly the statement that the reverse sweep reuses the forward computation operation for operation, so a scalar gradient costs a fixed multiple of the function regardless of — this is the central insight that makes large-scale optimization and the training of billion-parameter models possible. The two AD modes are dual, forward computing and reverse computing , and the choice between them is governed by the shape of the Jacobian just as the choice of finite-difference order is governed by the balance of Taylor terms; backpropagation is simply reverse mode at a scalar loss.

The memory cost of reversal generalises the time-space tradeoff that pervades scientific computing, and logarithmic checkpointing is its optimal resolution, putting these together so that even an arbitrarily deep computation can be differentiated in bounded memory. The bridge from this unit to the rest of optimization is that every Newton, quasi-Newton, and stochastic-gradient method downstream consumes the gradients and Hessian-vector products produced here, and their efficiency is inherited from the cheap-gradient bound — AD is dual to the optimizer in the sense that the optimizer chooses the search direction and AD supplies, almost for free, the curvature information that direction needs.

Full proof set Master

Proposition 1 (forward-difference error decomposition and optimal step). Under the Key theorem's hypotheses, the computed forward difference obeys with , minimised at with floor .

Proof. This is the Key theorem. Taylor with Lagrange remainder 02.05.05 bounds the exact-quotient truncation by ; the floating-point model of 43.01.01 bounds each stored value's error by , contributing after division; the triangle inequality sums them. Calculus on gives the unique positive critical point with , and .

Proposition 2 (central-difference order and floor). For with , , minimised at with floor .

Proof. Taylor to third order at gives ; subtracting cancels the even-order terms, so , bounded by . The two stored values each carry error , contributing . Minimising : the derivative gives , so , and back-substitution gives a floor of order .

Proposition 3 (forward mode computes via dual numbers). Running an evaluation procedure for on dual numbers over the ring with input returns .

Proof. The dual numbers form a commutative ring in which . Each elementary smooth operation extends to duals by its first-order Taylor jet, , since higher terms carry ; for a binary this gives , the chain rule on the -coefficient. By induction on the length of the Wengert list, after processing its dual carries with , which is the -th component of the propagated directional derivative. At the outputs the -coefficients assemble into .

Proposition 4 (reverse mode computes in function evaluations). For given by a procedure of elementary operations each of bounded arity, one forward sweep followed by one reverse adjoint sweep yields the exact in total work with an absolute constant.

Proof. Initialise and for . Process the operations in reverse order; when handling , add to each . By reverse induction this maintains the invariant (total derivative through all paths from to ), because every path from to the sink passes through exactly one of 's immediate successors and the partials multiply along edges and add over paths — the multivariate chain rule. At termination . Each operation is touched once in the forward sweep and once in the reverse sweep, and its reverse contribution is a fixed number of multiply-adds determined by its bounded arity, so the reverse work is at most a constant multiple of the forward work; with the forward sweep itself this gives total work , the constant absorbing the per-operation local-partial cost and independent of .

Proposition 5 (binomial checkpointing bound). A computation structured as a chain of steps can be reversed using stored checkpoints and at most extra forward recomputations whenever ; choosing reverses the chain in memory and time .

Proof. Let be the largest chain length reversible with checkpoints and recomputation passes. Place the first checkpoint after steps: the suffix is reversed with checkpoints and passes, the prefix with the remaining checkpoints and passes once its end state is recomputed, giving the recurrence with , whose solution is the binomial coefficient . Hence any is reversible within the stated resources. Taking gives for , so memory and total recomputation work . The schedule is optimal: no reversal of a length- chain with checkpoints and passes can exceed steps, by the same recurrence read as an upper bound.

Connections Master

  • Multivariable Taylor expansion and extrema 02.05.05 supplies the remainder estimates that make the finite-difference analysis quantitative: the forward and central truncation terms are the Lagrange remainders of the first- and second-order expansions, and the same second-order Taylor data — gradient and Hessian — is exactly what the optimizers downstream need and what AD delivers exactly. The vanishing-gradient condition for an extremum from that unit is the target every gradient-based method of this chapter drives toward, and the curvature (Hessian) it classifies critical points with is the object Hessian-vector products approximate or, through forward-over-reverse AD, compute exactly.

  • Floating-point arithmetic and the IEEE model 43.01.01 is the source of the accuracy floor: the unit roundoff that bounds each evaluation's relative error is precisely what forces the roundoff branch and caps differenced derivatives at . The catastrophic cancellation that the IEEE model predicts when subtracting nearby quantities is the exact mechanism that limits finite differences and that automatic differentiation sidesteps by never forming such a difference, so this unit is the applied payoff of that unit's error model.

  • The conjugate gradient method 43.07.04 and Newton-Krylov optimization consume Hessian-vector products of the kind built here: a truncated-Newton method solves the Newton system by CG, and CG needs only the action , supplied either by differencing the gradient (with the floor of the Key theorem) or, to full precision, by forward-over-reverse AD. The cheap-gradient principle is what makes the per-CG-iteration cost a small multiple of one function evaluation, so the matrix-free curvature access of that unit and the matrix-free derivative access of this one compose into large-scale second-order optimization.

  • The artificial-intelligence and machine-learning survey 25.09.01 pending is the large-scale consumer of reverse-mode AD: backpropagation is reverse-mode AD applied to a scalar training loss, and the cheap-gradient bound proved here is the reason a network with billions of parameters can be trained at all. This unit is the theorem-level cost-and-accuracy treatment that the survey references at a higher level; the survey covers the modelling and architectural context while this unit owns the derivative-computation cost theory, so the two are complementary rather than overlapping.

Historical & philosophical context Master

The finite-difference quotient is as old as the calculus, but its numerical-analysis treatment — the explicit balance of truncation against roundoff and the resulting optimal step near — belongs to the mid-twentieth-century error-analysis tradition associated with James H. Wilkinson, whose backward-error framework of the 1960s made the cancellation term a quantitative object. The forward mode of automatic differentiation was given its modern form by Robert E. Wengert in 1964, whose "simple automatic derivative evaluation program" introduced the list of intermediate operations now called the Wengert list [Wengert 1964].

The reverse mode has a more tangled lineage. Seppo Linnainmaa's 1970 master's thesis and 1976 paper described the reverse accumulation of rounding errors over a computational graph — the algorithm now called backpropagation — predating its 1986 popularization in neural networks by Rumelhart, Hinton, and Williams [Linnainmaa 1976]. Bert Speelpenning's 1980 dissertation proved that the reverse mode computes a gradient at a cost independent of the number of inputs, the cheap-gradient principle. The systematic theory — complexity bounds, optimal Jacobian accumulation, and the binomial checkpointing schedule — was consolidated by Andreas Griewank and Andrea Walther, the latter's Revolve algorithm of 1996 establishing the optimal logarithmic time-memory tradeoff for reversal [Griewank, A. & Walther, A. — Evaluating Derivatives]. The 2018 survey of Baydin, Pearlmutter, Radul, and Siskind documented how reverse-mode AD, rediscovered repeatedly across numerical analysis and machine learning, became the computational substrate of deep learning [Baydin, A. G., Pearlmutter, B. A., Radul, A. A. & Siskind, J. M. — Automatic Differentiation in Machine Learning: a Survey].

Bibliography Master

@book{NocedalWright2006,
  author    = {Nocedal, Jorge and Wright, Stephen J.},
  title     = {Numerical Optimization},
  edition   = {2},
  series    = {Springer Series in Operations Research and Financial Engineering},
  publisher = {Springer},
  year      = {2006}
}

@book{GriewankWalther2008,
  author    = {Griewank, Andreas and Walther, Andrea},
  title     = {Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation},
  edition   = {2},
  publisher = {Society for Industrial and Applied Mathematics},
  year      = {2008}
}

@article{BaydinEtAl2018,
  author  = {Baydin, At{\i}l{\i}m G\"{u}ne\c{s} and Pearlmutter, Barak A. and Radul, Alexey Andreyevich and Siskind, Jeffrey Mark},
  title   = {Automatic Differentiation in Machine Learning: a Survey},
  journal = {Journal of Machine Learning Research},
  volume  = {18},
  number  = {153},
  year    = {2018},
  pages   = {1--43}
}

@article{Wengert1964,
  author  = {Wengert, Robert E.},
  title   = {A Simple Automatic Derivative Evaluation Program},
  journal = {Communications of the ACM},
  volume  = {7},
  number  = {8},
  year    = {1964},
  pages   = {463--464}
}

@article{Linnainmaa1976,
  author  = {Linnainmaa, Seppo},
  title   = {Taylor Expansion of the Accumulated Rounding Error},
  journal = {BIT Numerical Mathematics},
  volume  = {16},
  number  = {2},
  year    = {1976},
  pages   = {146--160}
}

@article{GriewankWalther2000revolve,
  author  = {Griewank, Andreas and Walther, Andrea},
  title   = {Algorithm 799: Revolve: An Implementation of Checkpointing for the Reverse or Adjoint Mode of Computational Differentiation},
  journal = {ACM Transactions on Mathematical Software},
  volume  = {26},
  number  = {1},
  year    = {2000},
  pages   = {19--45}
}

@book{Wilkinson1963,
  author    = {Wilkinson, James H.},
  title     = {Rounding Errors in Algebraic Processes},
  publisher = {Prentice-Hall},
  year      = {1963}
}