Module contents
Lesson 7 of 27Core 100 min

Gradient descent and line search

Derive gradient descent as minimization of a local quadratic model and study step selection precisely: fixed steps, exact search, Armijo backtracking and Wolfe conditions. Spectral analysis on quadratics explains zigzagging, the stability limit η < 2/L and the role of conditioning.

After this lesson you can

  • Derive gradient descent as the minimizer of the quadratic upper bound for an L-smooth function.
  • Analyze GD on a quadratic by decomposing error into eigendirections with contraction factor |1 − ηλᵢ|.
  • Prove fixed-step GD diverges for η > 2/L on a quadratic and obtain the optimal step 2/(μ + L).
  • Implement Armijo backtracking and a line search satisfying the strong Wolfe conditions.
  • Diagnose zigzagging, slowness and divergence from loss and gradient-norm curves.

Before you start

Motivation: the simplest algorithm training almost everything

Almost everything you will train in this course, from logistic regression to a transformer, is optimized using a variant of the same recipe: calculate the gradient, step in the opposite direction, repeat. Gradient descent (GD) fits in one line,

xk+1=xk−ηk ∇f(xk),\vb{x}_{k+1} = \vb{x}_k - \eta_k\,\grad f(\vb{x}_k),

yet that line hides three questions separating an algorithm that works from one that does not:

  1. Why that direction? The gradient is a descent direction, but not the only one, or always the best.
  2. How far to move? Number ηk\eta_k is everything. Too small and the algorithm crawls; too large and loss explodes. The right value depends on curvature, invisible in the gradient.
  3. When to stop and what to do when things go wrong? A loss curve is a diagnostic instrument: it distinguishes an excessive step from a narrow valley or gradient error.

This lesson answers all three with specialist precision. First derive GD as minimizer of a local model, explaining η\eta as inverse curvature. Then solve the quadratic dynamics exactly, decomposing error into eigendirections shrinking at their own rates; this yields stability limit η<2/L\eta < 2/L, optimal step 2/(μ+L)2/(\mu + L) and rate (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1), numbers to remember. Finally study automatic step selection with line search: exact, Armijo backtracking and Wolfe conditions, needed for damped Newton and quasi-Newton methods in lessons 13 and 14.

This lesson uses what you already have: the first-order condition (at a minimum, ∇f=0\grad f = \vb{0}), LL-smoothness as an upper curvature bound, strong convexity as a lower bound, and the condition number κ=L/μ\kappa = L/\mu summarizing both. The next lesson, convergence analysis of first-order methods, turns what quadratics show here into theorems for general convex functions.

Descent directions

Before choosing how far to move, choose where. Given point x\vb{x} and direction d\vb{d}, everything that happens along that direction fits into a one-variable function, the slice φ(α)=f(x+αd)\varphi(\alpha) = f(\vb{x} + \alpha\vb{d}) with α≥0\alpha \ge 0. Its derivative at zero is the directional derivative φ′(0)=∇f(x)⊤d\varphi'(0) = \grad f(\vb{x})\T\vb{d}, and everything depends on its sign.

Proof

With φ(α)=f(x+αd)\varphi(\alpha) = f(\vb{x} + \alpha\vb{d}), the derivative definition says lim⁡α→0+φ(α)−φ(0)α=φ′(0)=∇f(x)⊤d<0\lim_{\alpha\to 0^+}\frac{\varphi(\alpha) - \varphi(0)}{\alpha} = \varphi'(0) = \grad f(\vb{x})\T\vb{d} < 0. A quotient with negative limit is negative for sufficiently small α\alpha, i.e. φ(α)<φ(0)\varphi(\alpha) < \varphi(0). Conversely, if φ(α)<φ(0)\varphi(\alpha) < \varphi(0) near 0+0^+, the quotient is negative and its limit cannot be positive.

∎

The theorem guarantees descent only near zero: how far αˉ\bar\alpha extends is precisely the line-search question. The boundary case ∇f(x)⊤d=0\grad f(\vb{x})\T\vb{d} = 0 is ambiguous (it may rise or fall), so the definition’s strict inequality supplies guarantees.

Which directions satisfy the condition? An entire half-space: all forming an acute angle with −∇f(x)-\grad f(\vb{x}). Two families recur:

  • Any d=−B ∇f(x)\vb{d} = -\mat{B}\,\grad f(\vb{x}) with symmetric positive definite B\mat{B}. Indeed ∇f⊤d=−∇f⊤B∇f<0\grad f\T\vb{d} = -\grad f\T\mat{B}\grad f < 0 if ∇f≠0\grad f \neq \vb{0}. With B=I\mat{B} = \mat{I} we get the gradient; with B=∇2f(x)−1\mat{B} = \hess f(\vb{x})\inv (when the Hessian is positive definite), Newton’s method; with diagonal B\mat{B}, adaptive methods of lessons 20 and 21; with BFGS’s approximation, quasi-Newton methods of lesson 14. Almost all unconstrained optimization algorithms have this form, changing B\mat{B}.
  • Appropriately signed coordinate directions, d=−sign⁡(∂if) ei\vb{d} = -\operatorname{sign}(\partial_i f)\,\vb{e}_i, used by coordinate descent (lesson 15).

Which direction decreases fastest? Among unit vectors, directional derivative ∇f⊤d\grad f\T\vb{d} is smallest when d\vb{d} opposes the gradient, by Cauchy-Schwarz: ∇f⊤d≥−∥∇f∥∥d∥\grad f\T\vb{d} \ge -\norm{\grad f}\norm{\vb{d}}, with equality iff d\vb{d} is a positive multiple of −∇f-\grad f. This is the steepest direction (here descent) in Euclidean norm. Under another norm the steepest direction differs (the gradient sign under ℓ∞\ell_\infty, for example): this is steepest descent in a general norm in lesson 26. “Steepest” describes the derivative at one point; it says nothing about two steps later, the subject of the following sections.

GD as minimization of a local model

The method’s fixed points, x=x−η∇f(x)\vb{x} = \vb{x} - \eta\grad f(\vb{x}), are exactly stationary points ∇f(x)=0\grad f(\vb{x}) = \vb{0}. This connects to the lesson-1 first-order condition: GD seeks points satisfying necessary optimality, and in the convex case that is the global optimum.

A more fruitful interpretation than “going downhill”: GD minimizes a model. Around xk\vb{x}_k, ff resembles its linear approximation, but a linear function has no minimum, so add a term penalizing distance:

mk(y)=f(xk)+∇f(xk)⊤(y−xk)+12η∥y−xk∥2.m_k(\vb{y}) = f(\vb{x}_k) + \grad f(\vb{x}_k)\T(\vb{y} - \vb{x}_k) + \frac{1}{2\eta}\norm{\vb{y} - \vb{x}_k}^2.

This is strictly convex quadratic in y\vb{y}, with gradient ∇f(xk)+1η(y−xk)\grad f(\vb{x}_k) + \frac1\eta(\vb{y} - \vb{x}_k). It vanishes at y=xk−η∇f(xk)\vb{y} = \vb{x}_k - \eta\grad f(\vb{x}_k): the GD step minimizes mkm_k. The quadratic term is assumed curvature: the model says “I believe ff curves like 1ηI\frac1\eta\mat{I} in every direction”. Larger η\eta assumes less curvature and takes a bolder step. Newton does the same with true curvature ∇2f(xk)\hess f(\vb{x}_k); GD replaces it by a multiple of the identity. This explains why GD ignores problem geometry and struggles when curvature differs greatly by direction.

When is the model reliable? If ff is LL-smooth, lesson 3’s quadratic upper bound says f(y)≤f(x)+∇f(x)⊤(y−x)+L2∥y−x∥2f(\vb{y}) \le f(\vb{x}) + \grad f(\vb{x})\T(\vb{y} - \vb{x}) + \frac L2\norm{\vb{y} - \vb{x}}^2. When η≤1/L\eta \le 1/L, the model’s penalty term exceeds the bound’s, so f(y)≤mk(y)f(\vb{y}) \le m_k(\vb{y}) for every y\vb{y}: the model is a global upper bound of ff touching ff at xk\vb{x}_k. Minimizing a touching upper bound guarantees descent, the idea of majorization-minimization:

f(xk+1)≤mk(xk+1)=f(xk)−η2∥∇f(xk)∥2(η≤1/L).f(\vb{x}_{k+1}) \le m_k(\vb{x}_{k+1}) = f(\vb{x}_k) - \frac\eta2\norm{\grad f(\vb{x}_k)}^2 \qquad (\eta \le 1/L).

