Module contents
Lesson 18 of 20Advanced 110 min

Stability, Lyapunov functions and gradient flows

What happens near an equilibrium of a nonlinear system and how to certify it without solving the equation. Study stability notions, linearization (Hartman–Grobman), Lyapunov's direct method with LaSalle, gradient flow with its natural Lyapunov function, explicit Euler step stability as the gradient-descent step limit, and basic bifurcations. The lesson closes with the edge of stability in real networks.

After this lesson you can

  • Distinguish Lyapunov, asymptotic and exponential stability with examples.
  • Decide stability of hyperbolic equilibria by linearization and recognize inconclusive cases.
  • Construct quadratic and energy Lyapunov functions and apply LaSalle's principle.
  • Prove gradient flow decreases f and relate Euler's stable step to the gradient-descent condition η < 2/λ_max.
  • Identify saddle-node, pitchfork and Hopf bifurcations in one-parameter systems.
  • Observe the edge of stability experimentally during MLP training.

Before you start

Motivation: training follows a dynamical system

When training a network by gradient descent you are not solving an equation: you iterate a map, θt+1=θt−η∇R^(θt)\theta_{t+1} = \theta_t - \eta\grad\hat{R}(\theta_t), hoping the sequence ends somewhere reasonable. When a controller keeps an inverted pendulum or robot arm in position, it does not solve one either: it designs a velocity field x˙=f(x)\dot{\vb{x}} = \vb{f}(\vb{x}) whose only possible destination is that position. In both cases the question is the same, and almost never answerable by solving the equation:

  • Does it stay near? Starting close to the resting point, do I stay close, or does a small perturbation send me far away?
  • Does it return? Do nearby trajectories end at the resting point? From what region?
  • Does it survive discretization? Does something stable in continuous time remain stable when simulated or trained with a finite step?
  • Does it change suddenly? When a parameter (learning rate, friction, gain) moves, do equilibria or oscillations appear or disappear?

The previous lesson answered all this for linear systems, where the matrix exponential tells everything and the phase portrait is read from eigenvalues. This lesson moves to nonlinear systems with three tools. Linearization examines a system close to equilibrium and inherits the linear verdict when justified. Lyapunov functions certify stability and even whole attraction regions without solving trajectories: find a quantity decreasing along them. Gradient flow is the case where that quantity is given: the function being minimized. Discretizing it by Euler gives gradient descent and, as a stability theorem, rule η<2/λmax⁡\eta < 2/\lambda_{\max} known from the Hessian lesson. Finally, real networks live right at the edge of that rule.

Equilibria and three notions of stability

We work with an autonomous system x˙=f(x)\dot{\vb{x}} = \vb{f}(\vb{x}), with f:D⊆Rn→Rn\vb{f}: D \subseteq \R^n \to \R^n locally Lipschitz, so by Picard–Lindelöf each initial condition has a unique solution x(t;x0)\vb{x}(t; \vb{x}_0). An equilibrium is a point x∗\vb{x}^* with f(x∗)=0\vb{f}(\vb{x}^*) = \vb{0}: the solution starting there stays there forever. By translation, u=x−x∗\vb{u} = \vb{x} - \vb{x}^*, we may always assume the equilibrium is the origin.

Each definition is strictly stronger than the previous, and counterexamples are simple:

  • Stable but not asymptotically. Oscillator x˙=−y\dot x = -y, y˙=x\dot y = x preserves x2+y2x^2 + y^2: trajectories are circles. Starting at distance δ\delta you remain at distance δ\delta (take δ=ε\delta = \eps), but never return to the origin.
  • Asymptotically but not exponentially. In x˙=−x3\dot x = -x^3 the solution is x(t)=x0/1+2x02tx(t) = x_0/\sqrt{1 + 2x_0^2 t}. It converges to 0, but as t−1/2t^{-1/2}, slower than every exponential.
  • Attractive but unstable. The stability condition is not redundant. On the circle, θ˙=1−cos⁡θ\dot\theta = 1 - \cos\theta has a unique equilibrium θ=0\theta = 0, and all trajectories end there. But starting at θ0=0.01\theta_0 = 0.01 you first make a full turn and only then reach θ=2π≡0\theta = 2\pi \equiv 0: however close you start, you move distance π\pi away. Vinograd (1957) constructed a similar example in the plane.

For a linear system x˙=Ax\dot{\vb{x}} = \mat{A}\vb{x} you already know the full answer: the origin is exponentially stable if and only if all eigenvalues of A\mat{A} have negative real parts (A\mat{A} is Hurwitz), because then ∥etA∥≤Ke−αt\norm{e^{t\mat{A}}} \le Ke^{-\alpha t} for any α\alpha less than min⁡i∣Re⁡λi∣\min_i\abs{\operatorname{Re}\lambda_i}. For linear systems asymptotic and exponential stability coincide. What you just saw with x˙=−x3\dot x = -x^3 is purely nonlinear.

Linearization: the Jacobian at equilibrium

If f\vb{f} is of class C1C^1, near equilibrium f(x∗+u)=Ju+g(u)\vb{f}(\vb{x}^* + \vb{u}) = \mat{J}\vb{u} + \vb{g}(\vb{u}), where J=Jf(x∗)\mat{J} = \mat{J}_{\vb{f}}(\vb{x}^*) is the Jacobian matrix and remainder satisfies ∥g(u)∥=o(∥u∥)\norm{\vb{g}(\vb{u})} = o(\norm{\vb{u}}). This is linearization from lesson 7 applied to the field. The hope is that near x∗\vb{x}^* the nonlinear system behaves like u˙=Ju\dot{\vb{u}} = \mat{J}\vb{u}. Before the theorem, check it.

InteractiveNonlinear phase plane
lupa
  • trajectory (click to launch another)
  • equilibrium (filled if asymptotically stable)
Nonlinear, near (0, 0)
Linearization u˙=Ju\dot{\vb{u}} = \mat{J}\vb{u}
0.50
Zoom at
×1.00
J(x∗)=[0.001.00−1.00−0.50]\mat{J}(\vb{x}^*) = \begin{bmatrix} 0.00 & 1.00 \\ -1.00 & -0.50 \end{bmatrix}
λ=−0.25±0.97 i\lambda = -0.25 \pm 0.97\,i
Type (linearization)stable focus
Energy E=12y2+1−cos⁡xE = \tfrac12 y^2 + 1 - \cos x: start → end1.994 → 0.000
Hyperbolic (no eigenvalue with zero real part): by Hartman–Grobman, near x∗\vb{x}^* the nonlinear portrait is a deformed copy of the linear one. Verdict: asymptotically stable.
Click the plane to launch trajectories and click an equilibrium to put it under the magnifying glass: below are enlarged nonlinear portrait and linearization u˙=Ju\dot{\vb{u}} = \mat{J}\vb{u}, with eigenspaces in color. For the pendulum, compare the origin focus and saddle at (π,0)(\pi, 0), and bring friction cc to 0: what happens to the nonlinear view? In Lotka–Volterra, linearization at (1,1)(1, 1) is a center; observe quantity HH does not change along the orbit. In the bilinear game, switch from ‘Flow’ to ‘Simultaneous’ and increase step hh.

At the pendulum saddle the nonlinear and linear magnified views become indistinguishable when reduced: eigenlines of J\mat{J} are tangents to the two special nonlinear curves entering and leaving the saddle. The same happens at the origin focus. At both centers (Lotka–Volterra and the frictionless pendulum), linearization says “closed orbits” and the nonlinear system also has them, but for a reason linearization cannot see: a conserved quantity. The next theorem explains why that agreement was not guaranteed.

Proof

We prove (1); (2) follows from a similar argument on the unstable part (Chetaev’s theorem), omitted here. Take x∗=0\vb{x}^* = \vb{0} and write u˙=Ju+g(u)\dot{\vb{u}} = \mat{J}\vb{u} + \vb{g}(\vb{u}). Since J\mat{J} is Hurwitz, there exist K≥1K \ge 1 and α>0\alpha > 0 with ∥etJ∥≤Ke−αt\norm{e^{t\mat{J}}} \le Ke^{-\alpha t} for t≥0t \ge 0. Since g(u)=o(∥u∥)\vb{g}(\vb{u}) = o(\norm{\vb{u}}), there exists ρ>0\rho > 0 such that ∥u∥<ρ\norm{\vb{u}} < \rho implies ∥g(u)∥≤α2K∥u∥\norm{\vb{g}(\vb{u})} \le \frac{\alpha}{2K}\norm{\vb{u}}.

While the trajectory is in the ball of radius ρ\rho, Duhamel’s formula gives

u(t)=etJu0+∫0te(t−s)Jg(u(s)) ⁣ds,∥u(t)∥≤Ke−αt∥u0∥+α2∫0te−α(t−s)∥u(s)∥ ⁣ds.\vb{u}(t) = e^{t\mat{J}}\vb{u}_0 + \int_0^t e^{(t-s)\mat{J}}\vb{g}(\vb{u}(s))\dd s, \qquad \norm{\vb{u}(t)} \le Ke^{-\alpha t}\norm{\vb{u}_0} + \frac{\alpha}{2}\int_0^t e^{-\alpha(t-s)}\norm{\vb{u}(s)}\dd s.

