Theoretical analysis: from empirical conjecture to theorem
The research cycle between experiment and theory: generate conjectures through experimental mathematics, seek computational counterexamples, decompose proofs into lemmas, choose rigor, and return predictions to the lab. The running example is gradient-descent stability, including the empirical edge of stability, the quadratic proof, and a small-network comparison.
After this lesson you can
- Generate quantitative conjectures from experiment families and fit candidate functional forms.
- Seek counterexamples systematically through random, adversarial, and symbolic search.
- Decompose a proof into lemmas using Pólya's heuristics of specialization, generalization, and working backward.
- Prove the gradient-descent convergence threshold for a quadratic and test the prediction on a network.
- Distinguish and state an argument's level of rigor: heuristic, theoretical physics, rigorous, or formalized.
Before you start
A regularity is not yet a theorem
In some networks trained by full-batch gradient descent, Cohen and colleagues observed that the largest training Hessian eigenvalue approaches , while loss can oscillate in the short term and fall in the long term. They call this regime the edge of stability. Their experiments include exceptions and qualifications, such as shallow networks or simple tasks where sharpness rises less. An observation across several architectures is not a law for every network, loss, or learning rate.
Experimental mathematics proposes a cycle: measure a family, formulate a precise relationship, hold out conditions to test it, seek counterexamples, prove a tractable case, and return to the lab with predictions. Fitting a curve to two points does not identify its form: a constant and a function of may seem plausible in one range and differ outside it. The panel uses results actually calculated in CPython with NumPy on a small regression network; two rates propose the form and a third is held out until opened.
In real research, decide beforehand which range, seeds, metrics, and tolerance will evaluate the prediction. An approximate relationship should state the error scale and region where it is expected to work. If sharpness depends on time, specify whether it is measured at the end, averaged over a window, or maximized; selecting the point that best confirms the rule yields a different conclusion. Keep the holdout unseen while choosing the conjecture.
Design an informative family
A family of experiments varies one factor in a controlled way and records the others. To study sharpness versus step size, fix architecture, initialization, data, loss, optimizer, and update count; then sweep several rates, including values yielding clearly different behavior. Repeat with other seeds to distinguish a regularity from a particular trajectory. Each repetition has a cost: measuring a Hessian throughout training can be more expensive than training.
The response variable must be defined before fitting. Initial, maximum, final, and last-window average sharpness answer different questions. A formula such as has two parameters and exactly fits two distinct observations, but that fit leaves no degrees of freedom to assess training error. A held-out point provides a check, though it remains insufficient to confirm a general relationship. Once examined, it cannot be an independent test of a new form chosen from it.
Sweep data can vary nonmonotonically and trials can fail or stop. Record failures, stopping rule, and nonfinite values instead of discarding rates that do not make a pleasant curve. If a divergent rate stops earlier than others, do not compare its last value as if measured at the same step. A graph should show each curve’s actual horizon and truncation criterion.
Look for where it fails
Counterexample search complements proof. A grid checks specific points, a random sample explores according to its distribution, and an optimizer can focus on an adversarial region. If the failure region is small, one hundred uniform samples may miss it. Positive excess at a point satisfying the assumptions refutes a universal inequality; failing to find it does not prove the inequality. The figure uses a synthetic disk of radius 0.02 and ascent with known gradient to make the difference visible.
In two dimensions, a grid can miss a region between nodes; an optimizer can get stuck or return an inadmissible point. Include boundaries and degenerate cases, check constraints, and reevaluate a candidate with enough precision. In a stochastic problem, estimate failure probability and its uncertainty before extrapolating. Symbolic methods can verify an exact identity or solve an inequality under explicit assumptions, but do not guarantee that the encoded statement is what you intended to prove.
From a candidate to a refutation
Write the claim as an excess function on a domain . A candidate is useful only if it belongs to and its values are finite. A floating-point evaluation with suggests a violation; check its margin and, when possible, substitute rational values or use an error bound to certify it. An optimizer can return a point near the boundary satisfying a constraint only within tolerance, so reevaluate constraints separately.
Sampling and optimization answer different questions. The former estimates how frequent an event appears under the selected distribution; the latter seeks an extreme case. Ascent finding a small region does not estimate its frequency. Nor is an adversarial algorithm guaranteed to find the worst violation: it may depend on initialization and become trapped. Combine methods and note budget, seed, convergence criterion, and best observed violation.
A symbolic search can start with a one- or two-dimensional instance. Substituting a diagonal matrix into a matrix claim helps find necessary conditions, but a property valid for diagonal matrices need not hold for noncommuting matrices. If a simple case fails, return to the full statement and check that the simplification respected every assumption. If the claim does not fail, seek cases breaking symmetry, independence, positivity, or regularity without leaving the allowed domain.
Decompose a proof
Pólya’s proof heuristics include specializing to understand a case, generalizing carefully, and working backward from the conclusion. Here diagonal specialization reveals each eigenvalue’s role. The auxiliary problem studies a scalar recurrence. The spectral theorem then transfers that result to a symmetric positive-definite matrix.
Decomposition into lemmas makes dependencies visible: orthogonal diagonalization, component independence, the geometric-sequence criterion, and boundary analysis. Order the steps in the panel and check what happens if you use a conclusion before establishing it.
Let with . By the spectral theorem, with orthogonal and . Gradient descent gives . Writing , each component satisfies . Therefore .
To converge to zero from any initialization it is necessary and sufficient that for every . Since all eigenvalues are positive, this is equivalent to . If , a nonzero component remains; if , a component in the maximum eigenvector oscillates with factor ; for a larger step that component grows in magnitude. A particular initialization without that component can converge outside the interval: quantification “from any point” matters.
If is positive semidefinite with zero eigenvalues, components in its null space remain constant. Convergence to a nonunique minimizer is possible, but not necessarily to the origin. If is indefinite, negative directions exist and the function has no finite global minimum over the whole space. Positive definiteness is therefore not a formality removable without reformulating the conclusion.
Necessity, sufficiency, and boundary cases
For sufficiency, every factor is strictly less than one. In finite dimensions, the maximum of finitely many such factors is also below one; the norm of converges to zero. The Euclidean-norm contraction rate is controlled by . On the quadratic, loss decays by at most a factor per step, although an initialization without the dominant component may decay faster.
For necessity, one working trajectory is not enough: the statement quantifies over all initializations. Choose a maximum eigenvector as the initial point. If , its factor is below -1 and magnitude grows. At equality the factor is -1 and the sequence alternates without converging unless the initial component is zero. If , any component associated with a positive eigenvalue grows; with it remains. These cases cover the complement of the interval.
The proof does not say that a nonlinear network’s loss behaves as a global quadratic. A local Taylor approximation has a remainder depending on displacement and Hessian variation; a large step may leave the region where the approximation is accurate. A network’s Hessian also changes with . The value suggests comparison with local stability, but does not itself establish a stable regime for the entire trajectory.
Return to the experiment
The loop between theory and lab uses the quadratic case to predict a local scale, not replace network dynamics. A network’s Hessian changes during training and may be indefinite; the largest algebraic eigenvalue measures a positive-curvature direction, whereas unshifted power iteration finds the eigenvalue of largest magnitude. If a negative eigenvalue has larger magnitude, these values differ.
For the quadratic, is the edge: the eigenvalue-4 component alternates and loss does not converge to zero for the drawn initialization. In the four-unit tanh network, with 41 synthetic regression points and 600 steps, final sharpness is approximately 3.87 for versus ; for it is 3.13 versus 20. The latter is a counterexample to the naive conjecture of equality at every rate and horizon. For computation stops when loss exceeds the stated limit. These values describe one initialization and model, not a proof about networks generally.
Lab: Hessian and conjecture
The network uses a linear output over four tanh units and squared loss. The Hessian-vector product is approximated by a centered gradient difference; for 13 parameters we also construct a symmetrized Hessian and calculate eigenvalues. Power iteration at the end of returns 3.8700 with small residual and matches the largest algebraic eigenvalue in that case. This match is not assumed for every Hessian. Pyodide lab trajectories can differ because small numerical differences are amplified in unstable regimes: in the checked run, final sharpness for η = 1 was 2.1001 versus 2.1377 in CPython. SymPy checks the scalar inequality with ; quantification over all eigenvalues is justified in the proof above.
import numpy as np
def data():
x=np.linspace(-2,2,41)[:,None];y=np.sin(2*x)+.2*x
return x,y
def loss_grad(theta):
x,y=data();w=theta[:4];b=theta[4:8];v=theta[8:12];c=theta[12];z=x*w+b;h=np.tanh(z);pred=h@v+c;err=(pred-y[:,0]);N=len(x)
loss=.5*np.mean(err**2);dp=err/N;dv=h.T@dp; dc=dp.sum();dh=dp[:,None]*v;dz=dh*(1-h*h);dw=(dz*x).sum(axis=0);db=dz.sum(axis=0)
return loss,np.r_[dw,db,dv,dc]
def hvp(theta,u,eps=1e-4):return (loss_grad(theta+eps*u)[1]-loss_grad(theta-eps*u)[1])/(2*eps)
def hessian(theta):
eye=np.eye(len(theta));H=np.column_stack([hvp(theta,u) for u in eye]);return (H+H.T)/2
def run(eta,steps=600):
rng=np.random.default_rng(31);theta=rng.normal(0,.25,13);rows=[]
for t in range(steps+1):
loss,g=loss_grad(theta)
if t%10==0 or t==steps:
H=hessian(theta);e=np.linalg.eigvalsh(H);rows.append([t,float(loss),float(e[-1]),float(e[0])])
if t<steps:theta-=eta*g
if not np.isfinite(theta).all() or loss>1e8:break
return rows
for eta in (.1,.5,1.,2.):
rows=run(eta);print('eta',eta,'last',rows[-1], 'range sharp',min(r[2] for r in rows),max(r[2] for r in rows),'nonmonotonic steps',sum(rows[i+1][1]>rows[i][1] for i in range(len(rows)-1)))
# Método de la potencia estima el autovalor de mayor magnitud, no siempre el mayor algebraico.
theta=np.random.default_rng(31).normal(0,.25,13)
for _ in range(600): theta-=.5*loss_grad(theta)[1]
u=np.random.default_rng(19).normal(size=13);u/=np.linalg.norm(u)
for _ in range(100):
u=hvp(theta,u);u/=np.linalg.norm(u)
Hu=hvp(theta,u);rayleigh=float(u@Hu);residual=float(np.linalg.norm(Hu-rayleigh*u));exact=np.linalg.eigvalsh(hessian(theta))
print('potencia',rayleigh,'residuo',residual,'extremos exactos',exact[0],exact[-1])
import sympy as sp
eta,lam=sp.symbols('eta lam',positive=True)
print('Solución de |1-eta lambda| < 1:',sp.reduce_inequalities([1-eta*lam<1,1-eta*lam>-1],eta))
A finite difference depends on perturbation size. Repeat with several values and compare with an exact Hessian or automatic differentiation when available; a small residual approximately verifies an eigenpair of the matrix used, not that the matrix correctly describes the real problem. Power iteration needs an initial vector with a component in the dominant direction and sufficient spectral separation. If eigenvalues have equal magnitude or a negative one is more extreme, use a method appropriate for the largest algebraic eigenvalue and check the residual.
Local lab: CNN on CIFAR-10
The following cell requires local Python with PyTorch, torchvision, SciPy, CUDA, and CIFAR-10. It first looks for the dataset prepared in this project environment; elsewhere place CIFAR-10 under data/ using torchvision.datasets.CIFAR10(root='data', train=True, download=True) before running. The cell does not download data. It uses 128 training images selected with seed 31, a two-channel convolution, tanh, spatial averaging, and linear classification: 86 parameters. It calculates the training-loss Hessian using Hessian-vector products and eigsh(which='LA'), checking the eigenpair residual.
In a 100-step RTX 3060 GPU run, for loss falls from 2.3026 to 2.0057 and final sharpness is 0.4652 versus ; for it is 0.3005 versus 10. At final sharpness 2.6421 exceeds threshold 2. Measured residuals were below . These are one sample and a short horizon, with metrics every 10 to 25 steps; they do not prove monotonic loss between measurements or that the relationship holds outside the experiment. Generalization is not evaluated.
import json,time
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from scipy.sparse.linalg import eigsh, LinearOperator
from torchvision.datasets import CIFAR10
torch.manual_seed(31);torch.set_num_threads(2)
if not torch.cuda.is_available(): raise RuntimeError('Se requiere CUDA para esta ejecución')
device='cuda';candidates = [Path('data')]
root = next((p for p in candidates if (p/'cifar-10-batches-py').exists()), Path('data'))
dataset=CIFAR10(root=str(root),train=True,download=False)
rng=np.random.default_rng(31);idx=rng.choice(len(dataset),128,replace=False)
X=torch.tensor(np.stack([np.asarray(dataset.data[i]) for i in idx]),device=device,dtype=torch.float32).permute(0,3,1,2)/255
Y=torch.tensor([dataset.targets[i] for i in idx],device=device,dtype=torch.long)
# Una convolución 3->2, tanh, media espacial y clasificación lineal: 86 parámetros.
def loss_fn(theta):
w=theta[:54].reshape(2,3,3,3);b=theta[54:56];v=theta[56:76].reshape(10,2);c=theta[76:86]
h=torch.tanh(F.conv2d(X,w,b,padding=1)).mean(dim=(2,3));return F.cross_entropy([email protected]+c,Y)
def sharp(theta):
p=theta.detach().clone().requires_grad_(True);loss=loss_fn(p);grad=torch.autograd.grad(loss,p,create_graph=True)[0]
def mv(x):
u=torch.as_tensor(x,device=device,dtype=p.dtype)
hv=torch.autograd.grad((grad*u).sum(),p,retain_graph=True)[0]
return hv.detach().cpu().numpy().astype(np.float64)
H=LinearOperator((p.numel(),p.numel()),matvec=mv,dtype=np.float64)
eigen,vec=eigsh(H,k=1,which='LA',v0=np.random.default_rng(31).normal(size=p.numel()),tol=1e-5,maxiter=300)
residual=np.linalg.norm(mv(vec[:,0])-eigen[0]*vec[:,0]);return float(eigen[0]),float(residual)
init=torch.cat([torch.randn(54,device=device)*.1,torch.zeros(2,device=device),torch.randn(20,device=device)*.1,torch.zeros(10,device=device)])
results=[];start=time.perf_counter()
for eta in (.2,1.,4.):
theta=init.clone();curve=[]
for t in range(101):
theta=theta.detach().requires_grad_(True);loss=loss_fn(theta)
if t in (0,10,25,50,75,100):
sh,res=sharp(theta);curve.append({'step':t,'loss':float(loss.detach()),'sharpness':sh,'residual':res})
if t<100:
g=torch.autograd.grad(loss,theta)[0];theta=theta-eta*g
if not torch.isfinite(theta).all():break
results.append({'eta':eta,'curve':curve})
print('GPU:',torch.cuda.get_device_name(0),'s:',round(time.perf_counter()-start,2))
for row in results:print(row)
print('Configuración: semilla 31, 128 ejemplos y 100 pasos; no se evalúa generalización.')
npm run lab and open the connection link.Interpret the GPU comparison
The CNN calculation uses a fixed training set for the entire trajectory and updates every parameter with that set’s gradient at each step. It uses no minibatches, momentum, or rate change. The loss is cross-entropy and sharpness refers to that same loss; the result does not measure accuracy on unseen images. The 128 images were chosen with a particular seed, so another selection may yield different trajectories.
At each saved point, eigsh applies a linear operator implemented with Hessian-vector products. The residual is small for the returned pair. A small residual alone does not guarantee that the pair is the largest eigenvalue: configuration which='LA', method convergence, and additional checks matter. With 86 parameters the complete matrix could also be built for an independent check at higher cost. The experiment states the method and does not confuse largest magnitude with largest algebraic value.
Measurements occur at a subset of steps and sharpness can oscillate between them. For a stronger comparison with Cohen’s work, save every step or a sufficiently dense sample, repeat rates and seeds, and use configurations closer to those published. The current comparison is a small proof of concept; it does not reproduce every architecture, size, or duration in the paper. Its value is showing one case near the threshold and another that is not under an executable protocol.
Rigor and scope
Levels of rigor describe how a claim is justified. A heuristic can motivate a prediction without controlling every error; a physical derivation can use approximations and limits that must be explicit; a rigorous proof checks every step under mathematical assumptions; formalization in a proof assistant checks a proof expressed in a formal system, whose connection to the original problem still needs review. Do not confuse computer output with a universal proof or dismiss a useful heuristic when identified as such.
When a counterexample appears, one can restrict the domain, strengthen assumptions, or abandon the conjecture. As the Lakatos tradition illustrates, the decision should explain the failure rather than merely exclude an inconvenient example. If a new assumption removes the regime motivating the study, the theorem may be correct but not answer the original question. Keep both original and revised versions and the evidence that prompted the change.
Record a revised conjecture
A conjecture record can include a verbal version, formula, domain, units, assumptions, and conditions under which it would be refuted. Link the motivating experiments and separate their data from the holdout. If a counterexample leads to a restricted claim, retain both versions: for example, “for every rate” may become “for rates and horizons in a specified family”. That restriction is informative only if it explains why the excluded region behaves differently.
A formalized argument also has a boundary between the world and its model. An assistant can verify that a theorem follows from encoded axioms and definitions; a definition misrepresenting Adam’s update or loss ordering proves something else. Review the translation, assumptions, and any admitted axiom. A paper proof or assistant proof can be rigorous within its system yet still need empirical validation to decide whether its assumptions approximate an application.
Exercises
Step 1 of 3. What is the factor for a component with eigenvalue lambda?
import numpy as np
from scipy.optimize import differential_evolution
def find_counterexample(claim, bounds, n_random, n_adversarial):
passStep 1 of 2. What does the example imply for the original conjecture?
Summary
A conjecture arises from observations and is tested under held-out and adversarial conditions. For a positive-definite quadratic, the strict threshold is necessary and sufficient from every initialization. In networks the Hessian changes and the edge of stability is an empirical regularity with limits; theory and simulation answer related but distinct questions.