Check the equality by substituting y=xk−η∇f(xk)\vb{y} = \vb{x}_k - \eta\grad f(\vb{x}_k) into mkm_k: we get f−η∥∇f∥2+η2∥∇f∥2f - \eta\norm{\grad f}^2 + \frac\eta2\norm{\grad f}^2. This is a form of the descent lemma proved generally in lesson 8, explaining why 1/L1/L is the “safe” step when LL is known. A third interpretation, used at the end of the next section: GD is explicit Euler with step η\eta for differential equation x˙=−∇f(x)\dot{\vb{x}} = -\grad f(\vb{x}) of gradient flow.

InteractiveDescent trajectories on four surfaces
  • contours of ff
  • iterates xk\vb{x}_k
  • starting point
  • minima (f⋆=0f^\star = 0)
  • f(xk)f(\vb{x}_k)
  • ∥∇f(xk)∥\norm{\nabla f(\vb{x}_k)}
Step rule
0.085
40
Iterations completed40
f(xk)f(\vb{x}_k)8.96e-4
∥∇f(xk)∥\norm{\nabla f(\vb{x}_k)}0.0423
Evaluations of ff and ∇f\nabla f0 and 40
2/λmax⁡2/\lambda_{\max} at x0\vb{x}_0 and xk\vb{x}_k0.1 and 0.1
With ηλmax⁡=1.7>1\eta\lambda_{\max} = 1.7 > 1 el factor 1−ηλmax⁡1 - \eta\lambda_{\max} is negative: the iterate jumps from side to side of the valley. This is the large-step zigzag.
Choose a surface and step rule; drag the blue point (or click the plane) to change the start. Below, f(xk)f(\vb{x}_k) and ∥∇f(xk)∥\norm{\nabla f(\vb{x}_k)} use a logarithmic scale, and readings show counts of ff and ∇f\nabla f evaluations, the actual cost. Start with the quadratic and fixed step η=0.085\eta = 0.085 (2/L=0.12/L = 0.1): the iterate jumps across the valley. Lower η\eta to remove zigzagging but slow progress; raise it above 0.10.1 and watch the explosion. Switch to “Exact”: each step turns exactly 90°. On Rosenbrock the safe fixed step is tiny and thousands of iterations are needed; try Armijo and Wolfe (increase iterations). On Himmelblau move the start close to the origin (within one unit of its initial position) and see the attained minimum change. On Beale the valley is long and flat toward (3,0.5)(3, 0.5): fixed step 0.0010.001 is very slow; compare Armijo.

Three aspects of the figure deserve names. Zigzagging (the iterate crosses from one side of the valley to the other) occurs when the step is large relative to transverse curvature. Slowness in the valley is the reverse: the step that does not explode in the steep direction is tiny for the flat direction, so progress along the valley floor is slow. Divergence is the limit of that tradeoff. With a fixed step there is no way to have all three at once; the next section explains exactly why.

Exact dynamics on a quadratic

The quadratic is the laboratory where GD has a closed-form solution, and approximates any smooth function near a minimum. Let

f(x)=12x⊤Ax−b⊤x,A=A⊤≻0,f(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} - \vb{b}\T\vb{x}, \qquad \mat{A} = \mat{A}\T \succ 0,

with unique minimum x⋆=A−1b\vb{x}^\star = \mat{A}\inv\vb{b} and gradient ∇f(x)=Ax−b=A(x−x⋆)\grad f(\vb{x}) = \mat{A}\vb{x} - \vb{b} = \mat{A}(\vb{x} - \vb{x}^\star). Subtracting x⋆\vb{x}^\star from both sides of xk+1=xk−η∇f(xk)\vb{x}_{k+1} = \vb{x}_k - \eta\grad f(\vb{x}_k), the error ek=xk−x⋆\vb{e}_k = \vb{x}_k - \vb{x}^\star follows a linear recurrence,

ek+1=(I−ηA) ek⟹ek=(I−ηA)k e0.\vb{e}_{k+1} = (\mat{I} - \eta\mat{A})\,\vb{e}_k \quad\Longrightarrow\quad \vb{e}_k = (\mat{I} - \eta\mat{A})^k\,\vb{e}_0.

Now the spectral theorem enters: A=QΛQ⊤\mat{A} = \mat{Q}\mat{\Lambda}\mat{Q}\T with orthogonal Q\mat{Q} and Λ=diag⁡(λ1,…,λn)\mat{\Lambda} = \diag(\lambda_1, \dots, \lambda_n). Write the error in the eigenvector basis, ci(k)=qi⊤ekc_i(k) = \vb{q}_i\T\vb{e}_k. Since Q⊤(I−ηA)Q=I−ηΛ\mat{Q}\T(\mat{I} - \eta\mat{A})\mat{Q} = \mat{I} - \eta\mat{\Lambda} is diagonal, coordinates do not mix:

ci(k+1)=(1−ηλi) ci(k)⟹ci(k)=(1−ηλi)k ci(0).c_i(k+1) = (1 - \eta\lambda_i)\,c_i(k) \quad\Longrightarrow\quad c_i(k) = (1 - \eta\lambda_i)^k\,c_i(0).

This is gradient descent dynamics on a quadratic: nn independent scalar problems, one per eigendirection, where each error coordinate is multiplied every step by its contraction factor 1−ηλi1 - \eta\lambda_i. The values of ff and error are

∥ek∥2=∑i(1−ηλi)2kci(0)2,f(xk)−f⋆=12∑iλi(1−ηλi)2kci(0)2.\norm{\vb{e}_k}^2 = \sum_i(1 - \eta\lambda_i)^{2k}c_i(0)^2, \qquad f(\vb{x}_k) - f^\star = \tfrac12\sum_i\lambda_i(1 - \eta\lambda_i)^{2k}c_i(0)^2.

Notice the factor’s sign. If 0<ηλi<10 < \eta\lambda_i < 1, it is positive and less than 1: the coordinate decreases without oscillation. If 1<ηλi<21 < \eta\lambda_i < 2, it is negative with magnitude below 1: the coordinate decreases changing sign each step (zigzagging). If ηλi>2\eta\lambda_i > 2, magnitude exceeds 1 and the coordinate grows with alternating sign (divergence). Small eigenvalues have factors close to 1: slow modes.

InteractiveError eigenmodes
u₁u₂
c₁1.6c₂1step k = 0
  • ∣c1∣\abs{c_1}
  • ∣c2∣\abs{c_2}
  • ∥ek∥\norm{\vb{e}_k}
step 0
  • component along u1\vb{u}_1 (low curvature)
  • component along u2\vb{u}_2 (high curvature)
  • iterate xk\vb{x}_k
0.28
0.5
5
1−ηλ11 - \eta\lambda_10.86
1−ηλ21 - \eta\lambda_2−0.4
ρ=max⁡i∣1−ηλi∣\rho = \max_i \abs{1 - \eta\lambda_i}0.86
1/λ21/\lambda_2 and 2/λ22/\lambda_20.2 and 0.4
κ=λ2/λ1\kappa = \lambda_2/\lambda_110
1<ηλ2<21 < \eta\lambda_2 < 2: c2c_2 changes sign at each step but shrinks (factor −0.4−0.4). This is zigzagging. The slow mode, with factor 0.860.86, determines the overall rate.
Initial error (blue point, draggable) decomposes into two eigendirections, orange (u1\vb{u}_1, low curvature λ1\lambda_1) and aqua (u2\vb{u}_2, high curvature λ2\lambda_2). Both arrows add to current error. Bars show coordinates c1c_1 and c2c_2 step by step, with dashed outline for the preceding step; the logarithmic graph shows lines of slope ln⁡∣1−ηλi∣\ln\abs{1 - \eta\lambda_i}. With λ2=5\lambda_2 = 5, thresholds are η=1/λ2=0.2\eta = 1/\lambda_2 = 0.2 (above it c2c_2 changes sign each step) and 2/λ2=0.42/\lambda_2 = 0.4 (above it grows). Explore with η\eta. Then set η=0.19\eta = 0.19 and reduce λ1\lambda_1 to 0.10.1: the orange mode barely moves. Which mode limits step size and which limits speed?

The figure contains the lesson’s most important idea: largest curvature limits the step; smallest curvature limits speed. To keep the λmax⁡\lambda_{\max} mode from exploding we need η<2/λmax⁡\eta < 2/\lambda_{\max}; but that step contracts the λmin⁡\lambda_{\min} mode only by factor 1−ηλmin⁡≈1−2λmin⁡/λmax⁡1 - \eta\lambda_{\min} \approx 1 - 2\lambda_{\min}/\lambda_{\max}, close to 1 if the ratio is small. The next result makes this precise: μ=λmin⁡(A)\mu = \lambda_{\min}(\mat{A}), L=λmax⁡(A)L = \lambda_{\max}(\mat{A}) and κ=L/μ\kappa = L/\mu are exactly strong convexity, smoothness and condition number of ff.