Multiply by eαte^{\alpha t} and write φ(t)=eαt∥u(t)∥\varphi(t) = e^{\alpha t}\norm{\vb{u}(t)}: this gives φ(t)≤K∥u0∥+α2∫0tφ(s) ⁣ds\varphi(t) \le K\norm{\vb{u}_0} + \frac{\alpha}{2}\int_0^t \varphi(s)\dd s. Grönwall’s inequality gives φ(t)≤K∥u0∥eαt/2\varphi(t) \le K\norm{\vb{u}_0}e^{\alpha t/2}, i.e.

∥u(t)∥≤K∥u0∥e−αt/2.\norm{\vb{u}(t)} \le K\norm{\vb{u}_0}e^{-\alpha t/2}.

It remains to show the trajectory never leaves the ball. If ∥u0∥<ρ/K\norm{\vb{u}_0} < \rho/K, the bound gives ∥u(t)∥<ρ\norm{\vb{u}(t)} < \rho on every interval [0,T][0, T] during which it has remained in the ball; a first exit time, if it existed, would satisfy both ∥u∥=ρ\norm{\vb{u}} = \rho and ∥u∥<ρ\norm{\vb{u}} < \rho. Thus it never leaves, the solution exists for every t≥0t \ge 0 and the bound always holds: exponential stability with δ=ρ/K\delta = \rho/K.

∎

An equilibrium is hyperbolic if no eigenvalue of J\mat{J} has zero real part. For these, the theorem always decides, and a stronger result says linearization gets not just stability but the entire portrait right.

This is stability by linearization: at a hyperbolic equilibrium, Jacobian eigenvalues decide. Two qualifications. First, h\vb{h} is only continuous, and at that level a stable node and stable focus are equivalent (both are sinks). For linearization also to get right whether orbits rotate or enter with a defined tangent requires more regularity: in the plane, with f\vb{f} of class C2C^2, Hartman proved h\vb{h} can be taken of class C1C^1, and a C1C^1 diffeomorphism cannot turn a spiral into a curve with limiting tangent. Second, more importantly, at nonhyperbolic points linearization can lie in either direction. The canonical example is

x˙=−y+a x(x2+y2),y˙=x+a y(x2+y2),\dot x = -y + a\,x(x^2 + y^2), \qquad \dot y = x + a\,y(x^2 + y^2),

whose linearization at the origin is center [0−110]\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} for every aa. In polar coordinates, r˙=ar3\dot r = a r^3 and θ˙=1\dot\theta = 1: with a<0a < 0 the origin is asymptotically stable (a slow, nonexponential spiral), with a>0a > 0 unstable and with a=0a = 0 a center. Linearization is identical in all three cases.

The figure’s bilinear game deserves its own section below: its flow is linear and its center exact, but discretization breaks the center.

Lyapunov’s direct method

Linearization is local and silent in nonhyperbolic cases. Lyapunov’s direct method avoids both limitations with a physical idea: if a positive “energy” keeps decreasing along trajectories, the system must end at its minimum. Remarkably this can be checked without knowing trajectories because by the chain rule the derivative of VV along a solution is

V˙(x):= ⁣d ⁣dtV(x(t))=∇V(x)⊤f(x),\dot V(\vb{x}) := \frac{\dd}{\dd t}V(\vb{x}(t)) = \grad V(\vb{x})\T\vb{f}(\vb{x}),

a function of the point, not the trajectory.

Proof

Stability. Given ε>0\eps > 0 with closed ball Bˉε⊂D\bar B_\eps \subset D, let m=min⁡∥x∥=εV(x)m = \min_{\norm{\vb{x}} = \eps} V(\vb{x}), positive because the sphere is compact and V>0V > 0 on it. By continuity of VV at the origin there is δ∈(0,ε)\delta \in (0, \eps) with V(x)<mV(\vb{x}) < m if ∥x∥<δ\norm{\vb{x}} < \delta. If ∥x0∥<δ\norm{\vb{x}_0} < \delta, since VV does not increase along the trajectory, V(x(t))≤V(x0)<mV(\vb{x}(t)) \le V(\vb{x}_0) < m and the trajectory can never touch sphere ∥x∥=ε\norm{\vb{x}} = \eps, where V≥mV \ge m. Remaining in a compact set, the solution also exists for all t≥0t \ge 0.

Attraction. Suppose V˙<0\dot V < 0 away from the origin. V(x(t))V(\vb{x}(t)) decreases and is bounded below, so has limit L≥0L \ge 0. If L>0L > 0, continuity gives r>0r > 0 with V<LV < L on BrB_r, so the trajectory lives in compact C={r≤∥x∥≤ε}C = \{r \le \norm{\vb{x}} \le \eps\}, where V˙\dot V attains maximum −γ<0-\gamma < 0. Then V(x(t))≤V(x0)−γt→−∞V(\vb{x}(t)) \le V(\vb{x}_0) - \gamma t \to -\infty, absurd. Hence V(x(t))→0V(\vb{x}(t)) \to 0, forcing x(t)→0\vb{x}(t) \to \vb{0}: if ∥x(tk)∥≥r\norm{\vb{x}(t_k)} \ge r on a sequence tk→∞t_k \to \infty, then V(x(tk))≥min⁡CV>0V(\vb{x}(t_k)) \ge \min_C V > 0.

Globality. If VV is radially unbounded, each sublevel set {V≤c}\{V \le c\} is bounded, so any trajectory stays in compact {V≤V(x0)}\{V \le V(\vb{x}_0)\} and the argument applies from any x0\vb{x}_0.

∎

The proof contains the lesson’s most useful idea. If Ωc={x:V(x)≤c}\Omega_c = \{\vb{x} : V(\vb{x}) \le c\} is bounded and V˙≤0\dot V \le 0 on it, no trajectory starting in Ωc\Omega_c can leave: to do so it must cross boundary V=cV = c outward, increasing VV. If also V˙<0\dot V < 0 on Ωc∖{0}\Omega_c \setminus \{\vb{0}\}, all Ωc\Omega_c lies inside the basin of attraction. A sublevel set on which VV decreases is a certified basin estimate.

Quadratic functions and the Lyapunov equation

For a linear system x˙=Ax\dot{\vb{x}} = \mat{A}\vb{x} the natural candidate is a quadratic form V(x)=x⊤PxV(\vb{x}) = \vb{x}\T\mat{P}\vb{x} with P\mat{P} positive definite. Its derivative is

V˙=x˙⊤Px+x⊤Px˙=x⊤(A⊤P+PA)x,\dot V = \dot{\vb{x}}\T\mat{P}\vb{x} + \vb{x}\T\mat{P}\dot{\vb{x}} = \vb{x}\T(\mat{A}\T\mat{P} + \mat{P}\mat{A})\vb{x},

another quadratic form. Requiring V˙=−x⊤Qx\dot V = -\vb{x}\T\mat{Q}\vb{x} with Q≻0\mat{Q} \succ 0 is the Lyapunov equation A⊤P+PA=−Q\mat{A}\T\mat{P} + \mat{P}\mat{A} = -\mat{Q}.

Proof

If P≻0\mat{P} \succ 0 exists, V=x⊤PxV = \vb{x}\T\mat{P}\vb{x} is a strict radially unbounded Lyapunov function, so the origin is globally asymptotically stable, equivalent for a linear system to A\mat{A} being Hurwitz. Conversely, if A\mat{A} is Hurwitz the integral converges (integrand decays as e−2αte^{-2\alpha t}), is symmetric and positive definite because x⊤Px=∫0∞∥Q1/2etAx∥2 ⁣dt>0\vb{x}\T\mat{P}\vb{x} = \int_0^\infty \norm{\mat{Q}^{1/2}e^{t\mat{A}}\vb{x}}^2\dd t > 0 for x≠0\vb{x} \neq \vb{0}, and

A⊤P+PA=∫0∞ ⁣d ⁣dt(etA⊤QetA) ⁣dt=[etA⊤QetA]0∞=−Q.\mat{A}\T\mat{P} + \mat{P}\mat{A} = \int_0^\infty \frac{\dd}{\dd t}\left(e^{t\mat{A}\T}\mat{Q}e^{t\mat{A}}\right)\dd t = \Big[e^{t\mat{A}\T}\mat{Q}e^{t\mat{A}}\Big]_0^\infty = -\mat{Q}.

Uniqueness follows because linear operator P↦A⊤P+PA\mat{P} \mapsto \mat{A}\T\mat{P} + \mat{P}\mat{A} has eigenvalues λi+λj\lambda_i + \lambda_j, all with negative real part and therefore nonzero.

∎

For a nonlinear system, P\mat{P} of its linearization is a local candidate: term g\vb{g} is small near the origin and cannot spoil V˙\dot V, negative of order ∥x∥2\norm{\vb{x}}^2 (another proof of the linearization theorem). Far from the origin, nonlinear terms may make V˙>0\dot V > 0, and the question becomes how far you can inflate Ωc\Omega_c before touching that region.

InteractiveCertifying with Lyapunov
  • region where V˙>0\dot V > 0
  • set {V≤c}\{V \le c\}
  • actual basin boundary (simulated)
  • launched trajectory
