14.4 Hessian-vector products and the recompute-versus-memory schedule
Concepts from other sections (13)
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.
- Reverse mode: automatic differentiation that records the computation and walks it backward once from the output, pushing adjoints into inputs. Read more: 14.2 Scalar reverse mode: the Value graph
- 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
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- Directional derivative: , the rate of change of along a unit vector . Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- relative accuracy: the number of correct significant digits, which subtraction of nearly equal numbers destroys. Read more: 7.3 Activation Functions and Their Derivatives
- Power iteration: repeated multiplication and normalization, converging to the dominant eigenvector. Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Forward mode: automatic differentiation that carries tangents alongside values, costing one pass per input direction. Read more: 14.1 Dual numbers and forward-mode autodiff
- Vector-Jacobian product (VJP): , what one backward pass from leaves in the leaves. Read more: 14.2 Scalar reverse mode: the Value graph
- training step: one zero-grad, loss, finiteness check, backward, clip, and optimizer update on one batch. Read more: 6.6 Training loop and the autograd bigram in AI Engineering
- Golden test: a comparison against numbers an independent implementation produced and a maintainer recorded. Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
Reverse mode buys its speed with memory. Consider the capstone of AI Engineering: an 8-layer Llama with a 512-token context, trained on a laptop. Its backward pass needs every layer’s saved activations at once. At batch 16 that is several hundred megabytes in float32 before the logits, and it is the activations, not the 10M weights, that run the process out of memory. Mixed precision, loss scaling, gradient accumulation, and activation checkpointing fixes this with activation checkpointing: keep only some layer inputs and recompute the rest during backward. Which layers to keep is a counting problem with an exact answer, and you need that answer before the mechanism can be written.
The same stage of training is where curvature questions come up. Is the learning rate past , the stability limit of gradient descent? The tool for such questions is the Hessian-vector product, which gives you curvature along a direction without ever forming the Hessian. This section provides both pieces: hvp_fd, and the schedule functions the checkpointing code calls. The Optimization chapter can then estimate the top Hessian eigenvalue with hvp_fd as an optional extension.
Nothing here depends on earlier code, but the reading builds on Matrix differentials, the trace trick, and closed-form VJPs (its cross-entropy gradient is the one whose is compared with PyTorch), on the forward-versus-reverse cost counts of the chapter problem set, and on the Hessian and second-derivative test of Jacobians, the multivariable chain rule, and numeric JVP/VJP. The complete implementation is hvp.py, with its interface in the contract course/contracts/py/tinyllm/autograd/hvp.pyi.
Learning objectives
- Derive the central-difference Hessian-vector product and its error from a Taylor expansion of the gradient.
- Explain why the central difference is exact on a quadratic and why a finite-difference Hessian must be symmetrized.
- Compute the peak memory and recomputation of any checkpoint schedule, and the least achievable peak .
- Construct the optimal schedule under a memory budget and explain why the greedy construction is correct.
Notation
Section titled “Notation”The section uses two families of symbols, one for curvature and one for schedules.
| Symbol | Meaning | Type / shape |
|---|---|---|
| a scalar loss of parameters | function | |
| the point (parameters) | float64[...] | |
the gradient (grad_fn) | same shape as | |
| the Hessian: | , symmetric | |
| a direction | same shape as | |
the finite-difference step along (eps) | float | |
| the -th directional derivative of along (a derivative of order of ) | same shape as | |
| the -th unit vector | float64[n] | |
(n_layers) | layers in a stack | int |
| segments in a schedule | int | |
| layers in segment (), | int | |
starts | first layer of each segment: | list[int] |
(mem_budget_layers) | the memory budget, in saved layer inputs | int |
| the peak number of saved layer inputs held at once | int |
The Hessian-vector product as a derivative of the gradient
Section titled “The Hessian-vector product as a derivative of the gradient”The key observation is that is a directional derivative of the gradient. Taylor-expand the gradient around along :
The first-order term is , so . That limit is a derivative, and derivatives can be taken numerically, as in Derivatives and Finite Differences.
A central difference does much better than a one-sided one. Subtract the expansion at from the one at : and the term cancel, and
The one-sided quotient keeps the term: halving halves its error, while halving it in the central quotient quarters the error. The step cannot be made arbitrarily small either. Each gradient carries rounding error of about ( in float64), and dividing by magnifies it to about . Balancing against puts the best step near times the scale of the problem; the default gives about relative accuracy on smooth losses and is far from the rounding floor.
On a quadratic the central difference is exact. For , the gradient is affine, , and the central difference returns for every (up to rounding). Using a non-symmetric makes the point that the Hessian is the symmetric part.
What curvature costs
Section titled “What curvature costs”One costs two gradient calls, each about one forward and one backward pass. Forming would take of them and numbers of memory: for a 10M-parameter model, entries. So everything that needs curvature uses products instead. Newton-CG solves with , and the power iteration finds the top eigenvalue .
For small , hessian_fd builds column by column from and returns . The symmetrization matters: the columns carry errors that differ between and , and code that assumes symmetry (eigenvalues, Cholesky) must get it exactly.
Frameworks compute exactly at the same cost with Pearlmutter’s -operator, forward mode over reverse mode. That needs an autograd that differentiates its own backward pass, which the book’s engine does not, so finite differences are the right tool here.
Why reverse mode stores activations
Section titled “Why reverse mode stores activations”Now the memory side. A stack of layers , , computes the VJP of layer from its saved input (a matmul’s needs ). Count memory in units of one saved layer input. A plain forward pass keeps all , and backward frees them from the top down, so the peak is .
Recomputation breaks that. Split the stack into consecutive segments of layers. Every segment but the last runs forward keeping only its input (one unit) and discards its internal activations; the last segment runs normally and keeps its . During backward, segment is rerun from its saved input to rebuild its activations, then backpropagated and freed. This is what torch.utils.checkpoint.checkpoint_sequential does.
While segment is being backpropagated, memory holds the inputs of segments (still needed later) plus segment ‘s activations (the first of which is its saved input). The end of the forward pass is the case . So
Both extremes cost : one segment () is no checkpointing, and one layer per segment holds inputs while recomputing layers for nothing. The interesting schedules lie between.
The classic choice is uniform segments. With segments of layers (), . Setting the derivative to zero gives and : the sublinear-memory result of Chen et al.
You can do better by noticing that the term grows with , so later segments should be smaller. If every , then , and segments hold at most
layers. That is largest at (the segment sizes ), where it is the triangular number . So the least peak of any schedule is the least with , about : for , against 7 for uniform segments of 4. Compute it with integers (math.isqrt); a float square root is wrong by one for large .
In practice you are given a budget rather than asked for the minimum. Given , the goal is to minimize recomputation, that is, maximize the last segment. With segments the last holds at most layers (its , and every other segment needs at least one), and the other segments must cover the rest within . That bound on the last segment shrinks as grows, so the fewest feasible segments is optimal. Fill the first segments greedily, largest first, , leaving at least one layer for each later segment. The order fixes one answer among ties, so every caller checkpoints the same layers. A brute force over all schedules agrees for every .
Working it by hand
Section titled “Working it by hand”Both halves of the section deserve a hand check; these numbers become the first two tests of the implementation.
For the Hessian-vector product, take the quartic in one dimension: , , , and . At , , :
| quantity | value |
|---|---|
| , | , |
| central: | |
| exact | |
| error, predicted | (exact here: is cubic, so the series stops) |
| one-sided: | , error , thirty times larger |
| forgetting the 2: |
For checkpointing, take a six-layer stack, , and compare five schedules:
schedule (starts) | sizes | peak | recomputed | |
|---|---|---|---|---|
[0] | 6 | 6 | 6 | 0 |
[0, 1, 2, 3, 4, 5] | 1, 1, 1, 1, 1, 1 | 1, 2, 3, 4, 5, 6 | 6 | 5 |
[0, 2, 4] (uniform, ) | 2, 2, 2 | 2, 3, 4 | 4 | 4 |
[0, 3, 5] | 3, 2, 1 | 3, 3, 3 | 3 | 5 |
[0, 3] | 3, 3 | 3, 4 | 4 | 3 |
The least peak is 3, because , and [0, 3, 5] reaches it. With a budget of 4: one segment needs 6 units, too many; two segments can keep a last segment of layers if the first covers the other 3 within , which it does. So checkpoint_schedule(6, 4) == [0, 3]: the same peak as uniform segments and one recomputed layer fewer.
Designing the interface
Section titled “Designing the interface”Five functions cover both halves:
def hvp_fd(grad_fn, x, v, eps: float = 1e-4) -> NDArray # (g(x + eps v) - g(x - eps v)) / (2 eps)def hessian_fd(grad_fn, x, eps: float = 1e-4) -> NDArray # 1-D x: columns H e_j, then (H + H^T) / 2def checkpoint_cost(n_layers: int, starts) -> tuple[int, int] # (peak, recomputed)def min_checkpoint_memory(n_layers: int) -> int # least P with P (P + 1) / 2 >= ndef checkpoint_schedule(n_layers: int, mem_budget_layers: int) -> list[int] # segment startshvp_fd calls grad_fn exactly twice, each time with a new float64 array, and copies each result, so a gradient that returns its own argument is safe. The step is , not normalized: the caller scales if its norm is far from 1. Shape mismatches, a non-positive or non-finite step, and an infeasible budget raise ValueError.
Building it step by step
Section titled “Building it step by step”The reasoning behind the code runs in six steps.
- is the derivative of the gradient along , and the central difference has error where the one-sided one has . So
hvp_fdis two gradient calls at divided by , with used as given. - A cheap
grad_fnmay return its own argument or a buffer it reuses. The two results must therefore be private copies, taken before the second call. - A dense Hessian is products with the unit vectors, one per column. The columns carry different errors, so the result is symmetrized, which makes exact in floating point.
- The cost model needs only the segment sizes: peak and recompute . Validating the schedule first (starts at 0, strictly increasing, below ) means every size is at least 1.
- The least peak is the least with .
math.isqrt(2n)is within one of it, so start there and adjust with integer comparisons, never a float square root. - Under a budget , fewer segments means a larger last segment means less recompute. So try and stop at the first whose largest allowed last segment leaves a remainder the other segments can cover; then fill those greedily, largest first.
The Hessian-vector product comes first:
def _grad_at(grad_fn, x): """grad_fn(x) as a new float64 array of x's shape (a copy, never a view).""" g = np.array(grad_fn(x), dtype=np.float64) # np.array copies; asarray would not if g.shape != x.shape: raise ValueError(...) return g
def hvp_fd(grad_fn, x, v, eps=1e-4): x = np.asarray(x, dtype=np.float64) v = np.asarray(v, dtype=np.float64) if x.shape != v.shape: raise ValueError(...) if not (math.isfinite(eps) and eps > 0): raise ValueError(...) # x + eps * v and x - eps * v are two NEW arrays; each gradient is copied # before the next call, so an aliasing grad_fn cannot change gp under us gp = _grad_at(grad_fn, x + eps * v) gm = _grad_at(grad_fn, x - eps * v) return (gp - gm) / (2.0 * eps) # central: the eps^2 term cancelsThe dense Hessian, for small , is a loop of products:
def hessian_fd(grad_fn, x, eps=1e-4): x = np.asarray(x, dtype=np.float64) if x.ndim != 1 or x.size == 0: raise ValueError(...) n = x.size H = np.empty((n, n)) for j in range(n): e = np.zeros(n) e[j] = 1.0 H[:, j] = hvp_fd(grad_fn, x, e, eps) # column j is H e_j return (H + H.T) / 2.0 # exactly symmetric in floating pointThe cost model validates the schedule and applies the two formulas:
def _sizes(n_layers, starts): """Segment sizes of a valid schedule; ValueError otherwise.""" if n_layers < 1: raise ValueError(...) s = [int(b) for b in starts] if not s or s[0] != 0: raise ValueError(...) if any(b <= a for a, b in zip(s, s[1:])) or s[-1] >= n_layers: raise ValueError(...) # so every segment has >= 1 layer return [b - a for a, b in zip(s, s[1:] + [n_layers])]
def checkpoint_cost(n_layers, starts): sizes = _sizes(n_layers, starts) # while segment i is backpropagated: i saved inputs of earlier segments # plus its own s_i activations; i = k - 1 is the end of the forward pass peak = max(i + s for i, s in enumerate(sizes)) return peak, n_layers - sizes[-1] # the last segment is never rerunThe least peak is computed entirely in integers:
def min_checkpoint_memory(n_layers): if n_layers < 1: raise ValueError(...) p = math.isqrt(2 * n_layers) # floor(sqrt(2n)): close to the answer while p * (p + 1) // 2 < n_layers: # too small: grow p += 1 while p > 1 and (p - 1) * p // 2 >= n_layers: # one smaller still fits: shrink p -= 1 return pFor , isqrt(12) is 3 and , while , so it returns 3. A float ceil(sqrt(12)) would give 4.
Finally, the budgeted schedule:
def _cover(k, budget): """Most layers k segments can hold when segment i has at most budget - i.""" return k * budget - k * (k - 1) // 2
def checkpoint_schedule(n_layers, mem_budget_layers): n, b = n_layers, mem_budget_layers if b < min_checkpoint_memory(n): # no schedule fits: refuse loudly raise ValueError(...) for k in range(1, n + 1): # fewest segments first # the last segment (index k - 1) may hold b - (k - 1) layers, and must # leave at least one layer for each of the k - 1 earlier segments last = min(b - k + 1, n - k + 1) if last >= 1 and n - last <= _cover(k - 1, b): break # the first feasible k is optimal rest = n - last sizes = [] for i in range(k - 1): # as large as the budget allows, keeping one layer for each later segment s = min(b - i, rest - (k - 2 - i)) sizes.append(s) rest -= s sizes.append(last) starts, at = [], 0 for s in sizes: # sizes to starting layers starts.append(at) at += s return startsTrace it on , . gives last = 4 but leaves 2 layers for zero segments; gives last = 3, and 3 layers fit in one segment of at most 4. The fill gives sizes = [3, 3], so starts = [0, 3], peak 4, recompute 3, matching the hand table. The full solution is hvp.py.
Why this design
Section titled “Why this design”hvp_fd costs two gradient calls and memory; hessian_fd costs gradient calls and memory, for small only. The schedule functions are integer work, negligible next to one training step.
Finite differences stand in for Pearlmutter’s exact because the exact product needs forward mode over reverse mode, an autograd that can differentiate its own backward. The book’s engine cannot. Two gradient calls give to about relative accuracy, plenty for estimating .
Uniform segments are not good enough because they peak at about while shrinking segments reach , and under a loose budget the uniform rule recomputes layers it did not need to. The greedy schedule is optimal (checked against brute force for ) and costs nothing extra.
Integer arithmetic for the least peak is a correctness issue, not a style choice. math.sqrt of a large integer rounds, and ceil of a rounded value can be off by one; for near the error is large. isqrt and integer comparisons are exact for every .
The tradeoff accepted is that the cost model counts saved layer inputs as equal units and ignores the logits and optimizer state. That is a good approximation for a uniform stack of transformer blocks, which is what the checkpointing code applies it to.
What a correct implementation must handle
Section titled “What a correct implementation must handle”On the curvature side, the tests start from the hand-computed quartic, with error , which pins the formula. A quadratic must give at three step sizes with not a unit vector, confirming that the step is . Halving must divide the error by 4, confirming a central rather than one-sided difference. Two golden tests compare with PyTorch: the exact double-backward of a cross-entropy loss whose gradient is the rule from the previous section (the curvature an optimizer would estimate), and a dense Hessian, exactly symmetric (small-model Newton steps). Rosenbrock at must give bit for bit and stay close to the analytic Hessian, because eigenvalue code assumes symmetry. A gradient that returns its own input must be called exactly twice, with x untouched, since cheap gradients alias. Shape and step errors must raise, and the default step must be accurate.
On the schedule side, the hand table above must come out exactly, since the checkpointing code checkpoints exactly these layers. No checkpointing and all checkpoints must both peak at , and invalid schedules must raise. The least peak must satisfy for up to , which tests integer arithmetic at scale. The budgeted schedule must stay within budget and recompute as few layers as brute force for ; ties must go to the largest first segment, on four cases, so every caller gets the same schedule; and a budget below the least peak must raise rather than overrun silently.
The pitfalls these tests catch:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| A one-sided difference | error : 0.5517 instead of 0.5017 in the hand example | evaluates at both and |
| Dividing by instead of | every twice too large | divides by 2.0 * eps, the distance between the two points |
| Reusing one buffer for | a gradient that aliases its input changes under the caller; | two new arrays for the points; _grad_at copies each result |
| Not symmetrizing the finite-difference Hessian | by | returns (H + H.T) / 2.0 |
| Peak as (segments 1) + (largest segment) | overcounts when the largest segment comes first; the optimizer picks worse schedules | max(i + s for i, s in enumerate(sizes)) |
| The uniform rule whatever the budget | over budget when it is tight, needless recomputation when it is loose | searches for the fewest feasible segments under the given budget |
A float ceil(sqrt(2n)) for the least peak | one too many at , wrong at large | math.isqrt and integer adjustment |
| Counting the last segment as recomputed | recomputation off by | recompute is n_layers - sizes[-1] |
| A budget check off by one | peaks one unit over the budget | last segment b - k + 1, so its exactly; earlier segments at most b - i |
Normalizing inside hvp_fd | returns | uses as given; the step is |
Where this leads
Section titled “Where this leads”Looking back, the cross-entropy VJP of Matrix differentials, the trace trick, and closed-form VJPs, for a linear model, is the gradient whose is compared with PyTorch; the forward-versus-reverse cost counts of the chapter problem set are behind “two gradients per ”; and Jacobians, the multivariable chain rule, and numeric JVP/VJP supplies the Hessian and the second-derivative test.
Looking forward, checkpoint_sequential in Mixed precision, loss scaling, gradient accumulation, and activation checkpointing runs the segments with checkpoint_schedule and recomputes them in backward, which is what lets the capstone train with checkpointing on a laptop. In the Optimization chapter, an optional extension runs power iteration on hvp_fd to estimate and compare the learning rate with .
Production tools extend each piece. torch.autograd.functional.hvp and torch.func.jvp(grad(f)) give exact forward-over-reverse products (Pearlmutter’s -operator) at the cost of two backward passes (torch/autograd/functional.py). PyHessian computes Hessian spectra of real networks by power iteration and stochastic Lanczos, from only (pyhessian/hessian.py). torch.utils.checkpoint.checkpoint_sequential uses uniform segments, RNG state replay, and non-reentrant saved-tensor hooks (torch/utils/checkpoint.py). Checkmate (Jain et al., 2020) solves optimal rematerialization for arbitrary graphs as an integer program (checkmate/core/solvers/ in the checkmate repository).
Further reading:
- Pearlmutter, “Fast Exact Multiplication by the Hessian” (Neural Computation, 1994).
- Chen, Xu, Zhang, and Guestrin, Training Deep Nets with Sublinear Memory Cost (2016).
- Griewank and Walther, Evaluating Derivatives, chapter 12 (checkpointing).
Key terms
Section titled “Key terms”- Hessian-vector product: , the derivative of the gradient along , computed without forming .
- Central difference: , whose even-order error terms cancel, leaving .
- Activation checkpointing: saving only some layer inputs in the forward pass and recomputing the rest during backward.
- Segment: a run of consecutive layers that is recomputed from its saved input during backward.
- Peak memory: , the most saved layer inputs held at once under a schedule.
- Pearlmutter’s -operator: forward mode applied over reverse mode, giving an exact at the cost of about two gradients.
Summary
Section titled “Summary”- The Hessian-vector product is the derivative of the gradient along , so two gradient calls give it to without forming the Hessian.
- On a quadratic the central difference is exact at every , because the gradient is affine; a dense finite-difference Hessian must be symmetrized.
- Reverse mode keeps one saved input per layer. Recomputing segments trades forward time for memory: the peak is and the extra work is every layer outside the last segment.
- Uniform segments of layers peak near ; shrinking segments (sizes ) reach the optimum , and under a budget the best schedule is found greedily.
- Exact integer arithmetic (
math.isqrt) is required for the least peak at large .
Review questions
Section titled “Review questions”-
Why does
_grad_atusenp.array(...)rather thannp.asarray(...)?Answer
np.asarrayreturns the same object when it is already a float64 array. Ifgrad_fnreturns its argument (or a buffer it reuses),gpwould be that array, and the second call could overwrite it, orgpandgmwould be the same object and the difference 0.np.arraycopies. -
On the quartic of the hand example, how does the error change if goes from 0.1 to 0.05, and what would it do with a one-sided difference?
Answer
Central: the error is , so it goes from to , a factor 4. One-sided: the error is about , from about to , a factor 2.
-
Why is the peak and not ?
Answer
While segment is rebuilt, only the inputs of the earlier segments are still held: units, not . The inputs of later segments have already been freed after their own backward. So a large segment early costs less than the same segment late; the second formula overcounts whenever the largest segment comes first, and an optimizer using it would prefer worse schedules.
-
Why does
checkpoint_schedulestop at the first feasible ?Answer
Recompute is , and the largest possible last segment, , shrinks as grows. So the fewest segments that can still cover the remaining layers gives the largest last segment and the least recompute.
-
Why does
hvp_fdnot normalize ?Answer
is linear in ; a caller doing power iteration or Newton-CG expects exactly . Normalizing inside would return , which is a different quantity. The step size is , so a caller with a huge or tiny scales it before calling.
-
What is the least peak for a 16-layer stack, and how does it compare with uniform segments?
Answer
The least with is 6 (), reached by shrinking segments. Uniform segments of 4 give .