Proof

(1) Factor 1−ηλ1 - \eta\lambda is affine decreasing in λ\lambda, so its absolute value max⁡{1−ηλ,ηλ−1}\max\{1 - \eta\lambda, \eta\lambda - 1\} is maximized at a spectral endpoint: max⁡i∣1−ηλi∣=max⁡{1−ημ,ηL−1}\max_i\abs{1 - \eta\lambda_i} = \max\{1 - \eta\mu, \eta L - 1\}. The bound follows from ∥ek∥2=∑i(1−ηλi)2kci(0)2≤ρ2k∑ici(0)2\norm{\vb{e}_k}^2 = \sum_i(1 - \eta\lambda_i)^{2k}c_i(0)^2 \le \rho^{2k}\sum_i c_i(0)^2, with equality if all error lies in an extreme eigenvector.

(2) ρ(η)<1\rho(\eta) < 1 is equivalent to −1<1−ηλi<1-1 < 1 - \eta\lambda_i < 1 for every ii, meaning 0<ηλi<20 < \eta\lambda_i < 2; since λi≤L\lambda_i \le L the tightest condition is η<2/L\eta < 2/L. For η≤0\eta \le 0, factor 1−ηλi≥11 - \eta\lambda_i \ge 1. If η≥2/L\eta \ge 2/L, the factor for eigenvalue LL is 1−ηL≤−11 - \eta L \le -1 and ∣c(k)∣=∣1−ηL∣k∣c(0)∣↛0\abs{c(k)} = \abs{1 - \eta L}^k\abs{c(0)} \not\to 0.

(3) On (0,2/L)(0, 2/L), 1−ημ1 - \eta\mu decreases and ηL−1\eta L - 1 increases with η\eta; their maximum is minimized where they cross, 1−ημ=ηL−11 - \eta\mu = \eta L - 1, i.e. η=2/(μ+L)\eta = 2/(\mu + L), with value 1−2μμ+L=L−μL+μ=κ−1κ+11 - \frac{2\mu}{\mu + L} = \frac{L - \mu}{L + \mu} = \frac{\kappa - 1}{\kappa + 1}.

∎

At the optimal step, extreme modes contract by the same factor with opposite signs: low curvature decreases without oscillating; high curvature changes sign each time. It balances the slow mode and the exploding mode.

InteractiveThe step stability map
2/L2/(μ+L)
  • optimal step 2/(μ+L)2/(\mu+L)
  • step 1/L1/L

The vertical line marks your κ\kappa. Both curves have slope 1 on the log-log scale: cost grows linearly with κ\kappa.

  • ∣1−ηλi∣\abs{1 - \eta\lambda_i} for each eigenvalue
  • ρ(η)\rho(\eta) (maximum)
  • optimum
  • divergent region (η>2/L\eta > 2/L)
Number of eigenvalues
μ\mu and LL1 and 10
κ=L/μ\kappa = L/\mu10
2/L2/L (limit)0.2
2/(μ+L)2/(\mu + L) (optimum)0.182
(κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1)0.8182
η\eta and ρ(η)\rho(\eta)0.15 and 0.85
Steps to ×10−6\times 10^{-6}: with η\eta, with 1/L1/L, optimal86, 132, 69
To the left of the optimum, the slow mode dominates, 1−ημ1 - \eta\mu. Increasing η\eta improves ρ\rho up to 2/(μ+L)=0.1822/(\mu + L) = 0.182.
Each V-shaped line is factor ∣1−ηλi∣\abs{1 - \eta\lambda_i} for an eigenvalue draggable on the line below; the thick curve is their envelope ρ(η)\rho(\eta), explored by dragging the large point. To the right of 2/L2/L (red region), ρ>1\rho > 1. The curve's minimum lies exactly where the smallest-eigenvalue line (decreasing) crosses the largest (increasing). Starting eigenvalues give κ=10\kappa = 10. Bring λ1\lambda_1 and λ4\lambda_4 together and watch ρ⋆→0\rho^\star \to 0 as κ→1\kappa \to 1: one step solves the problem. Separate them and inspect the plot of steps versus κ\kappa (vertical bar marks your κ\kappa) to see iteration costs of the two recommended steps. Do intermediate eigenvalues change anything? Why?

Intermediate eigenvalues change nothing: the envelope depends only on extremes. To determine the cost of poor conditioning, calculate steps reducing error by factor ε\varepsilon. Since ln⁡κ+1κ−1=2artanh⁡1κ≥2κ\ln\frac{\kappa + 1}{\kappa - 1} = 2\operatorname{artanh}\frac1\kappa \ge \frac2\kappa, ρ⋆≤e−2/κ\rho^\star \le e^{-2/\kappa}, so

∥ek∥≤ε∥e0∥ifk≥κ2ln⁡1ε.\norm{\vb{e}_k} \le \varepsilon\norm{\vb{e}_0} \quad\text{if}\quad k \ge \frac\kappa2\ln\frac1\varepsilon.

Cost is linear in κ\kappa. With η=1/L\eta = 1/L, the prudent choice when only LL is known, the factor is ρ=1−1/κ\rho = 1 - 1/\kappa and nearly κln⁡(1/ε)\kappa\ln(1/\varepsilon) steps are needed: twice as many.

Two qualifications to avoid over-extrapolation. First, if A\mat{A} is only semidefinite (μ=0\mu = 0, as in least squares with dependent columns) and b\vb{b} lies in the image of A\mat{A} (always true in least squares; otherwise ff is unbounded below), modes with λi=0\lambda_i = 0 never move: with η<2/L\eta < 2/L, GD converges, but only to the point in the minimizer set sharing x0\vb{x}_0‘s component in the nullspace of A\mat{A}. Second, for a nonquadratic function ∇2f\hess f varies with position: limit 2/λmax⁡(∇2f(xk))2/\lambda_{\max}(\hess f(\vb{x}_k)) is local and may be far smaller away from the minimum than near it: for Beale, λmax⁡≈2105\lambda_{\max} \approx 2105 at (−2,2)(-2, 2) versus 4949 at the minimum; for Rosenbrock, λmax⁡≈1506\lambda_{\max} \approx 1506 at (−1.2,1)(-1.2, 1) versus 10021002 at the minimum (and κ≈2508\kappa \approx 2508 there). The trajectory figure reads 2/λmax⁡2/\lambda_{\max} at the start and last iterate. An η\eta chosen only at the start may diverge ten iterations later, and one working far away may fail near the minimum: for Rosenbrock, η=0.0021\eta = 0.0021, barely above 2/λmax⁡≈0.002002/\lambda_{\max} \approx 0.00200 at the minimum, does not explode, but after 60,000 iterations still jumps between two points near (0.96,0.94)(0.96, 0.94), a period-2 cycle with f≈0.04f \approx 0.04, never reaching the minimum.

Limit 2/L2/L also has a classical interpretation: the stability edge of explicit Euler for c˙=−λc\dot c = -\lambda c. Gradient flow decays as e−λte^{-\lambda t} for any λ>0\lambda > 0, but Euler with step η\eta mimics it only if ηλ<2\eta\lambda < 2; GD is flow with a time step too large for the fastest modes.

Line search: choosing ηk\eta_k on the fly

Choosing a fixed step requires knowing LL (or μ\mu and LL for the optimum) and assumes curvature is the same everywhere. The alternative is a line search: each iteration, with direction dk=−∇f(xk)\vb{d}_k = -\grad f(\vb{x}_k) fixed, choose αk>0\alpha_k > 0 by examining slice φ(α)=f(xk+αdk)\varphi(\alpha) = f(\vb{x}_k + \alpha\vb{d}_k). Each trial costs an evaluation of ff (perhaps ∇f\grad f), so search should be cheap: seek a good, guaranteed α\alpha, not the best.

Exact search and orthogonal zigzagging

The natural idea is to minimize the slice.

Proof

At an interior minimum of φ\varphi, φ′(αk)=0\varphi'(\alpha_k) = 0, and by the chain rule φ′(αk)=∇f(xk+αkdk)⊤dk=∇f(xk+1)⊤dk\varphi'(\alpha_k) = \grad f(\vb{x}_k + \alpha_k\vb{d}_k)\T\vb{d}_k = \grad f(\vb{x}_{k+1})\T\vb{d}_k. With dk=−∇f(xk)\vb{d}_k = -\grad f(\vb{x}_k) this gives orthogonality. On the quadratic, with g=∇f(xk)\vb{g} = \grad f(\vb{x}_k) and d=−g\vb{d} = -\vb{g}, φ(α)=f(xk)−α∥g∥2+α22g⊤Ag\varphi(\alpha) = f(\vb{x}_k) - \alpha\norm{\vb{g}}^2 + \frac{\alpha^2}2\vb{g}\T\mat{A}\vb{g} is a parabola minimized at α=∥g∥2/g⊤Ag\alpha = \norm{\vb{g}}^2/\vb{g}\T\mat{A}\vb{g}.

