Module contents
Lesson 6 of 23Advanced 110 min

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 2/η2/\eta, 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 1/η1/\eta 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.

InteractiveFit and test a conjecture

Fit: η = 0.1, final sharpness 3.134; η = 0.5, final sharpness 3.870. These use a single initialization and 600-step horizons. The inverse form has two parameters and fits both points exactly, without establishing a law.

Candidate form
Prediction at η = 13.502
Absolute errorheld out
Compare two forms against final sharpness of the same network and reveal the held-out point. The holdout ceases to be independent if used to choose the formula.

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 a+b/ηa+b/\eta 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.

InteractiveMap of a small violation

Search for a violation of h(x,y) ≤ 0, with h = 0.0004 − (x−0.6)² − (y−0.6)². The orange disk violates the statement; blue points are samples and the tested point follows ascent. A sample that misses the disk does not prove validity.

31
0
Violating samples0 / 100
Adversarial excess-0.31960
Change the seed and number of ascent steps. The orange disk represents values that violate the constructed inequality.

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 h(z)≤0h(z)\leq0 on a domain DD. A candidate is useful only if it belongs to DD and its values are finite. A floating-point evaluation with h(z)>0h(z)>0 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.

InteractiveSkeleton of the quadratic proof

    At η = 2/λmax the maximum component changes sign without vanishing; outside the interval it may grow. The claim requires convergence from any starting point.

    Steps in order0 / 5
    Build a convergence proof from every initialization, including equality at the threshold.

    Let f(x)=12x⊤Axf(x)=\tfrac12x^\top A x with A=A⊤≻0A=A^\top\succ0. By the spectral theorem, A=QΛQ⊤A=Q\Lambda Q^\top with orthogonal QQ and 0<λi≤λmax⁡0<\lambda_i\leq\lambda_{\max}. Gradient descent gives xt+1=(I−ηA)xtx_{t+1}=(I-\eta A)x_t. Writing ct=Q⊤xtc_t=Q^\top x_t, each component satisfies ct+1,i=(1−ηλi)ct,ic_{t+1,i}=(1-\eta\lambda_i)c_{t,i}. Therefore ct,i=(1−ηλi)tc0,ic_{t,i}=(1-\eta\lambda_i)^t c_{0,i}.

    To converge to zero from any initialization it is necessary and sufficient that ∣1−ηλi∣<1|1-\eta\lambda_i|<1 for every ii. Since all eigenvalues are positive, this is equivalent to 0<η<2/λmax⁡0<\eta<2/\lambda_{\max}. If η=0\eta=0, a nonzero component remains; if η=2/λmax⁡\eta=2/\lambda_{\max}, a component in the maximum eigenvector oscillates with factor −1-1; 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 AA 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 AA 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 ∣1−ηλi∣|1-\eta\lambda_i| is strictly less than one. In finite dimensions, the maximum of finitely many such factors is also below one; the norm of ctc_t converges to zero. The Euclidean-norm contraction rate is controlled by ρ=max⁡i∣1−ηλi∣\rho=\max_i|1-\eta\lambda_i|. On the quadratic, loss decays by at most a factor ρ2\rho^2 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 η>2/λmax⁡\eta>2/\lambda_{\max}, 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 η<0\eta<0, any component associated with a positive eigenvalue grows; with η=0\eta=0 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 tt. The value 2/η2/\eta 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.

    InteractiveCompare a quadratic and a small network
    0.5step 600

    The orange line indicates 2/η in sharpness mode. In the network, 2.0 stops early because of large loss; sampling every ten steps can hide oscillations. A value near the threshold in this run is not a universal law.

    System
    Step size η
    Magnitude
    Last recorded step600
    2 / η4.00
    Final sharpness3.870
    The quadratic uses diagonal A with eigenvalues 1 and 4. The network shows CPython NumPy measurements; the reference line is 2/η.

    For the quadratic, η=0.5\eta=0.5 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 η=0.5\eta=0.5 versus 2/η=42/\eta=4; for η=0.1\eta=0.1 it is 3.13 versus 20. The latter is a counterexample to the naive conjecture of equality at every rate and horizon. For η=2\eta=2 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 η=0.5\eta=0.5 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 η,λ>0\eta,\lambda>0; quantification over all eigenvalues is justified in the proof above.

    [ ]Small network and sharpnessBrowser
    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 η=4\eta=4 loss falls from 2.3026 to 2.0057 and final sharpness is 0.4652 versus 2/η=0.52/\eta=0.5; for η=0.2\eta=0.2 it is 0.3005 versus 10. At η=1\eta=1 final sharpness 2.6421 exceeds threshold 2. Measured residuals were below 7⋅10−77\cdot10^{-7}. 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.

    [ ]CNN and sharpness on GPULocal GPU
    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.')
    
    This cell needs the local lab (PyTorch with your GPU). Start it with 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 ∥Hv−λv∥\|Hv-\lambda v\| 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

    ProofQuadratic convergence
    Prove: For symmetric positive-definite A, prove convergence of gradient descent from any x0 if and only if 0 < eta < 2/lambda_max.
    0
    Use an orthonormal eigenvector basis and examine each component.

    Step 1 of 3. What is the factor for a component with eigenvalue lambda?

    Numeric
    For eigenvalues 0.5, 4, and 10 and eta = 0.15, what is the largest contraction factor in magnitude?
    Code
    Implement find_counterexample(claim, bounds, n_random, n_adversarial): claim(x) returns positive excess when an inequality is violated; bounds is a list of (minimum,maximum) pairs. Use uniform sampling with seed 31 and n_adversarial runs of scipy.optimize.differential_evolution with seeds 31+i. Return (point, excess) for the best candidate. Require at least one evaluation across both methods and evaluate the results actually found; do not promise a global optimum.
    import numpy as np
    from scipy.optimize import differential_evolution
    
    def find_counterexample(claim, bounds, n_random, n_adversarial):
      pass
    Shift+Enter to run
    Quiz
    A paper explains a trend with an approximation that ignores terms without bounding the error. How should it be presented?
    ProofRevise a conjecture
    Prove: A conjecture claims empirical risk always decreases when observations are added. A valid example increases it.
    0
    Distinguish the original universal claim from a possible version with additional assumptions.

    Step 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 0<η<2/λmax⁡0<\eta<2/\lambda_{\max} 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.