Mathematical Foundations

VI.2 · Optimization

When does a stop mean we have found the best point?

Compare local neighborhoods with the entire objective domain. Zero gradients locate candidates; curvature and explicit lower-value witnesses decide what those candidates actually guarantee.

Inspect what a stationary point means

Parameter space: θ₁ and θ₂

Candidate θ ≈ (2, 1); objective ≈ 4; gradient ≈ (2, 4). Coordinates are model parameters; data inputs are held fixed. This candidate is not a stationary point. The marked points are the complete analytic stationary set of this example.

Loss slice: θ₂ = 0

This is a slice of the objective in parameter space, with θ₂ fixed at zero.

Candidate parameters
(2, 1)
Objective value
4
Actual gradient
(2, 4)
Hessian of the objective
(1, 0); (0, 4)
Stationary classification
not a smooth stationary point

≈ binary64 calculation · = analytic classification. Replay selects the same evaluated step in every view.

This candidate is not a stationary point. The marked points are the complete analytic stationary set of this example.

L=a2(θ1−c)2+2θ22L=\tfrac a2(\theta_1-c)^2+2\theta_2^2
Analytically classified stationary points
θClassificationGlobal behavior
(0, 0)strict minimumunique global minimum

Evaluate the candidate

Candidate θ ≈ (2, 1); objective ≈ 4; gradient ≈ (2, 4). Coordinates are model parameters; data inputs are held fixed.

L=a2(θ1−c)2+2θ22L=\tfrac a2(\theta_1-c)^2+2\theta_2^2

from −3 to 3, up to 2 decimal places

from −3 to 3, up to 2 decimal places

from 0.25 to 4, up to 2 decimal places

from −2 to 2, up to 2 decimal places

Compare a stationary point with nearby and distant points. A zero gradient supplies a candidate; loss comparisons and curvature explain its status.

For the cubic x3−3x+y2x^3-3x+y^2, inspect (1,0)(1,0) and then (−3,0)(-3,0). The first is a strict local minimum with loss −2-2; the second has loss −18-18. Predict why a correct local-minimum label and a failed global claim can both describe the same candidate.

Intuition: best nearby and best everywhere

Imagine tuning a controller in small increments. Every small change from a setting may worsen its score, while a very different setting performs much better. The first comparison is local. A global claim must compare every feasible parameter choice, including regions a short run never visits.

A stationary point is where first-order sensitivity vanishes. It may be a valley, a peak, a saddle, or a degenerate point that second-order curvature cannot classify. A gradient-based algorithm can remain fixed at any of these. No movement is a fact about its update rule; optimality is a claim about the objective.

Definition: neighborhoods, domains, and stationarity

A point p∈Dp\in D is a local minimum if some radius r>0r>0 satisfies

L(p)≤L(q)for all q∈D with ∥q−p∥<r.L(p)\leq L(q)\quad\text{for all }q\in D\text{ with }\norm{q-p}<r.

It is a strict local minimum when the inequality is strict for every such q≠pq\ne p. A global minimum satisfies L(p)≤L(q)L(p)\leq L(q) for every q∈Dq\in D. Maxima reverse these inequalities. A stationary point is a differentiable point with ∇L(p)=0\nabla L(p)=0.

Here a saddle has both higher and lower objective values arbitrarily near a stationary point. The term is local; it does not say whether distant global optima exist. Stationarity is a necessary condition for a differentiable interior local optimum, not a sufficient condition. Boundary and nonsmooth optima require different reasoning.

Mechanics: inspect the candidate and its witnesses

For each candidate read its parameter coordinates, loss, and gradient, then calculate its Hessian for the curvature test. First check whether the objective is differentiable there and whether the gradient vanishes. Only then apply a stationary-point curvature test. A positive-definite Hessian at a nonstationary point describes local bending, not an optimum at that point.

Use nearby displacements along both coordinate directions to test the meaning of a label. To disprove globality, one valid lower-loss point is enough. To prove globality, several successful comparisons are insufficient: use a bound or a whole-domain property. Resetting the view or changing its extent cannot supply that proof.

Derivation: why zero gradient is necessary but insufficient

At a differentiable interior local minimum, consider any direction uu. The one-variable function ϕ(t)=L(p+tu)\phi(t)=L(p+tu) has a minimum at t=0t=0, so

0=ϕ′(0)=∇L(p)⋅u.0=\phi'(0)=\nabla L(p)\cdot u.

Taking each coordinate direction gives ∇L(p)=0\nabla L(p)=0. This argument uses valid points on both sides of zero and differentiability. It cannot be applied to ∣x∣\abs{x} at zero or to a direction leaving a feasible boundary.

If LL is twice continuously differentiable near a stationary point, Taylor expansion gives

