Back to blog

Cinq équations, un seul CPU

Five Equations, One Laptop

Quantum cosmology, gauge theory, relativistic wave mechanics and random matrices — solved by neural networks on a single CPU, with every loss function coming from a Rust library and every answer checked against something that doesn't share a line of code with it.

Contents

  1. Why a language-model project is solving the Wheeler–DeWitt equation
  2. Where these equations come from
  3. How a network solves a differential equation
  4. The architecture, drawn
  5. Objectives as a library
  6. Exact input-derivatives without nested differentiation
  7. Curvature: L-BFGS against a first-order method
  8. The mean-field limit, and an error the proof caught
  9. The five problems, one at a time
  10. Results
  11. Four implementations of the same gradient
  12. Where this sits, and the GPU question
  13. Using thotbook-ai
  14. What we'd do next
  15. Coming up: the whole toolchain
  16. References and further reading
Animation: 400 eigenvalues repelling from a tight cluster and settling onto Wigner's semicircle

Generalized Dyson Brownian motion: 400 eigenvalues of a Hermitian matrix diffusing under Brownian noise. They repel logarithmically, so none ever collide; a confining potential holds them in. The balance is Wigner's semicircle. This is the real SDE at the step size the paper uses, animated straight out of the companion notebook.

Why a language-model project is solving the Wheeler–DeWitt equation

thotbook-ai started from a question about ownership rather than benchmarks: what does a research assistant look like if every part of it runs on hardware you control, and every number it produces traces back to a line of code you can read?

Taking that seriously imposes a constraint — CPU only, no GPU, no external inference API — and the constraint turned out to be productive. It rules out treating a model as an oracle, because a CPU budget forces you to know which part of the computation is expensive and why.

The system has two halves. One is an ordinary language-model pipeline: a corpus of research sessions and papers is redacted, ingested into a versioned Delta Lake, tokenised, used to fine-tune a small open-weights model, and served behind an OpenAI-compatible endpoint you can point your editor at. The other half is numerical — a differentiation tape, an objective library, a set of optimisers — and it exists because the research the assistant is meant to help with is mathematical physics.

Both halves obey one rule, and that rule is the interesting part:

A loss function is a mathematical object, not an implementation detail of a training loop. It belongs in one audited place, callable from anywhere, and it should return its own gradient.

That sounds procedural. It is load-bearing, and we learned it the embarrassing way: a hand-written cross-entropy in our trainer returned $+\frac{1}{N}\sum_n \log q_{n,y_n}$ instead of its negative. The missing minus sign means gradient descent maximises the loss — it trains a model away from its targets. Worse, the unit test guarding the function asserted the wrong sign, so the defect was stable under testing. A confidently wrong prediction scored $-8.00$ where a confidently right one scored $-10^{-3}$. One definition, checked once against finite differences, makes that class of error impossible to hold.

Where these equations come from

None of the five is new. Each is a place where someone asked what happens when two established ideas are forced to coexist.

How a network solves a differential equation

A physics-informed neural network doesn't learn from solved examples. It takes the equation itself as the objective: write the network as $u_\theta(x)$, substitute it into the equation, and you get a residual that is zero exactly when the equation holds. Scatter some points, square the residual, add the boundary conditions, and minimise :

$$\mathcal{J}(\theta) \;=\; \sum_k w_k\,\frac{1}{N_k}\sum_{i=1}^{N_k} r_{k,i}(\theta)^2$$

The idea is older than the name — Dissanayake and Phan-Thien did it in 1994, Lagaris and colleagues in 1998 — but Raissi, Perdikaris and Karniadakis made it practical in 2019. What makes it attractive is that nothing about it cares whether the equation is linear, whether the domain is awkward, or whether you have any data at all.

Animation: a relativistic wave packet translating and spreading, network against exact propagator

A wave packet under the Dirac equation: the network (dashed) against the exactly diagonalised propagator (solid). It travels at the relativistic group velocity $k_0c^2/E$, not at $k_0/m$, and it spreads. Unitarity was never part of the objective — we left it out so its constancy is evidence the network learned the dynamics rather than an assumption we fed it.

That last point is a habit worth stealing. If you penalise a conserved quantity during training, its conservation afterwards tells you nothing. Leave it out and it becomes a measurement.

