A gradient is a local straight-line model of the loss; a Hessian is a local bowl-shaped model; every optimiser is a rule for how far to trust that model.
Write the loss near where you stand as a Taylor model, . Every section reads something off it: which way is down (), how sharply it curves (), how big a step is safe (), where the bottom is (), and when the bottom you find is the only one (convexity). Constraints (Lagrange, KKT) and minibatch noise change the model; deep networks show where it stops being enough. Figure 1 draws it on a real loss: logistic regression with two weights on the breast-cancer data (two standardised features, mean radius and mean texture; 569 patients; the Optimisation lab's real landscape).
You need: eigenvalues and eigenvectors of a symmetric matrix and what positive definite means (Linear algebra for ML, sections 8 and 9). Elsewhere: how gradients are computed through a network (Jacobians, vector-Jacobian products, Hessian-vector products) is Matrix calculus and backprop; SGD, Adam, Muon and schedules in practice are Optimisers and learning-rate schedulers; floating point and stable softmax are Numerical computing for ML. This page is the mathematics underneath them.
| Idea | In one line | One number to remember | Where ML uses it |
|---|---|---|---|
| Derivative | slope of the curve; the best straight-line fit near a point | slope of at 3 is 6; line error | every gradient |
| Gradient | all the slopes; points uphill fastest | tiny model: | the direction of every update |
| Taylor model | value + slope term + curvature term | predicts loss 1.768 for a step that gives 1.773 | derives every optimiser |
| Loss gradients | canonical pairs give prediction minus target | CE beats MSE-on-sigmoid by 203x at | output layers, debugging |
| Hessian | matrix of curvatures; its eigenvalues classify a flat point | : eigenvalues 2, : saddle | sharpness, step limits |
| Step limit and rate | diverge above ; best rate | : 0.818 per step, 35 steps for 1000x | learning rates, warmup |
| Momentum | remember the last step; rate | : 0.519, 11 steps | SGD with momentum, Adam's first moment |
| Newton | jump to the bottom of the local bowl, | 7 steps to on real logistic regression; diverges from a bad start | small models, XGBoost, the ideal others approximate |
| Quasi-Newton | learn the curvature from gradient differences | L-BFGS: 21 steps where gradient descent needs 109 | scikit-learn's default solver |
| Convexity | chords lie above the curve; any minimum is the minimum | : 0.916 against 0.693 | logistic regression, SVMs, ELBO, KL |
| Lagrange, KKT | at a constrained optimum the gradients line up | multiplier = price of loosening the constraint | SVMs, weight decay, softmax, TRPO |
| Stochastic gradients | noisy but unbiased; noise falls as | constant step stalls at a floor proportional to the step | every minibatch |
| Deep landscapes | saddles, not bad minima; sharpness rises to | measured here: 10.02 against | reading training curves |
Worked numbers come from the root page's tiny model (input , weight rows cat , dog , sat , scores , true next word sat, loss 2.408), from small functions you can check by hand, and from two real runs made for this page: logistic regression on a real medical dataset, and a small neural network whose curvature is measured while it trains. All are recomputed by the scripts in this page's source folder.
The Optimisation lab runs eight methods (gradient descent, momentum, Nesterov, Adam, Newton, damped Newton, saddle-free Newton, BFGS) on a quadratic, Rosenbrock's valley, a saddle and a real logistic loss, with the Hessian, its eigenvalues and the local Taylor model at every step; sections 4, 5 and 11 point to it.
Near , a smooth function is a straight line plus an error that shrinks faster than the step:
For at 3 the line is and the remainder is exactly : 1, 0.01, 0.0001, 0.000001 for . Halve the step and the error quarters. No other straight line has that property, which is why the tangent is called the best linear approximation: any other slope leaves an error of about , which shrinks only as fast as itself. Every gradient-based optimiser rests on this reading (for a small enough step the loss changes by slope times step); gradient checking, comparing the analytic slope with , rests on the limit definition (the root's Gradient lab, panel 1, runs that check on five losses).
The derivative is the limit of the secant slope as the gap shrinks to zero, (also written ; at the fraction would be 0/0, so the limit is the value it settles on as gets as close to zero as you like). For at 3: ; with the secant slopes are 7, 6.1, 6.01, 6.001, and the limit is . In general .
| Rule | Formula | Worked case |
|---|---|---|
| Constant, power | , | ; at 2: 12 |
| Sum and constant multiple | ||
| Product | ; at 1: | |
| Quotient | ||
| Exponential, log | , | |
| Chain |
is the sigmoid and the softplus: the last line says softplus's slope is the sigmoid. Every line was checked symbolically (sympy) by the page's script. Why the chain rule multiplies slopes: a step moves by about , which moves by about ; both approximations become exact in the limit. If moves 3 units per unit of and moves 2 per unit of , moves 6 per unit of .
The sigmoid's slope: , because . At it is , its largest value; far from zero it falls towards 0, which is why a sigmoid output trained with squared error stalls (section 2). The same steps give . Derivatives of functions of vectors and matrices, the two layout conventions and the chain rule as a product of Jacobians: Matrix calculus and backprop (sections 1 to 4).
The second-order model matches the value, the slope and the bend (the second derivative , the slope of the slope):
The makes the parabola's second derivative equal . The error of the order- model shrinks like when is smooth enough (Taylor's theorem; Nocedal and Wright, Theorem 2.1, states the multivariate version optimisers use).
A partial derivative is the derivative along one input with the others frozen: for , and . The gradient (often ) stacks them into a vector the shape of the input. Applying the linear approximation in every coordinate at once, the slope along a unit direction is
where is the angle between and the gradient. So the gradient is the direction of steepest ascent, its length is that steepest slope, is steepest descent, and the gradient is perpendicular to the contour. The tiny model: the gradient of its loss in the three scores is , length 1.153. Moving the sat score alone has slope ; the best unit move, , lowers the loss at rate 1.153, faster than any single score could. "Steepest" depends on how length is measured: with a per-coordinate scale (Adam) or a curvature-weighted norm (Newton, natural gradient) the steepest direction changes, a clean way to see every optimiser (Boyd and Vandenberghe, section 9.4). A vector function has one gradient per output; stacked as rows they form the Jacobian (Matrix calculus and backprop, section 2).
With many inputs the bend becomes the Hessian, , how the slope in direction changes as you move in direction :
is the slope term; is the curvature felt along the step , one number.
| Method | Model of the loss | How far it trusts it |
|---|---|---|
| Gradient descent | order 1: | a step-size penalty (section 4) |
| Newton | order 2 with the true | fully: jump to the model's minimum (section 5) |
| Damped Newton, trust region | order 2 | only inside a radius, or with |
| Quasi-Newton (BFGS, L-BFGS) | order 2 with estimated from gradients | with a line search (section 6) |
| Adam, Adagrad | order 1, measured in a per-coordinate scale | a step of about per coordinate |
| Natural gradient, TRPO | order 1, measured in KL divergence | a KL budget (section 9) |
The first-order term is behind influence functions and gradient-based saliency; the second-order term is behind sharpness, pruning scores (Optimal Brain Damage) and the learning-rate limit (section 4).
Backprop starts from , the gradient of the loss in the logit (the raw score before any squashing). For every standard pairing of final activation and loss it comes out as prediction minus target, , , or ; the result, the table of pairings and what it means for training (why squared error on a sigmoid goes silent when the model is most wrong) are owned by Loss functions, and why each loss is a negative log-likelihood by Probability for ML, section 7; this section owns the derivation steps (closed below). The step that makes them all short: in the binary case the slope of the loss in , , blows up as saturates, and the slope of in is : they cancel exactly.
Two more consequences. Stability: frameworks fuse the softmax into the loss (CrossEntropyLoss and BCEWithLogitsLoss take logits) and compute with ; for logits , overflows even in float64, while the shifted form gives 1001.313. Cost: the softmax Jacobian is never built; costs operations, with the vocabulary for a language model. From here the gradient flows back through the network: Matrix calculus and backprop (sections 4, 5 and 7, including the old page's worked logistic unit, , , loss 0.644, one step to ).
Mean squared error and the factor of a half. with gives . The half is a convention. Without it the gradient is ; averaged over a batch, gives each example (the old page's "", which the root's Gradient lab corrected by stating both conventions). PyTorch's MSELoss has no half; the constant only rescales the learning rate. Example: , : with the half, and gradient 0.5; without it, and gradient 1.0.
Linear regression. With and the batch-mean loss without the half, ; setting it to zero gives the normal equations : at the optimum the residual is perpendicular to every column of . Worked example (old page, recomputed): points with an intercept column give , , determinant 6, so : the line . The residuals sum to 0 and . Solving it stably (QR rather than the normal equations): Linear algebra for ML, section 7.
Binary cross-entropy. , : . Computed stably on the logit as , which never exponentiates a large positive number. Examples (old page, recomputed): , : , loss 6.0025, gradient , nearly the largest push possible. , : , loss 0.1269, gradient .
Softmax cross-entropy. Write : the slope of in is , and the slope of the log-sum-exp is , so . Going through the softmax Jacobian (as a matrix ) gives the same answer. With soft targets (label smoothing, distillation) because the sum to 1. Old page example: , class 1 true: , sum 11.2125, which rounds to 11.213 (the old page printed 11.212), so , loss 0.417, gradient . The components sum to 0, because adding a constant to every logit leaves the softmax unchanged. The tiny model, true word sat: ; with soft target : .
Poisson. Rate , loss , gradient ; with and , the loss is 1.712 and the gradient .
Where the gradient is zero the ground is flat in every direction: a critical point. A bowl, an upside-down bowl, a saddle and a flat-floored trough all share that flatness; only the second derivatives tell them apart.
The Hessian is symmetric when the second derivatives are continuous (Schwarz's theorem; has both mixed derivatives equal to ), so it has real eigenvalues and perpendicular eigenvectors (the spectral theorem; Linear algebra for ML, sections 8 and 9). Along an eigenvector the Taylor model at a critical point is a plain parabola, : each eigenvalue is the curvature along its direction, and the second-derivative test follows.
| Eigenvalues of at | Name | Point | Example, at the origin |
|---|---|---|---|
| all | positive definite, | local minimum | : diag(2, 2) |
| all | negative definite, | local maximum | : diag() |
| both signs | indefinite | saddle | : diag(2, ) |
| some zero, rest one sign | semidefinite | test inconclusive | : diag(2, 0), a minimum; , same , a saddle |
The fraction of negative eigenvalues is the critical point's index (section 11 uses it). For softmax cross-entropy, differentiating once more gives
The label has disappeared: the curvature does not depend on the target. For one sigmoid output it is the number (the root's Gradient lab, panel 4, shows why it equals the Fisher information). For logistic regression the chain rule through gives with .
In the input (from the sibling page): , eigenvalues 0.084 and 0.702.
Sharpness (the top eigenvalue) and the learning-rate limit (section 4); classifying where training stalls (section 11); Newton and its approximations (sections 5 and 6); Laplace approximations, influence functions , Optimal Brain Damage pruning (score ). Computing without building (two backward passes) is on Matrix calculus and backprop, in its closed Depth section.
The plane has no bottom, so add a penalty for stepping far from where it was measured:
The learning rate is how far you trust a straight-line model. Replace by another distance and you get another optimiser: a per-coordinate scaling gives Adagrad and Adam's shape, gives Newton, a KL divergence gives natural gradient.
If the curvature never exceeds in any direction (: the loss is -smooth), the loss is guaranteed to fall whenever , and the guaranteed fall is largest at (the descent lemma). Real networks are not globally smooth in a useful way, so practice measures the local curvature instead (section 11); in the Optimisation lab you can watch the guarantee fail on Rosenbrock's valley when is too large.
With ( has no negative eigenvalue) the second-order term is at most , so for the step :
The bracket is positive whenever . At the guaranteed fall is (Boyd and Vandenberghe, equation 9.17). Example: has ; from , where , the step must lower by at least (it lowers it from 4 to 0.444, a fall of 3.56).
Near a minimum every smooth loss looks like , whose gradient is , so one step is . Along each eigenvector of this multiplies the coordinate by the single number ; the directions do not interact. A coordinate shrinks only if (with between 1 and 2 it flips sign each step but shrinks; above 2 it flips and grows), and the steepest direction is the hardest, so
The rate is the worse of the two ends because is V-shaped in ; setting gives . This is the rate Linear algebra for ML (section 11) quotes, and its correction stands: the rate holds only at this best fixed step; at any other step it is slower.
What it means in training: the largest usable learning rate is set by the sharpest direction and the speed by the flattest. That is why normalisation layers and good initialisation, which make the bowl rounder, speed training (Normalisation and initialisation), and why learning-rate warmup exists (curvature is often high early). The root's Gradient lab (panel 3) animates the bowl; for a strongly convex, smooth function () the same reasoning bounds the loss gap: at it shrinks by at least per step (Boyd and Vandenberghe, equation 9.18).
Heavy-ball momentum (Polyak 1964) keeps a running velocity: steps that agree from one iteration to the next (along the valley floor) add up, to about times a single step, and steps that flip sign (across the walls) cancel. On a quadratic with the best settings the rate becomes (Goh 2017, "Why Momentum Really Works"). On diag(1, 10) that is 0.519 per step, about 11 steps for a thousandfold cut against plain gradient descent's 35; for , 0.818 against 0.980, about 34 steps against 345. Nesterov's accelerated gradient evaluates the gradient where momentum is about to carry you, and on smooth convex functions (not just quadratics) provably reaches a loss gap of order after steps, against for gradient descent; no method using only gradients can do better in the worst case. How momentum, Nesterov and Adam behave on real networks: Optimisers and learning-rate schedulers (sections 2 to 6, and its Optimiser race tab with thirteen update rules).
In Goh's form: , , with step and momentum . On a quadratic each eigen-coordinate carries position and velocity, updated by a fixed 2x2 matrix whose eigenvalues set the rate. Goh's analysis (section "The Dynamics of Momentum") gives three results:
diag(1, 10): , , rate , so a thousandfold reduction takes steps. Running those settings in the page's script measures 0.524 per step (the rate is approached, with a polynomial factor, because the 2x2 matrices at the optimum have repeated eigenvalues).
Nesterov (Nesterov 1983, in the form of Sutskever et al. 2013): , . The look-ahead corrects an overshoot one step earlier. The bound and its optimality are in Nesterov, Introductory Lectures on Convex Optimization, 2004, sections 2.1 and 2.2; heavy ball has no such guarantee beyond quadratics.
On real data: on the breast-cancer logistic regression, Nesterov with the textbook constants ( with the global smoothness bound , momentum ) reaches a loss gap of in 274 iterations, where plain gradient descent at the same step does not get there in 500 (section 6 has the full race). Momentum's 2x2 analysis drawn interactively: Goh 2017; momentum against gradient descent on a bowl is the root's Gradient lab, panel 3, and this page's Optimisation lab.
Minimise the second-order model : its gradient is zero at
This is a minimum of the model only if . In one dimension it is , slope over curvature. In eigen-coordinates it divides each direction's gradient by that direction's curvature, so flat directions get big steps and steep ones small steps at once: the condition number no longer matters.
Both methods on the same real function: the logistic-regression loss of one weight on one breast-cancer feature (the "worst concave points" measurement, standardised; label 1 is malignant), with the small L2 penalty of section 6. At each point gradient descent trusts the tangent line under a step penalty with , from the largest curvature this function can have, (its model is a parabola of curvature ); Newton trusts the parabola with the true curvature. Predict before step 5: from , where the loss is almost flat, where does Newton go?
For parameters, has entries and solving costs about operations. At : entries, 2 exabytes in 16-bit numbers, before any solve. Minibatch noise makes the curvature estimate itself noisy, and the many saddles make an undamped step unsafe. So practice uses stand-ins that need only gradients or Hessian-vector products: Gauss-Newton and Fisher matrices, Hessian-free conjugate gradient, K-FAC, Shampoo, SOAP and Muon, diagonal scalings such as Adam, and quasi-Newton (next section).
After a step the gradient changes by . For a quadratic exactly, so ask the curvature estimate to satisfy the secant equation . BFGS (Broyden, Fletcher, Goldfarb, Shanno, 1970) picks the solution closest to the previous estimate and keeps its inverse directly; the step is followed by a line search. It still stores numbers. L-BFGS (Liu and Nocedal 1989) keeps only the last pairs , typically 5 to 20, and applies the inverse to the gradient with a "two-loop recursion" of multiplications: memory numbers instead of . It is scikit-learn's default solver for logistic regression. It needs full-batch, deterministic gradients: with minibatch noise is dominated by sampling noise rather than curvature and the estimate degrades.
Newton, with the exact curvature, needs 7 iterations, each solving a 31x31 system (cheap here, impossible at ). L-BFGS learns enough curvature from 10 gradient pairs to need 21 iterations and 23 gradient evaluations. First-order methods pay for the condition number (1,855 at the start, 85.9 at the optimum): plain gradient descent with the safe global step is still from the optimum after 500 iterations. Adam does well here, but at a learning rate of 1.0 that no default would choose.
. The update needs (the curvature condition; the Wolfe line-search conditions guarantee it), which keeps positive definite (Nocedal and Wright, Numerical Optimization, 2nd edition, chapter 6). Each update is a rank-two correction costing . The L-BFGS two-loop recursion is in chapter 7.
LogisticRegression(C=1), whose answer the page's script matches to ). Vertical axis: loss minus the optimum, log scale. Every method starts at . Settings: gradient descent at with the global bound ; gradient descent with a backtracking (Armijo) line search; Nesterov with and momentum 0.955; Adam at its best learning rate from a grid of 0.001 to 3 (it was 1.0); L-BFGS with (SciPy); Newton with the exact Hessian.| Method | Iterations to a gap of | Cost per iteration |
|---|
XGBoost adds one regression tree per round to the current prediction and takes a second-order Taylor expansion of each example's loss around it (Chen and Guestrin 2016, equation 3), with per-example slope and curvature , plus a penalty on a tree of leaves with values . Every example in leaf gets the same value, so with and each leaf's objective is a parabola , minimised at
A Newton step for the leaf, damped by ; a split is worth the drop in the objective (their equations 5 to 7). That is why XGBoost needs losses with a second derivative, and why its custom-objective API asks for both the gradient and the Hessian of each example.
The round- objective (their equation 2 and 3) is , with and at the current prediction . Grouped by leaves it is ; each bracket's slope is zero at , and substituting back gives . The gain is the parent's value minus the two children's. Worked: , , , , Gain . Boosting in context, and whether boosted trees still win on tables: Classical ML (sections 3 and 4).
A function is convex if the chord between any two points on its graph never dips below the graph: a bowl, not a wave.
| Problem | Convex in its parameters? | Why |
|---|---|---|
| Least squares, ridge | yes | Hessian (plus ) |
| Logistic and softmax regression | yes | log-sum-exp minus a linear term, of an affine map of ; Hessian |
| Support vector machine | yes | hinge is a maximum of affine functions, plus |
| Lasso | yes (not smooth) | is a sum of |
| Cross-entropy in the logits | yes | Hessian (section 3) |
| Any network with a hidden layer, in its weights | no | the permutation argument below |
Why deep networks are not convex. Swap two hidden units of a layer (their incoming and outgoing weights together): the network computes exactly the same function, so the loss is the same at two different points. If the loss were convex the midpoint would be at least as good, but the midpoint averages the two units into identical copies, usually a worse network. So there are many separate minima of equal value, and convexity in the logits says nothing about earlier layers' weights. What convexity buys: no bad local minima, a certificate of optimality (, or the KKT conditions with constraints), and rates that depend only on the condition number: with , gradient descent converges linearly at per step (section 4), Nesterov at about , and Newton quadratically near the end.
The chord definition over a whole distribution is Jensen's inequality (Boyd and Vandenberghe, section 3.1.8): for convex , , and for a concave such as it reverses. Example: is 1 or 4 with equal chance: against . It is why KL divergence is never negative (Information theory for ML):
and it gives the evidence lower bound (ELBO) of VAEs and diffusion models from (Variational inference and generative-model maths); EM is coordinate ascent on that bound.
Boyd and Vandenberghe, section 3.2: non-negative weighted sums of convex functions are convex; a convex function of an affine map is convex; the pointwise maximum of convex functions is convex; (log-sum-exp) is convex. These rules give every "yes" row of the table.
Sometimes the parameters must satisfy a condition: probabilities sum to 1, a weight vector stays inside a ball, a policy stays close to the old one. Walk along the constraint curve (here is a constraint function, not a gradient): where stops changing, every direction you may move is perpendicular to , and the curve's own normal is , so at the optimum the two gradients are parallel.
is the Lagrange multiplier and the Lagrangian: its gradient in gives the parallel condition and its derivative in gives back the constraint, so one unconstrained system replaces the constrained problem. The multiplier is a price: with the constraint , , how much the best value improves per unit the constraint is loosened. In the figure, and the constraint give , , ; on the circle the optimum is , whose derivative is 0.707 at , equal to .
To minimise subject to , the Karush-Kuhn-Tucker conditions at a solution with multipliers are (Boyd and Vandenberghe, section 5.5.3): stationarity ; primal feasibility ; dual feasibility (a constraint can only push, not pull); complementary slackness : either the constraint is tight or its multiplier is zero. For a convex problem with a strictly feasible point (Slater's condition) they are necessary and sufficient. Example: minimise subject to : the unconstrained answer 2 is outside, so the constraint binds, , and gives . With instead, the constraint is slack and .
Softmax. Among distributions over outcomes with scores , maximise the entropy with average score fixed at :
Differentiating in : , so , and the sum-to-one constraint fixes (Boyd and Vandenberghe, section 7.2, solve the same problem as a convex program).
TRPO. The paper (equation 55 in appendix C) maximises "subject to ". The Lagrangian gives ; the paper's "" is the length above with (they write for the Fisher), solved by conjugate gradient with Fisher-vector products and followed by a line search. TRPO and the clipped objective of PPO that replaced it: Policy gradients and actor-critic; the KL penalty in RLHF and GRPO: RL for LLMs.
Duality, in brief. Minimise the Lagrangian over for fixed multipliers: , the dual function. For any it is a lower bound on the best feasible value (weak duality), because on feasible points the added terms are . The dual problem maximises that bound; for convex problems under Slater's condition the best bound equals the answer (strong duality; Boyd and Vandenberghe, sections 5.2.2 and 5.2.3). The SVM's dual has one multiplier per training example and only inner products , which is what lets kernels replace them. Convex optimisation in full: Boyd and Vandenberghe, chapters 2 to 5.
The full loss is an average over examples, so a minibatch of random examples gives . It is unbiased, , and its variance falls as :
where is the average squared distance of one example's gradient from the mean, and the last factor corrects for sampling without replacement (it is 0 at ).
Repeat the descent lemma of section 4 with : the noise adds a term (variance) that does not shrink as the gradient does. So with a constant step SGD does not converge to the minimum; it settles in a region whose size is proportional to (for a strongly convex, smooth loss, Bottou, Curtis and Nocedal 2018, Theorem 4.6: a geometrically decaying term plus a floor proportional to the step). With a decreasing step satisfying the Robbins-Monro conditions , (large enough in total to get anywhere, small enough that the noise they add stays finite) the gap goes to zero; with it falls like (Theorem 4.7, after Robbins and Monro 1951).
This is why schedules decay the learning rate at the end of training; why a larger batch tolerates a larger step (less noise per step: the linear-scaling heuristic of Goyal et al. 2017) until the curvature limit of section 4 takes over; and why L-BFGS (section 6) does not carry over to minibatches. The noise also helps: it pushes the iterate off saddles and plateaus. In practice: Optimisers and learning-rate schedulers (sections 1 and 7).
Saddles, not bad local minima. Dauphin et al. 2014 gather arguments from statistical physics and random-matrix theory that for typical high-dimensional error functions "the ratio of the number of saddle points to local minima increases exponentially with the dimensionality": a minimum needs all Hessian eigenvalues positive, and if signs were anything like independent that would be exponentially rare. Critical points with high error tend to have a large index (many negative eigenvalues), so the minima that exist tend to have low error; they check it on small networks trained on down-sampled MNIST and CIFAR-10. Saddles are slow because plateaus surround them: gradient descent escapes along negative curvature, slowly, and Newton is attracted to them (section 5). The Optimisation lab's saddle function shows all three.
The edge of stability. Section 4 says gradient descent with step is unstable once the top Hessian eigenvalue, the sharpness, exceeds . Cohen et al. 2021 measured the sharpness during full-batch training of real networks and found progressive sharpening (below the sharpness "tends to continually rise") and then the edge of stability: "the maximum eigenvalue of the training loss Hessian hovers just above the value 2/(step size), and the training loss behaves non-monotonically over short timescales, yet consistently decreases over long timescales". The quadratic theory predicts divergence; the network instead adjusts its own curvature. Reproduced for this page on a small network (64 inputs, two hidden layers of 64 tanh units, 10 outputs; 8,970 parameters) trained by full-batch gradient descent on 1,000 of scikit-learn's bundled 8x8 handwritten digits, with squared error on one-hot targets (one of the two losses Cohen et al. study). Predict before choosing a step: at , whose limit 6.67 is below the starting sharpness of 8.6, does training diverge?
What it means. The step-size limit is real, but in a network it is not a fixed property of the problem: training drives the curvature to whatever the learning rate allows, and a higher learning rate selects flatter regions. This is one reason the learning rate acts as a regulariser, and why sharpness-aware minimisation (SAM; Foret et al. 2021), which minimises the worst loss in a small ball around the weights, looks for flat minima on purpose. Whether flatness causes better generalisation is still debated (sharpness changes under reparameterisation: Dinh et al. 2017).
Every 25 steps the sharpness is measured by power iteration with Hessian-vector products: the vector is repeatedly replaced by , and the Rayleigh quotient converges to the top eigenvalue; checked once against SciPy's Lanczos solver: 10.106 against 10.107. Cohen et al. report both cross-entropy and squared error; this run uses squared error.
is the number of parameters; the number of stored L-BFGS pairs.
| Method | Uses | Cost per step | When |
|---|---|---|---|
| Gradient descent, SGD | gradient | one gradient; memory | the default for deep networks; slow when is large |
| Momentum, Nesterov, Adam | gradient plus numbers of state per moment | one gradient | deep learning in practice: momentum tolerates ill-conditioning, Adam adds per-coordinate scaling |
| Newton (damped) | gradient and full Hessian | memory, about to solve | small smooth problems; few steps near a minimum; IRLS for GLMs |
| L-BFGS | gradient plus gradient differences | about plus a line search | full-batch deterministic problems of moderate size (logistic regression, CRFs, physics fits); not for noisy minibatches |
| Hessian-free, K-FAC, Shampoo | Hessian- or Fisher-vector products, or per-layer factors | a few gradients per step | when curvature matters and a full Hessian is out of reach |
| XGBoost leaves | per-example , | two numbers per example | boosted trees, one Newton step per leaf |
| Lagrange, KKT, duality | constraint gradients | problem-dependent | constraints: simplex, norm balls, KL budgets, margins |
For derivatives themselves (reverse mode for one loss and many parameters, forward mode for few inputs and many outputs, Hessian-vector products for curvature without the matrix) see Matrix calculus and backprop, section 7.
BCEWithLogitsLoss or CrossEntropyLoss, which expect logits, squashes twice and shrinks gradients. Computing log(softmax(z)) in two steps underflows; use the fused log-softmax.Pick a function and a method, then step through the run. At every iterate the inspector shows the gradient, the Hessian and its eigenvalues, what kind of point the curvature says this is, and the step Newton would take from here; on the plot the dashed curves are the contours of the second-order Taylor model at that point and the arrows are the Hessian's eigenvectors (blue: curves up, orange: curves down). Click anywhere on the plot to start from there. This lab is about the second-order view; for thirteen practical optimisers raced against each other see the Optimiser race tab of Optimisers and learning-rate schedulers.
Times are estimates for a careful first read. Book chapters are the ones this page leans on.
The parent: which maths each part of ML uses, the tiny model's training step with every number, and the objects that wear several hats. Its Gradient lab tab (loss explorer, backprop, curvature bowl with GD, momentum, Adam and Newton, Bernoulli curvature, log-sum-exp, eight gradient bugs) goes with this page.
Jacobians, layouts, the chain rule in matrix form, vector-Jacobian products, autodiff, backprop's cost and memory, Hessian-vector products.
Eigenvalues, symmetric and positive definite matrices, the condition number, least squares: the linear algebra behind sections 3 to 6.
Why each loss of section 2 is a negative log-likelihood; MLE and MAP (weight decay as a Gaussian prior).
Estimation, bias and variance, the bootstrap, hypothesis tests.
Entropy, cross-entropy, KL divergence (the TRPO constraint and Jensen's inequality of section 8).
Floating point, precision formats, the stable softmax and log-sum-exp.
The ELBO (Jensen), VAEs and diffusion.
How SGD, momentum, Adam, Muon, Shampoo and schedules behave in practice, with the evidence and an Optimiser race tab of thirteen update rules.
The catalogue of losses and when to use each; this page supplies their gradients.
Conditioning fixes in practice.
Weight decay and its constraint view.
Logistic regression, SVMs and boosted trees (XGBoost) in context.
TRPO's KL-constrained update and PPO.
KL penalties and constraints in language-model training.
Activation checkpointing and the memory of the backward pass at scale.
Vector calculus (Taylor series, gradients, Hessians) and continuous optimisation (gradient descent, momentum, constrained optimisation, convexity). Free PDF.
Convex functions and Jensen (3.1), duality and KKT (5.2, 5.5), gradient descent and Newton's method with their analyses (9.3, 9.5). Free PDF.
Taylor's theorem and optimality conditions, line searches (Wolfe), quasi-Newton and BFGS, L-BFGS. The reference for how real solvers work.
Why SGD works, with the fixed-step floor and the diminishing-step rate of section 10.
A deep-learning-focused refresher on derivatives of vector functions.
Momentum on a quadratic, eigenvalue by eigenvalue, with live figures; the source of section 4's formulas.
Progressive sharpening and sharpness at 2/η (section 11).
Why saddles, not local minima, dominate in high dimensions; saddle-free Newton.
The second-order expansion, leaf weights and split gain of section 7. Also the Introduction to boosted trees tutorial (20 min).
The KL-constrained step solved with conjugate gradient (section 9).
Fisher, Gauss-Newton and the Hessian; natural gradient as a second-order method.
The update rule and, in section 5, its relation to the diagonal Fisher.
Nesterov momentum in the form used by deep-learning libraries.
Seeking flat minima on purpose; read with Dinh et al. 2017 on why sharpness is not reparameterisation-invariant (30 min).
Hand-worked numbers and the tiny model: recomputed by src/recompute.py (numpy, sympy). Real runs: src/inputs/lr_real.py (scikit-learn 1.9.1's bundled breast-cancer data, NumPy, SciPy 1.18.1 L-BFGS-B) and src/inputs/eos.py, eos_extra.py (PyTorch 2.14.1, float64, scikit-learn's bundled digits), all run on 5 October 2026. The old page "Calculus and optimisation for ML" is saved verbatim in src/live.md; src/coverage.json says where each of its facts is now.