L(p+δ)−L(p)=12δTH(p)δ+o(∥δ∥2).L(p+\delta)-L(p)=\frac12\delta^{\mathsf T}H(p)\delta+o(\norm{\delta}^2).

Positive-definite HH makes the leading quadratic positive in every nonzero direction, establishing a strict local minimum. Negative-definite HH establishes a strict local maximum. Opposite-sign eigenvalues establish a saddle. A zero eigenvalue leaves the test inconclusive because the remainder can decide the sign along a flat quadratic direction.

For the cubic, solve the equations directly:

∇L=(3x2−3,2y)=0⟹(x,y)=(−1,0) or (1,0),H=diag⁡(6x,2).\nabla L=(3x^2-3,2y)=0 \quad\Longrightarrow\quad (x,y)=(-1,0)\text{ or }(1,0), \qquad H=\operatorname{diag}(6x,2).

Worked examples: one local minimum, no global minimum

At (1,0)(1,0) the cubic has loss −2-2 and Hessian diag⁡(6,2)\operatorname{diag}(6,2). An exact expansion makes the local guarantee visible:

L(1+u,v)−L(1,0)=3u2+u3+v2=u2(3+u)+v2.L(1+u,v)-L(1,0)=3u^2+u^3+v^2=u^2(3+u)+v^2.

For ∣u∣<1\abs{u}<1, this is positive whenever (u,v)≠(0,0)(u,v)\ne(0,0). Thus the point is a strict local minimum. Yet

L(−3,0)=−27+9=−18<−2,L(−n,0)=−n3+3n⟶−∞.L(-3,0)=-27+9=-18<-2, \qquad L(-n,0)=-n^3+3n\longrightarrow-\infty.

The witness disproves globality; the limit shows the entire objective is unbounded below, so it has no global minimum. At (−1,0)(-1,0) the Hessian diag⁡(−6,2)\operatorname{diag}(-6,2) gives a saddle, not a two-dimensional maximum.

The worked stage returns to the canonical quadratic rather than the cubic. At (2,1)(2,1) it has loss 44 and gradient (2,4)(2,4), so the current candidate is not stationary. Its marked stationary point is (0,0)(0,0); nonnegativity of both squared terms proves that point is the unique global minimum. Use the opening explorer for the cubic comparisons.

Worked example: Inspect what a stationary point means

Parameter space: θ₁ and θ₂

Candidate θ ≈ (2, 1); objective ≈ 4; gradient ≈ (2, 4). Coordinates are model parameters; data inputs are held fixed. This candidate is not a stationary point. The marked points are the complete analytic stationary set of this example.

Loss slice: θ₂ = 0

This is a slice of the objective in parameter space, with θ₂ fixed at zero.

Candidate parameters
(2, 1)
Objective value
4
Actual gradient
(2, 4)
Hessian of the objective
(1, 0); (0, 4)
Stationary classification
not a smooth stationary point

≈ binary64 calculation · = analytic classification. Replay selects the same evaluated step in every view.

This candidate is not a stationary point. The marked points are the complete analytic stationary set of this example.

L=a2(θ1−c)2+2θ22L=\tfrac a2(\theta_1-c)^2+2\theta_2^2
Analytically classified stationary points
θClassificationGlobal behavior
(0, 0)strict minimumunique global minimum

Evaluate the candidate

Candidate θ ≈ (2, 1); objective ≈ 4; gradient ≈ (2, 4). Coordinates are model parameters; data inputs are held fixed.

L=a2(θ1−c)2+2θ22L=\tfrac a2(\theta_1-c)^2+2\theta_2^2

Replay the canonical quadratic candidate (2,1), which is not stationary, and compare it with the marked unique global minimizer (0,0).

The double well behaves differently. Its gradient and Hessian are

∇L=(4x(x2−1),2y),H=diag⁡(12x2−4,2).\nabla L=(4x(x^2-1),2y),\qquad H=\operatorname{diag}(12x^2-4,2).

The stationary points are (−1,0),(0,0),(1,0)(-1,0),(0,0),(1,0). Both outer points have loss 00. Because (x2−1)2+y2≥0(x^2-1)^2+y^2\geq0 everywhere, these are global minima. At the middle the loss is 11 and the Hessian is diag⁡(−4,2)\operatorname{diag}(-4,2): movement along x lowers loss, while movement along y raises it. The middle is a saddle even though the horizontal slice has a local maximum there.

Executable reference code

The independent standard-library reference solves the polynomial stationary cases by explicit substitution and evaluates their loss and diagonal Hessian entries exactly. Assertions include the literal cubic witness −18-18, both double-well minimizers, a maximum, a saddle, and inconclusive Hessians. Higher-order and one-sided evaluations check why inconclusive and nonsmooth cases need separate arguments.

