16.1 Convexity, smoothness, gradient descent, and Armijo line search
The first decision you make when you train a model is the learning rate, and the first ways it fails are dramatic. In Training loop and the autograd bigram from AI Engineering, the bigram stops being a table of counts and becomes 65536 weights trained by gradient descent. Pick the learning rate too large and the loss jumps to inf, then NaN, within a few steps. Pick it too small and the loss crawls for thousands of steps toward the negative log-likelihood that the count model of Byte bigram: counts, logits, safetensors v0 reached instantly.
Concepts from other sections (6)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Negative log-likelihood (NLL): , the surprise of the true token under the model, in nats. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Backtracking: depth-first search over a tree of partial solutions that makes a choice, recurses, and undoes the choice, abandoning any branch that cannot lead to a valid solution; it enumerates subsets, permutations, and solutions to constraint problems. Read more: Chapter 11: Backtracking in Programming and Algorithms
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Tangent plane: the plane that best approximates the surface near a point, the two-variable analogue of the tangent line. Read more: Chapter 10: Calculus 3
Both symptoms have exact explanations on a quadratic, which is the local model of every smooth loss. The step must stay under , where measures the steepest curvature, and the number of steps scales with the condition number . This section derives both facts, then builds plain gradient descent and a backtracking line search that chooses a step without knowing at all. The update you build here is exactly what the next section, The Optimizer protocol: SGD, momentum, Nesterov, weight decay, generalizes.
You will need gradients, from Partial derivatives, gradients, and gradcheck, and the eigenvalues of a symmetric matrix, from Eigenvalues, power iteration, and the spectral radius. The reference solution is course/solutions/python/tinyllm/optim/gd.py, and its interface is fixed by the contract course/contracts/py/tinyllm/optim/gd.pyi.
Learning objectives
- Derive the step-size limit for gradient descent on a quadratic from its eigen-decomposition.
- Prove that gradient descent with step shrinks the optimality gap by at least per step on an -smooth, -strongly convex function.
- State the Armijo sufficient-decrease condition and explain why backtracking terminates on a smooth function.
- Implement
gradient_descentandarmijo_stepso that divergence, NaN trial points, and non-descent directions are handled correctly.
Notation
Section titled “Notation”The section uses a small set of symbols throughout; this table collects them with the type each takes in code.
| Symbol | Meaning | Type / shape |
|---|---|---|
| the function to minimize (a loss) | callable | |
| its gradient at | float64[n] | |
| , | a minimizer and the minimum value | float64[n], float |
(lr) | the learning rate (step size) | float |
| the iterate after steps | float64[n] | |
| smoothness constant: | float | |
| strong convexity constant | float | |
| the condition number | float | |
| a symmetric positive definite matrix; for a quadratic, the Hessian | float64[n, n] | |
| eigenvalues of , with and | floats | |
| a search direction | float64[n] | |
| , , , | trial step, first trial, shrink factor, sufficient-decrease constant | floats |
Convexity, smoothness, and the condition number
Section titled “Convexity, smoothness, and the condition number”A function is convex if the chord between any two points of its graph lies above the graph: for . For differentiable this is equivalent to every tangent plane lying below the graph:
Then implies for all : every stationary point is a global minimum. Neural network losses are not convex, but near a minimum they look like convex quadratics, and that is where the rates below describe what you actually see.
Convexity says the function lies above its tangents. To say anything about rates you also need to sandwich it between two parabolas. Smoothness supplies the upper one. If the gradient is -Lipschitz, the function never curves up faster than a parabola of curvature ; this is the descent lemma:
Strong convexity supplies the lower one. is -strongly convex if : it curves up at least as fast as a parabola of curvature . For a quadratic , the gradient is , and the best constants are the extreme eigenvalues of : and .
The ratio of the two curvatures is the condition number, . It measures how stretched the level sets are: is a round bowl, is a long narrow valley. In Error analysis, condition numbers, and tolerance budgets you will meet the condition number of a matrix, ; for a symmetric positive definite it is the same .
Gradient descent and its rate
Section titled “Gradient descent and its rate”With the two bounds in hand, the rate of gradient descent follows in three lines. The update is . Put in the descent lemma with :
Strong convexity implies ; you get this by minimizing both sides of its defining inequality over . Combining the two,
To shrink the gap by a factor takes about steps: ten times the condition number, ten times the steps.
On a quadratic you can do better than a bound and see the dynamics exactly. For , write in the eigenvectors of . Gradient descent then acts independently on each coordinate:
The coordinate shrinks when , that is, . For all coordinates at once the condition is . Above the stiffest direction grows by per step, and that is the loss that jumps to inf. At the stiffest direction is solved in one step and the flattest shrinks by , so the bound above is attained.
Line search: a step without knowing
Section titled “Line search: a step without knowing LLL”The analysis assumes you know , and real losses do not announce it. A line search picks the step adaptively. Given a direction with (a descent direction, for example ), try and accept it if the Armijo condition holds:
The right side is a line through with a fraction of the initial slope, and the step must land below it. If it does not, set and try again. For an -smooth and , the descent lemma shows every is accepted, so backtracking stops after a bounded number of reductions with a step of at least . If is not a descent direction, no small step helps, and the search must refuse instead of halving forever.
One numerical detail turns out to matter as much as the math. A trial point outside the function’s domain (a log of a negative number, an overflow) gives nan, and every comparison with NaN is false. Written as if f(x + a d) <= bound: return a, a NaN fails the test and the step shrinks. Written as while f(x + a d) > bound: a *= rho, the NaN makes the loop condition false and the bad step is accepted. The two forms are the same math with opposite behavior, so NaN must be treated as a rejection by construction.
Working it by hand
Section titled “Working it by hand”Run gradient descent on . Here , so , , , and . Start at with ; the first two steps are:
| 0 | 55 | |||
| 1 | 40.5 | 0.736 | ||
| 2 | 32.805 | 0.81 |
The stiff coordinate is multiplied by and is done in one step. The flat one is multiplied by , so its share of shrinks by per step, inside the bound . With , just over , the stiff coordinate is multiplied by per step: it alternates sign and grows without bound.
Now run one Armijo search on at along , with , , . The slope is , and the trials go like this:
| bound | accept? | |||
|---|---|---|---|---|
| 1 | 1 | 0.9996 | no | |
| 0.5 | 0 | 0 | 0.9998 | yes |
The full step overshoots to the mirror point with the same value; half of it lands on the minimum. The search returns 0.5. These two hand computations are the first things a correct implementation must reproduce.
Designing the interface
Section titled “Designing the interface”The two functions have small signatures:
def gradient_descent(f, grad, x0, lr: float, steps: int) -> list[NDArray] # [x_0, ..., x_steps]def armijo_step(f, grad, x, d, alpha0: float = 1.0, c: float = 1e-4, rho: float = 0.5) -> floatgradient_descent returns steps + 1 independent float64 arrays and never modifies x0. It evaluates f at each iterate only to detect divergence: a non-finite value raises FloatingPointError naming the step. A learning rate or a negative step count is a ValueError. armijo_step raises ValueError for a non-descent direction or for parameters outside , , , and RuntimeError after 60 reductions without success.
Those rules are what the tests hold the code to. Beyond the hand-worked trajectory and search, the gap must satisfy at every step on quadratics with = 2, 10, and 100, and a float trajectory must match an exact fractions.Fraction recomputation to rounding. On the same quadratic with , must raise FloatingPointError while converges. For the line search, the returned step must satisfy the Armijo condition while twice it does not, checked on 50 Rosenbrock points, so the search returns the largest acceptable step on its grid. A full step that already works is returned unchanged. On at 1 along the search needs two halvings and returns , which checks that each trial shrinks the previous one. A function whose trial values are NaN must have those trials rejected, ending at 0.125. Ascent and orthogonal directions and bad , , must raise. A lying gradient must end in RuntimeError, with the 60th halving, , still tried. Finally, 300 steepest-descent steps with Armijo on Rosenbrock must decrease monotonically, which is the whole point: a usable step size without knowing .
Building it step by step
Section titled “Building it step by step”The reasoning chain is short, and each step answers one of the requirements above.
- The update is one line. . Everything else in
gradient_descentexists to make the trajectory trustworthy as data. - A trajectory is a list of independent snapshots. Callers plot and compare iterates, so each must be a separate array, and the caller’s
x0must not change. Writingx = x - lr * g(a new array each step) rather thanx -= lr * ggives that for free. - Divergence must be loud. Above the stiff coordinate grows by per step. A list of
infand NaN returned as a “trajectory” hides the bug, so every iterate, including the last, is checked and the first non-finite value raises. - Armijo needs the slope once. The bound uses and the slope at ; compute both once, before the loop.
- Refuse a non-descent direction. If the slope is , no positive step can satisfy the bound for small , so backtracking would halve forever; raise instead.
- Write the test so NaN fails it.
if f(new) <= bound: returntreats NaN as a rejection; thewhile f(new) > boundform accepts it. - Bound the loop. For an -smooth the search stops after a bounded number of halvings. If it does not, the gradient is lying, and after 60 reductions (a factor ) it raises rather than returning a meaningless step.
Here is gradient descent with those decisions in place:
MAX_REDUCTIONS = 60
def gradient_descent(f, grad, x0, lr: float, steps: int) -> list[NDArray]: if not lr > 0: # also rejects lr = nan raise ValueError(f"lr must be > 0, got {lr}") if steps < 0: raise ValueError(f"steps must be >= 0, got {steps}") x = np.array(x0, dtype=np.float64, copy=True) # never alias the caller's x0 out = [x] # x_0 is part of the trajectory for t in range(steps + 1): fx = float(f(x)) if not (math.isfinite(fx) and np.isfinite(x).all()): raise FloatingPointError(f"gradient descent diverged at step {t}: f(x_t) = {fx}") if t == steps: break # x_steps is checked, but not stepped from x = x - lr * np.asarray(grad(x), dtype=np.float64) # a new array, not in place out.append(x) return outThe loop runs steps + 1 times so that the divergence check sees every iterate, through , while only steps updates are made. The guard is not lr > 0 instead of lr <= 0 because a NaN learning rate fails both comparisons, and only the first form rejects it. In the hand example, lr=0.1 from produces [(10, 1), (9, 0), (8.1, 0)] for steps=2. With lr=3 on the same quadratic, the stiff coordinate grows by per step and the function raises at the first iterate whose is no longer finite.
The line search follows the same pattern: validate, compute the fixed quantities once, then loop with a test that is safe on NaN.
def armijo_step(f, grad, x, d, alpha0=1.0, c=1e-4, rho=0.5) -> float: if not (0 < c < 1 and 0 < rho < 1 and alpha0 > 0): raise ValueError(f"need 0 < c < 1, 0 < rho < 1, alpha0 > 0; got c={c}, rho={rho}, alpha0={alpha0}") x = np.asarray(x, dtype=np.float64) d = np.asarray(d, dtype=np.float64) fx = float(f(x)) slope = float(np.dot(np.ravel(grad(x)), np.ravel(d))) # grad f(x)^T d, any shape if not slope < 0: # ascent, orthogonal, or nan: refuse raise ValueError(f"d is not a descent direction: grad(x) . d = {slope}") alpha = alpha0 for _ in range(MAX_REDUCTIONS + 1): # alpha0 and 60 reductions: 61 trials # Written so that a nan f(x + alpha d) fails the test and shrinks alpha. if f(x + alpha * d) <= fx + c * alpha * slope: return alpha # the first acceptable step, unshrunk alpha *= rho # shrink the previous trial, not alpha0 raise RuntimeError(f"no step satisfies the Armijo condition after {MAX_REDUCTIONS} reductions")Trace the hand search through it: and the slope is . Trial gives , so it is rejected and . Trial gives , and the function returns 0.5. The loop count is MAX_REDUCTIONS + 1 so that the 60th reduction, , is actually tried before giving up. np.ravel lets be a matrix (a weight array) as well as a vector.
The full solution is in gd.py.
Why this design
Section titled “Why this design”Consider cost first. gradient_descent makes steps gradient calls and steps + 1 function calls, and stores steps + 1 arrays: memory, which is the point, since it returns the trajectory. armijo_step costs one gradient, one , and one per trial; on an -smooth function the number of trials is at most .
Copies beat in-place updates here. In-place x -= lr * g saves an allocation per step, but appending the same array object every step makes every entry the final iterate. For a reference whose output is a trajectory, a fresh array per step is the correct choice. The optimizers of the next section update in place because they return nothing.
Raising beats clamping or skipping. Silently stopping at the last finite iterate would hide a learning-rate bug; raising names the step where it happened.
Backtracking Armijo beats exact line search for this purpose. Minimizing exactly costs many evaluations and buys little for gradient descent. Armijo needs only values, guarantees sufficient decrease, and is the building block of Wolfe searches (see Further reading). Halving instead of interpolating is simpler and loses at most a factor in step length.
What can go wrong
Section titled “What can go wrong”Most bugs in these two functions are one character away from the correct code, and each produces a recognizable symptom:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| a learning rate above with no divergence check | a list of inf and NaN returned as a trajectory | checks every iterate and raises FloatingPointError |
while f(new) > bound | a NaN trial point is accepted | if f(new) <= bound: return, so NaN is a rejection |
| searching along a direction that does not descend | halving forever, or accepting an ascent | if not slope < 0: raise ValueError |
updating x in place and appending it | every entry of the trajectory is the final iterate; x0 changes | copies x0 once and builds a new array each step |
| the sign of the step | gradient ascent | x - lr * grad(x) |
| the sign of the Armijo bound | steps that increase are accepted | the bound is fx + c * alpha * slope with slope < 0 |
| shrinking once more after success | steps half as long as they could be | returns alpha before alpha *= rho |
| returning a vanishing step instead of giving up | silent stalls at | raises RuntimeError after MAX_REDUCTIONS |
| leaving out of the trajectory | every index is off by one | out = [x] before the loop |
restarting each trial from , alpha = alpha0 * rho | only and are ever tried; a search that needs two halvings gives up | alpha *= rho shrinks the previous trial |
Warning: The NaN pitfall is the one that survives code review, because the
whileform looks like a faithful transcription of the math. Test it with a function that returns NaN outside its domain.
Where this leads
Section titled “Where this leads”The next section, The Optimizer protocol: SGD, momentum, Nesterov, weight decay, wraps this update behind a common interface: SGD with momentum 0 performs exactly this step, in place. In AI Engineering, Training loop and the autograd bigram chooses the bigram’s learning rate and reads its loss curve with and . Measuring the top Hessian eigenvalue during training against the edge of stability (Cohen et al., below) applies the same eigen-direction analysis to real networks, and Error analysis, condition numbers, and tolerance budgets generalizes to the condition number of a matrix and of a problem.
Further reading
Section titled “Further reading”- Boyd and Vandenberghe, Convex Optimization, sections 3.1 and 9.2 to 9.3; Nocedal and Wright, Numerical Optimization (2nd ed.), chapter 3.
scipy.optimize.line_search(scipy/optimize/_linesearch.py) is the production version ofarmijo_step: it enforces the strong Wolfe conditions (a curvature test as well as Armijo) and interpolates instead of halving.- PyTorch’s
torch.optim.LBFGS(line_search_fn="strong_wolfe")(torch/optim/lbfgs.py) puts a line search in a training loop with quasi-Newton directions that undo much of . - Conjugate gradient needs about instead of steps on quadratics, by choosing -orthogonal directions; see Nocedal and Wright, chapter 5.
Key terms
Section titled “Key terms”- Convex function: a function whose chords lie above its graph; every stationary point is a global minimum.
- -smooth: having an -Lipschitz gradient, so the function lies below a parabola of curvature (the descent lemma).
- -strongly convex: lying above a parabola of curvature at every point.
- Condition number : the ratio ; for a quadratic, of the Hessian.
- Descent direction: a direction with .
- Armijo condition: the sufficient-decrease test .
- Backtracking line search: trying until the Armijo condition holds.
Summary
Section titled “Summary”- On an -smooth, -strongly convex function, gradient descent with step shrinks the optimality gap by at least per step, so it needs about steps.
- On a quadratic, each eigen-direction is multiplied by per step, so the iteration converges exactly when and blows up beyond it.
- Backtracking with the Armijo condition finds a step that decreases enough without knowing , and returns the first acceptable step of .
- Numerical edge cases are part of the algorithm: a NaN trial value must be rejected, a direction that does not descend must be refused, and divergence must raise.
Review questions
Section titled “Review questions”-
Why does the gradient-descent loop run
steps + 1times when it makes onlystepsupdates?Answer
So that every iterate, including the last one, passes the divergence check. The final pass checks and then breaks before computing another update. Running only
stepstimes would return a final iterate that might already beinf. -
Why
x = x - lr * gand notx -= lr * g?Answer
The trajectory list holds references. With an in-place update, every appended entry is the same array, so the whole list shows the final iterate; and on the first step it would also modify the caller’s
x0ifxwere not a copy. Creating a new array per step makes each entry an independent snapshot. -
What goes wrong if the acceptance test is written
while f(x + alpha * d) > bound: alpha *= rho?Answer
When the trial point is outside the function’s domain, returns NaN, and
nan > boundis false, so the loop exits and accepts the bad step. In the solution’s form,nan <= boundis also false, so the step is rejected and shrunk. The two forms are equal in exact arithmetic and opposite on NaN. -
Why does
armijo_stepraise for a direction with instead of searching anyway?Answer
If the slope is , does not decrease to first order along . With a positive slope the bound lies above and small steps increase ; with a zero slope the bound asks for no decrease at all. Either way backtracking cannot deliver sufficient decrease: it halves until it gives up, or accepts a step that makes no progress. Refusing up front reports the caller’s bug where it happened.
-
With on , why is the stiff coordinate finished after one step?
Answer
Gradient descent multiplies each eigen-coordinate by . With and , that factor is exactly 0, so becomes 0 in one step; the flat coordinate is multiplied by per step, which is what limits the rate to .