A GPPrior makes three linear-algebra choices: the solver that applies , the preconditioner that speeds it up, and the log-determinant that estimates . The docstrings list a dozen valid combinations; this page says which one to pick for a size, a kernel and a likelihood, and what error and cost to expect. The advice comes from a benchmark, scripts/bench_gp_solvers.py, whose results are saved next to this notebook as gp_solver_choices.csv, one row per combination. Every claim below names the rows it rests on, as likelihood-kernel-N-configuration, and the cell after it prints them. The cells that run live use or less, so the page executes in a few minutes; the saved table goes up to .
What you’ll learn:
What the three choices of a
GPPriorare, and which quantity uses each.Which combination to pick for a size, a kernel and a likelihood, and what error and cost to expect.
How noisy the evidence gradient is, and what the preconditioner and the control variate do to that noise.
What a stochastic evidence means inside NUTS and SVI, and how to check whether its noise matters.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
"pyrox @ git+https://github.com/jejjohnson/pyrox@main#subdirectory=packages/pyrox",
"pyrox-gp[colab] @ git+https://github.com/jejjohnson/pyrox@main#subdirectory=packages/pyrox-gp",
"pandas",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import time
from pathlib import Path
import equinox as eqx
import gaussx as gx
import jax
import jax.numpy as jnp
import jax.random as jr
import kernellib as kl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyrox_gp as px
jax.config.update("jax_enable_x64", True)import importlib.util
try:
from IPython import get_ipython
ipython = get_ipython()
except ImportError:
ipython = None
if ipython is not None and importlib.util.find_spec("watermark") is not None:
ipython.run_line_magic("load_ext", "watermark")
ipython.run_line_magic(
"watermark",
"-v -m -p jax,equinox,numpyro,gaussx,kernellib,pyrox_gp,matplotlib,pandas",
)
else:
print("watermark extension not installed; skipping reproducibility readout.")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.13.0
jax : 0.10.2
equinox : 0.13.8
numpyro : 0.21.0
gaussx : 0.8.4
kernellib : 0.0.22
pyrox_gp : 0.3.2
matplotlib: 3.10.9
pandas : 3.0.3
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
1. The three choices¶
With training points, the kernel matrix (jitter included) and the noise or site variances , every quantity of a GP solves against one system,
For Gaussian noise ; inside a Laplace fit , the inverse site precision of point , and changes at every Newton step. The Gaussian evidence, with the residual of the prior mean, uses both maps:
| Choice | GPPrior field | Computes | Shape | Used by |
|---|---|---|---|---|
| solver | solver | , or for test points | the quadratic term, condition and predict, every Newton step | |
| preconditioner | preconditioner | inside CG, of rank plus | the number of CG steps, and the variance of a stochastic log-determinant | |
| log-determinant | logdet | scalar | the evidence (log_marginal, gp_factor, the Laplace evidence) and its gradient |
A dense solver factorises once, at time and memory, and gives both maps exactly. An iterative one never forms (GPPrior(..., matrix_free=True) evaluates it block by block in each product) and estimates the log-determinant by stochastic Lanczos quadrature (SLQ) over random probes , with the Lanczos tridiagonal of probe :
With a preconditioner the estimate splits as , the first term exact and the second near zero, so its probe noise is smaller. The benchmark compares these configurations, all on matrix_free=True except dense, and all built with throw=False so a solve that misses its tolerance is reported rather than raised:
| Name | Solver | Preconditioner | Log-determinant |
|---|---|---|---|
dense | DenseSolver (Cholesky) | none | exact |
cg | CGSolver(rtol=1e-4) | none | CG’s own SLQ, 20 probes, 30 Lanczos steps |
cg-nystrom | CGSolver(rtol=1e-4) | NystromPreconditioner.lazy(200) | SLQLogdet(num_probes=50), preconditioned, gradient with the control variate of gaussx#826 |
cg-nystrom-fixedP | CGSolver(rtol=1e-4) | the same Nyström, built once at the evaluation point | the same SLQ; has no gradient, so the control variate adds nothing |
matfree | px.matfree_solver(rank=200) | Nyström, rebuilt from | NystromLogdet: exact plus SLQ of the remainder, 50 probes, 30 steps |
matfree-fitc, matfree-r50, matfree-r800, matfree-lanczos60 | matfree_solver with preconditioner="fitc", rank 50, rank 800, or 60 Lanczos steps | ||
bbmm | px.bbmm_solver(rank=200) | lazy Nyström | BBMM’s shared pass, 50 probes drawn from , gradient with the control variate |
The two presets are one call each and return an ordinary gaussx strategy, as the cell below shows.
key = jr.key(0)
dense = None # GPPrior(solver=None): gaussx.DenseSolver, a Cholesky of A
# the three fields, set one by one
solver = gx.CGSolver(rtol=1e-4)
preconditioner = gx.NystromPreconditioner.lazy(200, key=key)
logdet = gx.SLQLogdet(num_probes=50)
composed = gx.compose_solver(solver, preconditioner=preconditioner, logdet=logdet)
# or one preset call each, with the same three parts inside
matfree = px.matfree_solver(rank=200, key=key)
bbmm = px.bbmm_solver(rank=200, key=key)
for name, strategy in [
("CG + Nyström + SLQ", composed),
("matfree_solver", matfree),
("bbmm_solver", bbmm),
]:
print(f"{name:20s} -> {type(strategy).__name__}")CG + Nyström + SLQ -> ComposedSolver
matfree_solver -> ComposedSolver
bbmm_solver -> KeyedSolver
The saved results¶
The benchmark draws inputs uniformly on the unit square, sets the latent function to , and observes it with Gaussian noise of variance or as Bernoulli labels with probability . The kernel is a Matérn-3/2 of unit variance with a smooth () or a rough () lengthscale, and each evidence is evaluated at those hyperparameters. The sizes are for both likelihoods and for the Gaussian one, with three keys per stochastic configuration below 8000 and one at 8000. The run had to fit a shared VM (it took about 46 minutes), so 8000 is the largest size, the Bernoulli likelihood stops at 2000, and the rough kernel at 8000 has dense and matfree only. The dense reference is exact at every size measured, so every error is against it; at , with one key, the RMS error is the error of that key.
The timings are on the CPU of the VM, four cores (taskset -c 0-3), in float64, after ahead-of-time compilation, with jax.block_until_ready, and the median over the keys. There is no GPU on the VM, so no row is a GPU timing. passes_evidence counts the calls of the kernel operator’s matvec in one evidence: each call evaluates once, block by block, and applies it to one vector or to a batch of probes, so it is the unit of cost of a matrix-free GP. mem_evidence_mb and mem_grad_mb are XLA’s temporary allocation of the compiled executable. logz_bias, logz_std and logz_rms are in nats against the dense evidence, with over the keys, and grad_rel_rms_* is the RMS error of each component of the gradient over the keys, divided by the dense component. The effective dimension
counts the eigen-directions of that stand above the noise; it is what a preconditioner’s rank has to cover, and the cell below prints it for each data set.
# next to this notebook (or from the repository root); on Colab, from GitHub
CSV = "gp_solver_choices.csv"
local = [path for path in (Path(CSV), Path("docs/notebooks") / CSV) if path.is_file()]
URL = f"https://raw.githubusercontent.com/jejjohnson/pyrox/main/docs/notebooks/{CSV}"
results = pd.read_csv(local[0] if local else URL).set_index("id")
def cite(*ids: str, columns: tuple[str, ...] | None = None) -> pd.DataFrame:
"""The saved rows a claim on this page rests on."""
cols = columns or (
"logz_rel_rms",
"logz_bias",
"logz_std",
"grad_rel_rms_max",
"pred_mean_rel_err",
"t_evidence_s",
"t_grad_s",
"passes_evidence",
"mem_evidence_mb",
)
return results.loc[list(ids), list(cols)]
print(
f"{len(results)} rows: N in {sorted(results.n.unique().tolist())}, device {results.device.iloc[0]}"
)
results.groupby(["likelihood", "kernel", "n"]).d_eff.first().dropna().round(
1
).to_frame()53 rows: N in [500, 2000, 8000], device cpu:x86_64
2. The decision table¶
What to use, filled from the saved rows. “Larger” means beyond the sizes measured here: on this CPU the dense solver gave the fastest evidence at every size up to , so the iterative rows are for a problem whose dense factor no longer fits in memory.
| Situation | Solver | Preconditioner | Log-determinant |
|---|---|---|---|
| (the largest measured), memory permitting | DenseSolver (the default) | none | dense |
| larger, Gaussian noise, smooth kernel | bbmm_solver for training (the cheapest gradient and memory), matfree_solver for single evidences | Nyström, rank | BBMM’s shared pass, or NystromLogdet |
| larger, non-Gaussian | the same, on LaplaceInference | Nyström, scaled per point by the presets; rank 200 gave 0.010 nats at and 0.47 to 0.78 nats at | the same |
| very rough kernel ( near ) | dense, or inducing points | none | dense |
| NUTS | dense, or a preset with a fixed key whose logz_std is well below one nat | as above | as above |
The rows behind each line, in order:
Dense is the fastest evidence at every size: 3.64 s at on the smooth kernel against 25.0 s for
matfreeand 40.7 s forbbmm, and its gradient (47.7 s) is level withbbmm’s (48.3 s) and half ofmatfree’s (88.7 s); the price is memory, 4.9 GB of temporaries for the dense gradient against 742 MB forbbmm(rowsgaussian-smooth-8000-dense,-matfree,-bbmm).On the smooth kernel
bbmmhas the cheaper gradient of the two presets at every size, and at every size the smaller gradient memory (113 MB against 1028 MB formatfreeat , rowsgaussian-smooth-2000-bbmm,-matfree), andmatfreethe cheaper evidence at (25.0 against 40.7 s).The rank: on the smooth kernel at , , and only rank 800 brings the evidence error from 1.3 to 0.18 nats (rows
gaussian-smooth-2000-dense,-matfree,-matfree-r800).Non-Gaussian: the Laplace evidence errors of the presets at are 0.010 to 0.011 nats on the smooth kernel and 0.47 to 0.78 nats on the rough one (rows
bernoulli-*-2000-matfree,-bbmm,bernoulli-*-2000-densefor ).Rough: of 2000 and 5572 of 8000, an evidence error of 6.6 to 9.9 nats for every preconditioned configuration at 2000 and 78 nats for
matfreeat 8000, which also takes 85.7 s against 3.8 s dense (rowsgaussian-rough-2000-*,gaussian-rough-8000-dense,-matfree).NUTS: see section 6.
cite(
"gaussian-smooth-8000-dense",
"gaussian-smooth-8000-matfree",
"gaussian-smooth-8000-bbmm",
"gaussian-smooth-2000-dense",
"gaussian-smooth-2000-matfree",
"gaussian-smooth-2000-bbmm",
"gaussian-smooth-2000-matfree-r800",
"bernoulli-smooth-2000-matfree",
"bernoulli-smooth-2000-bbmm",
"bernoulli-rough-2000-matfree",
"bernoulli-rough-2000-bbmm",
"gaussian-rough-2000-matfree",
"gaussian-rough-8000-dense",
"gaussian-rough-8000-matfree",
columns=(
"logz_rms",
"logz_std",
"t_evidence_s",
"t_grad_s",
"mem_grad_mb",
"passes_evidence",
),
)3. The Gaussian GP¶
The same Matérn-3/2 problem at , smooth kernel, run live: the dense reference, unpreconditioned CG and the two presets, each compiled once and then timed. The error columns compare the log marginal and the predictive mean and variance at 64 test points with the dense ones. These numbers illustrate the code; the claims below rest on the saved rows, which use three keys and more sizes.
N = 1000
NOISE_VAR = 0.01
X = jr.uniform(jr.key(0), (N, 2))
X_star = jr.uniform(jr.key(1), (64, 2))
f_true = jnp.sin(6.0 * X[:, 0]) + jnp.cos(4.0 * X[:, 1])
y = f_true + jnp.sqrt(NOISE_VAR) * jr.normal(jr.key(2), (N,))
labels = jr.bernoulli(jr.key(2), jax.nn.sigmoid(2.0 * f_true)).astype(X.dtype)
kernel = kl.Matern(nu=1.5, lengthscale=0.3, variance=1.0)
def compiled_and_timed(fn, *args, repeats=3):
"""Compile ``fn``, then return its output and the median time of a call."""
out = jax.block_until_ready(fn(*args))
times = []
for _ in range(repeats):
start = time.perf_counter()
jax.block_until_ready(fn(*args))
times.append(time.perf_counter() - start)
return out, float(np.median(times))
@eqx.filter_jit
def gaussian(solver, matrix_free):
prior = px.GPPrior(kernel, X, solver=solver, matrix_free=matrix_free)
log_marginal = prior.log_marginal(y, jnp.asarray(NOISE_VAR))
mean, var = prior.condition(y, jnp.asarray(NOISE_VAR)).predict(X_star)
return log_marginal, mean, var
live = {
"dense": (None, False),
"cg": (gx.CGSolver(rtol=1e-4, throw=False), True),
"matfree": (px.matfree_solver(rank=200, key=key, throw=False), True),
"bbmm": (px.bbmm_solver(rank=200, key=key, throw=False), True),
}
rows = {}
for name, (strategy, matrix_free) in live.items():
rows[name] = compiled_and_timed(gaussian, strategy, matrix_free)
(ref_logz, ref_mean, ref_var), _ = rows["dense"]
pd.DataFrame(
{
name: {
"log marginal": float(logz),
"error (nats)": float(logz - ref_logz),
"mean rel. error": float(
jnp.linalg.norm(mean - ref_mean) / jnp.linalg.norm(ref_mean)
),
"variance rel. error": float(
jnp.linalg.norm(var - ref_var) / jnp.linalg.norm(ref_var)
),
"time (s)": seconds,
}
for name, ((logz, mean, var), seconds) in rows.items()
}
).TThe saved rows extend this to and 8000 and to the rough kernel. Four things stand out.
Time. The dense evidence is the fastest at every size: 0.13 s at and 3.6 s at on the smooth kernel, against 1.7 s and 25.0 s for
matfreeand 2.0 s and 40.7 s forbbmm(rowsgaussian-smooth-2000-*,gaussian-smooth-8000-*). For the gradient the gap closes: at dense takes 47.7 s,bbmm48.3 s andmatfree88.7 s.Memory. XLA’s temporary allocation for the dense gradient grows from 275 MB at to 4.9 GB at , while
bbmmneeds 113 MB and 742 MB; thematfreegradient is the large one among the presets, 1.0 GB and 4.4 GB (same rows).Error. On the smooth kernel the presets’ RMS evidence error is 1.3 nats (
matfree) and 0.78 nats (bbmm) at over three keys, and 2.0 and 2.6 nats at with one key, a relative error of to . Unpreconditionedcgis at 26.7 nats on the same problem at , with 370 kernel passes against 55 formatfree(rowgaussian-smooth-2000-cg). The predictions are accurate everywhere: the relative error of the predictive mean is at most in every row (largest ingaussian-rough-2000-bbmm) and of the predictive variance at most (gaussian-smooth-2000-cg), so the evidence’s error comes from the log-determinant, not from the solves.The rough kernel. With of 2000 points, every iterative configuration is off by 6.6 to 22 nats at , and
bbmmneeds 431 kernel passes and 11.0 s per evidence (rowsgaussian-rough-2000-*); atmatfreeis 78 nats off and takes 85.7 s (rowgaussian-rough-8000-matfree).
def scaling_plot(likelihood):
_, axes = plt.subplots(1, 3, figsize=(18, 5))
for kernel_name, style in [("smooth", "-"), ("rough", "--")]:
part = results[
(results.likelihood == likelihood) & (results.kernel == kernel_name)
]
for i, config in enumerate(["dense", "cg", "cg-nystrom", "matfree", "bbmm"]):
rows = part[part.config == config].sort_values("n")
if rows.empty:
continue
label = f"{config} ({kernel_name})"
axes[0].loglog(
rows.n, rows.t_evidence_s, style, marker="o", color=f"C{i}", label=label
)
axes[1].loglog(
rows.n, rows.t_grad_s, style, marker="o", color=f"C{i}", label=label
)
if config != "dense":
axes[2].loglog(
rows.n,
rows.logz_rel_rms,
style,
marker="o",
color=f"C{i}",
label=label,
)
axes[0].set_title(
"one evidence (s)" if likelihood == "gaussian" else "one Laplace fit (s)"
)
axes[1].set_title("one evidence gradient (s)")
axes[2].set_title("relative RMS error of the evidence")
for ax in axes:
ax.set_xlabel("N")
axes[0].legend(fontsize=8, ncol=2)
plt.tight_layout()
plt.show()
scaling_plot("gaussian")
gauss_ids = [
f"gaussian-{k}-{n}-{c}"
for k in ("smooth", "rough")
for n in (500, 2000, 8000)
for c in ("dense", "cg", "cg-nystrom", "matfree", "bbmm", "matfree-fitc")
]
cite(
*[i for i in gauss_ids if i in results.index],
columns=(
"logz_rel_rms",
"logz_bias",
"logz_std",
"pred_mean_rel_err",
"pred_var_rel_err",
"t_evidence_s",
"t_grad_s",
"passes_evidence",
"mem_evidence_mb",
"mem_grad_mb",
),
)4. The Bernoulli Laplace fit¶
The Bernoulli labels on the same inputs, fitted by LaplaceInference. The strategy takes the solver from the prior, so the presets go on GPPrior as before; inside the fit is the vector of inverse site precisions, which the presets read from the system at every Newton step. The tolerance of the Newton loop is 10-3, ten times looser than the CG tolerance, as the LaplaceInference docstring asks for an iterative solver.
strategy = px.LaplaceInference(tol=1e-3)
@eqx.filter_jit
def laplace(solver, matrix_free):
prior = px.GPPrior(kernel, X, solver=solver, matrix_free=matrix_free)
fit = strategy.fit(prior, px.BernoulliLikelihood(), labels)
return fit.log_marginal_approx, fit.predict_mean(X_star), fit.n_iter
rows = {}
for name in ["dense", "matfree", "bbmm"]:
rows[name] = compiled_and_timed(laplace, *live[name])
(ref_logz, ref_mean, _), _ = rows["dense"]
pd.DataFrame(
{
name: {
"Laplace evidence": float(logz),
"error (nats)": float(logz - ref_logz),
"mean rel. error": float(
jnp.linalg.norm(mean - ref_mean) / jnp.linalg.norm(ref_mean)
),
"Newton steps": int(n_iter),
"time of the fit (s)": seconds,
}
for name, ((logz, mean, n_iter), seconds) in rows.items()
}
).TThe Laplace system is much better conditioned than the Gaussian one: a Bernoulli site has , so , against for the Gaussian noise. The effective dimension drops accordingly, to 26.8 on the smooth kernel and 220.6 on the rough one at (rows bernoulli-smooth-2000-dense, bernoulli-rough-2000-dense, against 355 and 1778 for the Gaussian rows), and the errors of the presets drop with it. On the smooth kernel the RMS error of the Laplace evidence at is 0.010 nats for matfree and 0.011 nats for bbmm, against 1.41 nats for unpreconditioned cg (rows bernoulli-smooth-2000-matfree, -bbmm, -cg); on the rough kernel the presets are at 0.78 and 0.47 nats and cg at 2.95 (rows bernoulli-rough-2000-*). The dense fit is still the fastest at this size: 1.06 s for the whole fit against 3.02 s and 2.59 s for the presets on the smooth kernel, and 0.87 s against 3.21 s and 2.87 s on the rough one. The gradient follows the same order, with bbmm the cheapest iterative one (3.87 s against 4.67 s dense on the smooth kernel), and the unpreconditioned cg gradient is the outlier, 60 % off in its lengthscale component on the smooth kernel (row bernoulli-smooth-2000-cg).
scaling_plot("bernoulli")
bern_ids = [
f"bernoulli-{k}-{n}-{c}"
for k in ("smooth", "rough")
for n in (500, 2000)
for c in ("dense", "cg", "cg-nystrom", "matfree", "bbmm", "matfree-fitc")
]
cite(
*[i for i in bern_ids if i in results.index],
columns=(
"logz_rel_rms",
"logz_bias",
"grad_rel_rms_max",
"pred_mean_rel_err",
"t_evidence_s",
"t_grad_s",
"passes_evidence",
"newton_iters",
"d_eff",
),
)
5. Gradients¶
Training or sampling needs the gradient of the evidence, with , whose log-determinant part is a Hutchinson estimate with one sample per probe, . A preconditioner changes where the probes come from but, on its own, leaves the variance of that sample; the control variate of gaussx#826 subtracts , whose mean is known, so the noise falls as approaches . gaussx v0.8.4 has no switch that turns the control variate off, so the benchmark gets “the preconditioner alone” from cg-nystrom-fixedP: the same Nyström preconditioner, built once at the evaluation point, has no gradient, so its control variate contributes none.
At on the smooth kernel (rows gaussian-smooth-2000-*), the relative RMS error of the three gradient components is 26 to 59 % without a preconditioner (cg, whose own SLQ uses 20 probes, against 50 for the others), 1.4 to 2.3 % with the preconditioner alone, 1.0 to 1.6 % with the preconditioner and the control variate, 0.45 to 0.76 % for bbmm and 0.84 to 1.3 % for matfree. The control variate therefore divides the error by 1.2 to 1.4 on this kernel. On the rough kernel (rows gaussian-rough-2000-*) the noise component dominates for every configuration, at 1.7 to 2.5 % for the four preconditioned ones and 6.1 % for cg; the control variate moves it from 1.69 to 1.67 %, and the lengthscale component from 0.30 to 0.20 %. The pattern measured at in the issue (4 % with or without the preconditioner, 0.1 to 0.3 % with the control variate) does not reappear here: at most of the gain comes from the preconditioned estimator itself.
grad_configs = ["cg", "cg-nystrom-fixedP", "cg-nystrom", "bbmm", "matfree"]
grad_labels = [
"no P",
"P alone",
"P + control variate",
"BBMM (P + CV)",
"matfree (Nyström logdet)",
]
hyper = ["lengthscale", "variance", "noise"]
fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharey=True)
for ax, kernel_name in zip(axes, ["smooth", "rough"]):
width = 0.15
for i, (config, label) in enumerate(zip(grad_configs, grad_labels)):
row = results.loc[f"gaussian-{kernel_name}-2000-{config}"]
values = [row[f"grad_rel_rms_{h}"] for h in hyper]
ax.bar(
np.arange(3) + (i - 2) * width, values, width, color=f"C{i}", label=label
)
ax.set_xticks(np.arange(3), [rf"$\partial / \partial \log$ {h}" for h in hyper])
ax.set_yscale("log")
ax.set_title(f"relative RMS error of the gradient, N = 2000, {kernel_name}")
fig.legend(*axes[0].get_legend_handles_labels(), loc="lower center", ncol=5, fontsize=9)
plt.tight_layout(rect=(0, 0.07, 1, 1))
plt.show()
cite(
*[f"gaussian-{k}-2000-{c}" for k in ("smooth", "rough") for c in grad_configs],
columns=(
"grad_rel_rms_lengthscale",
"grad_rel_rms_variance",
"grad_rel_rms_noise",
"t_grad_s",
"passes_grad",
),
)
The rank. The preconditioner’s rank has to cover the effective dimension. On the smooth kernel at , (row gaussian-smooth-2000-dense); rank 50, 200 and 800 give an RMS evidence error of 1.08, 1.30 and 0.18 nats and a largest gradient error of 1.6, 1.3 and 0.24 %, for 2.05, 1.71 and 3.95 s per evidence (rows gaussian-smooth-2000-matfree-r50, -matfree, -matfree-r800). Only the rank above moves the error. On the rough kernel of 2000 (row gaussian-rough-2000-dense), and no rank up to 800 helps (6.6, 6.7 and 8.2 nats, rows gaussian-rough-2000-matfree-r50, -matfree, -matfree-r800): that kernel is a case for the dense solver. The FITC preconditioner gives the same evidence as Nyström in matfree_solver, whose NystromLogdet builds its own sketch, and costs more CG steps (79 against 55 passes on the smooth kernel, 200 against 174 on the rough one, rows gaussian-*-2000-matfree-fitc).
The Lanczos order. A preconditioner lowers the variance of the evidence but not the bias of truncated Lanczos, which the Lanczos order sets. With the same probes, 60 steps instead of 30 leave the mean evidence unchanged on the smooth kernel (a difference of 0.0 nats) and move it by 0.94 nats on the rough one at (bias 2.99 against 3.93 nats, rows gaussian-rough-2000-matfree, -matfree-lanczos60), against a standard deviation over keys of 7.3 nats. The truncation bias exists on the rough kernel, but at this size the probe noise is about eight times larger.
cite(
*[
f"gaussian-{k}-2000-{c}"
for k in ("smooth", "rough")
for c in (
"matfree-r50",
"matfree",
"matfree-r800",
"matfree-fitc",
"matfree-lanczos60",
)
],
columns=(
"rank",
"logz_rel_rms",
"logz_bias",
"logz_std",
"logz_rms",
"grad_rel_rms_max",
"t_evidence_s",
"passes_evidence",
),
)6. Inside NUTS and SVI¶
A stochastic log-determinant makes the evidence a random function of the hyperparameters. With a fixed key the probes are the same at every call (common random numbers): the evidence is then a smooth, deterministic function, and an optimiser or a sampler sees a fixed approximation of the exact one. SVI and gradient-based fits want exactly that. NUTS also runs on it, but it samples the posterior of that fixed approximation, not the exact posterior, and a longer chain does not remove the difference. With a fresh key per call (gaussx.KeyedSolver(solver, key); the key is a pytree leaf, so it can change under jit without recompiling) the error is different at every call, which a stochastic-gradient method averages out but which breaks the detailed balance of a Metropolis or NUTS step.
The cell below evaluates the log marginal at 25 lengthscales on points with the matfree preset, once with one fixed key and once with a fresh key per lengthscale, against the dense curve.
X_small, y_small = X[:500], y[:500]
base = px.matfree_solver(rank=200, key=jr.key(0), throw=False)
@eqx.filter_jit
def evidence_at(log_lengthscale, solver, matrix_free):
k = kl.Matern(nu=1.5, lengthscale=jnp.exp(log_lengthscale), variance=1.0)
prior = px.GPPrior(k, X_small, solver=solver, matrix_free=matrix_free)
return prior.log_marginal(y_small, jnp.asarray(NOISE_VAR))
grid = jnp.log(jnp.linspace(0.15, 0.45, 25))
exact = np.array([evidence_at(g, None, False) for g in grid])
fixed = np.array([evidence_at(g, base, True) for g in grid])
fresh = np.array(
[evidence_at(g, gx.KeyedSolver(base, jr.key(i)), True) for i, g in enumerate(grid)]
)
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
lengthscales = np.exp(np.asarray(grid))
axes[0].plot(lengthscales, exact, "k--", label="dense")
axes[0].plot(
lengthscales, fixed, "C0", marker="o", ms=3, label="matfree, one fixed key"
)
axes[0].plot(
lengthscales, fresh, "C1", marker="o", ms=3, label="matfree, a fresh key per point"
)
axes[0].set_xlabel("lengthscale")
axes[0].set_title("log marginal, N = 500")
axes[0].legend()
axes[1].plot(lengthscales, fixed - exact, "C0", marker="o", ms=3, label="one fixed key")
axes[1].plot(
lengthscales, fresh - exact, "C1", marker="o", ms=3, label="a fresh key per point"
)
axes[1].axhline(0.0, color="k", lw=0.8)
axes[1].set_xlabel("lengthscale")
axes[1].set_title("error against dense (nats)")
axes[1].legend()
plt.tight_layout()
plt.show()
print(
f"fixed key: error spread {np.ptp(fixed - exact):.3f} nats; fresh keys: {np.ptp(fresh - exact):.3f} nats"
)
print(f"dense evidence range over the grid: {np.ptp(exact):.1f} nats")
fixed key: error spread 0.779 nats; fresh keys: 2.302 nats
dense evidence range over the grid: 195.7 nats
To see whether the noise matters, compare the spread of the error over keys with the differences of the evidence that the fit or the sampler has to resolve. Above, the dense evidence moves by many nats across the grid, while the fixed-key error is a smooth offset and the fresh-key error jumps from point to point. A NUTS step compares log densities that differ by about one nat, so an evidence whose standard deviation over keys (logz_std in the saved rows) is near one nat or more changes the answer. At it is 1.4 nats for matfree and 0.51 nats for bbmm on the smooth Gaussian problem and 7.3 and 8.0 nats on the rough one (rows gaussian-*-2000-matfree, gaussian-*-2000-bbmm), while the Bernoulli Laplace evidence on the smooth kernel is at 0.012 and 0.013 nats (rows bernoulli-smooth-2000-matfree, -bbmm). For NUTS, then, use the exact solver where it fits, and otherwise a fixed key with a rank high enough that logz_std is well below one nat, checked with a few keys as this benchmark does. Inside a NumPyro model a fixed key is the preset’s own key; a fresh key per step, for SVI, is a KeyedSolver around it:
import numpyro
import numpyro.distributions as dist
base = px.matfree_solver(rank=800, key=jr.key(0)) # fixed key: one fixed approximation
def model(X, y):
lengthscale = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
kernel = kl.Matern(nu=1.5, lengthscale=lengthscale)
# for SVI only: fresh probes at every step
solver = gx.KeyedSolver(base, numpyro.prng_key())
prior = px.GPPrior(kernel, X, solver=solver, matrix_free=True)
px.gp_factor("y", prior, y, jnp.asarray(0.01))7. When not to¶
Exact below a few thousand, and here up to 8000. On the measured CPU the dense solver gives the exact evidence faster than any iterative one at every size up to , and its gradient as fast as bbmm’s at 8000 (the rows printed below). Switch when the dense factor and its gradient no longer fit: their temporaries were 977 MB and 4.9 GB at (row gaussian-smooth-8000-dense) and grew 18-fold from to (rows gaussian-smooth-2000-dense, gaussian-smooth-8000-dense). No GPU was measured, since the VM has none.
Rough kernels. When is close to , no low-rank preconditioner captures , and the stochastic log-determinant stays several nats off at every rank tried (section 5). Use the dense solver while it fits; beyond, an approximation that does not need a low-rank to be accurate, such as inducing points (SparseGPPrior) or, on a time axis, a Markov GP (pyrox_ssm.MarkovGPPrior). Those were not part of this benchmark.
Sparse, Markov and structured kernels. A Markov GP on a 1-D time grid runs a Kalman filter in , and kernels with grid or Kronecker structure have exact structured solves in gaussx. This page measures only the unstructured exact GP, so it does not compare them.
cite(
*[
row
for k in ("smooth", "rough")
for n in (500, 2000, 8000)
for c in ("dense", "matfree", "bbmm")
if (row := f"gaussian-{k}-{n}-{c}") in results.index
],
columns=(
"t_evidence_s",
"t_grad_s",
"mem_evidence_mb",
"mem_grad_mb",
"logz_rel_rms",
),
)Summary¶
Up to on a CPU, keep the default
DenseSolver: it was the fastest evidence at every size and level withbbmmon the gradient at 8000 (rowsgaussian-smooth-8000-*).Beyond that, on a smooth kernel,
bbmm_solvergave the cheapest gradient and the least memory of the presets, andmatfree_solverthe cheaper single evidence; both are accurate to to relative at (rowsgaussian-smooth-8000-matfree,-bbmm).Set the rank from , not from : rank 800 at cut the evidence error from 1.3 to 0.18 nats, and no rank up to 800 helped at (rows
gaussian-*-2000-matfree-r800).The Laplace evidence of a Bernoulli GP is far easier, 0.010 nats with either preset at on the smooth kernel (rows
bernoulli-smooth-2000-*).Under NUTS, compare
logz_stdwith one nat before trusting a stochastic evidence; with a fixed key the chain targets a fixed approximation of the posterior.The defaults of the presets (rank 200, 50 probes, 30 or 100 Lanczos steps) are left as they are: no single rank was better across the problems measured, since the rank that works follows .