The NumPy reference batches the candidates and sends their symmetric Hessians to numpy.linalg.eigvalsh. This is a library cross-check of the signs, not a floating search for roots. Its finite tail values illustrate the cubic’s decline; the analytic polynomial limit remains the proof of unboundedness.

code/python/optimization_optima.py
"""Exact stationary-point calculations and counterexamples to local/global claims."""
from fractions import Fraction as F


def cubic(x, y):
    x, y = F(x), F(y)
    return x**3 - 3*x + y*y, (3*x*x - 3, 2*y), (6*x, F(2))


def double_well(x, y):
    x, y = F(x), F(y)
    return (x*x - 1)**2 + y*y, (4*x*(x*x - 1), 2*y), (12*x*x - 4, F(2))


def diagonal_test(diagonal):
    # A zero eigenvalue leaves this second-order test inconclusive.
    first, second = diagonal
    if first > 0 and second > 0:
        return "strict local minimum"
    if first < 0 and second < 0:
        return "strict local maximum"
    if first * second < 0:
        return "saddle"
    return "inconclusive"


def main():
    for x, expected in ((-1, "saddle"), (1, "strict local minimum")):
        loss, gradient, diagonal = cubic(x, 0)
        assert gradient == (0, 0)
        assert diagonal_test(diagonal) == expected
        assert loss == (2 if x == -1 else -2)
    assert cubic(-3, 0)[0] == -18 < cubic(1, 0)[0]
    # Along x=-n, y=0 the values -n^3+3n tend to minus infinity.
    assert [cubic(-n, 0)[0] for n in (2, 3, 4)] == [-2, -18, -52]
    for x, expected in ((-1, "strict local minimum"), (0, "saddle"), (1, "strict local minimum")):
        loss, gradient, diagonal = double_well(x, 0)
        assert gradient == (0, 0) and diagonal_test(diagonal) == expected
        assert loss == (1 if x == 0 else 0)
    assert diagonal_test((-2, -2)) == "strict local maximum"  # -x^2-y^2.
    assert diagonal_test((2, -2)) == "saddle"  # x^2-y^2.
    assert diagonal_test((0, 0)) == "inconclusive"  # x^4+y^4 has a minimum.
    assert diagonal_test((0, 2)) == "inconclusive"  # x^3+y^2 has a saddle.
    h = F(1, 10)
    assert h**4 + h**4 > 0
    assert (-h)**3 < 0 < h**3
    assert (abs(-h)/(-h), abs(h)/h) == (-1, 1)  # |x|+y^2: no gradient at x=0.
    print("Exact cubic stationary points: (-1,0) saddle; (1,0) local minimum")
    print("Exact lower witness (-3,0):", cubic(-3, 0)[0], "; no global minimum")
    print("Exact double-well minimizers: (-1,0), (1,0); loss 0")


if __name__ == "__main__":
    main()
code/python/optimization_optima_numpy.py
"""Vectorized stationary candidates and NumPy Hessian eigenvalue cross-checks."""
import numpy as np


def main():
    candidates = np.array([[-1, 0], [1, 0]], dtype=np.float64)
    x, y = candidates.T
    cubic_gradients = np.column_stack((3*x*x - 3, 2*y))
    cubic_hessians = np.zeros((2, 2, 2), dtype=np.float64)
    cubic_hessians[:, 0, 0], cubic_hessians[:, 1, 1] = 6*x, 2
    np.testing.assert_array_equal(cubic_gradients, np.zeros((2, 2)))
    eigenvalues = np.linalg.eigvalsh(cubic_hessians)
    np.testing.assert_array_equal(eigenvalues, [[-6, 2], [2, 6]])
    np.testing.assert_array_equal(x**3 - 3*x + y*y, [2, -2])
    witnesses = -np.array([2, 3, 4], dtype=np.float64)
    np.testing.assert_array_equal(witnesses**3 - 3*witnesses, [-2, -18, -52])
    well_x = np.array([-1, 0, 1], dtype=np.float64)
    well_gradients = 4*well_x*(well_x*well_x - 1)
    well_hessians = np.zeros((3, 2, 2), dtype=np.float64)
    well_hessians[:, 0, 0], well_hessians[:, 1, 1] = 12*well_x*well_x - 4, 2
    np.testing.assert_array_equal(well_gradients, [0, 0, 0])
    np.testing.assert_array_equal(np.linalg.eigvalsh(well_hessians), [[2, 8], [-4, 2], [2, 8]])
    degenerate_hessians = np.array([[[0, 0], [0, 0]], [[0, 0], [0, 2]]], dtype=np.float64)
    np.testing.assert_array_equal(np.linalg.eigvalsh(degenerate_hessians), [[0, 0], [0, 2]])
    h = np.array([-0.1, 0.1], dtype=np.float64)
    assert np.all(h**4 > 0) and h[0]**3 < 0 < h[1]**3
    print("Binary64 Hessian eigenvalues at cubic candidates ≈", eigenvalues)
    print("Zero eigenvalues are inconclusive: compare x^4+y^4 with x^3+y^2.")
    print("Finite witnesses disprove globality; the polynomial tail proves unboundedness.")