∎

A trajectory with orthogonal consecutive gradients turns exactly 90° at each step. This causes the trajectory figure’s zigzag with “Exact”. It is not an implementation defect: it means reaching the bottom of the slice. Curiously that zigzag is the calculable worst case:

That factor cannot be improved in the worst case, as the next theorem states, worth remembering as GD’s exact-search benchmark bound.

Proof

Let g=Ae\vb{g} = \mat{A}\vb{e} be the gradient at x\vb{x} (with e=x−x⋆\vb{e} = \vb{x} - \vb{x}^\star). Then f(x)−f⋆=12e⊤Ae=12g⊤A−1gf(\vb{x}) - f^\star = \frac12\vb{e}\T\mat{A}\vb{e} = \frac12\vb{g}\T\mat{A}\inv\vb{g}, and substituting α=∥g∥2/g⊤Ag\alpha = \norm{\vb{g}}^2/\vb{g}\T\mat{A}\vb{g} in the slice parabola,

f(x+)−f⋆=12g⊤A−1g−∥g∥42 g⊤Ag⟹f(x+)−f⋆f(x)−f⋆=1−∥g∥4(g⊤Ag)(g⊤A−1g).f(\vb{x}^+) - f^\star = \tfrac12\vb{g}\T\mat{A}\inv\vb{g} - \frac{\norm{\vb{g}}^4}{2\,\vb{g}\T\mat{A}\vb{g}} \quad\Longrightarrow\quad \frac{f(\vb{x}^+) - f^\star}{f(\vb{x}) - f^\star} = 1 - \frac{\norm{\vb{g}}^4}{(\vb{g}\T\mat{A}\vb{g})(\vb{g}\T\mat{A}\inv\vb{g})}.

Let pi=(qi⊤g)2/∥g∥2p_i = (\vb{q}_i\T\vb{g})^2/\norm{\vb{g}}^2, a probability distribution on eigenvalues. The denominator divided by ∥g∥4\norm{\vb{g}}^4 is E[λ] E[1/λ]\E[\lambda]\,\E[1/\lambda], and we must show E[λ]E[1/λ]≤(μ+L)24μL\E[\lambda]\E[1/\lambda] \le \frac{(\mu + L)^2}{4\mu L} (Kantorovich inequality). For λ∈[μ,L]\lambda \in [\mu, L], (λ−μ)(λ−L)≤0(\lambda - \mu)(\lambda - L) \le 0 is equivalent to λ+μL/λ≤μ+L\lambda + \mu L/\lambda \le \mu + L; taking expectations, E[λ]+μL E[1/λ]≤μ+L\E[\lambda] + \mu L\,\E[1/\lambda] \le \mu + L. By arithmetic-geometric mean, 2μL E[λ]E[1/λ]≤E[λ]+μLE[1/λ]≤μ+L2\sqrt{\mu L\,\E[\lambda]\E[1/\lambda]} \le \E[\lambda] + \mu L\E[1/\lambda] \le \mu + L, and squaring yields the inequality. Therefore the ratio is at most 1−4μL(μ+L)2=(L−μL+μ)21 - \frac{4\mu L}{(\mu + L)^2} = \big(\frac{L - \mu}{L + \mu}\big)^2.

∎

Compare fixed-step theorem: exact search achieves the same contraction per step as optimal step 2/(μ+L)2/(\mu + L) (with it each error coordinate is multiplied by a factor of magnitude ≤ρ⋆\le \rho^\star, and f−f⋆f - f^\star, quadratic in error, by ≤(ρ⋆)2\le (\rho^\star)^2), without knowing μ\mu and LL. This is line search’s great virtue: it adapts step to problem. Its drawback: for a quadratic the formula is free, but for a general function finding the minimum of φ\varphi requires many evaluations for small benefit (zigzag remains). It is used on quadratics (conjugate gradient in numerical analysis, which corrects zigzag by choosing conjugate directions) and almost never otherwise.

Armijo backtracking: decrease enough

For a general function a step decreasing ff sufficiently suffices. “Sufficiently” cannot mean “a little”: a sequence of steps decreasing ff by ever-smaller amounts can converge to a nonstationary point. The correct condition compares actual decrease with the tangent’s prediction.

The condition requires φ\varphi to lie below the line starting at φ(0)\varphi(0) with slope c1φ′(0)c_1\varphi'(0): a fraction c1c_1 of the tangent-predicted decrease. In practice c1c_1 is tiny (10−410^{-4}) and β=0.5\beta = 0.5. Backtracking only shrinks the step, so α0\alpha_0 must be large enough not to fall short (1 is usual for well-scaled directions).

Proof

By the quadratic upper bound, φ(α)≤φ(0)+αφ′(0)+L2α2∥d∥2\varphi(\alpha) \le \varphi(0) + \alpha\varphi'(0) + \frac L2\alpha^2\norm{\vb{d}}^2. It suffices that αφ′(0)+L2α2∥d∥2≤c1αφ′(0)\alpha\varphi'(0) + \frac L2\alpha^2\norm{\vb{d}}^2 \le c_1\alpha\varphi'(0), i.e. (divide by α>0\alpha > 0 and recall φ′(0)<0\varphi'(0) < 0), L2α∥d∥2≤(c1−1)φ′(0)=(1−c1)∣φ′(0)∣\frac L2\alpha\norm{\vb{d}}^2 \le (c_1 - 1)\varphi'(0) = (1 - c_1)\abs{\varphi'(0)}, which is α≤αˉ\alpha \le \bar\alpha. Backtracking tries αj=βjα0\alpha_j = \beta^j\alpha_0. If α0≤αˉ\alpha_0 \le \bar\alpha it accepts α0\alpha_0. Otherwise it stops at the first jj with βjα0≤αˉ\beta^j\alpha_0 \le \bar\alpha, which exists as βj→0\beta^j \to 0; the previous step αj/β\alpha_j/\beta was rejected, so αj/β>αˉ\alpha_j/\beta > \bar\alpha and αj>βαˉ\alpha_j > \beta\bar\alpha. Trial count is the smallest j+1j + 1 with βjα0≤αˉ\beta^j\alpha_0 \le \bar\alpha. The last inequality is Armijo with φ′(0)=−∥∇f∥2\varphi'(0) = -\norm{\grad f}^2 and α≥min⁡{α0,βαˉ}\alpha \ge \min\{\alpha_0, \beta\bar\alpha\}.

∎

Three interpretations. It always terminates, without knowing LL. The accepted step is never below ≈2β(1−c1)/L\approx 2\beta(1 - c_1)/L, which with β=0.5\beta = 0.5 and small c1c_1 is ≈1/L\approx 1/L: backtracking guarantees at least what safe step 1/L1/L guarantees, while exploiting low-curvature areas where it accepts larger steps. It is an automatic local curvature estimator, the complement requested in lesson 3 for sampled LL estimates, useful only to start. And a decrease is guaranteed of at least c1αmin⁡∥∇f∥2c_1\alpha_{\min}\norm{\grad f}^2, which, if ff is bounded below, suffices to prove min⁡j≤k∥∇f(xj)∥=O(1/k)\min_{j \le k}\norm{\grad f(\vb{x}_j)} = \bigO(1/\sqrt k) (lesson 8).

Cost is the number of trials, each one ff evaluation without gradient. With a good α0\alpha_0 (e.g. twice the last accepted step, allowing it to grow), usually 1 or 2 per iteration.

Wolfe conditions: do not fall short

Armijo has a gap: any sufficiently small α\alpha satisfies it (as the theorem shows), so alone it does not prevent tiny steps. Backtracking avoids this by starting large, but other search algorithms or too small an α0\alpha_0 do not. A second condition must force progress: the slope of φ\varphi must have flattened.

Since φ′(0)<0\varphi'(0) < 0, weak Wolfe says the slope at α\alpha has risen from φ′(0)\varphi'(0) at least to c2φ′(0)c_2\varphi'(0), less negative: the function no longer decreases as strongly, so moving further is less rewarding. Strong Wolfe also requires the slope not be very positive, meaning the valley has not been overshot: α\alpha lies near a stationary point of φ\varphi. As c2→0c_2 \to 0 exact search is recovered.