Quadratic candidate
1.50
−0.50
1.00
2.305
P=[1.50−0.50−0.501.00]\mat{P} = \begin{bmatrix} 1.50 & -0.50 \\ -0.50 & 1.00 \end{bmatrix}
Eigenvalues of P\mat{P}0.69, 1.81
Eigenvalues of A⊤P+PA\mat{A}\T\mat{P} + \mat{P}\mat{A}−1.00, −1.00
Largest certified level c∗c^*2.305
Certified area / basin areacalculating…
All of {V≤c}\{V \le c\} lies where V˙≤0\dot V \le 0: trajectories starting inside stay inside and reach the origin. This is a certified estimate of the basin.
The red region is where V˙>0\dot V > 0 for candidate V(x)=x⊤PxV(\vb{x}) = \vb{x}\T\mat{P}\vb{x}; the black curve (white in dark mode) bounds the true attraction basin, calculated by simulating thousands of trajectories. Level cc starts at c∗c^*, the largest for which ellipse {V≤c}\{V \le c\} does not invade the red region (the red point marks contact): increase it slightly and certification is lost. Move entries of P\mat{P} so the certified ellipse covers more basin. Try p11=p22=1p_{11} = p_{22} = 1, p12=0p_{12} = 0 in backward Van der Pol: why does V˙\dot V vanish on a line? Click the plane to see VV along a trajectory inside and outside the certified set.

In backward Van der Pol, x˙1=−x2\dot x_1 = -x_2, x˙2=x1+(x12−1)x2\dot x_2 = x_1 + (x_1^2 - 1)x_2, the origin is a stable focus and its basin is the interior of an unstable limit cycle (Van der Pol with time reversed). The P\mat{P} from the Lyapunov equation with Q=I\mat{Q} = \mat{I} is [1.5−0.5−0.51]\begin{bmatrix} 1.5 & -0.5 \\ -0.5 & 1 \end{bmatrix}, the largest certified level is c∗≈2.305c^* \approx 2.305, and the ellipse covers slightly less than half the true basin (about 6.486.48 of 13.713.7 area units). Moving P\mat{P} gains little: the best ellipse found optimizing three entries covers 48 %48\,\%, and none reaches half because the basin does not resemble an ellipse. This conservatism is the price of seeking certificates in a small family; higher-degree polynomials (sums of squares) or neural networks trained as Lyapunov functions, as in Neural Lyapunov Control (Chang, Roohi and Gao, 2019), estimate the true basin much more closely.

When V˙\dot V is only semidefinite: LaSalle

The damped pendulum’s energy, E(x,y)=12y2+1−cos⁡xE(x, y) = \tfrac12 y^2 + 1 - \cos x, is the obvious physical candidate, and E˙=yy˙+sin⁡x x˙=y(−sin⁡x−cy)+ysin⁡x=−cy2\dot E = y\dot y + \sin x\,\dot x = y(-\sin x - cy) + y\sin x = -cy^2. It is ≤0\le 0, but vanishes on the entire y=0y = 0 axis, not just the origin. Lyapunov’s theorem gives only stability. Yet clearly a trajectory cannot stay in y=0y = 0 except at equilibrium: if y≡0y \equiv 0, then y˙=−sin⁡x=0\dot y = -\sin x = 0. LaSalle’s principle turns this observation into a theorem.

Proof

Let x(t)\vb{x}(t) be a trajectory in Ω\Omega. Its ω\omega-limit set (limit points of x(tk)\vb{x}(t_k) with tk→∞t_k \to \infty) is nonempty and compact because Ω\Omega is, and is invariant and attracts x(t)\vb{x}(t), standard properties of bounded-trajectory limit sets. Since V(x(t))V(\vb{x}(t)) decreases and is bounded, it has limit LL, and by continuity V≡LV \equiv L on the ω\omega-limit set. A trajectory starting there stays there (invariance) with VV constant, so V˙=0\dot V = 0 there: the ω\omega-limit set lies in EE, is invariant and thus lies in MM.

∎

For the pendulum with c>0c > 0, take Ω={E≤c0, ∣x∣<π}\Omega = \{E \le c_0,\ \abs{x} < \pi\} with c0<2c_0 < 2, the energy of saddle (π,0)(\pi, 0). It is compact and invariant (energy does not increase and level c0c_0 does not reach the saddles). On it, E={y=0}E = \{y = 0\}, and the only trajectory staying on that axis is the equilibrium: M={0}M = \{\vb{0}\}. Conclusion: every point of energy less than 2 and ∣x∣<π\abs{x} < \pi comes to rest at the bottom, a much better basin estimate than any ellipse. In the lab you will check that along a trajectory EE never rises, although its derivative vanishes momentarily whenever the trajectory crosses axis y=0y = 0, at the ends of oscillations where velocity is zero.

Gradient flow: the Lyapunov function comes built in

There is a family of systems where no Lyapunov function needs to be sought.

Along the flow,  ⁣d ⁣dtf(x(t))=−∥∇f(x(t))∥2\frac{\dd}{\dd t}f(\vb{x}(t)) = -\norm{\grad f(\vb{x}(t))}^2: you will prove this in the first guided exercise. Almost all flow properties follow from this identity:

  1. ff decreases, strictly except at critical points. Trajectories cross level sets of ff perpendicularly because the gradient is normal to them.
  2. No periodic orbits exist (except equilibria): on closing an orbit ff would return to its initial value, but it decreased strictly.
  3. Equilibria are critical points, and the Jacobian of the field at one is −∇2f(x∗)-\hess f(\vb{x}^*), symmetric. By the spectral theorem eigenvalues are real: gradient flow has no foci or centers. A nondegenerate minimum (∇2f≻0\hess f \succ 0) is an exponentially stable node, a nondegenerate maximum an unstable node and a nondegenerate saddle a saddle. This is the critical-point classification of lesson 9 read dynamically.
  4. At an isolated strict minimum, even degenerate, V=f−f(x∗)V = f - f(\vb{x}^*) is a strict Lyapunov function and the minimum is asymptotically stable. For example f(x)=x4/4f(x) = x^4/4 gives x˙=−x3\dot x = -x^3: stable, but not exponentially.
  5. Bounded trajectories approach the critical set (LaSalle with V=fV = f). Convergence to a single point is not guaranteed: there are C∞C^\infty functions in the plane, such as Palis and de Melo’s “Mexican hat”, whose trajectories wind forever approaching a circle of critical points. For analytic functions Łojasiewicz’s inequality does ensure convergence to a point.

Rate without convexity

If ff satisfies the Polyak–Łojasiewicz (PL) inequality, 12∥∇f(x)∥2≥μ (f(x)−f∗)\tfrac12\norm{\grad f(\vb{x})}^2 \ge \mu\,(f(\vb{x}) - f^*) with μ>0\mu > 0, then  ⁣d ⁣dt(f−f∗)=−∥∇f∥2≤−2μ(f−f∗)\frac{\dd}{\dd t}(f - f^*) = -\norm{\grad f}^2 \le -2\mu(f - f^*) and, by Grönwall,

f(x(t))−f∗≤e−2μt(f(x0)−f∗).f(\vb{x}(t)) - f^* \le e^{-2\mu t}\big(f(\vb{x}_0) - f^*\big).

Exponential value convergence without requiring convexity. Strongly convex functions satisfy PL, but so do many nonconvex ones, including squared loss of overparameterized models near their manifolds of minima. You will revisit this in optimization.

Saddles: unstable but almost never a destination

At a nondegenerate saddle, −∇2f(x∗)-\hess f(\vb{x}^*) has kk negative eigenvalues (directions where ff curves upward) and n−kn - k positive. The set of initial conditions converging to the saddle, its stable manifold, is a dimension-k<nk < n submanifold tangent to the positive-curvature eigenspace: a measure-zero set. In f(x,y)=x2−y2f(x, y) = x^2 - y^2, flow is x˙=−2x\dot x = -2x, y˙=2y\dot y = 2y and only initial conditions with y0=0y_0 = 0 reach the origin. Thus with random initialization gradient flow almost surely does not end at a saddle. The same holds for gradient descent with small steps (Lee, Simchowitz, Jordan and Recht, 2016), although progress near a saddle may be very slow: the subject of saddle escape.

Dynamics that are not gradients: games

Not all training minimizes a function. In a zero-sum game min⁡xmax⁡yf(x,y)\min_{\vb{x}}\max_{\vb{y}} f(\vb{x}, \vb{y}) (GAN, robust problem, adversarial training), each player naturally follows its gradient: simultaneous gradient descent-ascent (GDA), with continuous limit

x˙=−∇xf(x,y),y˙=+∇yf(x,y).\dot{\vb{x}} = -\grad_{\vb{x}} f(\vb{x}, \vb{y}), \qquad \dot{\vb{y}} = +\grad_{\vb{y}} f(\vb{x}, \vb{y}).

This field is no longer the gradient of anything. Its Jacobian is [−fxx−fxyfyxfyy]\begin{bmatrix} -f_{\vb{x}\vb{x}} & -f_{\vb{x}\vb{y}} \\ f_{\vb{y}\vb{x}} & f_{\vb{y}\vb{y}} \end{bmatrix}, not symmetric: the interaction block appears with opposite signs and generates rotation. In the simplest case, f(x,y)=xyf(x, y) = xy, the field is x˙=−y\dot x = -y, y˙=x\dot y = x: a center with x2+y2x^2 + y^2 conserved. Players orbit Nash equilibrium (0,0)(0, 0) without approaching it.

Discretization makes it worse. A simultaneous step at rate hh is