The architecture, drawn

The revised paper opens the box. A single input $x$ flows through two $\tanh$ hidden layers of width 32 — about 1 200 parameters, small enough to fit in L2 cache — to a scalar field $u_\theta$. The tape then returns not one quantity but three: $u_\theta$, $\partial_x u_\theta$ and $\partial_{xx} u_\theta$. Those feed the PDE residual and the boundary residual, whose weighted squared norms are the loss. The optimiser closes the loop.

Why $\tanh$ and not ReLU, which every deep-learning tutorial starts with? Because ReLU's second derivative is zero almost everywhere. A residual containing $u_{xx}$ would be constant in $\theta$, its gradient identically zero, and the network would learn precisely nothing. The choice of activation is not a style preference here — it is a correctness condition.

Animation: the network progressively fitting the Wheeler-DeWitt wavefunction during training

The same architecture, learning. The network starts from Xavier noise and converges onto the Wheeler–DeWitt wavefunction; the oscillation in the classically allowed region and the decay under the barrier both emerge from the residual alone, never from a fitted target.

The part we think is new: objectives as a library

Here is the architectural problem. Automatic differentiation works by recording operations on a tape, and the tape can differentiate whatever was built on it. But if your loss function lives in a Rust crate — because you want it audited once and shared between a physics solver and a language-model trainer — then the tape has never seen it, and the chain rule appears to be broken.

It isn't. A reverse-mode tape doesn't need the objective; it needs the objective's derivative with respect to the residuals. Call that vector $g$. Then :

$$\nabla_\theta\big(L\circ r\big)(\theta) \;=\;\Big(\tfrac{\partial r}{\partial\theta}\Big)^{\!\top} g \;=\;\nabla_\theta\big\langle g,\,r(\theta)\big\rangle\Big|_{g\ \text{const}}$$

Differentiating the plain inner product $\langle g, r(\theta)\rangle$, with $g$ held fixed, gives exactly the gradient of the real objective. One extra dot product, no extra backward pass, and no approximation anywhere. The hypothesis that $g$ be constant is essential: differentiate through it and the product rule adds a Hessian term that doesn't vanish. Measured against central differences over randomly chosen parameters, the assembled gradient agreed to $4.1\times10^{-8}$ relative error with cosine similarity $1.000000000000$ — the finite-difference truncation, not our assembly.

The practical dividend: the cross-entropy that fine-tunes the language model and the weighted mean-squared error that fits a Wheeler–DeWitt wavefunction are now the same Rust code, with the same finite-difference-checked gradients. Masking, label smoothing and a numerically stable log-softmax were written once. When we rewired the trainer onto it, the sign bug disappeared by construction — there was no second implementation left to be wrong.

Animation: the network learning the Wheeler-DeWitt wavefunction over L-BFGS iterations

The network learning $\Psi(a)$ for the Wheeler–DeWitt equation, one frame per L-BFGS snapshot. It starts as the near-zero output of a Xavier-initialised tanh network and is pulled onto the Numerov solution by the optimiz-rs objective alone. The forbidden region fills in first: the regularity conditions at $a=0$ carry weight 200, so they are satisfied long before the oscillatory tail is resolved.

Exact input-derivatives without nested differentiation

This is the piece most readers ask about, so it deserves spelling out. A PINN needs $u_{xx}$. The obvious way to get it is to differentiate the tape with the tape — call autograd on the output of autograd, the "double backward". It works, and in PyTorch it is two chained autograd.grad calls with create_graph=True. But it builds a second graph on top of the first, roughly doubling memory and making the backward pass noticeably more expensive.

We do something older and cheaper: propagate the derivatives alongside the activations. Write $h=\tanh(a)$ for one layer, and let $'$ mean $d/dx$. Then

