Change
How does a model with billions of parameters find out which way to change each one?
Full training of a model like Qwen3-4B needs four billion derivatives at every step, and Part 1 took its gradient on trust. This part builds the calculus. The derivative is the best linear approximation, the gradient points along steepest ascent by Cauchy-Schwarz, and the Jacobian is the local linear map, with the chain rule as a product of Jacobians. Real layers are differentiated (the matrix product, the softmax, layer normalization), and forward and reverse mode are counted: for one loss and many parameters, backwards wins by a factor of the parameter count. Backpropagation is done by hand and then written as the series' own autodiff library, checked against finite differences, and used to train Part 1's letter model. The part turns to what a computer does to the mathematics: floating point, cancellation, the gradient check's V-curve, and memory traded for recomputation. It ends with curvature (Newton's method, Hessian-vector products, descent on a quadratic and saddles), constraints (Lagrange multipliers, KKT and duality) and differentiating through a fixed point.
What you need. Derivatives of one variable help but are rebuilt in chapter 1; matrices as in Part 3.
- Mathematics and history
- gradients, Jacobians, reverse-mode autodiff (the series' own library), numerics, curvature, Lagrange and KKT, implicit differentiation
What you will be able to do
Undergraduate
- Explain a derivative as the slope of the best line, and a gradient as the direction of steepest ascent.
- Backpropagate by hand through a small network with one hidden layer, and check the result with a finite difference.
- Train a small model by gradient descent and read its loss curve.
Master's
- Derive the Jacobian of the softmax and the vector-Jacobian products of a matrix product.
- Implement reverse-mode autodiff on a graph in topological order, and count forward against reverse mode for a given network.
- Derive the stable step sizes and the rate (kappa - 1)/(kappa + 1) of gradient descent on a quadratic, and compute a Hessian-vector product without the Hessian.
Research
- State the KKT conditions and the assumptions under which strong duality holds, and derive the dual of the hard-margin SVM.
- Derive the implicit derivative of a fixed point, and state when it exists and when the iteration that finds the fixed point converges.
Engineering
- Choose the step of a gradient check from the precision in use, and recognise cancellation and overflow in a loss.
- Trade activation memory against recomputation with checkpoints, and say what the count leaves out.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 16 min · Master's 46 min · Research 52 min · Engineering 25 min.
- 0Four billion derivativesUndergraduate2 min
- 1The derivativeUndergraduate3 min
- 2Many inputs: the gradientUndergraduate3 min
- 3Maps that bend: the JacobianMaster's2 min
- 4The Jacobians of real layersMaster's3 min
- 5Forwards or backwards?Master's3 min
- 6Backpropagation, by handUndergraduate3 min
- 7Calculus in a few pages of codeMaster's2 min
- 8Training with our libraryUndergraduate3 min
- 9Numbers in a computerEngineering4 min
- 10Cancellation, and the gradient checkEngineering3 min
- 11Memory: storing or recomputingEngineering3 min
- 12Curvature, and Newton's methodMaster's2 min
- 13Hessian-vector productsMaster's2 min
- 14Descent on a quadratic; saddlesMaster's3 min
- 15Constraints: Lagrange multipliersMaster's3 min
- 16Inequalities, KKT and dualityResearch3 min
- 17Differentiating through a fixed pointResearch3 min
- Recap, problems, and what comes nextAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
Four billion derivativesUndergraduate2 min
In part one we worked out a single derivative by hand: the gradient of the surprise with respect to the scores, the model's guess minus the truth, for natural-log cross-entropy. In bits there is an extra factor of one over ln two. The recorded parameter counts are about million for GPT-2 and billion for Qwen3-4B. Each source is labeled on screen. In full-parameter training, every step needs the derivative of the loss with respect to every trainable parameter, and nobody works those out by hand.
The mathematics is three centuries older than the computers that run it. Leibniz printed the calculus in 1684, while Newton had his own, his fluxions. In 1788 Lagrange showed how to optimize under constraints, and in 1847 Cauchy proposed walking downhill. Karush, and then Kuhn and Tucker, added inequalities. Then came programs: in 1964 Wengert had one carry derivatives along with its values, and in 1970 Linnainmaa ran the chain rule backwards. In 1985 a standard fixed how computers round, and in 1986 Rumelhart, Hinton and Williams demonstrated learning hidden representations with backpropagation. From 2010, libraries did all of it automatically, and some of today's largest models train with numbers only eight bits long.
This is Part 4 of AI, Built: change, the calculus of learning. In it: derivatives as the best straight-line approximations, and the derivatives of real layers; the two ways to run the chain rule, counted; backpropagation by hand, then our own library, and a model trained with it; what goes wrong with numbers in a computer; memory; curvature, from Newton's method to the shape of a trained network's landscape; and optimizing under constraints, which ends with differentiating through an equation's solution.
1The derivativeUndergraduate3 min
Zoom in on a smooth curve, closer and closer, and it starts to look like a straight line. The slope of that line is the derivative: how much the output changes, for each small change of the input.
Written down: f at x plus a small step h, is about f of x, plus the derivative times h. The smaller the step, the better the guess. A derivative is the best straight-line description of a function, near one point.
The idea is Leibniz's, in print in 1684, and Newton's, who had worked it out in the 1660s and called it fluxions. Here is the precise version. A function is differentiable at x if one number, the derivative, makes the straight-line guess so good that its error shrinks faster than the step itself. Measure it, for Part 1's surprise curve. On these logarithmic axes, the error with the true slope falls with a slope of 2.00: like h squared. Use a slope just ten percent off, and the error falls only like h, a slope of 1.01. Exactly one line wins as the step shrinks. That is what best means.
Let's use the definition once, on the surprise, log base two of one over p. The change over a step h is a difference of logarithms, which is the logarithm of a ratio. Near one, the logarithm is its own tangent: log of one plus u is u, plus an error smaller than u. So the number in front of h is minus one over p log two. At a quarter, that's -5.77 bits per unit of p: the slope the lens showed.
A few derivatives come up over and over. The exponential is its own derivative. The logarithm's derivative is one over x. That's why the surprise climbs so steeply as p shrinks. And the chain rule, for a composition: f of g of x means do g first, then f. Writing f prime for the slope of f, the derivative of f of g of x is f prime at g of x, times g prime at x. Change flows through a composition, multiplying as it goes.
2Many inputs: the gradientUndergraduate3 min
A loss depends on many numbers at once. With two, it's a surface over a plane. Nudge one number while holding the other still, and you get a partial derivative: the slope along that axis. The best flat approximation to a surface near a point is a plane, the tangent plane, tilted by those two slopes; its error falls like the square of the distance, just as the line's did: measured, a slope of 2.00. Collect the slopes into one vector, and you have the gradient. It points uphill, and, as we'll prove, the steepest way there is. So step the other way, again and again, and you slide down into a valley.
Why steepest? At a differentiable point, pick any direction, a unit vector u, and ask for the slope that way. The tangent plane answers it: the slope along u is the gradient dotted with u. By the Cauchy–Schwarz inequality from Part 3, a dot product is at most the product of the lengths, and u has length one: no direction climbs faster than the length of the gradient. If the gradient is nonzero, the maximum occurs in its positive direction. So the gradient's own direction is the steepest way up, its opposite the steepest way down, and the directions at right angles give zero first-order change. If the gradient is zero, every directional derivative is zero.
Seen from above, the surface becomes a map of contour lines, each at one height. Swing a direction around the point and read the slope. It's largest straight along the gradient, zero along the tangent to the contour line, and most negative pointing against it. Measured by finite differences in seven hundred and twenty directions, the steepest slope is , the gradient's length is , and the two directions are degrees apart: .
Walking downhill this way is a standard optimization method. In 1847 Augustin-Louis Cauchy, wanting to solve the equations of an orbit, wrote them as a sum of squares and proposed stepping against its gradient. Written today: the next point is the current one, minus a step size eta times the gradient there. How large a step, and how fast it arrives, depends on the curvature, which comes in chapter fourteen and again in Part 11.
3Maps that bend: the JacobianMaster's2 min
Now let a function take a whole vector to another vector, the way a layer of a network does. Here's one that bends the plane: the grid lines curve. But zoom in close to any point, and the curves straighten out. Up close, every smooth map looks like a matrix: its Jacobian, the table of all its partial derivatives.
In general, a map from n numbers to m numbers has an m by n Jacobian: one row per output, one column per input, the one matrix that makes the straight-line guess best. A gradient is the special case of a single output. For this two-dimensional map, the absolute value of the Jacobian's determinant, from part three, gives the local area factor. And the chain rule for maps is matrix multiplication: the Jacobian of one map after another is the product of their Jacobians, each taken where its input lands. Applying this chain rule backwards is the basis of backpropagation, as chapter five will show.
Chain many maps and their Jacobians multiply. The product's norm is at most the product of the individual norms; it need not equal it. Here is a deep stack of tanh layers, of them, with random weights scaled by a gain. We plot the mean log of the product's largest singular value, with the range across seeds. This is the maximum possible amplification, also for the transposed product in backpropagation, not what happens in every direction. A norm below one shrinks every direction; a norm above one allows growth in some direction. At gain , the mean log size ends at . At gain , it ends at . Such products help explain vanishing and exploding gradients. Parts 9 and 10 return to how initialization affects their scale.
4The Jacobians of real layersMaster's3 min
Real layers first. The most common one is a matrix product: inputs X, one row per token, times weights W. A weight in row j and column k touches only column k of the output, so its gradient collects the gradient arriving from above, G, times the inputs it multiplied. That sum is itself a matrix product: X transposed times G. And the gradient for the inputs, which flows on to the layer below, is G times W transposed. Notice what we never wrote down: the Jacobian itself. For one of GPT-2's matrices over 1,024 tokens it would hold 7.4 trillion numbers. Backpropagation needs only its product with G, which costs about as much as the layer did on the way forward.
Next, the softmax, which turns scores into probabilities. Differentiate with the quotient rule. Split the fraction, and every entry is p i times delta i j, minus p i times p j. As a matrix: the probabilities on the diagonal, minus the outer product of p with itself. Here it is for five scores, computed, and matching our library. Its rows add to zero, because adding the same number to every score changes nothing; and it is symmetric with no negative eigenvalues, one of them zero. Again we never need the matrix: its product with a vector takes n steps instead of n squared, which matters with GPT-2's fifty thousand tokens in the vocabulary. Joined with the cross-entropy, it collapses to Part 1's q minus p when the loss uses natural logarithms; a loss in bits adds a factor of one over ln two.
Last, layer norm: subtract the mean of the vector, divide by its spread, before any learned scale and shift. The mean and the spread move when x moves, so the Jacobian has two corrections: a projection that removes the direction of all ones, and another that suppresses the radial direction, all divided by sigma. Computed for six numbers, 2 eigenvalues have magnitude below one thousandth, and the rest are equal. Mean shifts are removed exactly; scale changes are strongly suppressed, with a small remaining sensitivity from epsilon.
5Forwards or backwards?Master's3 min
There are two ways to use a Jacobian without ever writing it down. Push a direction forward: if the inputs move by v, the outputs move by J v, a Jacobian-vector product. Or pull a sensitivity back: if the outputs matter with weights u, the inputs matter by u transposed J, a vector-Jacobian product. A network is a chain of maps, from its parameters, theta, to the loss, and its Jacobian is a product of the links' Jacobians. A JVP multiplies that product from the right, in the order the network runs: forward mode. A VJP multiplies from the left, starting at the loss: reverse mode. Either one is about one pass through the network. For the whole Jacobian you need a JVP per input, or a VJP per output.
Let's count. These are networks with two hidden layers of sixty-four, with n inputs and m outputs, from one to two hundred and fifty-six. We count dense derivative matrix products and tanh multiplications, relative to a reference primal pass; this is not every scalar operation. The full Jacobian takes n forward directions. Or m reverse directions. Few inputs and many outputs favor forward mode; many inputs and few outputs favor reverse mode. Timings include primal computation and implementation overhead, separately from the derivative count. In this recorded benchmark,
Training is the extreme case: every parameter is an input, and the loss is a single output. Forwards, you carry a matrix with a column for every parameter. Backwards, a single row, the size of the layer you've reached. Our small classifier has parameters. Forward mode pushes directions through it: counted, times the dense derivative work of one backward pass, counting matrix products and tanh multiplications. Only parameter gradients are requested, not an input gradient. The measured gradient difference is shown. For GPT-2 the same column-by-column strategy would require directions against one reverse pass. That is why standard large-parameter gradient training usually uses reverse mode, called backpropagation for neural networks. Forward and hybrid methods still have other uses.
Reverse mode was found more than once. Seppo Linnainmaa described it in his 1970 master's thesis in Helsinki, to work out how rounding errors accumulate through a program. Paul Werbos proposed it for training networks in his 1974 thesis, and in 1986 David Rumelhart, Geoffrey Hinton and Ronald Williams showed, in Nature, what it could do: networks that learn their own internal representations. Control engineers had already used the same backward recursion around 1960, to steer rockets along the best flight paths.
6Backpropagation, by handUndergraduate3 min
Let's run it by hand, on the smallest network there is, drawn as a flowchart of operations called a computation graph, each circle a node. One input, x, times one weight, plus one bias, a shift; then a squashing function, the sigmoid, an S-curve that presses any number into the range zero to one; and a squared error: the miss from the target y, squared. Forwards first: the values flow from left to right, and end in the loss, 0.854.
Now backwards. Start at the loss, with a gradient of one, and walk back. Each step multiplies the gradient arriving from the right by its own local derivative, and passes the result to the left. At the weight, the gradient is minus 0.259: raise the weight a little, and the loss falls by about a quarter as much. No step needed to know anything but its own derivative.
One more rule. When a value feeds into two places, the gradients coming back from both are added together. That's the whole algorithm: visit the nodes in reverse order, and let each one pass its gradient back to its inputs.
Now a real network, in matrices: an input x, a layer with weights W one and a tanh, a second layer, a softmax and the cross-entropy. Call the gradient with respect to a layer's pre-activation z its delta, the error signal there. At the top, delta two is Part 1's answer: the predicted probabilities minus the one-hot truth. Each weight in W two multiplies one input into one output, so its gradient is that output's delta times that input: an outer product, delta two times a one transposed. To go down a layer, pull delta back through W two, which for a matrix means multiplying by its transpose, and then through the tanh, multiplying by its slope. And the same rule again: the gradient of W one is delta one times x transposed. Those four lines are backpropagation, for any depth.
Here is that outer product for one example, computed: the error signal at the hidden layer, a column, times the input, a row. Every row of the result is a multiple of the same input, so the matrix has rank at most one. Here its measured rank is : . A batch adds such matrices, so its rank is at most the batch size and the matrix dimensions. Here it reaches rank , . That structure comes back when models are fine-tuned with low-rank adapters in Part 27. And these hand-derived gradients match our library and PyTorch with the recorded maximum absolute differences shown here, including zero if they coincide.
7Calculus in a few pages of codeMaster's2 min
Here it is in code: the series' own automatic differentiation, about 180 lines in all. Every operation remembers its inputs, along with a small function that sends a gradient back to each one. Here's multiplication: the gradient for one input is the incoming gradient, times the other input. And backward visits the graph in reverse order, adds up what arrives at each node, and passes it on.
Backward needs an order: a node may pass its gradient on only after every use of it has reported. A depth-first search through the graph gives exactly that, a topological order, each node after its inputs. Here is chapter six's example, numbered by our library in that order. Written out, the graph is a list, each line one elementary operation on earlier lines. In 1964 R. E. Wengert had programs keep such lists to carry derivatives along with their values; tools today call the record a tape. Forwards, the values run down the list. Backwards, the list runs from the bottom up, each line sending its gradient to the lines it used.
Does it work? Nudge each checked number a millionth in both directions, take the central difference, and compare: . Chapter ten explains the limits of that numerical check. Against PyTorch, an independent automatic differentiation implementation, . These are absolute errors, not a count of matching printed digits.
Ours is the smallest member of a long family. In 1980 Bert Speelpenning compiled reverse mode from ordinary programs. In 2010 Theano, from Montreal, had you declare a graph first and then compiled it, gradients included. In 2015 Chainer recorded the graph as the code ran, define by run, while TensorFlow kept a static graph. PyTorch, in 2017, ran define by run on GPUs, as ours does on the CPU, and in 2018 JAX traced whole functions and transformed them: gradients, both kinds of product, compilation, batching. The line you write is almost the same in all three.
8Training with our libraryUndergraduate3 min
Before we train, look at the first gradient. Differentiate the average natural-log surprise, in nats, with respect to one score, z i j: every pair of letters that starts with i adds its guess minus its truth. Collected, that's the share of pairs starting with i, times Part 1's q minus p hat: the model's probabilities minus the counted ones. At the start every guess is one twenty-seventh. Computed on the books, the library's gradient matches the formula, and the biggest pushes, in red, go to the commonest pairs. Gradient descent is counting, done a little at a time. The plots report bits by dividing the natural-log loss by log two.
Now let's train. Counting gives a reference of bits per letter. The training loop instead samples letter pairs from the books. It learns 729 raw scores, initially zero, with Adam. The picture shows their row-normalized natural log probabilities, not the raw scores. Its scale is shared with the counted comparison: values below minus eight are equally dark. Underneath, samples use the same random dice at every checkpoint. Heatmaps are after the labeled update; the curve records minibatch loss just before that update. The final train and new-text numbers use the full respective corpora.
Raw scores can shift by a different constant in each row without changing probabilities, so the comparison uses normalized logs. Maximum likelihood connects the counting solution to the optimization objective; a finite run need not reach it. The same optimization loop, with richer models, trains the later systems in this series.
How large a step can plain full-batch gradient descent take here? Chapter fourteen will derive the local quadratic stability scale, two over the largest curvature. It is not a global guarantee as curvature changes. At the start, every score zero, the Hessian's largest eigenvalue is , which would allow steps up to . But the counting solution has curvature , giving a local scale of .
9Numbers in a computerEngineering4 min
Every number in this series so far has been a float. In 1985 one standard, IEEE 754, designed largely by William Kahan, specified basic operations and rounding. The same format, operation and rounding mode agree; changing the order or fusing operations can change a program's answer. A normal finite float has a sign, an exponent and a mantissa: one point the mantissa, times two to the exponent. Exponent bits buy range; mantissa bits buy precision. Float32 has eight and twenty-three. Bfloat16 keeps float32's eight exponent bits and only seven for the mantissa; float16 has five and ten; and the eight-bit formats of 2022 have four and three, or five and two. The E4M3 finite variant shown here reserves NaN but has no infinities.
The gap between neighbouring floats, the unit in the last place, grows with the number itself: a staircase, one step per power of two in the normal range. Normal relative precision is about decimal digits in float32, in bfloat16. Below the smallest normal number, subnormals instead have a fixed absolute gap: two to the minus twenty-four for float16. Relative error can then grow to one on underflow. The plot enumerates format values; some device arithmetic flushes subnormals to zero. Each format also ends somewhere. Float16 stops at , the four-bit-exponent FP8 at , while bfloat16 keeps float32's exponent range. That is why bfloat16, Google's format for its TPUs, usually avoids the loss scaling often needed with float16. Part 17 covers the hardware, and Part 19 how models are squeezed into fewer bits still.
Rounding has consequences. In bfloat16, one plus one two-hundred-and-fifty-sixth is one, and 257 is 256. Even 0.1 is not 0.1 in float32. Add 0.01 ten thousand times; the answer should be 100. Float32 gets . Float16 stalls at , and bfloat16 at : once the sum is big enough, the gap between floats is more than twice 0.01, and every addition rounds back to where it was. In this experiment, keep each input in bfloat16 and accumulate sequentially in float32: , because 0.01 itself was rounded to . Mixed-precision matrix units use the same wider-accumulation idea; their reduction order can differ.
Range has consequences too. The softmax exponentiates its scores, and e to the power is already too big for float32; in float16, e to the is. So scores of a thousand, nine hundred and ninety-nine and nine hundred and ninety-eight become infinities, and the probabilities become not a number. The fix is to subtract the largest score first. The log of a sum of exponentials is the maximum, plus the log of a sum in which every exponent is at most zero. For finite scores, no shifted exponential overflows, and the largest term is exactly one, so the sum can't vanish either. Very small terms may underflow harmlessly to zero. The same three scores now give clean probabilities, and our library's log-softmax does exactly this, in its first line.
10Cancellation, and the gradient checkEngineering3 min
One more way numbers go wrong, and it explains how to check a gradient. Take one minus cos x, over x squared: for small x it is very nearly one half. Computed as written, in float32, the error explodes as x shrinks, and at x of ten to the minus four, cos x rounds to exactly one, and the answer is zero. This is cancellation: subtracting two nearly equal numbers keeps their rounding errors but loses their size, so the relative error grows like one over x squared, just as predicted. Float64 only delays it. Rewritten without the subtraction, the same formula avoids that cancellation over this sampled range. Errors below the display floor, including zero, are drawn at the floor.
A gradient check is a cancellation on purpose. Expand f a step either side of x, by Taylor's theorem. Subtract and divide by two h: the even terms cancel, leaving the derivative plus a truncation error that shrinks like h squared. But each value of f was rounded, by about u times f, u the unit roundoff, and the subtraction keeps those errors while dividing by a tiny 2 h: a rounding error that grows like one over h. Add the two, and set the derivative to zero: this local model predicts a step near the cube root of three u times the absolute value of f over the absolute third derivative, when that derivative is nonzero. Too large a step and Taylor's error wins; too small and rounding does.
Here it is measured, on chapter seven's network, along the same eight random directions in both precisions. The solid curves are pointwise median errors, and the shaded bands show the range. First inspect float64 for the competition between truncation and rounding. Now compare float32. Each dot marks the minimum of the median curve actually drawn; it is not the median of the eight best steps. For comparison, The local error model guides the step choice; the measured curve checks it. Values outside the displayed error range are shown at its stated floor or ceiling.
11Memory: storing or recomputingEngineering3 min
Reverse mode has a price, and it is memory. On the ordinary forward pass, every layer's output is kept, because on the way back each step needs it: a layer's Jacobian depends on its input. Only as the backward pass reaches a layer can its activations be freed. So the memory grows with the depth, and with the batch and the width too; training large models, activations can become a major share of GPU memory, alongside parameters and optimizer state, which is Part 18's problem.
The way out is to trade memory for time. Keep only every k-th output, a checkpoint; when the backward pass reaches a segment, run that segment forward again from its checkpoint, and keep its k outputs just while they're needed. The memory is n over k checkpoints plus one segment of k. It's smallest where its slope is zero, at k equal to the square root of n, where it is two root n instead of n. The cost: every segment is recomputed once, about one extra forward pass. Tianqi Chen and colleagues brought this to deep networks in 2016; Andreas Griewank had shown in 1992 that recursive checkpoint schedules can use logarithmic storage and logarithmic recomputation overhead, relative to the original linear evaluation cost: total work of order n log n in that model. Today it is one line in PyTorch, and FlashAttention uses the same trade, recomputing attention's weights in the backward pass instead of storing them, as Part 19 shows.
Counted in an ideal activation-liveness model, on a chain of layers. The most activations held at once follows n over k plus k: if you keep everything, and at the minimum. The minimizing intervals span k of to . The price is in evaluations: layers run forward if everything is kept, with checkpoints, and if nothing is kept and every input is recomputed from the start. Timed on a deeper, wider chain, checkpoints cost times the time in this benchmark. This counts logical activation lifetimes, not measured physical memory; parameters, gradients, allocator behavior and temporary workspace are excluded.
12Curvature, and Newton's methodMaster's2 min
The gradient says which way is downhill. It doesn't say how the slope itself is changing. That's the second derivative, curvature. With many inputs it's a matrix of second derivatives, the Hessian. For a twice continuously differentiable function it is symmetric, so, from part three, it has perpendicular eigenvectors, the directions of pure curvature, and its eigenvalues say how sharply the surface bends along each. This quadratic is a bowl when both are positive. With mixed signs it is a saddle at its stationary origin. Mixed curvature at an arbitrary point does not establish stationarity.
The Hessian gives a better step. The first derivative made the best straight line; with the second, the local quadratic. When the Hessian is positive definite, this quadratic has a minimum. Solve for that minimum, where its gradient is zero: the step is minus H inverse times the gradient. That's Newton's method. Newton used the idea in 1669 for roots of equations, Raphson simplified it in 1690, and Thomas Simpson extended it in 1740 to several variables and to finding minima.
A test: logistic regression, a classifier Part 6 builds, with two correlated features. The curvature ratio at the reference solution is . Gradient descent uses the conservative step one over L, where L globally bounds curvature. These are iteration counts, not equal amounts of work per step. Local quadratic convergence requires a sufficiently close starting point and a nonsingular Hessian with suitable smoothness; three digit counts alone do not certify it. The catch is the Hessian itself: each step solves a linear system with it, and for a billion parameters it would have a billion squared entries. The next chapter uses curvature without ever building it.
13Hessian-vector productsMaster's2 min
A Hessian with a billion rows is out of reach, but its product with one vector is not. H times v is how the gradient changes as you move along v. Since v is fixed, that's the gradient of a single number, the gradient dotted with v. And a gradient of one number is what reverse mode does cheaply: run it once more, through the computation of the gradient itself, and you get H v exactly, for a small multiple of the cost of a gradient. Barak Pearlmutter published the trick in 1994.
Check it on the stored final parameters of a small network. Against the full Hessian, the maximum product discrepancy is . In this benchmark a product takes times a gradient's time. The best recorded finite-difference relative error is . Repeated products and normalization are power iteration. With a strictly dominant eigenvalue magnitude and a nonzero initial projection on its eigenspace, they approach that eigenspace. The eigenvalue may be negative: largest magnitude is not largest algebraic value. Display floors and ceilings are stated below the plots.
Now watch a landscape change as a network learns three interleaved spirals. This network has parameters, with its full Hessian computed at stored checkpoints. Accuracy is on the training examples. The signed-log plot divides each spectrum by its own absolute spectral radius, so its shape and absolute size must be read separately. Final counts: Absolute scale: The cutoffs are stated relative to each checkpoint's spectral radius. High-positive is a selected cutoff, not a fitted statistical outlier test. Sagun and colleagues studied concentration of neural network Hessian spectra in 2016; this small training example reports its own measured outcome.
14Descent on a quadratic; saddlesMaster's3 min
How fast is downhill? On a quadratic bowl with a positive-definite Hessian, gradient descent can be solved exactly. Each step multiplies the position by I minus eta H. In the Hessian's eigenvectors that matrix is diagonal, so each coordinate shrinks on its own, by one minus eta times its eigenvalue. Every factor must be less than one in size, so the step must be positive and smaller than two over the largest curvature. And the slowest coordinate sets the pace. The best step balances the two extremes, and the rate is kappa minus one over kappa plus one, where kappa, the condition number, is the largest curvature over the smallest. This factor bounds the position-error norm; the quadratic objective shrinks by at most its square.
Here is a valley with kappa of twenty-five: it bends twenty-five times more sharply across than along. The steepest way down points mostly at the opposite wall, so the steps zigzag from wall to wall and crawl along the floor. For the objective to fall below one percent of its initial value, . Momentum carries speed from step to step. Part 11 derives the method. Newton's step undoes the curvature and lands at the bottom at once.
Measured on bowls from kappa of one to a thousand: the rates, in orange, . The grey curve is the large-kappa norm-error estimate. At kappa , . Triangles mark capped or unresolved runs, not converged counts. The theoretical stability boundary is two over the largest curvature. Real losses are not quadratics, but this is the calculus behind every learning-rate rule, and Part 11 builds the faster methods on it.
A saddle can delay descent. Here's a surface with a saddle at the centre and a minimum above and below it. Start almost on the line through the saddle, a tiny distance y nought off it. The walk slides in towards the saddle, where the gradient nearly vanishes, and waits, until the tiny offset has grown enough to fall off. Near the saddle the offset grows by one plus eta each step, so the local prediction is logarithmic in one over y nought. We fit only runs that reached absolute y above one half; . Capped runs are marked separately. Start exactly on the line and it never leaves: the gradient falls to times ten to the minus , at a point that is not a minimum. Only the Hessian, with its negative eigenvalue, tells them apart. In practice the noise of stochastic gradients kicks a network off; Yann Dauphin and colleagues argued in 2014 that in many dimensions saddles, more than bad minima, are what slow training.
15Constraints: Lagrange multipliersMaster's3 min
Often the numbers aren't free: probabilities must add to one, a budget must be kept. Here, minimize f, whose contours are these ellipses, but only on the circle. Walk along the circle and watch two arrows: the gradient of f, and the gradient of the constraint, which points straight out of the circle. Wherever the gradient of f has a part along the circle, you can slide against that part and go lower. So at the constrained minimum that part is zero: the two gradients are parallel. Joseph-Louis Lagrange turned that picture into a method in 1788, in his Mécanique analytique.
Write it down: at the constrained minimum, the gradient of f is a multiple of the constraint's gradient, minus lambda times it. Lagrange's device folds the constraint into a single function, the Lagrangian, f plus lambda times g. Stationarity in x and lambda gives necessary conditions for a regular constrained optimum, not a guarantee of a minimum. The derivative in lambda gives back the constraint. At the numerical circle candidate, the multiplier is . At a regular optimum it is a signed price: how the optimal value changes as the circle's squared radius changes.
A famous constrained problem: a die whose average roll is 4.5, not 3.5. Which probabilities assume the least beyond that? The ones with the most entropy. Set the Lagrangian's derivative to zero, with one multiplier for each constraint, and the answer is a softmax: each face's probability is e to the beta times the face, normalized. Computed, beta is . Edwin Jaynes made this a principle of inference in 1957. It's where the softmax comes from: it is the maximum-entropy distribution with a fixed average score. In this convention beta is inverse temperature, one over T, and it is the score-constraint multiplier.
The same algebra gives reinforcement learning one of its closed forms. Maximize the expected reward, minus a positive beta times the KL divergence from a positive reference policy. Here beta names the KL penalty, so it plays the temperature role, unlike the inverse-temperature beta for the die. With the constraint that the probabilities add to one, the best policy is the reference, reweighted by e to the reward over beta. Here for six actions. Part 27's direct preference optimization starts from this formula.
16Inequalities, KKT and dualityResearch3 min
Most constraints are inequalities: a probability can't be negative, a margin must be at least one. William Karush worked out the conditions in his 1939 master's thesis; Harold Kuhn and Albert Tucker found them again in 1951. Under a constraint qualification, at a minimum there are multipliers mu, one per constraint, with the gradient of the Lagrangian zero, every constraint met, every multiplier non-negative, and each multiplier times its constraint equal to zero: complementary slackness. Either the minimum is inside and the wall is idle, its multiplier zero, or the minimum is on the wall. Its multiplier may be positive or zero; in this right-hand example it is positive and measures how hard the wall pushes.
The multipliers lead to a second problem. Fix them, and ask how low the Lagrangian can go over x: that's the dual function, q of mu. For any feasible x the added terms are at most zero, so the dual function is a lower bound on f, everywhere it can be met. The best lower bound, d star, is at most the true minimum, p star: weak duality, true for every problem. For convex problems with a strictly feasible point, the two are equal: strong duality. Both give the same optimal value.
Two small examples. Minimize x squared, keeping x at least one. Its dual function is a hump that rises to touch the true minimum, one, exactly: no gap. Now a double well, the same kind of constraint, and no convexity. On finite grids, the estimated primal value is and the best estimated dual value is , a difference of . These are grid estimates, not a certified continuous dual bound. The exact weak-duality theorem still holds; this numerical picture illustrates how a gap can arise.
Duality's most famous use: the support vector machine of Part 6. Find the widest street between two classes: the smallest w that puts every point at least one unit of margin from the line. Its dual has one multiplier per point, and depends on the points only through their dot products, which is what lets kernels in. Minimizing over the free intercept also requires the label-weighted multipliers to sum to zero. We attempted separate primal and dual solves on points. The candidate objective values are displayed with six decimal places. We ring the points whose multipliers exceed the stated numerical zero threshold; points have margins within the stated tolerance of one. At an optimum, a positive multiplier forces a point onto a margin, but a margin point can have a zero multiplier in degenerate data. Bernhard Boser, Isabelle Guyon and Vladimir Vapnik built the method on this dual in 1992.
17Differentiating through a fixed pointResearch3 min
Some layers aren't a fixed list of steps. A deep equilibrium layer feeds its output back into itself until nothing changes: its output is the fixed point z star, which satisfies z star equals f of z star and theta. How do you backpropagate through that? Differentiate both sides of the equation. Collect the terms: the derivative of the solution is the inverse of I minus J, times the direct derivative, as long as that inverse exists, which is the implicit function theorem. For a loss, run it as a vector-Jacobian product: one linear solve at the fixed point, however many iterations it took to get there. No history of iteration states is needed, but parameters, local derivatives and the linear solver still take memory. If the loss also depends directly on theta, add that direct derivative.
Check it on a layer with an -dimensional state; . The displayed residual and contraction bound describe this iteration solver; invertibility of I minus J is the separate differentiation condition. The usual alternative is to unroll: run K iterations and backpropagate through all of them with our library. As K grows, that gradient is compared with the implicit candidate. For the final comparisons, . This is not a certified bound on fixed-point accuracy. Unrolling stores every iteration; implicit differentiation avoids that history while retaining the equilibrium state and linear-solver workspace.
And it trains. A deep equilibrium model with a -dimensional state and trainable scalars is fitted using implicit candidate gradients, with its feedback matrix kept at spectral norm at most . The stored fits replay the run; , and . Capped solves are not counted as converged equilibria. For the final comparison input, . Shaojie Bai, Zico Kolter and Vladlen Koltun proposed such models in 2019. The same trick differentiates through an inner optimization, in meta-learning, or through a solver used as a layer: wherever the answer is defined by an equation rather than a recipe.
Recap, problems, and what comes nextAll tracks2 min
Let's take stock. A derivative is the best straight line, the one whose error shrinks faster than the step; a gradient, the steepest direction, by Cauchy–Schwarz; a Jacobian, the best matrix, and real layers' Jacobians need not be formed, only multiplied. For the full Jacobian, forward mode pays per input and reverse mode per output, so training runs backwards: backpropagation, whose weight gradients are outer products of an error signal and an input. We built it, checked it and trained with it. Floats round and cancel, so softmaxes subtract their maximum and gradient checks pick their step. Checkpoints trade memory for recomputation work in an ideal activation-memory model. Curvature sets the pace of descent, and Hessian-vector products reach it cheaply. Our measured spectrum distinguishes directions using stated relative cutoffs. Constraints bring multipliers, KKT and a dual problem: positive multipliers imply active constraints, and a free SVM intercept adds a label-weighted zero-sum constraint. An equation's solution can be differentiated when its local implicit-function conditions hold.
This is the engine of everything that follows. Our library trains the series' first neural networks in Part 9; Jacobians multiplied through depth decide whether deep networks can learn, in Parts 9 and 10; curvature, saddles and better optimizers fill Part 11; duality builds the support vector machine in Part 6, and the closed form of chapter fifteen becomes direct preference optimization in Part 27; and number formats and memory come back in Parts 17 to 19.
Here are six problems to try, from the softmax's Jacobian to reinforcement learning's closed form. Pause here and work through them; full solutions are in this part's notes.
Next time: randomness. Probability distributions that move, random walks that become Brownian motion, gradients that are only estimates, and the noise that diffusion models learn to undo. It's the last piece of mathematics we need before the models themselves.
Griewank and Walther's Evaluating Derivatives is the book on automatic differentiation, and Blondel and Roulet's Elements of Differentiable Programming is the modern one. Thanks for watching, and see you in Part 5.
Where it goes next. The library trains the series' first neural networks in Part 9; Jacobians multiplied through depth return in Parts 9 and 10, curvature and optimizers in Part 11, duality as the support vector machine in Part 6, the KL-regularized closed form as direct preference optimization in Part 27, and number formats and memory in Parts 17 to 19.
Key results
The part's results in one place, for revision.
Try it
Lab 4 · The gradient check and its V-curve
Build a two-layer network on the series' autodiff library, take its gradient with one backward pass, and compare directional derivatives with central and forward finite differences for steps from 1e-1 to 1e-12: the error falls like h squared until round-off, growing like 1/h, takes over.
python -m videos.ai.labs 4
needs numpy, scipy, matplotlib · download lab04.py ·
source on GitHubparameters, loss 92, 1.3889 nats
dL/dlogits: library against (q - y)/n largest difference 6.9e-18
central difference: best step h = 3.2e-05, relative error 8.6e-11
forward difference: best step h = 1.0e-07, relative error 4.2e-08
slopes of the central V +2.00 on the right (theory +2), -1.01 on the left (theory -1)
slope of the forward error +1.00 on the right (theory +1)
The backward pass agrees with finite differences to about ten digits, and no further: a finite difference trades truncation error (too large a step) against cancellation (too small a step), so a gradient check passes at the bottom of the V, not at the smallest step.
The code (107 lines; it asserts its own result)
"""Lab 4: check the series' autodiff against finite differences, and find the V-curve of the gradient check."""
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor, cross_entropy, log_softmax
TITLE = "The gradient check and its V-curve"
GOAL = ("Build a two-layer network on the series' autodiff library, take its gradient with one backward pass, and "
"compare directional derivatives with central and forward finite differences for steps from 1e-1 to 1e-12: "
"the error falls like h squared until round-off, growing like 1/h, takes over.")
TASKS = [
"Cast the parameters and the data to float32 inside loss_at (np.float32) for the finite differences only. "
"Where does the V's minimum move, and how deep is it now?",
"Break the library on purpose: in a copy of Tensor.tanh return g * (1 - t) instead of g * (1 - t * t). "
"Which numbers in the table expose the bug?",
"Train the network: repeat p.data -= 0.5 * p.grad for 300 steps (zeroing the gradients each time) and plot "
"the loss. Then rerun the check at the trained weights.",
]
SIZES = ((6, 8), (8,), (8, 4), (4,)) # W1, b1, W2, b2: 6 inputs, 8 tanh units, 4 classes
def forward(params, x, y, shift=0.0):
W1, b1, W2, b2 = params
logits = (x @ W1 + b1).tanh() @ W2 + b2 + shift
return cross_entropy(logits, y), logits
def loss_at(theta, x, y):
"""The loss as a plain function of one flat parameter vector (no gradients requested)."""
params, i = [], 0
for shape in SIZES:
n = int(np.prod(shape))
params.append(Tensor(theta[i:i + n].reshape(shape)))
i += n
return float(forward(params, Tensor(x), y)[0].data)
def run(seed=0):
rng = np.random.default_rng(seed)
x, y = rng.standard_normal((16, 6)), rng.integers(0, 4, 16)
params = [Tensor(rng.standard_normal(s) * 0.5, requires_grad=True) for s in SIZES]
logits_in = Tensor(np.zeros((16, 4)), requires_grad=True) # a zero added to the logits, to read dL/dlogits
loss, logits = forward(params, Tensor(x), y, shift=logits_in)
loss.backward()
theta = np.concatenate([p.data.ravel() for p in params])
grad = np.concatenate([p.grad.ravel() for p in params])
lab = labs.Lab()
lab.row("parameters, loss", f"{theta.size}, {float(loss.data):.4f} nats")
# Part 1's formula at the logits: (softmax - one-hot) / batch size.
q = np.exp(log_softmax(Tensor(logits.data)).data)
formula = (q - np.eye(4)[y]) / len(y)
lab.row("dL/dlogits: library against (q - y)/n", f"largest difference {np.abs(logits_in.grad - formula).max():.1e}")
assert np.abs(logits_in.grad - formula).max() < 1e-14
# Directional derivatives along eight random unit directions.
hs = 10.0 ** np.arange(-1, -12.01, -0.25)
dirs = rng.standard_normal((8, theta.size))
dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
central, fwd = np.empty((8, len(hs))), np.empty((8, len(hs)))
base = loss_at(theta, x, y)
for i, v in enumerate(dirs):
exact = grad @ v
for j, h in enumerate(hs):
central[i, j] = abs((loss_at(theta + h * v, x, y) - loss_at(theta - h * v, x, y)) / (2 * h) - exact) / abs(exact)
fwd[i, j] = abs((loss_at(theta + h * v, x, y) - base) / h - exact) / abs(exact)
c, f = np.median(central, axis=0), np.median(fwd, axis=0)
c, f = np.maximum(c, 1e-17), np.maximum(f, 1e-17)
right = (hs <= 1e-2) & (hs >= 1e-3) # truncation rules here
left = (hs <= 1e-8) & (hs >= 1e-11) # round-off rules here
slope_r = np.polyfit(np.log10(hs[right]), np.log10(c[right]), 1)[0]
slope_l = np.polyfit(np.log10(hs[left]), np.log10(c[left]), 1)[0]
slope_f = np.polyfit(np.log10(hs[right]), np.log10(f[right]), 1)[0]
lab.row("central difference: best step", f"h = {hs[c.argmin()]:.1e}, relative error {c.min():.1e}")
lab.row("forward difference: best step", f"h = {hs[f.argmin()]:.1e}, relative error {f.min():.1e}")
lab.row("slopes of the central V", f"{slope_r:+.2f} on the right (theory +2), {slope_l:+.2f} on the left (theory -1)")
lab.row("slope of the forward error", f"{slope_f:+.2f} on the right (theory +1)")
lab.note = ("The backward pass agrees with finite differences to about ten digits, and no further: a finite "
"difference trades truncation error (too large a step) against cancellation (too small a step), so "
"a gradient check passes at the bottom of the V, not at the smallest step.")
assert c.min() < 1e-8, "the library's gradient matches central differences"
assert 1.8 < slope_r < 2.2 and 0.8 < slope_f < 1.2, "truncation: h squared for central, h for forward"
assert -1.4 < slope_l < -0.6, "round-off grows like 1/h"
assert 1e-7 < hs[c.argmin()] < 1e-3 and hs[f.argmin()] < hs[c.argmin()], "the minimum sits near eps^(1/3)"
assert f.min() > 20 * c.min(), "forward differences cannot check as tightly"
fig, ax = labs.figure(2, size=(11, 4.2))
for row in central:
ax[0].loglog(hs, np.maximum(row, 1e-17), color=labs.BLUE, alpha=0.25, lw=1)
ax[0].loglog(hs, c, color=labs.BLUE, label="central difference (median of 8 directions)")
ax[0].loglog(hs, f, color=labs.RED, label="forward difference")
eps = np.finfo(float).eps
ax[0].loglog(hs, eps / hs, ":", color=labs.MUTED, lw=1, label=r"$\varepsilon/h$, round-off")
ax[0].loglog(hs, c[right][0] * (hs / hs[right][0]) ** 2, "--", color=labs.MUTED, lw=1, label=r"$\propto h^2$, truncation")
ax[0].set(title="Finite differences against the backward pass", xlabel="step h", ylabel="relative error",
ylim=(1e-14, 1e5))
ax[0].legend(loc="upper left")
order = np.argsort(np.abs(grad))[::-1][:40]
fd = np.array([(loss_at(theta + 1e-5 * e, x, y) - loss_at(theta - 1e-5 * e, x, y)) / 2e-5 for e in np.eye(theta.size)[order]])
ax[1].bar(np.arange(40), grad[order], color=labs.BLUE, label="backward pass")
ax[1].plot(np.arange(40), fd, "o", ms=3.5, color=labs.GOLD, label="central difference, h = 1e-5")
ax[1].set(title="The 40 largest partial derivatives, two ways", xlabel="parameter (sorted by size of derivative)",
ylabel="dL / d parameter")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Cast the parameters and the data to float32 inside loss_at (np.float32) for the finite differences only. Where does the V's minimum move, and how deep is it now?
- Break the library on purpose: in a copy of Tensor.tanh return g * (1 - t) instead of g * (1 - t * t). Which numbers in the table expose the bug?
- Train the network: repeat p.data -= 0.5 * p.grad for 300 steps (zeroing the gradients each time) and plot the loss. Then rerun the check at the trained weights.
Problems, with solutions
Try each problem before opening its solution.
- The softmax Jacobian. Show J = diag(p) − ppᵀ is positive semidefinite, vᵀJv = Var_p(v), and J1 = 0.
Solution
vᵀJv = Σᵢpᵢvᵢ² − (Σᵢpᵢvᵢ)² = Var_p(v) ≥ 0; (J1)ᵢ = pᵢ − pᵢΣⱼpⱼ = 0. Equality in the variance holds for vectors constant on the support of p. If all pᵢ>0, the null space is span(1).
- Forward against reverse. For L≥2 dense layers with hidden width w mapping ℝⁿ→ℝᵐ, count dense
multiply-accumulates (MACs) for a full input Jacobian, holding weights fixed.
Solution
The primal dense work is F = nw + (L−2)w² + wm, plus nonlinearities. Each input JVP or output VJP is comparable to one primal pass, so full-Jacobian work is O(F+nF) or O(F+mF), with implementation-dependent constants. For a scalar loss, reverse mode needs one output seed rather than a seed for each input/parameter. This comparison is distinct from timing and from counting all scalar multiplication/addition operations.
- The best finite-difference step. For positive coefficients in the model
E(h)=(h²/6)|f‴|+u|f|/h with h>0, find h*; repeat for the forward-difference model.
Solution
E′(h)=h|f‴|/3−u|f|/h²=0 gives h*=(3u|f|/|f‴|)^(1/3) and E(h*)=½(3u|f|)^(2/3)|f‴|^(1/3), of order u^(2/3). For E(h)=h|f″|/2+2u|f|/h, h*=2√(u|f|/|f″|) and E(h*)=2√(u|f||f″|), of order u^(1/2). These model balances assume nonzero derivative coefficients and a valid truncation/roundoff regime; they do not guarantee a particular empirical optimum. The current fp64 median curves reach 8.132e−10 forward and 6.473e−13 central absolute error.
- Checkpoints. Minimize the leading-order logical activation model n/k+k, ignoring integer/end effects;
show two checkpoint levels give O(n^(1/3)) storage.
Solution
−n/k²+1=0 gives k=√n and M=2√n. Two levels give M=n/k₁+k₁/k₂+k₂; k₂=n^(1/3), k₁=n^(2/3) yield M=3n^(1/3), with additional forward recomputation. This model excludes weights, gradients, workspace and allocator memory; it is not a measured process-memory bound.
- Descent on an SPD quadratic. Let H=Hᵀ≻0, 0<λmin≤λmax, κ=λmax/λmin and
η=2/(λmin+λmax). For f(x)=½xᵀHx, prove a worst-case Euclidean error bound and estimate the steps to relative
norm ε, where 0<ε<1 and x₀≠0 (x₀=0 is already optimal).
Solution
In an orthonormal eigenbasis, cᵢ←(1−ηλᵢ)cᵢ, so ‖x_t‖₂≤ρ^t‖x₀‖₂ with ρ=(κ−1)/(κ+1). The endpoint eigenvalues attain ±ρ; interior factors have magnitude at most ρ, so arbitrary initial errors need not shrink by exactly ρ at every step. For κ>1, the sufficient worst-case count is ceil[ln(1/ε)/ln((κ+1)/(κ−1))], approximately (κ/2)ln(1/ε) for large κ. For κ=1 one step reaches zero. Function-gap contraction is bounded by ρ^(2t), rather than ρ^t. The current κ=1000 two-dimensional example, initialized in the endpoint eigendirections, needs 6,908 steps for relative iterate norm <1e−6.
- The KL-regularized closed form. On a finite action set, assume finite rewards, β>0, π_ref(a)>0 for every
action and Σₐπ_ref(a)=1. Maximize Σₐπ(a)r(a)−βΣₐπ(a)ln(π(a)/π_ref(a)) over the probability simplex.
Solution
The interior stationarity equation is r(a)−β[ln(π(a)/π_ref(a))+1]−λ=0, giving π*(a)=π_ref(a)e^{r(a)/β}/Z with Z=Σₐπ_ref(a)e^{r(a)/β}. This candidate is positive and normalized. Strict concavity for β>0 makes it the unique global maximizer; its objective value is β ln Z. At β=0 the formula is undefined; a reference with zeros requires restricting the optimization to its support rather than dividing by zero.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| derivative; best linear approximation | 导数;最好的线性近似 |
| tangent plane; partial derivative; directional derivative | 切平面;偏导数;方向导数 |
| steepest ascent; Cauchy–Schwarz inequality | 最陡上升;柯西–施瓦茨不等式 |
| Jacobian (matrix) | 雅可比矩阵 |
| Jacobian-vector product (JVP), vector-Jacobian product (VJP) | 雅可比-向量积,向量-雅可比积 |
| forward mode, reverse mode | 前向模式,反向模式 |
| computation graph, topological order | 计算图,拓扑顺序 |
| tape, Wengert list | 磁带(运算记录),文格特列表 |
| define-by-run, static graph, tracing | 边运行边定义,静态图,追踪 |
| error signal δ, outer product, rank one | 误差信号δ,外积,秩为1 |
| floating point; sign, exponent, mantissa | 浮点数;符号位,指数,尾数 |
| unit in the last place (ulp), unit roundoff | 最后一位单位(ulp),单位舍入误差 |
| overflow, underflow, NaN | 溢出,下溢,非数(NaN) |
| log-sum-exp trick | log-sum-exp技巧 |
| loss scaling | 损失缩放 |
| (catastrophic) cancellation, truncation error | (灾难性)抵消,截断误差 |
| central / forward difference, gradient check | 中心差分 / 前向差分,梯度检验 |
| checkpointing (activation recomputation) | 检查点(激活重计算) |
| Hessian, curvature | 黑塞矩阵,曲率 |
| Newton's method, quadratic convergence | 牛顿法,二次收敛 |
| Hessian-vector product (Pearlmutter's trick), power iteration | 黑塞-向量积(珀尔马特技巧),幂迭代 |
| Hessian spectrum: bulk, outliers | 黑塞谱:主体,离群值 |
| condition number κ; stability edge 2/λmax | 条件数κ;稳定边界2/λmax |
| saddle point, escape | 鞍点,逃离 |
| Lagrange multiplier, Lagrangian, shadow price | 拉格朗日乘子,拉格朗日函数,影子价格 |
| maximum entropy, Boltzmann distribution | 最大熵,玻尔兹曼分布 |
| KKT conditions, complementary slackness | KKT条件,互补松弛 |
| dual function, weak / strong duality, duality gap, Slater's condition | 对偶函数,弱对偶 / 强对偶,对偶间隙,斯莱特条件 |
| support vector, margin | 支持向量,间隔 |
| implicit function theorem, fixed point | 隐函数定理,不动点 |
| deep equilibrium model (DEQ), unrolling, contraction, spectral radius | 深度平衡模型(DEQ),展开,压缩映射,谱半径 |
Sources
- Cauchy's note: Comptes rendus 25, 536–538 (1847), on solving simultaneous equations (Lemaréchal, "Cauchy and the gradient method", Doc. Math. 2012).
- Wengert, "A simple automatic derivative evaluation program", Comm. ACM 7(8), 463–464 (1964).
- Linnainmaa's 1970 master's thesis (Helsinki) and BIT 16 (1976); Werbos's 1974 Harvard thesis; Kelley (1960) and Bryson (1961) as in Schmidhuber's survey (2015).
- FP8 E4M3/E5M2: Micikevicius et al., arXiv:2209.05433 (2022): E4M3 max 448 and no infinities, E5M2 IEEE-like.
- The Brandeis dice problem's year varies between sources (1957, 1962, 1963); the film names only Jaynes (1957) for the principle.
- Newton (1669), Raphson (1690), Simpson (1740): Ypma, "Historical development of the Newton–Raphson method", SIAM Review 37 (1995).
- Framework dates: Theano (Bergstra et al., SciPy 2010), Chainer (Tokui et al., 2015), TensorFlow (released November 2015; Abadi et al. 2016), PyTorch (public release 2017; Paszke et al. 2017, 2019), JAX (Frostig, Johnson & Leary, SysML 2018).
Sources
Books: A. Griewank & A. Walther, Evaluating Derivatives, 2nd ed. (2008); M. Blondel & V. Roulet, The Elements of Differentiable Programming (2024); J. Nocedal & S. J. Wright, Numerical Optimization, 2nd ed. (2006); S. Boyd & L. Vandenberghe, Convex Optimization (2004); N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed. (2002); I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (2016).
Papers: Cauchy (1847); Karush (1939); Kuhn & Tucker (1951); Jaynes (1957); Kelley (1960); Bryson (1961); Wengert (1964); Linnainmaa (1970, 1976); Werbos (1974); Speelpenning (1980); IEEE 754 (1985); Rumelhart, Hinton & Williams (1986); Goldberg (1991); Griewank (1992); Boser, Guyon & Vapnik (1992); Pearlmutter (1994); Cortes & Vapnik (1995); Bergstra et al., Theano (2010); Dauphin et al. (2014); Tokui et al., Chainer (2015); Abadi et al., TensorFlow (2016); Chen et al., Training Deep Nets with Sublinear Memory Cost (2016); Sagun, Bottou & LeCun (2016); Jin et al. (2017); Amos & Kolter, OptNet (2017); Paszke et al. (2017, 2019); Frostig, Johnson & Leary, JAX (2018); Baydin et al. (2018); Bai, Kolter & Koltun, Deep Equilibrium Models (2019); Rajeswaran et al., iMAML (2019); Karpathy, micrograd (2020); Micikevicius et al., FP8 Formats for Deep Learning (2022).
About this partfrom its README
Part 4 of the thirty-one-part series on how modern AI works and how it came to be (plan, syllabus): the calculus of learning. This part derives derivatives, gradients and Jacobians as best linear approximations; differentiates real layers; compares forward and reverse mode; builds and checks the series' own autodiff library; and trains a letter model. Floating point, activation recomputation, curvature, constraints and implicit differentiation complete the picture.
- Four billion derivatives. Recall q − p̂ for natural-log cross-entropy; a loss in bits multiplies this gradient by 1/ln 2. Show GPT-2 and Qwen3-4B parameter counts with independent provenance, the schematic parameter sea, the calculus timeline from 1684 to 2022, and the plan. Full-parameter training differentiates every trainable parameter; frozen-parameter or adapter training has a different scope.
- 1. The derivative. Surprise −log₂p under a lens; secants approaching the tangent; the definition f(x+h) = f(x) + f′(x)h + o(h); the measured best-line error; Leibniz and Newton; derivation of s′(¼) = −4/ln 2; exponential, logarithm and chain-rule local stretch factors. The shown finite intervals are illustrative, and the final number line is drawn six times smaller.
- 2. Many inputs: the gradient. Partial slices and a tangent plane at the same point used for the measurements; differentiability and Cauchy–Schwarz give steepest ascent along a nonzero gradient, descent against it, and zero first-order change along contour tangents. A finite difference sweeps 720 unique directions (721 samples include the repeated endpoint). Cauchy's descent update follows.
- 3. Maps that bend: the Jacobian. A nonlinear grid and its local linear map, the m × n definition, local area factor |det J|, and correctly ordered matrix chain rule. Jacobians multiply; spectral norms satisfy ‖J_L⋯J_1‖₂ ≤ ∏ₗ‖Jₗ‖₂, generally with strict inequality. The product norm is maximum possible directional amplification, also for its transpose in backpropagation. A norm below one contracts every unit direction; a norm above one permits growth in some direction. Depth curves show mean log₁₀ norms and seed min–max bands.
- 4. The Jacobians of real layers. Matrix-product VJPs XᵀG and GWᵀ; a dense Jacobian versus its contracted evaluation; softmax diag(p) − ppᵀ and its linear-cost VJP; epsilon-aware layer normalization before learned affine scale/shift. Theory has exact null directions; computed eigenvalues retain numerical roundoff signs.
- 5. Forwards or backwards? JVPs, VJPs and contraction order; full input Jacobians across 25 networks; parameter gradients of a 16–32–10 classifier with 874 parameters. Counted dense derivative work and observed wall time are reported separately. The parameter reverse count requests W₁,b₁,W₂,b₂ and excludes dX for the constant input. The forward count describes this dense tangent implementation, not a lower bound on optimized forward AD.
- 6. Backpropagation, by hand. Scalar sigmoid/squared-error example, fan-in addition, two-layer tanh/softmax cross-entropy, rank-one per-example matrix gradients and their batch sum; checks against the library and PyTorch.
- 7. Calculus in a few pages of code. Multiplication's VJP, reverse traversal, topological order, values and gradients on a Wengert list; central finite-difference and PyTorch checks; related frameworks and code examples.
- 8. Training with our library. The first gradient of Part 1's letter-pair model, then 729 raw scores trained with Adam for 1,500 updates. The heatmap displays normalized log q(j|i), not raw scores z. Correlation is between log q and log counted conditionals on the 552 entries with counted probability > 10⁻⁴. The optimization objective uses nats; reported losses use bits per transition. Minibatch curve row t evaluates pre-update parameters t−1, while snapshot t is post-update. A separate full-batch GD experiment tracks five step sizes and the curvature-dependent stability scale.
- 9. Numbers in a computer. IEEE 754, normal/subnormal numbers, float32, bfloat16, float16 and FP8 E5M2/E4M3FN layouts; enumerated ulp staircases, rounding and accumulation, overflow, and stable log-sum-exp. Relative round-to-nearest precision bounds apply in the normal finite range; subnormal spacing gives an absolute-error regime instead.
- 10. Cancellation, and the gradient check. (1 − cos x)/x² and its stable rewrite; central/forward truncation and roundoff error; V-curves on eight identical normalized directions shared by both precisions. A plotted optimum is the argmin of the plotted median error curve, distinct from the median of individual optima.
- 11. Memory: storing or recomputing. Logical retained activations and the leading-order n/k + k model; checkpointing, recomputed forward-layer evaluations and gradient agreement. This count excludes weights, gradients, temporaries and allocator/process memory. Timing uses a separate 1,024-layer width-64 chain.
- 12. Curvature, and Newton's method. Hessian, bowl/saddle and local quadratic model; logistic regression with condition number about 187. Newton's reported first hit uses gradient norm < 10⁻¹⁰; GD uses objective gap to the final numerical Newton reference < 10⁻¹⁰. These are different criteria, and the reference is not a certified exact optimum. Explicit budgets and convergence states remain recorded.
- 13. Hessian-vector products. Hv = ∇(∇f·v), comparison with a full 371 × 371 Hessian and finite differences; power iteration targets the signed eigenvalue of largest absolute value, assuming a unique dominant magnitude and a nonzero initial component in its eigendirection. The trained 2–16–16–3 network's six spectra and decision maps concern 300 training examples. Relative thresholds classify negative, flat and outlier eigenvalues; a zero count below a threshold does not establish positive semidefiniteness. Top curvature initially increases and later decreases as training progresses.
- 14. Descent on a quadratic; saddles. For a symmetric positive-definite Hessian, stability 0 < η < 2/λmax and the worst-case Euclidean error contraction (κ−1)/(κ+1) at the optimal constant step. Measured norm thresholds, explicit iteration caps, the unstable step-size edge, saddle escape and an invariant zero-gradient direction.
- 15. Constraints: Lagrange multipliers. Local tangency at a constrained extremum, Lagrangian and multiplier; circle optimization, maximum-entropy die and KL-regularized policy. Solver status/residuals accompany numerical comparisons. The entropy exponential-family parameter and the positive KL penalty coefficient are separate uses of the symbol β.
- 16. Inequalities, KKT and duality. Necessary KKT conditions under a constraint qualification, weak duality, and convex strong-duality assumptions. The hard-margin SVM has a free intercept b: its dual requires α ≥ 0 and Σᵢαᵢyᵢ = 0. Positive α implies a tight margin; a tight margin need not imply positive α in a degenerate solution. The nonconvex example uses finite x/λ grids and reports estimates, not certified continuous dual bounds.
- 17. Differentiating through a fixed point. Implicit derivatives when I−J is invertible, with a contraction sufficient for convergence. The initial example has eight state coordinates; the trained example has twelve state coordinates and 181 trainable parameters. Weight-norm caps, fixed-point residual tolerances, iteration budgets and converged/capped counts are explicit. A capped iterate is not an exact equilibrium derivative.
- Recap. Connections, bilingual problems and solutions, Part 5's teaser, and references.
What is computed and builtThe series' autodiff library
explainer/ai/autodiff.py supplies topological_order(root), tape(root) and sigmoid(z) as well as the operations
used here. backward() accumulates requested leaf gradients; transient intermediate sensitivities are not all
exposed as persistent .grad fields. The tape omits constant inputs. The matrix-product VJP supports 2-D arrays;
the unrolled fixed-point check keeps the state as a 1 × d row.
What is computed and built
These values are rounded from the hashed current artifacts, with cohorts and units retained. Comparisons report observed errors, not exact mathematical equality of floating-point arrays.
| Item | Current result and scope |
|---|---|
| parameter counts | GPT-2 124,439,808; Qwen3-4B 4,022,468,096; both pinned headers, no historical fallback |
| best line / tangent plane | log-error slopes 1.998 (true scalar slope), 1.013 (slope 10% off), 2.001 (plane) |
| steepest ascent | finite-difference maximum 0.812625; gradient norm 0.812631; directions 0.207° apart |
| Jacobians through depth | mean log₁₀ norm at depth 60: gains 0.5/0.9/1/1.5/2 → −17.432/−2.464/−0.186/+2.146/+4.567; eight seeds |
| matrix-product VJP cost | 7,421,703,487,488 dense Jacobian entries; 29.69 decimal TB float32; 4,831,838,208 conventional FLOPs (2 per MAC), equivalent to 2,415,919,104 MACs for XᵀG; actual formula/library difference 0 |
| softmax / layernorm Jacobians | formula/library max differences 5.55e−17 / 1.94e−16; smallest stored eigenvalues −3.12e−17 / −2.12e−16; layernorm radial eigenvalue 9.93e−6 (ε=1e−5), before learned affine parameters |
| forward / reverse mode | cheaper counted input mode faster in 20/20 unequal-count networks; classifier P=874: 33,114,112 / 37,888 counted dense MACs plus tanh-derivative terms, ratio 874×; local parameter timing ratio 64.81×; gradient difference 4.16e−17 |
| scalar hand backprop | squared loss 0.854038; ∂L/∂w = −0.259143 |
| two-layer backprop | max differences to library/PyTorch 3.47e−17 / 5.55e−17; per-example dW rank 1 and batch-of-eight rank 4 under relative 1e−10 threshold |
| library gradient check | sampled central finite differences 2.20e−10; PyTorch 2.78e−17; 256 parameters |
| letter model | train/held-out 3.334868/3.335963 bits per transition; counting 3.330892; normalized-log-conditional correlation 0.996100 on 552 masked entries |
| first letter-model gradient | formula/library maximum difference 1.87e−14 on 300,000 training pairs |
| full-batch letter GD | λmax initially 0.0070756, at counting solution 0.0260055; 2/λmax ≈ 282.66/76.91; last-500-step mean losses at η≈2.83/28.27/56.53/84.80/141.33: 3.349622/3.332321/3.331538/3.355413/3.581980 bits; final-window monotonicity true/true/true/false/false |
| repeated addition of 0.01, 10,000 times | float32 100.002953; float16 32; bfloat16 4; bfloat16 inputs with float32 accumulator 100.097656 |
| cancellation at x=1e−4 | naive float32 (1−cos x)/x² = 0; stable rewrite = 0.5 |
| V-curve, fp64 | plotted median central-curve minimum at h=3.981e−5, error 6.473e−13; central model prediction 5.105e−5; median individual optimum 3.246e−5; forward-curve minimum error 8.132e−10 at h=1e−7 |
| V-curve, fp32 | plotted median central-curve minimum at h=0.015849, error 2.070e−6; central prediction 0.041493; paired eight directions; fp64 fitted right/left slopes +2.000/−0.884; fp32 right slope unavailable, left −0.895 |
| activation checkpointing | n=256: retained activations 257 → 32 (minimum at k=13…20); at k=16 forward-layer evaluations 256 → 496; keep-none 3 activations / 33,152 evaluations; max gradient difference 0; separate n=1024,width=64 local timing ratio 1.145× |
| Newton / GD | κ=186.73; Newton gradient-norm first hit at step 4 of cap 12; GD objective-gap first hit at step 2,362 of cap 200,000; both threshold 1e−10 in their respective units |
| HVP / trained Hessian | full-Hessian difference 1.08e−17; local HVP/gradient timing ratio 2.294×; finite-difference best 2.30e−9 at h=5.623e−5; final signed dominant-magnitude eigenvalue +0.00655422 |
| trained spectrum | λ < −0.01ρ count 72 → 0; λ > 0.1ρ count 56 → 4; fraction with abs(λ) ≤ 0.01ρ reaches 94.609%; final actual minimum −8.36e−6; ρ is spectral radius, and accuracy is training accuracy |
| SPD quadratics / valley | measured contraction rates match (κ−1)/(κ+1) to roundoff; κ=1000 needs 6,908 steps for relative iterate norm <1e−6; κ=25 valley reaches 1% in 26 steps; descent step cap 20,000 |
| saddle | escape to abs(y)>0.5 for all twelve starts within cap 4,999; initial y from 1e−1 to 1e−12 gives 19…284 steps; zero-axis gradient after 300 steps 2.81e−14 |
| Lagrange / entropy / KL | circle λ=0.625943, stationarity residual 1.56e−8; die parameter β=0.371049, numerical comparison 5.87e−9; KL coefficient β=0.5, comparison 2.98e−8; all three solver success flags true |
| free-intercept SVM | primal/dual ≈0.726908423262; absolute numerical gap 8.88e−16; Σαy residual 2.66e−15; complementarity residual 4.73e−16; positive multipliers and tight margins both at zero-based indices 2,5,17 in this run |
| nonconvex grid example | primal/dual-grid estimates −1.070230/−1.750000, estimated gap 0.679770; x-grid 440,001 points, spacing 1e−5 on [−2.2,2.2]; λ-grid 601 points, spacing 0.01 on [0,6] |
| implicit differentiation | initial 8-state solve converges in 29 iterations; unrolled relative-error fit 0.4603 per step, local ρ(J)=0.385982, error at K=60 8.76e−13; trained 12-state/181-parameter loss 0.106452 → 1.854e−6; mean training solve iterations 10.3125 → 28.25; final one-input solve 22; relative 200-unroll comparison 3.37e−13 |
The DEQ stores weight spectral-norm caps 0.8 (initial example) and 0.9 (training), and fixed-point solve cap 2,000. All 38,448 training/evaluation solves (801 parameter states × 48 examples, including the final evaluation) and 540 fit-grid solves converged; capped/nonfinite counts were zero. Their residual tolerance is 1e−10; the separate initial and final one-input solves use 1e−12. These counts are separate from the 800 optimizer updates and from unrolled reference evaluations.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Derivative as best linear approximation.
- Gradient as steepest ascent (Cauchy–Schwarz).
- Jacobians of real layers: softmax diag(p) − ppᵀ, layer norm, matmul.
- JVPs and VJPs; forward vs reverse cost, counted.
- Backprop through a two-layer MLP by hand (dW = δxᵀ).
- The series' autodiff library: topological sort, the tape.
- Numerics: float formats, ulp, cancellation, the log-sum-exp trick; gradient checking's V-curve (truncation vs roundoff).
- Memory: checkpointing at √n.
- Curvature: Hessian, Newton, Hessian–vector products (Pearlmutter).
- GD on quadratics: rate from the condition number; saddles.
- Constrained optimization: Lagrange multipliers, KKT, convex duality. SVMs, max-entropy and RL's closed forms use it.
- Implicit differentiation (implicit function theorem; deep equilibrium models, meta-learning).
Visuals: ComputeGraph; tangent planes on 3D surfaces; descent zig-zagging in narrow valleys; the Lagrange
picture (gradients parallel at the constrained optimum).
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
- softmax 的雅可比矩阵。 证明 J=diag(p)−ppᵀ 半正定,vᵀJv=Var_p(v),且 J1=0。 解答。 vᵀJv=Σᵢpᵢvᵢ²−(Σᵢpᵢvᵢ)²=Var_p(v)≥0;(J1)ᵢ=pᵢ−pᵢΣⱼpⱼ=0。 方差为零时,v 在 p 的支撑集上为常数;若每个 pᵢ>0,零空间恰好是 span(1)。
- 前向与反向。 对 L≥2、隐藏层宽度 w、从 ℝⁿ 到 ℝᵐ 的全连接网络,固定权重,数完整输入雅可比矩阵的稠密乘加次数(MAC)。 解答。 前向值计算的稠密工作为 F=nw+(L−2)w²+wm,另有非线性操作。一个输入 JVP 或输出 VJP 的代价与一次前向同阶, 所以完整雅可比矩阵约为 O(F+nF) 或 O(F+mF),常数随实现而变。标量损失只需一个反向输出种子。 这些计数不同于墙钟时间,也不同于把乘法和加法分别计数的标量操作数。
- 有限差分的最佳步长。 对正系数模型 E(h)=h²|f‴|/6+u|f|/h、h>0,求最优步长,再求前向差分模型的结果。 解答。 E′(h)=h|f‴|/3−u|f|/h²=0,得到 h*=(3u|f|/|f‴|)^(1/3), E(h*)=½(3u|f|)^(2/3)|f‴|^(1/3),量级为 u^(2/3)。前向模型 E(h)=h|f″|/2+2u|f|/h, 得 h*=2√(u|f|/|f″|)、E(h*)=2√(u|f||f″|),量级为 u^(1/2)。这些平衡需要非零导数系数及有效的截断/舍入近似, 不保证某个实测最优值。本次 fp64 中位数曲线的最小绝对误差为:前向 8.132e−10,中心 6.473e−13。
- 检查点。 忽略整数和端点效应,最小化逻辑激活存储模型 n/k+k,并证明两级检查点可达 O(n^(1/3))。 解答。 −n/k²+1=0 给出 k=√n、M=2√n。两级时 M=n/k₁+k₁/k₂+k₂; k₂=n^(1/3)、k₁=n^(2/3),得到 M=3n^(1/3),代价是额外的前向重计算。 这个模型不含权重、梯度、工作区或分配器内存,不是实测进程内存上界。
- 对称正定二次函数上的下降。 设 H=Hᵀ≻0,0<λmin≤λmax,κ=λmax/λmin, η=2/(λmin+λmax)。对 f(x)=½xᵀHx,证明欧氏误差范数的最坏情况上界,并估计到相对范数 ε(0<ε<1、x₀≠0)的步数;x₀=0 已经最优。 解答。 在正交特征基下 cᵢ←(1−ηλᵢ)cᵢ,因此 ‖x_t‖₂≤ρ^t‖x₀‖₂,ρ=(κ−1)/(κ+1)。 两端特征值的因子为 ±ρ,其余因子的绝对值至多为 ρ;任意初始误差不一定每步恰好缩小到 ρ 倍。 κ>1 时,最坏情况的充分步数为 ceil[ln(1/ε)/ln((κ+1)/(κ−1))],大 κ 时约为 (κ/2)ln(1/ε)。 κ=1 时一步归零。函数值误差的收缩上界是 ρ^(2t),不是 ρ^t。本次 κ=1000 的二维例子从两端特征方向出发, 在 6,908 步达到相对迭代范数 <1e−6。
- KL 正则化的闭式解。 有限动作集上,奖励有限,β>0,每个 π_ref(a)>0 且 Σₐπ_ref(a)=1。 在概率单纯形上最大化 Σₐπ(a)r(a)−βΣₐπ(a)ln(π(a)/π_ref(a))。 解答。 内点驻点满足 r(a)−β[ln(π(a)/π_ref(a))+1]−λ=0,因此 π*(a)=π_ref(a)e^{r(a)/β}/Z, Z=Σₐπ_ref(a)e^{r(a)/β}。这个分布严格为正且归一化;β>0 使目标严格凹,所以它是唯一全局最大值,目标值为 β ln Z。 β=0 时公式没有定义;若参考分布含零概率,必须把问题限制在其支撑集上,不能直接除以零。
Build the film
python -m videos.ai.ai4.compute # the part's numbers, into .cache/ai4
python tools/build.py ai4 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai4 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai4. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python tools/make.py ai4 # compute, then narrated English/Chinese builds
python -m videos.ai.ai4.compute # numerical items; Part 1's books in .cache/ai1
python tools/build.py ai4 # English
python tools/build.py ai4 --lang zh # Chinese
EXPLAINER_TTS=silent python tools/build.py ai4 -q l --fps 15
Finish the numerical jobs before rendering or dry-running scenes: an ordinary missing-data load can compute. The cache records recipe/source/library identity and external dependencies; cached-only QA must reject stale or missing results without computing. The current driver's 23 per-item subprocess durations sum to 63.72 seconds, including those subprocesses' startup and cache publication, and excluding corpus preparation, rendering and narration. This is one observed cloud run, not an expected runtime on every machine.
params reads bounded header/config/index metadata from canonical files at pinned repository revisions, without
loading full model weights. This run counted both models from headers: GPT-2 124,439,808 and Qwen3-4B 4,022,468,096.
Each model records its revision, header hashes and counting policy. A failed read may independently return a labeled
historical fallback; it must not be described as a fresh measurement.
Benchmark records name the software, declared one-thread environment, warmup, repetitions and individual timings. Native threadpool introspection was unavailable in this run. Timings are fixed-order local observations, with no confidence interval; work counts are a separate algebraic convention. In particular, the parameter-mode timing uses one forward repetition and twenty reverse repetitions, while HVP timing uses 200 of each.