[xk+1yk+1]=[1−hh1][xkyk],\begin{bmatrix} x_{k+1} \\ y_{k+1} \end{bmatrix} = \begin{bmatrix} 1 & -h \\ h & 1 \end{bmatrix}\begin{bmatrix} x_k \\ y_k \end{bmatrix},

with eigenvalues 1±ih1 \pm ih of magnitude 1+h2>1\sqrt{1 + h^2} > 1. Radius is multiplied by 1+h2\sqrt{1 + h^2} each step and diverges for any h>0h > 0. This appears in the phase-plane figure with the game in ‘Simultaneous’ mode. Two classical fixes:

  • Alternating step. If yy responds to already updated xx, the matrix becomes [1−hh1−h2]\begin{bmatrix} 1 & -h \\ h & 1 - h^2 \end{bmatrix}, with determinant 1 and trace 2−h22 - h^2: for h<2h < 2 its eigenvalues lie on the unit circle and iterates follow a closed ellipse. They do not converge, but do not diverge.
  • Extragradient. Take a trial step and use the gradient at the trial point for the real step. In the bilinear game the resulting matrix (1−h2)I−h[01−10](1 - h^2)\mat{I} - h\begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix} has eigenvalues 1−h2±ih1 - h^2 \pm ih of magnitude 1−h2+h4\sqrt{1 - h^2 + h^4}, less than 1 for 0<h<10 < h < 1: iterates converge.

This phenomenon, cycles and divergence explained by complex eigenvalues of the game Jacobian, underlies Mescheder, Geiger and Nowozin’s (2018) analysis of convergent GAN training methods, studied in detail in gradient descent-ascent and local GAN convergence.

Explicit Euler and the step-size limit

The previous example illustrates a general question: when does a numerical scheme preserve continuous-system stability? Start with the simplest scalar equation x˙=−λx\dot x = -\lambda x with λ>0\lambda > 0, whose solution x0e−λtx_0 e^{-\lambda t} decays for any initial condition. Explicit Euler with step hh replaces the derivative with a difference quotient:

xk+1=xk+h (−λxk)=(1−hλ) xk,xk=(1−hλ)kx0.x_{k+1} = x_k + h\,(-\lambda x_k) = (1 - h\lambda)\,x_k, \qquad x_k = (1 - h\lambda)^k x_0.

This is explicit Euler step stability, proved in a guided exercise. Geometrically, factor 1−hλ1 - h\lambda is positive and below 1 if hλ<1h\lambda < 1 (iterates decay without changing sign, like the exact solution), negative but of magnitude below 1 if 1<hλ<21 < h\lambda < 2 (they jump across the equilibrium less and less), and magnitude above 1 if hλ>2h\lambda > 2. For linear system x˙=Ax\dot{\vb{x}} = \mat{A}\vb{x} with A\mat{A} diagonalizable, the step multiplies each eigencomponent by 1+hλi1 + h\lambda_i, and the condition is ∣1+hλi∣<1\abs{1 + h\lambda_i} < 1 for every ii: each hλih\lambda_i must lie in the radius-1 disk centered at −1-1, Euler’s absolute stability region. That disk touches the imaginary axis only at the origin, so no Euler step preserves a center: exactly what happens to the bilinear game, with λ=±i\lambda = \pm i and ∣1±ih∣>1\abs{1 \pm ih} > 1.

Gradient descent is Euler on gradient flow

Apply Euler with step η\eta to flow x˙=−∇f(x)\dot{\vb{x}} = -\grad f(\vb{x}):

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

This is gradient descent, letter for letter. On quadratic f(x)=12x⊤Hx−b⊤xf(\vb{x}) = \tfrac12\vb{x}\T\mat{H}\vb{x} - \vb{b}\T\vb{x} with H≻0\mat{H} \succ 0 and minimum x∗\vb{x}^*, error satisfies xk+1−x∗=(I−ηH)(xk−x∗)\vb{x}_{k+1} - \vb{x}^* = (\mat{I} - \eta\mat{H})(\vb{x}_k - \vb{x}^*). In the eigenbasis of H\mat{H}, each component is multiplied by 1−ηλi1 - \eta\lambda_i, the Euler step for u˙=−λiu\dot u = -\lambda_i u. The previous theorem component by component gives the rule:

el descenso por gradiente converge desde cualquier punto  ⟺  0<η<2λmax⁡(H).\text{el descenso por gradiente converge desde cualquier punto} \iff 0 < \eta < \frac{2}{\lambda_{\max}(\mat{H})}.

The maximum-curvature direction destabilizes first, oscillating as it does. Inside the stable interval, rate is set by worst factor max⁡i∣1−ηλi∣\max_i\abs{1 - \eta\lambda_i}, minimized with η=2/(λmin⁡+λmax⁡)\eta = 2/(\lambda_{\min} + \lambda_{\max}) and then equal to (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1), with κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}.

InteractiveGradient descent as an Euler step
  • gradient flow
  • flow at t=kηt = k\eta
  • gradient descent
Factor per step ∣1−ηλ∣\abs{1 - \eta\lambda} versus η\eta
2/λmaxλ = 10λ = 1
Value of ff (logarithmic scale)
  • gradient descent
  • flow at t = kη
Function
0.1500
k = 40
η λmax⁡\eta\,\lambda_{\max} (limit: 2)1.500
Factor ∣1−ηλ1∣\abs{1 - \eta\lambda_1} in xx0.850
Factor ∣1−ηλ2∣\abs{1 - \eta\lambda_2} in yy0.500
f(x40)f(\vb{x}_{40})1.38e−5
1<ηλmax⁡=1.50<21 < \eta\lambda_{\max} = 1.50 < 2: along λmax⁡\lambda_{\max} the factor 1−ηλmax⁡1 - \eta\lambda_{\max} is negative. Iterates jump across the valley, but converge.
Quadratic f=12(x2+10y2)f = \tfrac12(x^2 + 10y^2): gray curve is exact gradient flow and hollow circles its positions at t=kηt = k\eta; blue dots are gradient-descent iterates. Increase η\eta across η=0.1\eta = 0.1 (iterates begin zigzagging) and η=0.2=2/λmax⁡\eta = 0.2 = 2/\lambda_{\max} (they diverge). The per-step factor panel shows ∣1−ηλ∣\abs{1 - \eta\lambda} for each direction: λ=10\lambda = 10 leaves the stable band much earlier than λ=1\lambda = 1. Then switch to the nonquadratic valley and compare η=0.15\eta = 0.15 with η=0.25\eta = 0.25: maximum curvature changes along the trajectory and threshold 2/λmax⁡2/\lambda_{\max} moves with it.

Two readings. With small η\eta, iterates track flow positions at t=kηt = k\eta: Euler is first order and over fixed time interval [0,T][0, T] global error is O(η)\bigO(\eta). With η\eta near 2/λmax⁡2/\lambda_{\max}, iterates look nothing like the flow despite converging: in direction λmax⁡\lambda_{\max} the flow decays almost instantly and iterates bounce wall to wall. Gradient flow is stable for all time; gradient descent only if the step respects curvature. The same phenomenon—components damped instantly by continuous dynamics that force an explicit method to take tiny steps—is ODE stiffness.

For nonquadratic ff, gradient descent iterates map T(x)=x−η∇f(x)T(\vb{x}) = \vb{x} - \eta\grad f(\vb{x}), having each minimum as a fixed point with Jacobian I−η∇2f(x∗)\mat{I} - \eta\hess f(\vb{x}^*). The discrete linearization theorem (spectral radius instead of real parts, with the same Grönwall proof in sums) says a minimum with ∇2f(x∗)≻0\hess f(\vb{x}^*) \succ 0 attracts nearby iterates if η<2/λmax⁡(∇2f(x∗))\eta < 2/\lambda_{\max}(\hess f(\vb{x}^*)) and repels them if η>2/λmax⁡(∇2f(x∗))\eta > 2/\lambda_{\max}(\hess f(\vb{x}^*)). The consequence: gradient descent with step η\eta cannot converge to a minimum whose maximum curvature exceeds 2/η2/\eta. That curvature is the minimum’s sharpness, and step size acts as a filter allowing only sufficiently flat minima. We return to this at the frontier.

Bifurcations and limit cycles

So far the system was fixed. If it depends on a parameter x˙=f(x,μ)\dot{\vb{x}} = \vb{f}(\vb{x}, \mu), equilibria move with μ\mu, and by the implicit function theorem an equilibrium with invertible Jacobian moves smoothly and retains its type while hyperbolic. Qualitative changes can occur only where an equilibrium ceases to be hyperbolic.

