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
- 03Phase portraits of linear systemsLinear ODE systemsMatrix exponentialJacobian matrixLinearization and tangent planeGradientHessian matrixClassification of critical pointsGrönwall inequalityLevel setsMultivariable chain ruleHessian-vector product
- 02Positive definite matrixSpectral theorem
- 00Canonical training and evaluation loopDevice placement and CPU-GPU transfers
Motivation: training follows a dynamical system
When training a network by gradient descent you are not solving an equation: you iterate a map, , 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 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 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 , with locally Lipschitz, so by Picard–Lindelöf each initial condition has a unique solution . An equilibrium is a point with : the solution starting there stays there forever. By translation, , 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 , preserves : trajectories are circles. Starting at distance you remain at distance (take ), but never return to the origin.
- Asymptotically but not exponentially. In the solution is . It converges to 0, but as , slower than every exponential.
- Attractive but unstable. The stability condition is not redundant. On the circle, has a unique equilibrium , and all trajectories end there. But starting at you first make a full turn and only then reach : however close you start, you move distance away. Vinograd (1957) constructed a similar example in the plane.
For a linear system you already know the full answer: the origin is exponentially stable if and only if all eigenvalues of have negative real parts ( is Hurwitz), because then for any less than . For linear systems asymptotic and exponential stability coincide. What you just saw with is purely nonlinear.
Linearization: the Jacobian at equilibrium
If is of class , near equilibrium , where is the Jacobian matrix and remainder satisfies . This is linearization from lesson 7 applied to the field. The hope is that near the nonlinear system behaves like . Before the theorem, check it.
At the pendulum saddle the nonlinear and linear magnified views become indistinguishable when reduced: eigenlines of 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 and write . Since is Hurwitz, there exist and with for . Since , there exists such that implies .
While the trajectory is in the ball of radius , Duhamel’s formula gives
Multiply by and write : this gives . Grönwall’s inequality gives , i.e.
It remains to show the trajectory never leaves the ball. If , the bound gives on every interval during which it has remained in the ball; a first exit time, if it existed, would satisfy both and . Thus it never leaves, the solution exists for every and the bound always holds: exponential stability with .
∎An equilibrium is hyperbolic if no eigenvalue of 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, 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 of class , Hartman proved can be taken of class , and a 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
whose linearization at the origin is center for every . In polar coordinates, and : with the origin is asymptotically stable (a slow, nonexponential spiral), with unstable and with 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 along a solution is
a function of the point, not the trajectory.
Proof
Stability. Given with closed ball , let , positive because the sphere is compact and on it. By continuity of at the origin there is with if . If , since does not increase along the trajectory, and the trajectory can never touch sphere , where . Remaining in a compact set, the solution also exists for all .
Attraction. Suppose away from the origin. decreases and is bounded below, so has limit . If , continuity gives with on , so the trajectory lives in compact , where attains maximum . Then , absurd. Hence , forcing : if on a sequence , then .
Globality. If is radially unbounded, each sublevel set is bounded, so any trajectory stays in compact and the argument applies from any .
∎The proof contains the lesson’s most useful idea. If is bounded and on it, no trajectory starting in can leave: to do so it must cross boundary outward, increasing . If also on , all lies inside the basin of attraction. A sublevel set on which decreases is a certified basin estimate.
Quadratic functions and the Lyapunov equation
For a linear system the natural candidate is a quadratic form with positive definite. Its derivative is
another quadratic form. Requiring with is the Lyapunov equation .
Proof
If exists, is a strict radially unbounded Lyapunov function, so the origin is globally asymptotically stable, equivalent for a linear system to being Hurwitz. Conversely, if is Hurwitz the integral converges (integrand decays as ), is symmetric and positive definite because for , and
Uniqueness follows because linear operator has eigenvalues , all with negative real part and therefore nonzero.
∎For a nonlinear system, of its linearization is a local candidate: term is small near the origin and cannot spoil , negative of order (another proof of the linearization theorem). Far from the origin, nonlinear terms may make , and the question becomes how far you can inflate before touching that region.
In backward Van der Pol, , , the origin is a stable focus and its basin is the interior of an unstable limit cycle (Van der Pol with time reversed). The from the Lyapunov equation with is , the largest certified level is , and the ellipse covers slightly less than half the true basin (about of area units). Moving gains little: the best ellipse found optimizing three entries covers , 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 is only semidefinite: LaSalle
The damped pendulum’s energy, , is the obvious physical candidate, and . It is , but vanishes on the entire axis, not just the origin. Lyapunov’s theorem gives only stability. Yet clearly a trajectory cannot stay in except at equilibrium: if , then . LaSalle’s principle turns this observation into a theorem.
Proof
Let be a trajectory in . Its -limit set (limit points of with ) is nonempty and compact because is, and is invariant and attracts , standard properties of bounded-trajectory limit sets. Since decreases and is bounded, it has limit , and by continuity on the -limit set. A trajectory starting there stays there (invariance) with constant, so there: the -limit set lies in , is invariant and thus lies in .
∎For the pendulum with , take with , the energy of saddle . It is compact and invariant (energy does not increase and level does not reach the saddles). On it, , and the only trajectory staying on that axis is the equilibrium: . Conclusion: every point of energy less than 2 and comes to rest at the bottom, a much better basin estimate than any ellipse. In the lab you will check that along a trajectory never rises, although its derivative vanishes momentarily whenever the trajectory crosses axis , 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, : you will prove this in the first guided exercise. Almost all flow properties follow from this identity:
- decreases, strictly except at critical points. Trajectories cross level sets of perpendicularly because the gradient is normal to them.
- No periodic orbits exist (except equilibria): on closing an orbit would return to its initial value, but it decreased strictly.
- Equilibria are critical points, and the Jacobian of the field at one is , symmetric. By the spectral theorem eigenvalues are real: gradient flow has no foci or centers. A nondegenerate minimum () 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.
- At an isolated strict minimum, even degenerate, is a strict Lyapunov function and the minimum is asymptotically stable. For example gives : stable, but not exponentially.
- Bounded trajectories approach the critical set (LaSalle with ). Convergence to a single point is not guaranteed: there are 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 satisfies the Polyak–Łojasiewicz (PL) inequality, with , then and, by Grönwall,
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, has negative eigenvalues (directions where curves upward) and positive. The set of initial conditions converging to the saddle, its stable manifold, is a dimension- submanifold tangent to the positive-curvature eigenspace: a measure-zero set. In , flow is , and only initial conditions with 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 (GAN, robust problem, adversarial training), each player naturally follows its gradient: simultaneous gradient descent-ascent (GDA), with continuous limit
This field is no longer the gradient of anything. Its Jacobian is , not symmetric: the interaction block appears with opposite signs and generates rotation. In the simplest case, , the field is , : a center with conserved. Players orbit Nash equilibrium without approaching it.
Discretization makes it worse. A simultaneous step at rate is
with eigenvalues of magnitude . Radius is multiplied by each step and diverges for any . This appears in the phase-plane figure with the game in ‘Simultaneous’ mode. Two classical fixes:
- Alternating step. If responds to already updated , the matrix becomes , with determinant 1 and trace : for 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 has eigenvalues of magnitude , less than 1 for : 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 with , whose solution decays for any initial condition. Explicit Euler with step replaces the derivative with a difference quotient:
This is explicit Euler step stability, proved in a guided exercise. Geometrically, factor is positive and below 1 if (iterates decay without changing sign, like the exact solution), negative but of magnitude below 1 if (they jump across the equilibrium less and less), and magnitude above 1 if . For linear system with diagonalizable, the step multiplies each eigencomponent by , and the condition is for every : each must lie in the radius-1 disk centered at , 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 and .
Gradient descent is Euler on gradient flow
Apply Euler with step to flow :
This is gradient descent, letter for letter. On quadratic with and minimum , error satisfies . In the eigenbasis of , each component is multiplied by , the Euler step for . The previous theorem component by component gives the rule:
The maximum-curvature direction destabilizes first, oscillating as it does. Inside the stable interval, rate is set by worst factor , minimized with and then equal to , with .
Two readings. With small , iterates track flow positions at : Euler is first order and over fixed time interval global error is . With near , iterates look nothing like the flow despite converging: in direction 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 , gradient descent iterates map , having each minimum as a fixed point with Jacobian . The discrete linearization theorem (spectral radius instead of real parts, with the same Grönwall proof in sums) says a minimum with attracts nearby iterates if and repels them if . The consequence: gradient descent with step cannot converge to a minimum whose maximum curvature exceeds . 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 , equilibria move with , 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, . For there are no equilibria; at one appears, , with ; for there are two, , with : positive stable, negative unstable. Two equilibria are born together from nothing (or traversed backward collide and annihilate).
- Pitchfork, (supercritical). Typical of systems with symmetry . The origin is stable for and unstable for , when two stable branches are born. In the subcritical form , branches exist for and are unstable: on crossing the origin loses stability and no stable equilibrium remains nearby. The transition is abrupt.
- Hopf, in polar coordinates , . The origin has eigenvalues : a complex pair crossing the imaginary axis at . For the focus destabilizes and a stable limit cycle is born, circle . 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.
In the subcritical Hopf form , cycle exists for , 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 is negative friction for , pumping energy, and positive for , dissipating it. Their balance produces, for every , one stable limit cycle (Liénard’s theorem), attracting every trajectory except the origin. With its period is and amplitude , 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 -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,
with , and , has three unstable equilibria yet bounded trajectories that never repeat: a strange attractor. Two trajectories starting apart separate as with , 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 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 during full-batch gradient descent across many architectures, finding a robust two-phase pattern:
- Progressive sharpening. While , sharpness grows steadily: training moves into increasingly curved regions.
- Edge of stability. When reaches , 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 , 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 again. Damian, Nichani and Lee (2023) call this self-stabilization and show that on average gradient descent follows gradient flow projected onto set . 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: , a valley with floor line and floor sharpness increasing toward the unique minimum , where it equals 10. With () iterates reach the minimum. With (), the minimum is unreachable: sharpness rises above 8, component starts oscillating and grows, and since contains term , that oscillation pushes toward the flat region. Sharpness falls, oscillation damps, and the cycle repeats. The first cycles are coarse: while sharpness is below 8, component nearly dies out, so instability takes time to appear and sharpness overshoots to almost 10. Later oscillation no longer dies out and sharpness hovers around the threshold: from iterations 800 to 1500 its mean is . Gradient descent does not diverge and loss is nonmonotonic. In the local lab network adjustment is fine: with , measurements at steps 2000 to 3000 never differ by more than 2% from . 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.
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 , is a saddle with eigenvalues and , 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 does not change.
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 requires, and the pendulum comes to rest. Variation of , order , is integrator error. Next is the Lyapunov equation, solved from scratch by vectorizing matrices: with stacking columns, and . For the resulting , a radial search computes the largest certified level , and several trajectories starting right on the boundary of confirm decreases along them.
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: , and certified area . Every trajectory starting on the boundary reaches the origin with strictly decreasing.
Now gradient descent versus flow on the figure’s quadratic . The cell measures error against exact flow at , expected to be , and locates by bisection the step beyond which component stops contracting.
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 error against flow at is and with it is , five times greater: first order. At error is already solution-sized, and at iterates exploded (). Bisection finds threshold . Finally the bilinear game with the three schemes in the games section.
# 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 in 200 steps, alternating oscillates between and without leaving an ellipse, and extragradient reduces it to .
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 instead of vectorization’s ), and trajectories integrated with scipy.integrate.solve_ivp, which chooses steps automatically to meet tolerance and can detect events.
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 , so for pass and . Both Van der Pol trajectories, one from very near the origin and one from far away, end on the same cycle, with period and amplitude . For a glimpse of chaos, vectorized RK4 integrating two Lorenz trajectories at once suffices.
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 for this particular pair (careful estimation of the largest exponent averaging over the attractor gives about ), exceeding 1 around : 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 activation trains with full-batch gradient descent and squared error on 2,000 synthetic examples (labels generated by a random “teacher”), with three steps . 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 , on GPU if available (device placement). It takes under a minute on a laptop 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()npm run lab and open the connection link.All three runs start with the same sharpness and see it rise: progressive sharpening. With () the threshold is distant and sharpness climbs to about 15 without touching it. With it reaches around step 450 and with around step 1650, remaining there thereafter: from steps 2000 to 3000 its mean is (threshold 20) and (threshold 10). Meanwhile loss keeps falling, with occasional rebounds. The largest-step run ends with lowest loss ( versus with ): 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
More than one answer may be correct.
Step 1 of 4. How do you calculate ?
Step 1 of 4. What closed form do the iterates have?
classify_equilibrium(f, x_star) for planar systems . 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 "?", "?"Summary
- 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 (, ) certifies stability without solving, and its sublevel sets give certified basin regions. For linear systems it comes from equation ; if is only semidefinite, LaSalle completes the argument.
- Gradient flow has as a Lyapunov function (): 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 is stable if and only if . Gradient descent is Euler on gradient flow, hence ; 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 and stays there, because nonquadratic loss terms stabilize what the quadratic model predicts would diverge.