← Projects · Models

Learn relations,
not functions.

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.

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.

  1. 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.

  2. 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.

  3. 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.

  4. 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:

explicitimplicit · Lenticulum
what is learneda function f : X → Y, like a polynomiala relation R ⊆ Z: the zero set of a polynomial, an algebraic variety
answering a queryone forward evaluationroot finding: solve r(z) = 0 for the unknowns
backpropagationreverse-mode automatic differentiationthe implicit function theorem
what it can approximateany continuous function on a bounded, closed set (Weierstraß)any compact smooth manifold: a closed surface, a loop (Nash–Tognoli)
how many answersalways exactly oneseveral, or none (then the closest point)
directionfixed: input → outputnone: any coordinate can be the input
cost of a querycheapexpensive: an iterative solver (Newton's method, …)
wiringa directed acyclic graph, as in a neural networkany graph, loops included
Relations compose

Wired into factor graphs.

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.
A factor graph: variables joined by factors, with messages passing along the wires x y z θ h w
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.

Six beliefs on a loop variable factor
x1 x2 x3 x4 x5 x6 cut
Schedule
Modifier
Free energy, sweep by sweep ready
Fsweeps →
sweeps
0
Bethe F
–
exact −log p(y)
–
change in last sweep
–

FBethe = Σf ( 𝔼bf[−log f] − H[bf] ) + Σv (dv − 1) H[bv]

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.

  1. 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.

    Bethe Free Energy, in the vault ↗
  2. 02

    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.

    Composing Optimisers, in the vault ↗
  3. 03

    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.

    Time as a Base, in the vault ↗
A moving target

One step behind, or on it

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
–
target observations position only position 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.

  • LenticulumCore
  • Mycelium
  • Lenticulum
Localisation tutorial
B

Relation learners

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.

  • VariationalDiffusion
Implicit Diffusion Learners

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.

builds on
  • LuxCore
LenticulumCore API documentation
In action

Results, with their sources.

Every result here links to the note or example it comes from, including what did not work.

Eight handwritten test digits, each titled with the two largest label coordinates of its root, e.g. 2: 0.49 · 3: 0.48 for a 2 written like an a

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.

MNIST in Both Directions
Where it stands

A prototype, tested.

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
  • Training a relation through its own inference, with any of Julia's automatic differentiation libraries, chosen per model: Zygote, Enzyme, ForwardDiff, Mooncake or Reactant
  • 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
Get started

Get started in Julia.

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

Where to start, by background

Cite and contribute

Open, and credited.

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.

Sister project: LenticulumLM, a language model assembled from such relations.

BibTeX · the concept DOI resolves to the latest version
@software{lenticulum,
  author    = {{MathStruct}},
  title     = {Lenticulum.jl},
  publisher = {Zenodo},
  doi       = {10.5281/zenodo.23314723},
  url       = {https://mathstruct.org/Lenticulum.jl/}
}