if __name__ == "__main__":
    main()

Explore: identical stopping behavior, different outcomes

At the origin, compare −x2−y2-x^2-y^2 and x2−y2x^2-y^2. Both have zero gradient. The first has a unique global maximum of 00; the second has a saddle, with losses h2h^2 and −h2-h^2 along the coordinate directions. Neither is a minimum for an unconstrained minimization problem.

Next compare x4+y4x^4+y^4 with x3+y2x^3+y^2. Both are stationary at the origin and have singular positive-semidefinite Hessians there. The fourth-power objective is positive at every nonzero point, proving a strict global minimum. The degenerate cubic takes values −h3-h^3 and h3h^3 at (−h,0)(-h,0) and (h,0)(h,0) for every h>0h>0, proving a saddle.

Finally inspect ∣x∣+y2\abs{x}+y^2. It is nonnegative and vanishes only at the origin, so it has a unique global minimum. Its left and right x slopes are −1-1 and 11, so the classical gradient is undefined there. A correct label must preserve both facts.

Common mistakes and counterexamples

“Gradient zero” does not mean “minimum”: the peak and saddle already disprove it. “Positive Hessian here” does not mean “global”: the cubic’s strict local minimum already disproves it. “Hessian semidefinite here” does not even mean “local minimum”: x3+y2x^3+y^2 at the origin disproves that stronger claim.

Do not judge classification by the sign of the loss. Adding a constant preserves every local and global comparison, so a positive loss can mark a minimum and a negative loss can mark a maximum. Also distinguish a one-dimensional slice from the full domain. The central double-well slice peaks in x while the full objective rises in y.

Numerical considerations

The rational polynomial examples support exact stationary equations and exact sign tests. A numerical trajectory is a binary64 approximation: a small computed gradient can reflect proximity to a stationary point, poor scaling, rounding, or an unreliable derivative. It does not supply an exact stationarity certificate or a global comparison.

Near a zero Hessian eigenvalue, small numerical errors can change a reported sign. Treat a numerically unresolved sign as unresolved and inspect scale and tolerances. Sampling a shrinking neighborhood can illustrate a saddle, but a plot that rounds all nearby values together may conceal higher-order behavior. For x4+y4x^4+y^4, the loss decays as the fourth power of displacement, faster than its quadratic model can reveal.

Engineering and ML connections

An optimizer’s initialization can determine which region of a nonconvex objective it explores. Trying several starts can expose alternative outcomes, but it does not prove that the best observed one is globally optimal. An engineering report should say whether its guarantee is local, global, or only empirical.

Hessian and curvature supplies the second-order test; convexity will add a whole-domain condition that converts local minima into global ones. In gradient descent, a zero update at a saddle will make the distinction operational. Nonsmooth penalties and feasible boundaries also require conditions beyond the differentiable-interior gradient test.

Exercises

Use explicit witnesses when rejecting a global claim, and a bound when proving one. Every classification must state which hypotheses justify it.

construction

Solve the cubic stationary equations

For L=x³−3x+y², solve ∇L=0. Give the negative stationary x, the positive stationary x, their common y, and the losses in that same x order.

explanation

Disprove a global claim with a witness

The cubic x³−3x+y² has positive-definite Hessian at (1,0), where L=−2. Which global conclusion follows?

Choose one answer

calculation

Classify the middle of the double well

For L=(x²−1)²+y², give losses at (−1,0), (0,0), (1,0), followed by the xx and yy Hessian entries at (0,0).

explanation

Go beyond a singular Hessian

At the origin, x⁴+y⁴ has Hessian diag(0,0), while x³+y² has Hessian diag(0,2). What do these objectives actually do nearby?

Choose one answer

explanation

A minimum without a classical gradient

What happens at (0,0) for L=|x|+y² on the whole plane?

Choose one answer

Summary and checkpoints

Local optima compare a neighborhood; global optima compare the whole domain. Zero gradients locate differentiable interior candidates, and definite Hessians classify them locally. Check that you can explain why (1,0)(1,0) is a cubic local minimum but not global, prove both double-well minima globally, and resolve singular or nonsmooth examples without fabricating a derivative. A stopped algorithm still needs an objective-level interpretation.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available