Near a generic bifurcation, any system reduces after a change of variables to a normal form, a simple polynomial capturing the phenomenon. The three basic forms:

  • Saddle-node, x˙=μ−x2\dot x = \mu - x^2. For μ<0\mu < 0 there are no equilibria; at μ=0\mu = 0 one appears, x=0x = 0, with f′(0)=0f'(0) = 0; for μ>0\mu > 0 there are two, ±μ\pm\sqrt{\mu}, with f′(±μ)=∓2μf'(\pm\sqrt\mu) = \mp 2\sqrt\mu: positive stable, negative unstable. Two equilibria are born together from nothing (or traversed backward collide and annihilate).
  • Pitchfork, x˙=μx−x3\dot x = \mu x - x^3 (supercritical). Typical of systems with symmetry x↦−xx \mapsto -x. The origin is stable for μ<0\mu < 0 and unstable for μ>0\mu > 0, when two stable branches ±μ\pm\sqrt{\mu} are born. In the subcritical form x˙=μx+x3\dot x = \mu x + x^3, branches ±−μ\pm\sqrt{-\mu} exist for μ<0\mu < 0 and are unstable: on crossing μ=0\mu = 0 the origin loses stability and no stable equilibrium remains nearby. The transition is abrupt.
  • Hopf, in polar coordinates r˙=μr−r3\dot r = \mu r - r^3, θ˙=1\dot\theta = 1. The origin has eigenvalues μ±i\mu \pm i: a complex pair crossing the imaginary axis at μ=0\mu = 0. For μ>0\mu > 0 the focus destabilizes and a stable limit cycle is born, circle r=μr = \sqrt{\mu}. Hopf’s theorem guarantees the same in any system where a complex pair crosses the imaginary axis at nonzero speed, provided a nondegeneracy coefficient (the first Lyapunov coefficient) does not vanish; its sign decides whether the bifurcation is supercritical or subcritical.
InteractiveBifurcation diagram
Bifurcation diagram: x∗x^* versus μ\mu
μ
Phase line: x˙=f(x)\dot x = f(x) for μ=0.50\mu = 0.50
f(x)
  • stable equilibrium
  • unstable equilibrium
Bifurcation
0.50
x˙=0.50 x−x3\dot x = 0.50\,x - x^3
Number of equilibria3
x∗=−0.71x^* = -0.71f′ = −1.00
x∗=0.00x^* = 0.00f′ = 0.50
x∗=0.71x^* = 0.71f′ = −1.00
Supercritical, μ>0\mu > 0: the origin becomes unstable and two stable branches ±μ\pm\sqrt{\mu} appear. The symmetry x↦−xx \mapsto -x breaks.
Move μ\mu or press ‘Sweep’: the bifurcation diagram is drawn at visited μ\mu values, with solid stable and dashed unstable equilibria. In the other panel, the phase line of x˙=f(x)\dot x = f(x) at current μ\mu, with arrows showing flow direction (for Hopf, the phase plane with two trajectories, one from inside and one from outside). Compare supercritical and subcritical pitchfork near μ=0\mu = 0: what stable equilibrium remains near the origin in each? In Hopf, watch cycle radius grow as μ\sqrt{\mu}.

In the subcritical Hopf form r˙=μr+r3\dot r = \mu r + r^3, cycle r=−μr = \sqrt{-\mu} exists for μ<0\mu < 0, is unstable and bounds the focus basin: the same structure as backward Van der Pol in the Lyapunov certificate, whose basin was inside an unstable cycle. Subcritical bifurcations are dangerous in engineering (and training) because they give no warning: the state seems stable until it is not, and jumps far away.

Limit cycles, Poincaré–Bendixson and a glimpse of chaos

In the Van der Pol oscillator, term −μ(1−x2)x˙-\mu(1 - x^2)\dot x is negative friction for ∣x∣<1\abs{x} < 1, pumping energy, and positive for ∣x∣>1\abs{x} > 1, dissipating it. Their balance produces, for every μ>0\mu > 0, one stable limit cycle (Liénard’s theorem), attracting every trajectory except the origin. With μ=1\mu = 1 its period is 6.6636.663 and amplitude 2.0092.009, as you will calculate with solve_ivp.

In the plane bounded trajectories have few choices. The Poincaré–Bendixson theorem says that if a forward semiorbit of a planar system remains in a compact set without equilibria, its ω\omega-limit set is a periodic orbit. Thus in the plane there are only equilibria, cycles and orbits connecting them: no chaos. At least three dimensions are needed. The Lorenz system,

x˙=σ(y−x),y˙=x(ρ−z)−y,z˙=xy−βz,\dot x = \sigma(y - x), \qquad \dot y = x(\rho - z) - y, \qquad \dot z = xy - \beta z,

with σ=10\sigma = 10, ρ=28\rho = 28 and β=8/3\beta = 8/3, has three unstable equilibria yet bounded trajectories that never repeat: a strange attractor. Two trajectories starting 10−910^{-9} apart separate as eλte^{\lambda t} with λ≈0.9\lambda \approx 0.9, the largest Lyapunov exponent, until separation is the size of the attractor. Stable as in “bounded”, unstable as in “unpredictable”: that is chaos.

Frontier: the edge of stability

Rule η<2/λmax⁡\eta < 2/\lambda_{\max} is a theorem for quadratics and isolated minima viewed closely. What happens in a neural network whose Hessian changes during training? Cohen, Kaur, Li, Kolter and Talwalkar (2021) measured sharpness λmax⁡(∇2R^(θt))\lambda_{\max}(\hess\hat{R}(\theta_t)) during full-batch gradient descent across many architectures, finding a robust two-phase pattern:

  1. Progressive sharpening. While λmax⁡<2/η\lambda_{\max} < 2/\eta, sharpness grows steadily: training moves into increasingly curved regions.
  2. Edge of stability. When λmax⁡\lambda_{\max} reaches 2/η2/\eta, it stops growing and hovers there, often slightly above. Loss continues falling in the long run, but nonmonotonically with occasional increases.

The second phase contradicts quadratic intuition: with ηλmax⁡>2\eta\lambda_{\max} > 2, the local model predicts divergence along the principal eigenvector. It does not happen because the function is nonquadratic. As oscillation in that direction grows, third-order loss terms push iterates toward lower-sharpness regions, and sharpness falls below 2/η2/\eta again. Damian, Nichani and Lee (2023) call this self-stabilization and show that on average gradient descent follows gradient flow projected onto set {λmax⁡≤2/η}\{\lambda_{\max} \le 2/\eta\}. The step does more than limit stability: it chooses which landscape region is reachable.

The gradient-descent figure’s ‘Nonquadratic valley’ mode is a toy version: f(x,y)=120(x−3)2+12(1+x2) y2f(x, y) = \tfrac{1}{20}(x - 3)^2 + \tfrac12(1 + x^2)\,y^2, a valley with floor line y=0y = 0 and floor sharpness 1+x21 + x^2 increasing toward the unique minimum (3,0)(3, 0), where it equals 10. With η=0.15\eta = 0.15 (2/η≈13.32/\eta \approx 13.3) iterates reach the minimum. With η=0.25\eta = 0.25 (2/η=82/\eta = 8), the minimum is unreachable: sharpness rises above 8, component yy starts oscillating and grows, and since ∂f/∂x\partial f/\partial x contains term xy2x y^2, that oscillation pushes xx toward the flat region. Sharpness falls, oscillation damps, and the cycle repeats. The first cycles are coarse: while sharpness is below 8, component yy nearly dies out, so instability takes time to appear and sharpness overshoots 2/η2/\eta to almost 10. Later oscillation no longer dies out and sharpness hovers around the threshold: from iterations 800 to 1500 its mean is 8.068.06. Gradient descent does not diverge and loss is nonmonotonic. In the local lab network adjustment is fine: with η=0.2\eta = 0.2, measurements at steps 2000 to 3000 never differ by more than 2% from 2/η2/\eta. This is the edge of stability studied in optimization.

Implementation from scratch

The lab starts with basics: the numerical Jacobian of lesson 7, Newton’s method to find equilibria and eigenvalue classification marking nonhyperbolic cases inconclusive.

[ ]Lab: equilibria, Jacobians and classificationBrowser
import numpy as np

def numerical_jacobian(f, x, eps=1e-6):
    """Jacobiano por diferencias centradas (lección 7)."""
    x = np.asarray(x, dtype=float)
    cols = []
    for j in range(x.size):
        e = np.zeros_like(x)
        e[j] = eps
        cols.append((np.asarray(f(x + e)) - np.asarray(f(x - e))) / (2 * eps))
    return np.column_stack(cols)

def equilibrio_newton(f, x0, tol=1e-12, max_iter=50):
    """Resuelve f(x) = 0 con Newton y el jacobiano numérico."""
    x = np.asarray(x0, dtype=float)
    for _ in range(max_iter):
        fx = np.asarray(f(x))
        if np.linalg.norm(fx) < tol:
            break
        x = x - np.linalg.solve(numerical_jacobian(f, x), fx)
    return x

def clasificar(J, tol=1e-7):
    """Tipo y veredicto de un equilibrio plano a partir de los autovalores del jacobiano."""
    lam = np.linalg.eigvals(J)
    escala = max(1.0, np.abs(J).max())
    re = lam.real
    if np.any(np.abs(re) <= tol * escala):
        return lam, "no hiperbólico", ("inestable" if re.max() > tol * escala else "no concluyente")
    complejo = abs(lam[0].imag) > tol * escala
    if re.max() < 0:
        return lam, ("foco" if complejo else "nodo") + " estable", "asint. estable"
    if re.min() > 0:
        return lam, ("foco" if complejo else "nodo") + " inestable", "inestable"
    return lam, "silla", "inestable"