InteractiveAccepting or rejecting a step
012Armijo lineφ(α)
02c₂ φ′(0)φ′(0)φ′(α)
Armijocurvatureboth
trial 2 of 2
  • φ(α)\varphi(\alpha)
  • Armijo line
  • tangent at 0
  • curvature band
  • Wolfe steps
  • backtracking: rejected step
  • backtracking: accepted step (satisfies Armijo)
Function slice
Curvature
0.1
0.6
3
0.5
Trial α\alpha0.3
Armijoyes
Curvatureno
Wolfe steps[0.5, 2]
Backtracking: trials and accepted α\alpha2 and 1.5
Does the accepted step satisfy curvature?yes
Your α\alpha satisfies Armijo but not curvature: the step is so small that the slope remains almost as negative. Armijo alone accepts arbitrarily small steps.
Above, slice φ(α)\varphi(\alpha) and Armijo line (blue); below, its derivative with curvature-condition band (aqua). Steps accepted by Armijo, curvature, and both appear in three bands at the bottom. Drag the large curve point to see which hold. Start with the parabola and α=0.3\alpha = 0.3: Armijo holds, curvature does not (too short). Raise c1c_1 to 0.9: the Armijo interval shrinks to (0,0.25](0, 0.25] and excludes the minimum itself (α=1.25\alpha = 1.25), which satisfies Armijo only if c1≤1/2c_1 \le 1/2; this is why c1c_1 should be small. Raise c2c_2: the curvature interval widens. In “Two valleys”, toggle weak and strong Wolfe: strong rejects a region with very positive slope. Play backtracking with small α0\alpha_0 (e.g. 0.3 on the parabola): it accepts a step satisfying Armijo but not curvature. With large α0\alpha_0, it enters from the right.

The curvature condition raises a question: are there always steps satisfying both conditions? Yes, under minimal assumptions.

Proof