$h' = (1-h^2)\,a', \qquad h'' = (1-h^2)\bigl(a'' - 2h\,(a')^2\bigr).$

Both follow from the chain rule in two lines: $h'=\tanh'(a)a'=(1-h^2)a'$, and differentiating that product again gives $h''=-2hh'a'+(1-h^2)a''$, which factorises to the expression above. The affine part is easier still — it is linear, so $a'=h'_{\text{prev}}W$ and $a''=h''_{\text{prev}}W$ with the same matrix. Starting from $h^{(0)}=x$, $(h^{(0)})'=1$, $(h^{(0)})''=0$, one sweep forward carries all three quantities to the output.

The decisive point: every operation in those recursions is an ordinary tape operation — a matrix product, an elementwise product, a subtraction. So the extended computation sits on the same single tape, and one backward sweep then yields $\nabla_\theta$ of a loss containing $u_{xx}$. We get the double-backward result without ever differentiating a derivative.

The method extends: a third-order term costs one more propagated array, linearly, where nesting tapes would cost exponentially. None of our five equations needs it, but a fourth-order problem — a beam, Cahn–Hilliard — would.

Curvature: L-BFGS against a first-order method

Here is the whole argument in one example. Minimise $\mathcal{L}(\theta)=\tfrac12\theta^\top A\theta$ with $A=\mathrm{diag}(1,10)$. Gradient descent with a constant step converges only if $\eta < 2/\lambda_{\max} = 0.2$. But in the flat direction ($\lambda=1$) the ideal step is $\eta=1$. You are forced into a step five times too small exactly where you most need to move. That factor is the condition number $\kappa=10$ — and a PINN loss, mixing an interior residual with a boundary term, is routinely far worse conditioned than that.

A first-order method only ever sees the slope. It cannot know that one direction is ten times stiffer, so it must pick one step for all of them. L-BFGS recovers that missing information from the differences of successive gradients. After a step it stores the secant pair

$s_k = \theta_{k+1}-\theta_k, \qquad y_k = \nabla\mathcal{L}_{k+1}-\nabla\mathcal{L}_k,$

and the scaling $\,(s_k^\top y_k)/(y_k^\top y_k)$ is, in the example above, exactly $0.1$: the algorithm has discovered that the dominant curvature is 10. It never formed a matrix to do so. The two-loop recursion of Nocedal reconstructs the action of the inverse Hessian on a vector from the last $m$ pairs in $O(mp)$ operations and $2mp$ stored reals — for $p=1200$ and $m=20$ that is 0.4 MB, against 11 MB and $O(p^2)$ work for the explicit matrix.

Two guards make it safe. A pair is kept only if the curvature condition $s_k^\top y_k > 0$ holds; on a non-convex loss it can fail, and keeping such a pair would make the implicit operator indefinite, so the search direction would stop being a descent direction at all. And the step is accepted only if it satisfies Armijo, $\mathcal{L}(\theta_k+\alpha p_k) \le \mathcal{L}(\theta_k) + c_1\alpha\, p_k^\top\nabla\mathcal{L}_k$ with $c_1=10^{-4}$ — a decrease proportional to the local slope, not merely any decrease. The constant is deliberately tiny: the test should reject absurd steps without slowing good ones.

In practice we run AdamW first and L-BFGS second. AdamW is robust and scale-invariant — multiply the loss by a constant and its iterates are unchanged — which makes it forgiving about the weights $w_k$; but it stalls. L-BFGS converges fast once it is already in a sane basin. Each tool where it is good.

Most deep learning uses first-order methods — SGD, Adam, AdamW — which take many cheap steps using only the gradient. Quasi-Newton methods like L-BFGS take fewer, more expensive steps, building an approximation of the curvature from successive gradients. For PINNs the trade is usually worth it, and the reason is specific: a PINN objective is ill-conditioned by construction, because the Hessian mixes a differential operator with boundary penalties weighted orders of magnitude apart.

On a well-conditioned problem the difference is unremarkable — in our benchmark L-BFGS reached tolerance in 18 iterations against AdamW's 351, but AdamW's steps are cheap enough that wall-clock time was comparable. Push the condition number to $10^6$ and it stops being a matter of constants: L-BFGS converged in 129 iterations, and AdamW failed to reach the same tolerance in 20,000 steps at either learning rate.

This is where the exact gradient earns its keep. L-BFGS builds its curvature estimate from differences of successive gradients, and its line search accepts a step only on a measured decrease. Both are wrecked by gradient noise: the secant pairs become inconsistent, the curvature condition $s^\top y > 0$ fails, and the method stalls or rejects every step. Approximating the external objective's gradient by finite differences would also cost one objective evaluation per parameter. The identity above is what makes a quasi-Newton method usable at all across a language boundary.

The symmetry is worth stating: for the language-model half we use AdamW, not L-BFGS. With millions of parameters there is no storing curvature, and the gradients are stochastic anyway. Same objective library, opposite optimiser — which is the whole argument for keeping them separate.

The mean-field limit, and an error the proof caught

As the number of eigenvalues grows, the randomness averages out and the empirical measure follows a deterministic flow — the McKean–Vlasov equation, which Li, Li and Xie identify as the Wasserstein gradient flow of Voiculescu's free entropy. Rather than quadrature a principal value, we solve for the Stieltjes transform $G_t(z)=\int (z-x)^{-1}\mu_t(dx)$, which satisfies a complex Burgers equation :

$$\partial_t G_t(z) \;=\; \Big(\tfrac{1}{2}z - G_t(z)\Big)\,\partial_z G_t(z) \;+\; \tfrac{1}{2}G_t(z)$$

That factor of a half matters, and it is the subject of the most instructive mistake in this project. We first transcribed the equation from the rendered PDF, where automated text extraction renders $\tfrac12$ as the digits “12” — silently dropping two factors of a half. The network converged happily to $7\times10^{-7}$ on the wrong equation. Only writing out the proof that Wigner's semicircle is stationary exposed it: substituting $G_\infty(z)=\tfrac12(z-\sqrt{z^2-4})$ into the mistranscribed form leaves a non-zero residual, and into the derived form annihilates it exactly. With the equation corrected, the result improved markedly — the distance to equilibrium now contracts five-fold over the run rather than barely moving.

Animation: the Stieltjes transform flowing to the semicircle equilibrium

The McKean–Vlasov flow. The network is given the Burgers equation and an initial condition, nothing else; it finds $G_\infty(z)=\tfrac12(z-\sqrt{z^2-4})$ on its own. The right panel tracks the sup-norm distance to equilibrium, which contracts from $1.25\times10^{-1}$ to $2.52\times10^{-2}$. Wigner's semicircle law was never supplied.

The five problems, one at a time

They were not chosen for variety's sake. Each one breaks a different part of the machinery, and each is checked against a reference that shares no code with the network.

1. Wheeler–DeWitt — quantum cosmology. The ADM Hamiltonian constraint, reduced to a universe described by its scale factor alone, becomes a second-order ODE with a potential barrier. The wavefunction oscillates where the universe is classically allowed and decays under the barrier. Tests: second derivatives and a boundary condition that forbids the trivial solution. Reference: Numerov integration.

2. Hermitian Yang–Mills — gauge theory on a torus. The periodic Laplacian is diagonal in Fourier modes, $\lambda_n=(2\pi n/L)^2$, so the reference is obtained by spectral inversion: divide mode by mode, no iterative solver, accurate to $10^{-14}$. We make no claim to beat it — we use it as a ruler.

3. Dirac in 1+1 dimensions — relativistic wave mechanics, and a two-component complex field. The Clifford algebra gives $E=\pm\sqrt{k^2+m^2}$, two branches separated by a gap $2m$. Reference: the exactly diagonalised propagator. The interesting part is what we did not do: unitarity is never imposed on the loss, only measured afterwards — and it holds to $10^{-3}$.

Animation: a Dirac wave packet propagating, its norm conserved

A Dirac packet in flight. Nothing in the loss asks the norm to be conserved; it is conserved because the trained evolution is genuinely unitary. That is the difference between evidence and assumption.

4. Generalized Dyson Brownian motion — a coupled system of stochastic differential equations. Eigenvalues diffuse but repel through a $1/(\lambda_i-\lambda_j)$ drift, so they never collide: the difference of two neighbours is a Bessel process of dimension $1+\beta$, which for $\beta\ge1$ never reaches zero. Not a statistical tendency — an impossibility.

5. McKean–Vlasov — the mean-field limit, and the only genuinely nonlinear problem of the five. The Stieltjes transform turns the transport equation into a complex Burgers equation. The network is handed that equation and an initial condition, nothing else — and recovers Wigner's semicircle. Reference: the simulated particle system plus the analytic transform.

Results

Every network is validated against an independent reference, never against itself.

Equation Reference Iters Seconds Rel. error
Wheeler–DeWittNumerov, 4001 pts150032.82.4×10−4
Hermitian Yang–Millsspectral inversion50027.64.9×10−2
Dirac 1+1exact propagator70090.59.8×10−2
McKean–Vlasovanalytic $G_\infty$70062.12.1×10−2
Dyson Brownian motionsemicircle moments—25.5$m_2$ 0.9865 / 1

Four minutes, all of it on one Intel i9-8950HK, no GPU. We make no claim to beat a tuned spectral method — on the Yang–Mills problem the spectral reference is exact to $10^{-14}$ and takes milliseconds. The claim is narrower: one objective library and a 250-line tape, no framework, solve four structurally different problems to engineering accuracy in minutes, with every number checked against something independent.

Two of those checks failed, and that was the point

Insisting that references be independent caught two defects in our own physics library. A Dirac split-step integrator turned out not to be unitary — the norm fell to 0.155 after a single step and reached $10^{58}$ after a hundred, identically for time steps from $5\times10^{-2}$ down to $10^{-4}$. A step-size-independent blow-up is not a stability limit; it's a bug. And a Poisson solver's grid convention couldn't be pinned down under either periodic or Dirichlet reading. Both are reported in the paper with reproducible evidence, and both were replaced rather than worked around.

The paper

Everything above is the overview. The paper derives each equation from its physical starting point, states existence and uniqueness precisely — with full proofs where they're ours and citations where they aren't — proves the vector–Jacobian theorem, and reports the benchmarks. 21 pages, 25 references, companion code that regenerates every figure.

Download the paper (PDF) All publications

Four implementations of the same gradient

The revised paper adds a Rust/PyO3 rewrite of the tape, thotgrad_rs, built on ndarray with no deep-learning framework. It runs the same algorithm: its gradients agree with the NumPy tape to $1.33\times10^{-15}$, machine precision. That parity is what makes the timing comparison meaningful — we are measuring four ways of computing the same number.

One loss-and-gradient evaluation — value and the full parameter gradient — on a 1-32-32-1 network with 256 collocation points, single thread, everything in float64, all four in one freshly built Python 3.12 environment:

Implementation ms / gradient vs Rust
thotgrad_rs (Rust / PyO3)0.62 – 1.021.0×
JAX 0.4.38 (jit, x64)0.64 – 0.94tie
PyTorch 2.2.2 (eager)1.32 – 1.541.3 – 2.3× slower
thotgrad (261-line NumPy tape)1.9 – 2.52.3 – 3.0× slower

The Rust port beats the NumPy tape and PyTorch's eager double-backward consistently. Against compiled JAX it is a tie: across repeated trials we measured both orderings, so we claim no winner there. A compiled XLA kernel and a hand-written Rust tape are simply comparable on a problem this small.

A trap worth passing on. Our first run said JAX was about twice as fast. It wasn't. JAX defaults to float32: unless you set jax.config.update("jax_enable_x64", True) you are timing a single-precision gradient against three double-precision ones. Half the bytes, half the memory traffic, and not the same computation. A benchmark that does not state its dtype is not a benchmark. We also caught a bug of our own — an early timing loop computed $u_{xx}$ and the loss but never called .backward(), so PyTorch was doing strictly less work and looked great.

Where this sits, and the GPU question

We are not competing with PyTorch or JAX, and it would be silly to pretend otherwise: they are superb, enormous, well-funded pieces of engineering, and for training a transformer on a cluster there is no argument to have. The claim is narrower. For a small, stiff, high-precision problem — a few thousand parameters, double precision, second derivatives, thousands of iterations — the overhead of a general-purpose framework is a real cost, and a few hundred lines of honest calculus is competitive.

And then there is the part nobody writes down. PyTorch publishes no macOS x86_64 wheel past 2.2.2, and none at all for Python 3.13. On the machine this paper was written on, the framework does not install. That is the actual origin of the 261-line tape: not a performance ambition, a availability problem. Research code that only runs on the hardware you happen to have funding for is research code that cannot be reproduced.

Which brings up the GPU. The default assumption in machine learning is that serious work needs one, ideally several, ideally rented. For a great deal of scientific computing that assumption is simply false. All five problems here train in minutes on one CPU core. Double precision, which most scientific work needs and which consumer GPUs are deliberately crippled at, is free on a CPU. There is no driver stack, no CUDA version to match, no VRAM ceiling, no cloud bill, and the thing runs on a laptop on a train. We think the fraction of computational science that genuinely requires a GPU is smaller than the fraction that currently uses one — and the gap is a reproducibility problem, and an access problem, before it is a technical one.

Using thotbook-ai

The repository is one Rust workspace plus a Python notebook layer. Nothing below needs a GPU, an API key, or a network connection after the first model download. make models reads live file sizes from the HuggingFace API, measures your real download bandwidth, and judges each model against the machine you're on before you commit to anything :

$ make models

host: Intel i9-8950HK | 12 threads | 32 GiB RAM | 777 GB free
measured bandwidth: 13.8 MB/s (111 Mbit/s)

KEY                BACKEND  PAR      SIZE    ETA  FITS
qwen3-1.7b         candle   1.7B   4.06 GB    5m  OK
qwen3-4b           candle   4B     8.05 GB   10m  OK
qwen3-8b           candle   8B    16.38 GB   20m  NO
                                        -> peak ~37 GB > 34 GB RAM
dllama-qwen3-8b    dllama   8B     6.75 GB    8m  OK   <- recommended

The FITS column applies the loader's real arithmetic rather than a rule of thumb: weights are read, materialised, then copied again by the dtype conversion, so peak memory is about three times the on-disk size plus the largest shard. Then :

# serve it, and point your editor at it
make setup-model MODEL=dllama-qwen3-8b   # shows the plan, waits for y/N
make serve MODEL=qwen3-1.7b              # OpenAI-compatible, :8100
make opencode-register MODEL=qwen3-1.7b  # adds it to opencode.json

# train on your own research history
make historia-db        # index the session corpus
make train-historia     # ingest -> tokenise -> CPU LoRA, end to end
make verify-paper       # check every paper claim against the tree

# reproduce the physics: 5 equations, 6 figures, 4 animations, ~4 min
cd notebooks && ../.venv/bin/python build_nb09_pinn_physics.py

Ingestion redacts at write time and refuses any row that still contains a secret, so the lakehouse never sees one. make verify-paper is the habit we'd most recommend copying: it reports each falsifiable claim as PASS, FAIL, BLOCKED or ABSENT with its evidence, and exits non-zero if anything regressed. The notebook build aborts if the finite-difference gate on the objective gradient fails, so a successful run is itself a check that the theorem is implemented correctly.

Prerequisites, if you want to follow the derivations

The paper assumes a particular mix that no single course covers: stochastic calculus, differential geometry, functional analysis, and enough quantum field theory to recognise why a Clifford algebra shows up in a first-order wave equation. We wrote that mix down — a 90-page course in six parts, in French, which is the actual prerequisite chain for this work rather than a general mathematics survey.

Mathematics and physics for quantitative finance

I — Fondations mathématiques · II — Physique théorique avancée · III — Applications financières · IV — Processus avancés et méthodes numériques · V — Équations rétrogrades, jeux et superespace · VI — Analyse fonctionnelle, transport optimal et convexité

90 pages, French. Parts IV to VI are the ones this paper leans on hardest: the numerical methods, the backward equations and mean-field games, and the optimal-transport view that turns the McKean–Vlasov equation into a gradient flow. $30 — English edition in preparation.

See the course

What we'd do next

In order. Residual-adaptive collocation, to move the errors still sitting at $10^{-2}$; the rank-$r$ Hermitian Yang–Mills problem, where the equation is genuinely nonlinear and the stability obstruction stops being a single scalar you can check by summing a grid; and a convergence study in $N$ for the eigenvalue system, which is the one place in the paper where we assert a rate without having measured it. Everything is open source, and the notebook runs on a laptop.

Equations 4 and 5 follow Li, Li & Xie, Generalized Dyson Brownian motion, McKean–Vlasov equation and eigenvalues of random matrices, arXiv:1303.1240.

Coming up: the whole toolchain

This paper is one piece of something larger, and the next article will treat it as a whole. The thesis is simple: you can do research-grade machine learning, optimisation and language-model work — the kind of thing that is usually assumed to need a cluster — on a laptop, if the stack is built for CPUs instead of ported to them as an afterthought.

The common thread is the one this post has been circling: own the numerical stack, check every number against something that does not share code with it, and report the results that are unfavourable along with the ones that are not.

References and further reading