sistemas = {
    "péndulo (c = 0.5)": (lambda z: np.array([z[1], -np.sin(z[0]) - 0.5 * z[1]]), [(0.3, 0.2), (3.0, 0.1)]),
    "Lotka-Volterra": (lambda z: np.array([z[0] * (1 - z[1]), z[1] * (z[0] - 1)]), [(0.9, 1.2), (0.1, -0.1)]),
    "Van der Pol (μ = 1)": (lambda z: np.array([z[1], (1 - z[0] ** 2) * z[1] - z[0]]), [(0.2, 0.1)]),
    "Van der Pol hacia atrás": (lambda z: np.array([-z[1], z[0] + (z[0] ** 2 - 1) * z[1]]), [(0.2, 0.1)]),
}
print(f"{'sistema':24s} {'equilibrio':>18s}   {'autovalores':30s} tipo / veredicto")
for nombre, (f, semillas) in sistemas.items():
    for x0 in semillas:
        xs = np.round(equilibrio_newton(f, x0), 12) + 0.0     # + 0.0 evita imprimir -0.0000
        lam, tipo, veredicto = clasificar(numerical_jacobian(f, xs))
        lam_txt = ", ".join(f"{l.real:+.3f}{l.imag:+.3f}i" for l in lam)
        print(f"{nombre:24s} ({xs[0]:7.4f}, {xs[1]:7.4f})   {lam_txt:30s} {tipo} / {veredicto}")

The table reproduces hand calculations: the pendulum origin is a stable focus with real part −0.25-0.25, (π,0)(\pi, 0) is a saddle with eigenvalues 0.7810.781 and −1.281-1.281, and the Lotka–Volterra center is inconclusive. Now a fourth-order Runge–Kutta integrator checks what Lyapunov functions say along particular trajectories: pendulum energy never rises, and Lotka–Volterra quantity HH does not change.

[ ]RK4, pendulum energy and conserved quantityBrowser
def rk4(f, x0, T, h):
    """Integra x' = f(x) con Runge-Kutta 4 de paso fijo; devuelve tiempos y estados."""
    n = int(round(T / h))
    X = np.empty((n + 1, len(x0)))
    X[0] = x0
    for k in range(n):
        x = X[k]
        k1 = f(x); k2 = f(x + h / 2 * k1); k3 = f(x + h / 2 * k2); k4 = f(x + h * k3)
        X[k + 1] = x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return np.linspace(0, T, n + 1), X

pendulo = sistemas["péndulo (c = 0.5)"][0]
energia = lambda X: 0.5 * X[:, 1] ** 2 + 1 - np.cos(X[:, 0])
t, X = rk4(pendulo, np.array([2.5, 0.0]), 40.0, 0.01)
E = energia(X)
print("péndulo desde (2.5, 0): estado final", np.round(X[-1], 6))
print(f"energía: {E[0]:.4f} -> {E[-1]:.2e};  mayor subida entre dos pasos: {np.diff(E).max():.1e}")

lv = sistemas["Lotka-Volterra"][0]
H = lambda X: X[:, 0] - np.log(X[:, 0]) + X[:, 1] - np.log(X[:, 1])
t, X = rk4(lv, np.array([1.0, 0.45]), 30.0, 0.01)
print(f"Lotka-Volterra: H varía {np.ptp(H(X)):.1e} en 30 unidades de tiempo (órbita cerrada)")

The “largest increase” in energy between steps is negative: it decreases at every step, as E˙=−cy2≤0\dot E = -cy^2 \le 0 requires, and the pendulum comes to rest. Variation of HH, order 10−1010^{-10}, is integrator error. Next is the Lyapunov equation, solved from scratch by vectorizing matrices: with vec⁡\operatorname{vec} stacking columns, vec⁡(A⊤P)=(I⊗A⊤)vec⁡(P)\operatorname{vec}(\mat{A}\T\mat{P}) = (\mat{I} \otimes \mat{A}\T)\operatorname{vec}(\mat{P}) and vec⁡(PA)=(A⊤⊗I)vec⁡(P)\operatorname{vec}(\mat{P}\mat{A}) = (\mat{A}\T \otimes \mat{I})\operatorname{vec}(\mat{P}). For the resulting P\mat{P}, a radial search computes the largest certified level c∗c^*, and several trajectories starting right on the boundary of {V≤c∗}\{V \le c^*\} confirm VV decreases along them.

[ ]Lyapunov equation and certified basinBrowser
def lyapunov_continua(A, Q):
    """Resuelve A^T P + P A = -Q vectorizando: (I ⊗ A^T + A^T ⊗ I) vec(P) = -vec(Q)."""
    n = A.shape[0]
    I = np.eye(n)
    M = np.kron(I, A.T) + np.kron(A.T, I)
    P = np.linalg.solve(M, -Q.reshape(-1, order="F")).reshape(n, n, order="F")
    return (P + P.T) / 2

atras = sistemas["Van der Pol hacia atrás"][0]
A = numerical_jacobian(atras, np.zeros(2))
P = lyapunov_continua(A, np.eye(2))
print("A =", np.round(A, 6).tolist(), "  P =", np.round(P, 6).tolist())
print("autovalores de P:", np.round(np.linalg.eigvalsh(P), 4), "  residuo:", np.abs(A.T @ P + P @ A + np.eye(2)).max())

def c_estrella(f, P, n_dir=720, r_max=6.0, dr=0.002):
    """Ínfimo de V(x) = x^T P x en la región donde V' = 2 x^T P f(x) > 0 (búsqueda radial)."""
    th = np.linspace(0, 2 * np.pi, n_dir, endpoint=False)
    r = np.arange(dr, r_max, dr)
    X = np.cos(th)[:, None] * r                  # n_dir x n_r
    Y = np.sin(th)[:, None] * r
    F = f(np.array([X, Y]))
    V = P[0, 0] * X**2 + 2 * P[0, 1] * X * Y + P[1, 1] * Y**2
    Vdot = 2 * ((P[0, 0] * X + P[0, 1] * Y) * F[0] + (P[0, 1] * X + P[1, 1] * Y) * F[1])
    return np.where(Vdot > 1e-12 * r**2, V, np.inf).min()

c = c_estrella(atras, P)
print(f"c* = {c:.4f}   área certificada = {np.pi * c / np.sqrt(np.linalg.det(P)):.3f}")

rng = np.random.default_rng(0)
L = np.linalg.cholesky(np.linalg.inv(P))          # x = sqrt(c) L u con |u| = 1 da x^T P x = c
fallos, max_subida = 0, -np.inf
for ang in rng.uniform(0, 2 * np.pi, 16):
    x0 = np.sqrt(0.999 * c) * L @ np.array([np.cos(ang), np.sin(ang)])
    _, X = rk4(atras, x0, 20.0, 0.04)
    Vt = np.einsum("ti,ij,tj->t", X, P, X)
    max_subida = max(max_subida, np.diff(Vt).max())
    fallos += np.linalg.norm(X[-1]) > 1e-3
print(f"16 trayectorias desde V = 0.999 c*: {fallos} no llegan al origen; mayor subida de V entre pasos: {max_subida:.1e}")

The result matches the certificate figure: P=[1.5−0.5−0.51]\mat{P} = \begin{bmatrix} 1.5 & -0.5 \\ -0.5 & 1 \end{bmatrix}, c∗≈2.305c^* \approx 2.305 and certified area 6.486.48. Every trajectory starting on the boundary reaches the origin with VV strictly decreasing.

Now gradient descent versus flow on the figure’s quadratic f=12(x2+10y2)f = \tfrac12(x^2 + 10y^2). The cell measures error against exact flow at t=1t = 1, expected to be O(η)\bigO(\eta), and locates by bisection the step beyond which component λmax⁡\lambda_{\max} stops contracting.

[ ]Gradient flow versus gradient descentBrowser
lam = np.array([1.0, 10.0])                     # f(x) = ½ x^T diag(1, 10) x
grad = lambda x: lam * x
x0 = np.array([-3.5, 1.2])
flujo = lambda t: x0 * np.exp(-lam * t)        # solución exacta del flujo de gradiente

def descenso(eta, K):
    X = [x0]
    for _ in range(K):
        X.append(X[-1] - eta * grad(X[-1]))
    return np.array(X)

print(" eta    eta*λmax   |x_100|      error frente al flujo en t = 1")
for eta in [0.01, 0.05, 0.1, 0.15, 0.19, 0.2, 0.21]:
    X = descenso(eta, 100)
    k1 = int(round(1 / eta))                   # el iterado que corresponde a t = 1
    err = np.linalg.norm(X[k1] - flujo(k1 * eta))
    print(f"{eta:5.2f}   {eta * lam.max():6.2f}   {np.linalg.norm(X[-1]):10.3e}   {err:.2e}")

def diverge(eta, K=400):
    return abs(descenso(eta, K)[-1, 1]) >= abs(x0[1])   # ¿deja de contraer la componente de λmax?

lo, hi = 0.1, 0.3                               # bisección del umbral
for _ in range(40):
    mid = (lo + hi) / 2
    lo, hi = (lo, mid) if diverge(mid) else (mid, hi)
print(f"\numbral medido: {lo:.6f}   2/λmax = {2 / lam.max():.6f}")
eta_opt = 2 / (lam.min() + lam.max())
print(f"paso óptimo 2/(λmin+λmax) = {eta_opt:.4f}, factor por paso {np.abs(1 - eta_opt * lam).max():.4f} = (κ-1)/(κ+1) = {9 / 11:.4f}")