Line ℓ(α)=φ(0)+c1αφ′(0)\ell(\alpha) = \varphi(0) + c_1\alpha\varphi'(0) tends to −∞-\infty and φ\varphi is bounded below, so they intersect. Since φ′(0)<c1φ′(0)\varphi'(0) < c_1\varphi'(0) (because φ′(0)<0\varphi'(0) < 0 and c1<1c_1 < 1), φ\varphi lies below ℓ\ell immediately right of 00; let α′>0\alpha' > 0 be the first point with φ(α′)=ℓ(α′)\varphi(\alpha') = \ell(\alpha'). Then φ<ℓ\varphi < \ell on (0,α′)(0, \alpha'). By the mean value theorem there is α′′∈(0,α′)\alpha'' \in (0, \alpha') with φ(α′)−φ(0)=α′φ′(α′′)\varphi(\alpha') - \varphi(0) = \alpha'\varphi'(\alpha''), and since φ(α′)−φ(0)=c1α′φ′(0)\varphi(\alpha') - \varphi(0) = c_1\alpha'\varphi'(0), φ′(α′′)=c1φ′(0)\varphi'(\alpha'') = c_1\varphi'(0). At α′′\alpha'' Armijo holds strictly (since α′′<α′\alpha'' < \alpha'), and c1φ′(0)>c2φ′(0)c_1\varphi'(0) > c_2\varphi'(0) gives weak curvature. Also ∣φ′(α′′)∣=c1∣φ′(0)∣<c2∣φ′(0)∣\abs{\varphi'(\alpha'')} = c_1\abs{\varphi'(0)} < c_2\abs{\varphi'(0)} strictly, so strong curvature holds too. By continuity of φ\varphi and φ′\varphi', all three inequalities hold in a neighborhood of α′′\alpha''.

∎

The proof says where to look: α′′\alpha'' is where φ\varphi‘s slope equals the Armijo line’s slope. Why does an algorithm want curvature? For GD it is not essential, so Armijo backtracking suffices. For quasi-Newton methods it is: BFGS updates a Hessian approximation Bk\mat{B}_k with pair sk=xk+1−xk\vb{s}_k = \vb{x}_{k+1} - \vb{x}_k, yk=∇f(xk+1)−∇f(xk)\vb{y}_k = \grad f(\vb{x}_{k+1}) - \grad f(\vb{x}_k), and the update preserves positive definiteness only if sk⊤yk>0\vb{s}_k\T\vb{y}_k > 0 (the secant equation Bk+1sk=yk\mat{B}_{k+1}\vb{s}_k = \vb{y}_k requires it with Bk+1≻0\mat{B}_{k+1} \succ 0). With sk=αkdk\vb{s}_k = \alpha_k\vb{d}_k and weak curvature,

sk⊤yk=αk(φ′(αk)−φ′(0))≥αk(c2−1)φ′(0)>0.\vb{s}_k\T\vb{y}_k = \alpha_k\big(\varphi'(\alpha_k) - \varphi'(0)\big) \ge \alpha_k(c_2 - 1)\varphi'(0) > 0.

Wolfe conditions guarantee by construction the curvature condition needed by BFGS (lesson 14), so quasi-Newton line searches use Wolfe with c1=10−4c_1 = 10^{-4} and c2=0.9c_2 = 0.9 (conjugate gradient uses c2=0.1c_2 = 0.1, closer to exact search).

How is a strong Wolfe step found? With Nocedal and Wright’s bracketing and zoom algorithm (algorithms 3.5 and 3.6). Bracketing tries α1,2α1,4α1,…\alpha_1, 2\alpha_1, 4\alpha_1, \dots until an interval [αlo,αhi][\alpha_{\text{lo}}, \alpha_{\text{hi}}] containing an acceptable step is found: either Armijo is violated (or φ\varphi has stopped decreasing), or the slope is positive. Zoom reduces this interval, maintaining the invariant “αlo\alpha_{\text{lo}} satisfies Armijo and has the smallest φ\varphi value so far; slope at αlo\alpha_{\text{lo}} points toward αhi\alpha_{\text{hi}}”, testing an interior point (cubic interpolation safeguarded by bisection) until curvature holds. Each trial costs an evaluation of ff and ∇f\grad f; in machine learning the backpropagated gradient costs a small multiple of ff (the cheap gradient principle), so it is not prohibitive but costs more than Armijo.

Stopping criteria and diagnostics

When does the loop stop? A decent stopping criterion combines several signals, since each can mislead alone:

  • Gradient norm: ∥∇f(xk)∥≤εabs+εrel∥∇f(x0)∥\norm{\grad f(\vb{x}_k)} \le \varepsilon_{\text{abs}} + \varepsilon_{\text{rel}}\norm{\grad f(\vb{x}_0)}. This is the optimality condition, but depends on units of x\vb{x} and ff: multiplying ff by 10610^6 multiplies its gradient by 10610^6. Scale it (by the initial gradient or max⁡(1,∣f∣)\max(1, \abs{f})).
  • Stalled ff: ∣f(xk+1)−f(xk)∣≤ε (1+∣f(xk)∣)\abs{f(\vb{x}_{k+1}) - f(\vb{x}_k)} \le \varepsilon\,(1 + \abs{f(\vb{x}_k)}). Misleading in flat valleys, where ff decreases slowly without being close to the minimum.
  • Small step: ∥xk+1−xk∥≤ε (1+∥xk∥)\norm{\vb{x}_{k+1} - \vb{x}_k} \le \varepsilon\,(1 + \norm{\vb{x}_k}). A tiny η\eta always satisfies it.
  • Budget: maximum iterations or evaluations so the program terminates.

In the strongly convex case, gradient norm is a quantitative certificate of proximity: if ff is μ\mu-strongly convex, ∥x−x⋆∥≤∥∇f(x)∥/μ\norm{\vb{x} - \vb{x}^\star} \le \norm{\grad f(\vb{x})}/\mu and f(x)−f⋆≤∥∇f(x)∥2/(2μ)f(\vb{x}) - f^\star \le \norm{\grad f(\vb{x})}^2/(2\mu). The second follows by minimizing lower bound f(y)≥f(x)+∇f(x)⊤(y−x)+μ2∥y−x∥2f(\vb{y}) \ge f(\vb{x}) + \grad f(\vb{x})\T(\vb{y} - \vb{x}) + \frac\mu2\norm{\vb{y} - \vb{x}}^2 over y\vb{y}, whose minimum f(x)−∥∇f(x)∥2/(2μ)f(\vb{x}) - \norm{\grad f(\vb{x})}^2/(2\mu) cannot exceed f⋆f^\star. The first follows from ∥∇f(x)∥ ∥x−x⋆∥≥⟨∇f(x)−∇f(x⋆),x−x⋆⟩≥μ∥x−x⋆∥2\norm{\grad f(\vb{x})}\,\norm{\vb{x} - \vb{x}^\star} \ge \inner{\grad f(\vb{x}) - \grad f(\vb{x}^\star)}{\vb{x} - \vb{x}^\star} \ge \mu\norm{\vb{x} - \vb{x}^\star}^2. With small μ\mu the certificate is weak: gradient 10−610^{-6} guarantees only ∥x−x⋆∥≤10−6/μ\norm{\vb{x} - \vb{x}^\star} \le 10^{-6}/\mu.

Loss and gradient-norm curves (as in the trajectory figure) help diagnose the algorithm. With moderate κ\kappa and a reasonable step, on a log scale the curve of f(xk)−f⋆f(\vb{x}_k) - f^\star is a line of slope ln⁡ρ2\ln\rho^2 (as quadratic theory predicts, asymptotically valid near any nondegenerate minimum).

What you seeUsual causeWhat to do
Descending line on log scalelinear convergence with rate ρ\rho; flatter means greater κ\kappaestimate κ\kappa from slope; precondition or use momentum
Fast initial fall then nearly horizontal, with ∥∇f∥\norm{\grad f} barely decreasingnarrow valley: low-curvature mode dominatesraise η\eta if safe; change method
ff grows geometrically and parameters alternate signsη>2/L\eta > 2/L in highest-curvature directionlower η\eta below 2/λmax⁡2/\lambda_{\max}; use line search
ff rises and falls with growing amplitudeη\eta near or above local 2/L2/L, or growing curvaturelower η\eta; clip the gradient
ff nearly constant from the starttiny η\eta, or incorrectly calculated gradienttry larger η\eta; check the gradient with finite differences
ff stalls and ∥∇f∥\norm{\grad f} goes to zero at a bad pointlocal minimum or saddle (nonconvex)change starting point; analyze the Hessian

This is first contact with a discipline developed in the deep-learning module (learning curve patterns) and learning-rate schedules replacing line search when ff is stochastic.

Implementation from scratch

Build four step rules and compare actual cost: evaluations of ff and ∇f\grad f, not iterations. A test bench with counters and rules as functions receiving problem, point, value and gradient, returning α\alpha.

[ ]A test bench with countersBrowser
import numpy as np

class Problema:
    """Envuelve f y su gradiente y cuenta cuántas veces se evalúa cada uno."""
    def __init__(self, f, grad):
        self._f, self._grad = f, grad
        self.nf = self.ng = 0
    def f(self, x):
        self.nf += 1
        return self._f(x)
    def grad(self, x):
        self.ng += 1
        return self._grad(x)
    def reiniciar(self):
        self.nf = self.ng = 0

def descenso(prob, x0, busqueda, tol=1e-6, max_iter=50000):
    """GD con una regla de paso: busqueda(prob, x, fx, g) -> alfa. Devuelve (x, k, convergió, historial)."""
    x = np.array(x0, dtype=float)
    fx, g = prob.f(x), prob.grad(x)
    historial = [(prob.nf + prob.ng, np.linalg.norm(g))]
    for k in range(max_iter):
        if np.linalg.norm(g) <= tol:
            return x, k, True, historial
        x = x - busqueda(prob, x, fx, g) * g
        fx, g = prob.f(x), prob.grad(x)
        historial.append((prob.nf + prob.ng, np.linalg.norm(g)))
    return x, max_iter, False, historial

def paso_fijo(eta):
    return lambda prob, x, fx, g: eta

def exacta_cuadratica(A):
    """Búsqueda exacta en f = x'Ax/2 - b'x: alfa = g'g / g'Ag."""
    return lambda prob, x, fx, g: (g @ g) / (g @ (A @ g))

def armijo(alfa0=1.0, c1=1e-4, beta=0.5, calido=False):
    """Retroceso de Armijo. Con calido=True se empieza en el doble del último paso, con tope alfa0."""
    estado = {"alfa": alfa0}
    def busqueda(prob, x, fx, g):
        alfa = min(2 * estado["alfa"], alfa0) if calido else alfa0
        pendiente = -(g @ g)                       # phi'(0) para d = -g
        while prob.f(x - alfa * g) > fx + c1 * alfa * pendiente:
            alfa *= beta
        estado["alfa"] = alfa
        return alfa
    return busqueda

def interp_cubica(a0, f0, d0, a1, f1, d1):
    """Mínimo del interpolante cúbico de Hermite por (a0, f0, d0) y (a1, f1, d1); None si no existe."""
    d1c = d0 + d1 - 3 * (f0 - f1) / (a0 - a1)
    rad = d1c * d1c - d0 * d1
    if rad < 0:
        return None
    d2 = np.sign(a1 - a0) * np.sqrt(rad)
    return a1 - (a1 - a0) * (d1 + d2 - d1c) / (d1 - d0 + 2 * d2)

def wolfe_ls(phi, dphi, f0, d0, a1, c1, c2, max_eval=30):
    """Búsqueda de Wolfe fuerte: acotación y zoom (Nocedal y Wright, algoritmos 3.5 y 3.6)."""
    def zoom(lo, flo, dlo, hi, fhi, dhi):
        for _ in range(max_eval):
            a = interp_cubica(lo, flo, dlo, hi, fhi, dhi)
            ancho = abs(hi - lo)
            if a is None or not (min(lo, hi) + 0.1 * ancho <= a <= max(lo, hi) - 0.1 * ancho):
                a = 0.5 * (lo + hi)                 # protección: bisección
            fa, da = phi(a), dphi(a)
            if fa > f0 + c1 * a * d0 or fa >= flo:   # Armijo violada: el intervalo se acorta por la derecha
                hi, fhi, dhi = a, fa, da
            else:
                if abs(da) <= -c2 * d0:              # curvatura fuerte: hecho
                    return a
                if da * (hi - lo) >= 0:
                    hi, fhi, dhi = lo, flo, dlo
                lo, flo, dlo = a, fa, da
        return lo
    previo, fprevio, dprevio = 0.0, f0, d0
    a = a1
    for i in range(max_eval):
        fa, da = phi(a), dphi(a)
        if fa > f0 + c1 * a * d0 or (i > 0 and fa >= fprevio):
            return zoom(previo, fprevio, dprevio, a, fa, da)
        if abs(da) <= -c2 * d0:
            return a
        if da >= 0:
            return zoom(a, fa, da, previo, fprevio, dprevio)
        previo, fprevio, dprevio = a, fa, da
        a *= 2                                       # acotación: duplicar
    return previo

def wolfe_fuerte(alfa0=1.0, c1=1e-4, c2=0.9, calido=False):
    estado = {"alfa": alfa0}
    def busqueda(prob, x, fx, g):
        phi = lambda a: prob.f(x - a * g)
        dphi = lambda a: -(g @ prob.grad(x - a * g))
        inicial = min(2 * estado["alfa"], alfa0) if calido else alfa0
        estado["alfa"] = wolfe_ls(phi, dphi, fx, -(g @ g), inicial, c1, c2)
        return estado["alfa"]
    return busqueda

# comprobación: el paso devuelto cumple de verdad las condiciones, en una parábola cuyo mínimo está en alfa = 125
phi = lambda a: (1 - 0.008 * a) ** 2
dphi = lambda a: -0.016 * (1 - 0.008 * a)
a = wolfe_ls(phi, dphi, 1.0, -0.016, 1.0, 1e-4, 0.1)
print(f"alfa = {a:.2f}; Armijo: {phi(a) <= 1 - 1e-4 * a * 0.016}; |phi'(a)| = {abs(dphi(a)):.2e} <= {0.1 * 0.016:.2e}: {abs(dphi(a)) <= 0.1 * 0.016}")

Two implementation details. In armijo the while loop always terminates by the preceding theorem provided ∇f\grad f is the gradient of ff and d\vb{d} is a descent direction: with a miscalculated gradient the condition might never hold and the loop would be infinite (a while iteration limit is good practice). In wolfe_ls bracketing doubles the step; if φ\varphi is bounded below it terminates soon, and both phases have an evaluation budget to prevent loops.

First test bench: a quadratic with κ=100\kappa = 100 (known exact answers) and Rosenbrock’s curved-valley landscape.

[ ]Quadratic and RosenbrockBrowser
import matplotlib.pyplot as plt

A = np.diag([1.0, 100.0])
cuadratica = Problema(lambda x: 0.5 * x @ A @ x, lambda x: A @ x)
rosenbrock = Problema(
    lambda p: (1 - p[0]) ** 2 + 100 * (p[1] - p[0] ** 2) ** 2,
    lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0] ** 2), 200 * (p[1] - p[0] ** 2)]),
)

