A neural network learns a function and runs one way. Lenticulum.jl learns
a relation and decides at query time what is input and what is output. One trained
model answers “given x, what is y?”, “given y, what is x?”
and “fill in whatever is missing”.
one model of a circle · - - the clamped x · ● the answers for y
Try it
One model, any direction.
This is the example from the README, running in your browser: a model of points on a
circle. The arrows show which way the model pushes a point to bring it onto the circle.
A query holds some coordinates fixed (“clamps” them) and follows the arrows in the others
until it stops. Given x, a circle has two values of y, or none: a
function can't return either. A relation returns both.
drag the line · click to start a query there
clamped (precision ∞)x = 0.60
free (precision 0)y
answers…
The model drawn is a Gaussian mixture on 48 points of the unit circle, the closed form the
README's example uses, a little more smoothed so that its field reads at this size. The
browser follows the field by mean shift; Lenticulum
solves for the same roots with Newton's method.
How it works
Four ideas, one library.
Everything else follows from these. If you know
deep equilibrium models (networks whose output is the fixed
point of a layer), steps 3 and 4 will look familiar. The difference is that the direction
is not fixed, and each factor has an energy that reads as a negative log-probability.
01
A relation is the zero set of a learned residual
Instead of a function y = f(x), the model learns a residual rθ(z): one function of all the coordinates together, z = (x, y, …), that is zero on the data and nonzero away from it. The relation is where it vanishes: Rθ = { z : rθ(z) = 0 }. The circle x² + y² − 1 = 0 is the simplest example.
02
A query chooses a polarity
Each query sorts the coordinates into inputs (known), outputs (wanted) and latents (neither); this choice is called a polarity. Each coordinate gets a precision, one over its variance: ∞ holds it fixed, 0 leaves it free, anything in between is a noisy measurement. Asked the other way round, the same model swaps inputs and outputs.
03
Inference is root finding
With the inputs held fixed, a solver such as Newton's method adjusts the free coordinates until the residual is zero, the way a deep equilibrium model is evaluated. Several roots mean several answers: one x on the circle has two y.
04
Backpropagation is the implicit function theorem
Training needs the gradient of the answer. The implicit function theorem gives it from one linear solve at the answer, for the parameters, the inputs and the precisions alike. The solver's steps are not unrolled (stored and differentiated through), so memory does not grow with them.
The analogy behind it
Polynomials and varieties.
A neural network is like a fitted polynomial y = fθ(x).
Lenticulum instead fits the set where a polynomial in all the coordinates is zero, as the
circle is the zero set of x² + y² − 1. The polynomial case is the clean
one, and it motivates every design choice:
explicit
implicit · Lenticulum
what is learned
a function f : X → Y, like a polynomial
a relation R ⊆ Z: the zero set of a polynomial, an algebraic variety
Larger models are factor graphs: variables (circles) joined
by factors (squares), the language of Kalman filters, robot mapping and probabilistic
programming. Each factor is a learned or hand-written relation; each variable carries a
belief, a probability distribution over its value. Inference is
message passing: neighbours exchange beliefs until they agree. The
training objective is the graph's free energy, the negative ELBO
of variational inference.
The same graphs and message passing as GTSAM, the library behind much of robot localisation and mapping (SLAM), generalised to learned, non-Gaussian factors
Any model built with Lux, Julia's neural-network library, wraps as a factor
Underneath, in the language of category theory, a factor is a Bayesian lens once a query picks its direction. You don't need any of that to use the code.
Free energy
Why it converges, and when it does not.
Inference, learning and, in active inference, acting are all descents on one number: the
graph's free energy. Lenticulum.jl computes it on any graph as the Bethe free energy. Whether a
descent arrives depends on the shape of the graph, on whether the beliefs carry their own
motion, and on how the loops that do the descending are put together.
Try: flooding at λ = 5, then round the loop. Then push λ to 30 and add momentum, once with each schedule. Then cut a wire and watch the gap to the dashed line close.
01
The Bethe free energy
Energies add over the factors. Entropies add with a correction: a variable seen by d factors appears in d factor beliefs, so d − 1 copies of its entropy come off. On a tree, at the fixed point, this is exactly −log p(y): cut a wire and the curve lands on the dashed line. On a loop it is an approximation, and the fixed points of belief propagation are exactly its stationary points. Belief propagation is not gradient descent on it, though: under flooding the curve goes up before it comes down.
Inferencers and optimisers compose. Convergence does not.
A sweep of messages is an inferencer, a step on the parameters is an optimiser, and damping, momentum or Anderson acceleration are modifiers wrapped round either. In Lenticulum.jl the optimisers are themselves nodes in the graph, next to the data and the priors. Every such stack keeps the same fixed points, so if it arrives, it arrives at the same answer. Whether it arrives depends on the composite: above, momentum on a flooding sweep diverges at strong coupling and converges on a sweep that goes round the loop. Measured in the vault: the right schedule takes a loop from 326 sweeps to 38, and Anderson acceleration on top of it turns 297 000 message evaluations into 414.
Higher orders: beliefs that carry their own motion
A free energy over positions alone is minimised by a belief that is always behind a moving world: plain descent follows a steady motion at a constant lag (speed ÷ gain). Give the belief a velocity, the generalised coordinates of motion of active inference, and descend in a frame that moves with it, and the lag goes away. The same holds one level up: momentum is a velocity on the parameters, and it helps or hurts depending on the spectrum it meets.
A target moves at steady speeds and is seen with noise. Both beliefs descend the same prediction error with the same gain. The one over position only trails each slope by a constant gap; the one that also carries a velocity catches up, and overshoots only where the motion turns.
position only · RMS error
–
with velocity · RMS error
–
targetobservationsposition onlyposition and velocity
What runs where: the Bethe free energy, belief propagation with flooding, sequential and spanning-tree schedules, damping, momentum and Anderson acceleration are in Lenticulum.jl (Mycelium.jl), tested against closed forms. Channels that carry derivatives (jets) are a design note, not code yet. Both labs on this page are small re-implementations that run in your browser.
What you can build
Three paths through it.
The library is built around three uses, and work on them comes first. Each is its own
set of packages; pick the one you need.
A
Gaussian factor graphs
Exact state estimation and smoothing, as a Kalman smoother does, on linear-Gaussian graphs; nonlinear measurements by linearisation; the free energy and its gradient. The graphs of GTSAM, with factors that can be learned.
A diffusion model queried in any direction by root finding, with gradients through the solver, a Gaussian error bar around each answer (the Laplace approximation) and conditional sampling.
Factors that switch between regimes, like a system with several operating modes; hierarchical models; expectation maximisation; and search over model structures.
Off the three paths are three more packages, not yet reviewed as the core was. They are
listed with the others below.
The sublibraries
Nine packages, one stack.
Lenticulum is split into small packages under lib/, each built on others;
pick one to see what it does and what it builds on. All of them depend only on LuxCore, the
small interface package of Lux, and not on Lux itself or on
training libraries like Zygote and
Optimisers. Automatic differentiation and
Reactant (which compiles models for GPUs and TPUs) are
switched on by package extensions, when you load them.
Off the paths · not yet reviewed
LenticulumCore
the vocabulary
What a factor is: its channels, polarities, energy and entropy. Also the belief types, the probability distributions a variable can carry (Gaussian, categorical, mixture, a point mass, samples), which convert to those of RxInfer. It is to Lenticulum what LuxCore is to Lux: the interface, without the implementations.
How factors are wired and in what order they talk: graphs, messages, schedules, plates (repeated copies of a subgraph), cluster nodes (variables handled jointly) and the free energy. Lux has no counterpart to this layer, because in a neural network the wiring is a directed acyclic graph and the order follows from it.
The user-facing package: linear-Gaussian and nonlinear factors, linear constraints, switching and regime factors, likelihoods, and their closed-form M-steps (the update step of EM). The Gaussian factor doubles as the test oracle: everything it computes has a closed form, so the rest of the library is checked against it.
Diffusion models as relations: the variance-preserving SDE of DDPM-style models, implicit inference with gradients through the solver, answers as a Gaussian (Laplace) or a mixture of branches, conditional sampling, and two inverse-problem solvers, RED-Diff and ProxDM.
The shared numerics: linear solves (dense, GMRES, MINRES), root finding (Picard, Broyden, Newton, trust region) and the linear systems that give gradients through the implicit function theorem. Every solve returns a report on how it converged.
Deep equilibrium networks and neural ODEs from SciML, wrapped as factors. Given the inner network rather than the finished layer, they can be queried in more than one direction.
Implicit generative models, with the GAN read as a factor graph. A generator is a function with no residual behind it, so these factors run one way only.
Every result here links to the note or example it comes from, including what did not
work.
Classify by clamping the image
One diffusion model of (image, label) on MNIST. Clamp the 784 pixels, free the 10 label coordinates (a one-hot code), and the root is the classification: 96.1% on 9000 test digits, about the same as a standard diffusion classifier built on the same network (95.8%). The most ambiguous digits land between two codes, like this “2” written as an “a” at 2: 0.49 / 3: 0.48. The other direction, label to image, does not work yet with this model; the note says why.
What is exact is tested against closed-form answers; what is approximate says so. One
author, in the MathStruct registry, with APIs still moving.
Works today
Exact inference on linear-Gaussian graphs, checked on random trees against solving the whole joint Gaussian at once
Switching chains, checked against enumerating every sequence of regimes
Diffusion models as relations, queried in any direction; the learned field checked against the exact score (gradient of the log-density) of a Gaussian mixture
Several answers per query: implicit_roots and implicit_mixture collect the branches, implicit_sample samples a query
Installable from the MathStruct registry, with eleven tutorials, the API documentation and a theory vault
Known limits
A multi-modal belief (a mixture) that reaches a Gaussian or constraint factor is replaced by one Gaussian with the same mean and covariance, unless the two share a cluster node
Inference cost grows quadratically with the number of factors that have their own parameters (plates, repeated copies with shared parameters, are not affected)
The diffusion learner finds the crest of a slightly blurred data density, not the exact set the data lies on, and every query returns a root, whether it lies on the relation or not
Learned networks are small by design: a factor relates only a handful of coordinates
Lenticulum is in the MathStruct registry, which Julia's
package manager uses alongside General, the default one. A
registered version is a snapshot; for the newest code, clone the repository and
Pkg.develop it.
Install
using Pkg
Pkg.Registry.add(RegistrySpec(url = "https://github.com/MathStruct/Registry.git")) # once
Pkg.add("Lenticulum") # paths A and C
Pkg.add("VariationalDiffusion") # path B
The circle, in code · no training needed
using VariationalDiffusion, LuxCore, Random
sched = VPSDE()
θ = range(0, 2π; length = 49)[1:48]
circle = NoisePredictor(GaussianMixtureEps(sched, vcat(cos.(θ)', sin.(θ)'); s = 0.05), sched)
ps, st = LuxCore.setup(Xoshiro(0), circle) # a diffusion model of the unit circle
m = ImplicitDiffusion(circle, field_nodes(Xoshiro(1), 2; samples = 8))
up, _ = implicit_infer(m, [0.6, 0.5], [Inf, 0.0], ps, st) # x clamped (∞), y free (0)
dn, _ = implicit_infer(m, [0.6, -0.5], [Inf, 0.0], ps, st) # same query, other start
up.z[2], dn.z[2] # ≈ (0.78, -0.78): two branches
Every release is archived on Zenodo. Contributions of every kind are welcome (code, notes,
derivations, reviews), and how credit and authorship work is written down in
CONTRIBUTING.md.
Every page of the vault has a comment thread.