With η=0.01\eta = 0.01 error against flow at t=1t = 1 is 6.5×10−36.5 \times 10^{-3} and with η=0.05\eta = 0.05 it is 3.3×10−23.3 \times 10^{-2}, five times greater: first order. At η=0.2\eta = 0.2 error is already solution-sized, and at 0.210.21 iterates exploded (∣x100∣≈1.7×104\abs{\vb{x}_{100}} \approx 1.7 \times 10^{4}). Bisection finds threshold 0.2000000.200000. Finally the bilinear game with the three schemes in the games section.

[ ]Bilinear game: simultaneous, alternating and extragradientBrowser
# juego min_x max_y f(x, y) = x y: el campo de descenso-ascenso es F(z) = (∂f/∂x, -∂f/∂y) = (y, -x)
F = lambda z: np.array([z[1], -z[0]])
eta, K = 0.1, 200
z0 = np.array([1.0, 0.0])

def simultaneo(z):
    return z - eta * F(z)

def alternado(z):
    x = z[0] - eta * z[1]                  # x se mueve primero
    y = z[1] + eta * x                     # y responde al x nuevo
    return np.array([x, y])

def extragradiente(z):
    medio = z - eta * F(z)                 # paso de prueba
    return z - eta * F(medio)              # paso real con el gradiente del punto de prueba

for nombre, paso in [("simultáneo", simultaneo), ("alternado", alternado), ("extragradiente", extragradiente)]:
    z = z0.copy()
    radios = []
    for _ in range(K):
        z = paso(z)
        radios.append(np.linalg.norm(z))
    print(f"{nombre:15s} |z| tras {K} pasos = {radios[-1]:.4f}   (máx {max(radios):.4f}, mín {min(radios):.4f})")
print(f"predicción simultáneo: (1 + η²)^(K/2) = {(1 + eta**2) ** (K / 2):.4f}")
print(f"predicción extragradiente: (1 - η² + η⁴)^(K/2) = {(1 - eta**2 + eta**4) ** (K / 2):.4f}")

Eigenvalue predictions hold to four digits: simultaneous multiplies radius by 2.702.70 in 200 steps, alternating oscillates between 0.980.98 and 1.031.03 without leaving an ellipse, and extragradient reduces it to 0.370.37.

With libraries

In practice equilibria are found with scipy.optimize.root, the Lyapunov equation solved with scipy.linalg.solve_continuous_lyapunov (using Bartels–Stewart, based on Schur form, in O(n3)\bigO(n^3) instead of vectorization’s O(n6)\bigO(n^6)), and trajectories integrated with scipy.integrate.solve_ivp, which chooses steps automatically to meet tolerance and can detect events.

[ ]root, solve_continuous_lyapunov and solve_ivpBrowser
import numpy as np
from scipy.optimize import root
from scipy.integrate import solve_ivp
from scipy.linalg import solve_continuous_lyapunov

# 1) equilibrios con root (método híbrido de Powell)
pend = lambda z, c=0.5: [z[1], -np.sin(z[0]) - c * z[1]]
for x0 in [(0.5, 0.0), (2.8, 0.3), (-3.5, 0.0)]:
    sol = root(pend, x0)
    print("root desde", x0, "->", np.round(sol.x, 10) + 0.0, " éxito:", sol.success)

# 2) la ecuación de Lyapunov: solve_continuous_lyapunov(a, q) resuelve a X + X a^H = q
A = np.array([[0.0, -1.0], [1.0, -1.0]])
P = solve_continuous_lyapunov(A.T, -np.eye(2))
print("P =", np.round(P, 12).tolist())

# 3) el ciclo límite de Van der Pol con solve_ivp (RK45 adaptativo) y eventos
def vdp(t, z, mu=1.0):
    return [z[1], mu * (1 - z[0] ** 2) * z[1] - z[0]]

def cruce(t, z):                 # x = 0 subiendo: una vez por vuelta
    return z[0]
cruce.direction = 1

for z0 in [(0.1, 0.0), (4.0, 3.0)]:
    s = solve_ivp(vdp, (0, 60), z0, rtol=1e-9, atol=1e-11, events=cruce, dense_output=True)
    tc = s.t_events[0]
    periodo = np.diff(tc)[-3:].mean()
    tt = np.linspace(tc[-2], tc[-1], 2000)
    print(f"Van der Pol desde {z0}: periodo {periodo:.4f}, amplitud {np.abs(s.sol(tt)[0]).max():.4f}")

Note the solve_continuous_lyapunov(a, q) convention: it solves aX+XaH=q\mat{a}\mat{X} + \mat{X}\mat{a}^{\mathsf{H}} = \mat{q}, so for A⊤P+PA=−Q\mat{A}\T\mat{P} + \mat{P}\mat{A} = -\mat{Q} pass A⊤\mat{A}\T and −Q-\mat{Q}. Both Van der Pol trajectories, one from very near the origin and one from far away, end on the same cycle, with period 6.66336.6633 and amplitude 2.00862.0086. For a glimpse of chaos, vectorized RK4 integrating two Lorenz trajectories at once suffices.

[ ]Lorenz: sensitivity to initial conditionsBrowser
import numpy as np
import matplotlib.pyplot as plt

def lorenz(Z, s=10.0, r=28.0, b=8 / 3):
    x, y, w = Z                      # Z: 3 x m, m trayectorias a la vez
    return np.array([s * (y - x), x * (r - w) - y, x * y - b * w])

h, n = 0.005, 8000                   # 40 unidades de tiempo con RK4 de paso fijo
Z = np.array([[1.0, 1.0 + 1e-9], [1.0, 1.0], [1.0, 1.0]])
tray = np.empty((n + 1, 3, 2))
tray[0] = Z
for k in range(n):
    k1 = lorenz(Z); k2 = lorenz(Z + h / 2 * k1); k3 = lorenz(Z + h / 2 * k2); k4 = lorenz(Z + h * k3)
    Z = Z + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    tray[k + 1] = Z
T = h * np.arange(n + 1)
d = np.linalg.norm(tray[:, :, 0] - tray[:, :, 1], axis=1)
ventana = (d > 1e-8) & (d < 1e-1) & (T < 30)
coef = np.polyfit(T[ventana], np.log(d[ventana]), 1)
print(f"separación inicial 1e-9; supera 1 en t = {T[np.argmax(d > 1)]:.1f}; ritmo medido e^({coef[0]:.2f} t)")

fig, ax = plt.subplots(1, 2, figsize=(10, 3.6))
ax[0].plot(tray[:, 0, 0], tray[:, 2, 0], lw=0.4)
ax[0].set_xlabel("x"); ax[0].set_ylabel("z"); ax[0].set_title("atractor de Lorenz")
ax[1].semilogy(T, d, lw=1)
ax[1].semilogy(T[ventana], np.exp(np.polyval(coef, T[ventana])), "--", color="gray")
ax[1].set_xlabel("t"); ax[1].set_ylabel("distancia"); ax[1].set_title("dos trayectorias que empiezan a 1e-9")
plt.tight_layout(); plt.show()

Distance grows linearly on a log scale at measured rate about 0.80.8 for this particular pair (careful estimation of the largest exponent averaging over the attractor gives about 0.910.91), exceeding 1 around t≈33t \approx 33: a perturbation the size of rounding error becomes macroscopic in a few tens of time units.

The edge of stability in an MLP

The final experiment reproduces Cohen et al.’s two phases on a laptop scale. An MLP with two 128-neuron hidden layers and tanh⁡\tanh activation trains with full-batch gradient descent and squared error on 2,000 synthetic examples (labels generated by a random “teacher”), with three steps η\eta. Every 50 steps sharpness is measured using power iteration on Hessian-vector products, never forming the 19,329-parameter Hessian. It is the usual training loop, handwritten so the update is exactly θ←θ−η∇R^\theta \leftarrow \theta - \eta\grad\hat{R}, on GPU if available (device placement). It takes under a minute on a laptop GPU.

[ ]Progressive sharpening and edge of stabilityLocal GPU
import time
import numpy as np
import torch
import matplotlib.pyplot as plt

dev = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(0)
n, d, h = 2000, 20, 128
X = torch.randn(n, d, device=dev)
W_prof = torch.randn(d, 64, device=dev) / d**0.5          # «profesor» aleatorio que genera las etiquetas
y = torch.sin(2 * X @ W_prof) @ torch.randn(64, 1, device=dev) / 8

def red():
    torch.manual_seed(1)                                   # la misma inicialización para todos los pasos
    return torch.nn.Sequential(
        torch.nn.Linear(d, h), torch.nn.Tanh(),
        torch.nn.Linear(h, h), torch.nn.Tanh(),
        torch.nn.Linear(h, 1),
    ).to(dev)

def perdida(m):
    return 0.5 * ((m(X) - y) ** 2).mean()                  # error cuadrático, lote completo

def agudeza(m, iters=20):
    """Mayor autovalor del hessiano: método de la potencia con productos hessiano-vector."""
    ps = list(m.parameters())
    g = torch.autograd.grad(perdida(m), ps, create_graph=True)
    v = [torch.randn_like(p) for p in ps]
    lam = 0.0
    for _ in range(iters):
        norma = torch.sqrt(sum((a * a).sum() for a in v))
        v = [a / norma for a in v]
        Hv = torch.autograd.grad(g, ps, grad_outputs=v, retain_graph=True)
        lam = sum((a * b).sum() for a, b in zip(Hv, v)).item()   # cociente de Rayleigh
        v = [t.detach() for t in Hv]
    return lam