def comparar(nombre, prob, x0, reglas, tol, max_iter=30000):
    print(nombre)
    print(f"  {'regla':20s} {'iter':>6s} {'eval f':>7s} {'eval grad':>10s} {'total':>7s}")
    historiales = {}
    for etiqueta, regla in reglas.items():
        prob.reiniciar()
        x, k, ok, hist = descenso(prob, x0, regla, tol, max_iter)
        historiales[etiqueta] = hist
        marca = "" if ok else "  (sin converger)"
        print(f"  {etiqueta:20s} {k:6d} {prob.nf:7d} {prob.ng:10d} {prob.nf + prob.ng:7d}{marca}")
    return historiales

comparar("Cuadrática diag(1, 100), x0 = (100, 1), |g| <= 1e-6", cuadratica, [100, 1], {
    "paso 1/L": paso_fijo(0.01),
    "paso óptimo 2/(mu+L)": paso_fijo(2 / 101),
    "búsqueda exacta": exacta_cuadratica(A),
    "Armijo, alfa0 = 1": armijo(1.0),
    "Armijo cálido": armijo(1.0, calido=True),
    "Wolfe cálido": wolfe_fuerte(1.0, calido=True),
}, 1e-6)

print()
hist = comparar("Rosenbrock, x0 = (-1.2, 1), |g| <= 1e-3", rosenbrock, [-1.2, 1.0], {
    "paso fijo 0.001": paso_fijo(1e-3),
    "Armijo, alfa0 = 1": armijo(1.0),
    "Armijo cálido": armijo(1.0, calido=True),
    "Wolfe cálido": wolfe_fuerte(1.0, calido=True),
}, 1e-3)

for etiqueta, h in hist.items():
    h = np.array(h)
    plt.semilogy(h[:, 0], h[:, 1], label=etiqueta, lw=1.4)
plt.xlabel("evaluaciones acumuladas de f y de ∇f"); plt.ylabel("‖∇f‖"); plt.legend(); plt.show()

The quadratic table confirms the theory line by line. Optimal step and exact search need the same number of iterations (939 for ∥∇f∥≤10−6\norm{\grad f} \le 10^{-6}, with the same per-step contraction), step 1/L1/L nearly twice as many (1833), and Armijo slightly fewer than both (839). The last deserves explanation: starting point (100,1)(100, 1) is precisely Akaike’s zigzag, exact search’s worst case. Backtracking from 1 can accept only powers of 1/21/2, accepting 1/64≈0.0161/64 \approx 0.016 or 1/32≈0.0311/32 \approx 0.031; the latter is above 2/L=0.022/L = 0.02, accepted (in 349 of 839 iterations) when error’s fast-mode component is so small that ff still decreases. That step amplifies the fast mode by 2.12.1 but moves twice as far in the slow one, and subsequent 1/641/64 steps recontract the fast mode by 0.560.56. No fixed step can do this: an adaptive rule can temporarily enter the unstable zone because it monitors ff. But consider cost: with α0=1\alpha_0 = 1, Armijo needs about 7.6 evaluations of ff per iteration (six or seven backtracks from 1), and warm starting lowers it to about 3. A search that looks more efficient in iterations can cost nearly four times as many evaluations (7204 versus 1880). On Rosenbrock iteration count misleads the other way. Fixed step 0.0010.001 (which must be known in advance: 0.00210.0021 already fails to converge) is cheapest per iteration, with one evaluation each of ff and ∇f\grad f, needing 14,789; Armijo with α0=1\alpha_0 = 1 needs under half as many iterations (5231), yet over twice as many total evaluations (62,352 versus 29,580), because each iteration evaluates ff about 11 times backtracking from 1 to a step on the order of 10−310^{-3}. Warm starting lowers the total to 26,354, slightly better than fixed step, and Wolfe takes 38,510. The plot of ∥∇f∥\norm{\grad f} against cumulative evaluations is the honest comparison, and no rule is drastically better: in this valley the limiting factor is κ≈2500\kappa \approx 2500, not step rule.

Second bench: regularized logistic regression with 200 examples and 10 features on very different scales, the problem from lesson 3.

[ ]Logistic regressionBrowser
rng = np.random.default_rng(0)
n, d = 200, 10
X = rng.normal(size=(n, d)) * np.linspace(0.3, 3, d)     # características con escalas distintas
w_verdadero = rng.normal(size=d)
y = np.where(X @ w_verdadero + 0.5 * rng.normal(size=n) > 0, 1.0, -1.0)
lam = 1e-3

def f_log(w):
    return np.mean(np.logaddexp(0, -y * (X @ w))) + 0.5 * lam * w @ w

def g_log(w):
    s = 0.5 * (1 - np.tanh(0.5 * y * (X @ w)))             # sigmoide(-y x'w), estable
    return -(X.T @ (y * s)) / n + lam * w

logistica = Problema(f_log, g_log)
L = np.linalg.eigvalsh(X.T @ X)[-1] / (4 * n) + lam       # L = lambda_max(X'X)/(4n) + lam
print(f"L = {L:.3f}, mu >= lambda = {lam}, kappa <= {L / lam:.0f}")

comparar("Regresión logística, |g| <= 1e-6", logistica, np.zeros(d), {
    "paso 1/L": paso_fijo(1 / L),
    "Armijo, alfa0 = 1": armijo(1.0),
    "Wolfe fuerte, alfa0 = 1": wolfe_fuerte(1.0),
}, 1e-6)

This bench teaches something different. Step 1/L1/L is safe but conservative: LL is the global worst case and actual curvature near the minimum is much smaller. Armijo cannot exploit it because it never exceeds α0\alpha_0 (backtracking only shrinks): with α0=1\alpha_0 = 1 it accepts steps no greater than 1, slightly more than twice 1/L=0.431/L = 0.43, and needs 2933 iterations versus 6830 for 1/L1/L. Wolfe does exploit it: when curvature fails because slope remains very negative, bracketing doubles the step until it holds, converging in 353 iterations. Each iteration costs more (calculating ∇f\grad f on each trial), but the total is much smaller: 3364 evaluations versus Armijo’s 8801 and 1/L1/L‘s 13,662. This is what Wolfe “does not fall short” means.

The library version

scipy.optimize.line_search implements strong Wolfe search (following Nocedal and Wright with interpolation). Use it as reference: on a battery of test functions and random points, check that our implementation and SciPy’s return steps satisfying the same conditions, and compare their ff evaluation counts.

[ ]Against scipy.optimize.line_searchBrowser
from scipy.optimize import line_search, rosen, rosen_der

def himmelblau(p): return (p[0]**2 + p[1] - 11)**2 + (p[0] + p[1]**2 - 7)**2
def himmelblau_der(p):
    a, b = p[0]**2 + p[1] - 11, p[0] + p[1]**2 - 7
    return np.array([4 * p[0] * a + 2 * b, 2 * a + 4 * p[1] * b])
def beale(p):
    x, y = p
    return (1.5 - x + x*y)**2 + (2.25 - x + x*y**2)**2 + (2.625 - x + x*y**3)**2
def beale_der(p):
    x, y = p
    a, b, c = 1.5 - x + x*y, 2.25 - x + x*y**2, 2.625 - x + x*y**3
    return np.array([2*a*(y-1) + 2*b*(y**2-1) + 2*c*(y**3-1), 2*a*x + 4*b*x*y + 6*c*x*y**2])
Q = np.array([[3.0, 1.0], [1.0, 10.0]])
bateria = {
    "Rosenbrock": (rosen, rosen_der, 2.0),
    "Himmelblau": (himmelblau, himmelblau_der, 4.0),
    "Beale": (beale, beale_der, 2.0),
    "cuadrática": (lambda p: 0.5 * p @ Q @ p, lambda p: Q @ p, 3.0),
}
c1, c2 = 1e-4, 0.9

def wolfe_fuerte_cumplida(f, df, x, d, a):
    phi0, dphi0 = f(x), df(x) @ d
    return f(x + a * d) <= phi0 + c1 * a * dphi0 and abs(df(x + a * d) @ d) <= c2 * abs(dphi0)

rng = np.random.default_rng(1)
print(f"{'función':12s} {'propia: cumple, eval f':>26s} {'SciPy: cumple, eval f':>26s}")
for nombre, (f, df, escala) in bateria.items():
    ok_p = ok_s = nf_p = nf_s = 0
    for _ in range(30):
        x = rng.uniform(-escala, escala, size=2)
        d = -df(x)
        prob = Problema(f, df)
        a = wolfe_ls(lambda t: prob.f(x + t * d), lambda t: prob.grad(x + t * d) @ d, f(x), df(x) @ d, 1.0, c1, c2)
        ok_p += wolfe_fuerte_cumplida(f, df, x, d, a)
        nf_p += prob.nf
        cuenta = [0]
        def f_contada(z):
            cuenta[0] += 1
            return f(z)
        res = line_search(f_contada, df, x, d, gfk=df(x), old_fval=f(x), c1=c1, c2=c2, amax=1e6)
        ok_s += res[0] is not None and wolfe_fuerte_cumplida(f, df, x, d, res[0])
        nf_s += cuenta[0]
    print(f"{nombre:12s} {ok_p:>16d}/30, {nf_p / 30:5.1f} {ok_s:>16d}/30, {nf_s / 30:5.1f}")

Both implementations satisfy conditions in all 120 cases with the same order of ff evaluations (on average 2.2–6.7 per search for ours and 2.2–8.5 for SciPy). Do not read that difference as our superiority: these are 30 random points per function, and SciPy has other safeguards (different interpolation, a maximum step, the ability to fail and return None). Remember that line search is interchangeable: a serious optimizer treats it as a black box.

To contrast with what follows, solve the same Rosenbrock problem with SciPy methods using Wolfe search on directions better than −∇f-\grad f:

[ ]Rosenbrock with CG, BFGS and L-BFGSBrowser
from scipy.optimize import minimize

for metodo in ("CG", "BFGS", "L-BFGS-B"):
    r = minimize(rosen, [-1.2, 1.0], jac=rosen_der, method=metodo, options={"gtol": 1e-3})
    print(f"{metodo:9s} iteraciones = {r.nit:3d}   eval f = {r.nfev:3d}   eval grad = {r.njev:3d}   f = {r.fun:.2e}")

Between 31 and 35 iterations and 38–76 evaluations of ff, versus 14,789 fixed-step iterations: over two orders of magnitude improvement from changing direction (conjugate gradient, quasi-Newton) and using Wolfe search. This is the rest of the module: even with the best possible step, GD is tied to the condition number, and later methods exist to escape it.

Common mistakes

Exercises

NumericPer-iteration factor with the optimal step
For f(x)=12x⊤diag⁡(1,100)xf(\vb{x}) = \frac12\vb{x}\T\diag(1, 100)\vb{x}, calculate GD's per-iteration contraction factor ρ=max⁡i∣1−ηλi∣\rho = \max_i\abs{1 - \eta\lambda_i} using optimal fixed step η=2/(μ+L)\eta = 2/(\mu + L).
NumericIterations required by the prudent step
For the same function f(x)=12x⊤diag⁡(1,100)xf(\vb{x}) = \frac12\vb{x}\T\diag(1, 100)\vb{x} and step η=1/L=0.01\eta = 1/L = 0.01, what is the smallest number of iterations kk guaranteeing error-norm reduction by factor 10−610^{-6} in the worst case (that is, ρk≤10−6)\rho^k \le 10^{-6})?
NumericArmijo backtracking by hand
Let f(x)=5x2f(x) = 5x^2 at x=1x = 1, with descent direction d=−f′(1)=−10d = -f'(1) = -10. Apply Armijo backtracking with c1=0.4c_1 = 0.4, β=0.5\beta = 0.5 and α0=1\alpha_0 = 1. What step α\alpha is accepted?
NumericStability limit of a nondiagonal quadratic
f(x)=12x⊤Axf(\vb{x}) = \frac12\vb{x}\T\mat{A}\vb{x} with A=[5222]\mat{A} = \begin{bmatrix} 5 & 2 \\ 2 & 2 \end{bmatrix}. Fixed-step GD with η\eta converges from every initial point iff η<ηmax⁡\eta < \eta_{\max}. Calculate ηmax⁡\eta_{\max}.
QuizDiagnosing a loss curve
You train using fixed-step gradient descent. Training loss oscillates up and down with amplitude that grows each iteration. What is the most likely diagnosis?
QuizWhat each condition guarantees
Which line-search statements are true?

More than one answer may be correct.

ProofOrthogonal gradients with exact search
Prove: Let ff be C1C^1 and xk+1=xk−αk∇f(xk)\vb{x}_{k+1} = \vb{x}_k - \alpha_k\grad f(\vb{x}_k) with αk>0\alpha_k > 0 an interior local minimizer of φ(α)=f(xk−α∇f(xk))\varphi(\alpha) = f(\vb{x}_k - \alpha\grad f(\vb{x}_k)). Then ∇f(xk+1)⊤∇f(xk)=0\grad f(\vb{x}_{k+1})\T\grad f(\vb{x}_k) = 0. If also f(x)=12x⊤Axf(\vb{x}) = \frac12\vb{x}\T\mat{A}\vb{x} with A≻0\mat{A} \succ 0, then αk=gk⊤gkgk⊤Agk\alpha_k = \frac{\vb{g}_k\T\vb{g}_k}{\vb{g}_k\T\mat{A}\vb{g}_k} with gk=∇f(xk)\vb{g}_k = \grad f(\vb{x}_k).
0
Write gk=∇f(xk)\vb{g}_k = \grad f(\vb{x}_k) and think of φ\varphi as a one-variable function.

Step 1 of 4. What condition does αk\alpha_k satisfy as an interior minimizer of φ\varphi?

ProofArmijo backtracking terminates
Prove: Let ff be LL-smooth, d\vb{d} a descent direction at x\vb{x}, c1∈(0,1)c_1 \in (0, 1), β∈(0,1)\beta \in (0, 1) and α0>0\alpha_0 > 0. Armijo backtracking terminates and the accepted step satisfies α≥min⁡{α0,βαˉ}\alpha \ge \min\{\alpha_0, \beta\bar\alpha\} with αˉ=2(1−c1)∣∇f(x)⊤d∣/(L∥d∥2)\bar\alpha = 2(1 - c_1)\abs{\grad f(\vb{x})\T\vb{d}}/(L\norm{\vb{d}}^2).
0
Write φ(α)=f(x+αd)\varphi(\alpha) = f(\vb{x} + \alpha\vb{d}) and use the quadratic upper bound from LL-smoothness.

Step 1 of 4. What bound does LL-smoothness give for φ\varphi?

Summary

Key idea
GD follows the negative gradient because it minimizes a model with assumed curvature 1/η1/\eta, and on a quadratic decomposes into eigendirections each shrinking by 1−ηλi1 - \eta\lambda_i: largest curvature limits the step (η<2/L\eta < 2/L), smallest limits speed, so the best fixed step 2/(μ+L)2/(\mu + L) contracts by (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1) and cost grows like κ\kappa.
  • A descent direction satisfies ∇f⊤d<0\grad f\T\vb{d} < 0 and decreases ff for small α\alpha. −∇f-\grad f is steepest in Euclidean norm; −B∇f-\mat{B}\grad f with B≻0\mat{B} \succ 0 covers Newton, quasi-Newton and adaptive methods.
  • GD minimizes f(xk)+∇f⊤(y−xk)+12η∥y−xk∥2f(\vb{x}_k) + \grad f\T(\vb{y} - \vb{x}_k) + \frac1{2\eta}\norm{\vb{y} - \vb{x}_k}^2. With η≤1/L\eta \le 1/L this model majorizes ff and guarantees f(xk+1)≤f(xk)−η2∥∇f∥2f(\vb{x}_{k+1}) \le f(\vb{x}_k) - \frac\eta2\norm{\grad f}^2.
  • On a quadratic, ci(k)=(1−ηλi)kci(0)c_i(k) = (1 - \eta\lambda_i)^kc_i(0). Convergence from every starting point iff η<2/L\eta < 2/L; optimal step is 2/(μ+L)2/(\mu + L) with rate (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1), and κ2ln⁡1ε\frac\kappa2\ln\frac1\varepsilon steps suffice.
  • Exact search gives orthogonal gradients (90° zigzag) and contraction (κ−1κ+1)2\big(\frac{\kappa - 1}{\kappa + 1}\big)^2 in ff, without knowing μ\mu or LL; for general functions its cost is not worthwhile.
  • Armijo, φ(α)≤φ(0)+c1αφ′(0)\varphi(\alpha) \le \varphi(0) + c_1\alpha\varphi'(0), with backtracking always terminates and accepts α≥min⁡{α0,2β(1−c1)/L}\alpha \ge \min\{\alpha_0, 2\beta(1 - c_1)/L\} without knowing LL, but only shrinks the step. Wolfe adds curvature (φ′(α)≥c2φ′(0)\varphi'(\alpha) \ge c_2\varphi'(0), or its absolute value) to avoid falling short; such a step always exists and guarantees s⊤y>0\vb{s}\T\vb{y} > 0 in BFGS.
  • Always compare evaluations, scale stopping criteria and read loss curves: a line on a log scale means linear convergence; growing oscillation means η>2/L\eta > 2/L.