pasos, cada = 3000, 50
resultados = {}
t0 = time.time()
for eta in [0.04, 0.1, 0.2]:
    m = red()
    hist = []
    for k in range(pasos + 1):
        if k % cada == 0:
            hist.append((k, perdida(m).item(), agudeza(m)))
        m.zero_grad()
        perdida(m).backward()
        with torch.no_grad():
            for p in m.parameters():
                p -= eta * p.grad                          # descenso por gradiente puro
    resultados[eta] = np.array(hist)
    H = resultados[eta]
    tramo = H[H[:, 0] >= 2000, 2]
    print(f"η = {eta:<5} 2/η = {2 / eta:5.1f}   agudeza: inicio {H[0, 2]:5.2f}, máx {H[:, 2].max():5.2f}, "
          f"media en los pasos 2000-3000 {tramo.mean():5.2f}   pérdida final {H[-1, 1]:.4f}")
print(f"tiempo total: {time.time() - t0:.0f} s en {dev}")

fig, ax = plt.subplots(1, 2, figsize=(11, 3.8))
for i, (eta, H) in enumerate(resultados.items()):
    c = f"C{i}"
    ax[0].plot(H[:, 0], H[:, 2], color=c, label=f"η = {eta}")
    ax[0].axhline(2 / eta, color=c, ls="--", lw=1)
    ax[1].semilogy(H[:, 0], H[:, 1], color=c, label=f"η = {eta}")
ax[0].set_xlabel("paso"); ax[0].set_ylabel("λmax del hessiano"); ax[0].set_title("agudeza (discontinua: 2/η)")
ax[1].set_xlabel("paso"); ax[1].set_ylabel("pérdida"); ax[1].set_title("pérdida de entrenamiento")
ax[0].legend(); plt.tight_layout(); plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All three runs start with the same sharpness 2.592.59 and see it rise: progressive sharpening. With η=0.04\eta = 0.04 (2/η=502/\eta = 50) the threshold is distant and sharpness climbs to about 15 without touching it. With η=0.2\eta = 0.2 it reaches 2/η2/\eta around step 450 and with η=0.1\eta = 0.1 around step 1650, remaining there thereafter: from steps 2000 to 3000 its mean is 19.819.8 (threshold 20) and 9.989.98 (threshold 10). Meanwhile loss keeps falling, with occasional rebounds. The largest-step run ends with lowest loss (0.0120.012 versus 0.0860.086 with η=0.04\eta = 0.04): spending most of the time at the edge of stability does not prevent progress. Exact numbers depend on GPU and PyTorch version, but the pattern is robust.

Common mistakes

Exercises

QuizStable without returning
Which equilibrium is Lyapunov stable but not asymptotically stable?
NumericThe pendulum focus
Calculate the real part of eigenvalues of the linearization at the origin of pendulum x¨+0.5x˙+sin⁡x=0\ddot x + 0.5\dot x + \sin x = 0.
QuizWhere does linearization decide?
For an equilibrium of a nonlinear planar system C1C^1, in which Jacobian cases does linearization decide stability?

More than one answer may be correct.

NumericMaximum stable step
What is the largest step η\eta for which gradient descent converges from any point for f(x)=12x⊤diag⁡(1,100) xf(\vb{x}) = \tfrac12\vb{x}\T\diag(1, 100)\,\vb{x}? (Give the supremum of stable steps.)
ProofThe minimized function is a Lyapunov function
Prove: Let f∈C2(Rn)f \in C^2(\R^n) and x(t)\vb{x}(t) be a solution of gradient flow x˙=−∇f(x)\dot{\vb{x}} = -\grad f(\vb{x}). Then  ⁣d ⁣dtf(x(t))=−∥∇f(x(t))∥2\frac{\dd}{\dd t}f(\vb{x}(t)) = -\norm{\grad f(\vb{x}(t))}^2, and if x∗\vb{x}^* is a strict local minimum isolated as a critical point, V=f−f(x∗)V = f - f(\vb{x}^*) is a strict Lyapunov function near x∗\vb{x}^*.
0
Write ϕ(t)=f(x(t))\phi(t) = f(\vb{x}(t)).

Step 1 of 4. How do you calculate ϕ′(t)\phi'(t)?

ProofThe stable Euler step
Prove: For x˙=−λx\dot x = -\lambda x with λ>0\lambda > 0, explicit Euler iterates xk+1=xk+h(−λxk)x_{k+1} = x_k + h(-\lambda x_k) with h>0h > 0 satisfy xk→0x_k \to 0 for every x0x_0 if and only if 0<hλ<20 < h\lambda < 2.
0
Let r=1−hλr = 1 - h\lambda.

Step 1 of 4. What closed form do the iterates have?

NumericA Lyapunov equation by hand
Solve A⊤P+PA=−I\mat{A}\T\mat{P} + \mat{P}\mat{A} = -\mat{I} for A=[−110−1]\mat{A} = \begin{bmatrix} -1 & 1 \\ 0 & -1 \end{bmatrix} with P=[p11p12p12p22]\mat{P} = \begin{bmatrix} p_{11} & p_{12} \\ p_{12} & p_{22} \end{bmatrix}. What is p22p_{22}?
NumericHow much energy fits in the basin
For damped pendulum x¨+cx˙+sin⁡x=0\ddot x + c\dot x + \sin x = 0 with c>0c > 0 and energy E=12x˙2+1−cos⁡xE = \tfrac12\dot x^2 + 1 - \cos x, what is the supremum of c0c_0 for which set {E≤c0, ∣x∣<π}\{E \le c_0,\ \abs{x} < \pi\} is compact, invariant and, by LaSalle, contained in the origin's basin?
NumericGrowth of simultaneous descent-ascent
In game min⁡xmax⁡yxy\min_x\max_y xy, simultaneous descent-ascent with step h=0.1h = 0.1 starts at (1,0)(1, 0). What is its distance from equilibrium (0,0)(0, 0) after 100 steps?
QuizAn overly sharp minimum
A smooth loss has a local minimum θ∗\theta^* with λmax⁡(∇2R^(θ∗))=50\lambda_{\max}(\hess\hat R(\theta^*)) = 50. You train with full-batch gradient descent and η=0.1\eta = 0.1. What can you assert?
CodeClassify an equilibrium
Implement classify_equilibrium(f, x_star) for planar systems x˙=f(x)\dot{\vb{x}} = \vb{f}(\vb{x}). Calculate the Jacobian at x_star by centered differences and return a tuple (tipo, estabilidad). tipo is one of 'nodo estable' (stable node), 'nodo inestable' (unstable node), 'foco estable' (stable focus), 'foco inestable' (unstable focus), 'silla' (saddle), or 'no hiperbólico' (nonhyperbolic, if any eigenvalue has zero real part within relative tolerance 1e-6). estabilidad is 'asintóticamente estable' (asymptotically stable), 'inestable' (unstable), or 'no concluyente' (inconclusive); a nonhyperbolic case is 'inestable' if any eigenvalue has positive real part and 'no concluyente' otherwise. Use only NumPy.
import numpy as np

def classify_equilibrium(f, x_star, eps=1e-6, tol=1e-6):
  """Devuelve (tipo, estabilidad) del equilibrio x_star de x' = f(x)."""
  x = np.asarray(x_star, dtype=float)
  # tu código: jacobiano por diferencias centradas, autovalores y casos
  return "?", "?"
Shift+Enter to run

Summary

Key idea
To know whether a system returns to rest, there is no need to solve it: inspect the Jacobian at equilibrium when hyperbolic, or find a quantity decreasing along trajectories. In gradient flow this quantity is the function itself, and discretizing with step η\eta requires η<2/λmax⁡\eta < 2/\lambda_{\max} for stability.
  • Stability (not moving away), asymptotic stability (also returning) and exponential stability (returning exponentially fast) are distinct notions, with simple counterexamples for each step.
  • At a hyperbolic equilibrium Jacobian eigenvalues decide stability and, by Hartman–Grobman, the local portrait. With zero real parts, linearization is inconclusive: centers, zero eigenvalues and cycles depend on nonlinear terms.
  • A Lyapunov function (V>0V > 0, V˙=∇V⊤f≤0\dot V = \grad V\T\vb{f} \le 0) certifies stability without solving, and its sublevel sets give certified basin regions. For linear systems it comes from equation A⊤P+PA=−Q\mat{A}\T\mat{P} + \mat{P}\mat{A} = -\mat{Q}; if V˙\dot V is only semidefinite, LaSalle completes the argument.
  • Gradient flow has ff as a Lyapunov function (f˙=−∥∇f∥2\dot f = -\norm{\grad f}^2): no cycles or foci, strict minima are stable and saddles attract only a measure-zero set. Game dynamics are not gradients and rotate.
  • Explicit Euler on x˙=−λx\dot x = -\lambda x is stable if and only if 0<hλ<20 < h\lambda < 2. Gradient descent is Euler on gradient flow, hence η<2/λmax⁡\eta < 2/\lambda_{\max}; a continuous center never survives Euler.
  • Qualitative changes as a parameter varies occur at nonhyperbolic equilibria: saddle-node, pitchfork and Hopf, including abrupt subcritical versions. No chaos in the plane (Poincaré–Bendixson); yes in three dimensions (Lorenz).
  • Real networks train at the edge of stability: sharpness grows to 2/η2/\eta and stays there, because nonquadratic loss terms stabilize what the quadratic model predicts would diverge.