GP API¶
The full GP stack: kernel math functions, concrete Parameterized
kernel classes, model-facing entry points (GPPrior, ConditionedGP,
gp_factor, gp_sample), sparse variational GPs with inter-domain
inducing features, variational guides and likelihoods, non-Gaussian
inference strategies (Laplace, Gauss-Newton, EP, posterior
linearization, quasi-Newton), pathwise (Matheron)
posterior samplers, and multi-output kernels.
Scalable matrix construction and solver strategies (numerically stable
assembly, implicit operators, batched matvec,
Cholesky / CG / BBMM / LSMR / SLQ) live in
gaussx.
Temporal GPs on a 1-D time grid (the SDE kernels, MarkovGPPrior, the
Kalman-based non-Gaussian and sparse Markov strategies, the normalizing
Kalman filter) live in pyrox-ssm: see the SSM API.
Split with gaussx
pyrox owns the kernel function side — closed-form math primitives
readable in a dozen lines — plus the NumPyro-aware model shell
(GPPrior, gp_factor, gp_sample). gaussx owns every piece of
linear algebra: stable matrix construction, solver strategies, and
the underlying MultivariateNormal distribution. The model entry
points accept any gaussx.AbstractSolverStrategy (default
gaussx.DenseSolver()).
Model entry points¶
import jax.numpy as jnp
import numpyro
from pyrox_gp import GPPrior, RBF, gp_factor, gp_sample
def regression_model(X, y):
"""Collapsed Gaussian-likelihood GP regression."""
kernel = RBF()
prior = GPPrior(kernel=kernel, X=X)
gp_factor("obs", prior, y, noise_var=jnp.array(0.05))
def latent_model(X):
"""Latent-function GP for non-conjugate likelihoods."""
kernel = RBF()
prior = GPPrior(kernel=kernel, X=X)
f = gp_sample("f", prior)
# ... attach any likelihood to f here, e.g. Bernoulli or Poisson.
prior.log_marginal(y, noise_var) returns the collapsed log marginal likelihood that gp_factor registers, for use outside a NumPyro model (an optimiser's loss, a model comparison); MultiOutputGPPrior.log_marginal(Y, noise_var) is the same for mo_gp_factor, Kronecker-exact where the Gram allows, and OILMMGPPrior.log_marginal(Y, noise_var) is the same for oilmm_factor, exact at the projected cost under isotropic noise.
For a non-Gaussian likelihood, gp_laplace_factor(name, prior, likelihood, y) registers the Laplace approximate evidence instead, the log_marginal_approx of a LaplaceInference (or GaussNewtonInference) fit. The mode is implicitly differentiable, so NUTS or SVI can run over the kernel hyperparameters with the latent function marginalised, as pyrox_ssm.markov_laplace_factor does on a Markov prior.
The conditioned results (ConditionedGP, ConditionedMultiOutputGP, ConditionedOILMMGP) predict the latent function by default; predict(X_star, include_noise=True) adds the noise variance they were conditioned on, for a band on a new observation.
Swap the solver strategy at construction time:
from gaussx import CGSolver, ComposedSolver, DenseLogdet, DenseSolver
prior = GPPrior(kernel=RBF(), X=X, solver=CGSolver())
# Or compose — CG for solve, dense Cholesky for logdet:
prior = GPPrior(
kernel=RBF(), X=X,
solver=ComposedSolver(solve_strategy=CGSolver(), logdet_strategy=DenseLogdet()),
)
The solver, the preconditioner and the log-determinant are three separate fields of GPPrior (and of SparseGPPrior, MultiOutputGPPrior and OILMMGPPrior), so each can be changed on its own. GPPrior.solver_strategy() composes them with gaussx's compose_solver, and every quantity of the prior uses the result:
| Quantity | Solve | Log-determinant |
|---|---|---|
log_marginal, gp_factor, log_prob |
yes | yes |
condition, predict |
yes | no |
| pathwise sampling | yes | no |
import gaussx as gx
preconditioner = gx.NystromPreconditioner.lazy(rank=300, key=key)
# BBMM with a preconditioner, which its shared pass also uses for the log-determinant
prior = GPPrior(kernel, X, solver=gx.BBMMSolver(num_probes=50), preconditioner=preconditioner, matrix_free=True)
# CG with the preconditioner, plus a separate stochastic log-determinant
prior = GPPrior(kernel, X, solver=gx.CGSolver(rtol=1e-4), preconditioner=preconditioner, logdet=gx.SLQLogdet(num_probes=50), matrix_free=True)
preconditioner and logdet are keyword-only. A combination that cannot work, such as a preconditioner with the default DenseSolver, raises ValueError at construction, naming the three fields. A stochastic log-determinant without a key reuses its probes at every call, so NUTS then targets a fixed approximation of the posterior; gx.KeyedSolver binds a key per step.
For a large exact GP there are two presets, each one call that returns an ordinary gaussx strategy. matfree_solver is lineax conjugate gradients preconditioned by a low-rank approximation of \(K\) plus a log-determinant through matfree: logdet="nystrom" (the default) is gaussx's NystromLogdet, the exact log-determinant of a Nyström preconditioner plus stochastic Lanczos quadrature on the preconditioned remainder, and logdet="slq" is stochastic Lanczos quadrature on the system itself. The library matfree has no conjugate gradients of its own, so "matfree" means lineax CG plus the matfree-backed log-determinant. bbmm_solver is gaussx's BBMMSolver with the same preconditioner, whose one batched pass gives both the solve and the log-determinant from probes drawn from the preconditioner. Both read the diagonal from the system with gaussx's split_diagonal: the scalar noise of a matrix_free=True system, or a diagonal that varies by point, such as site variances or heteroscedastic noise, for which the preconditioner is built by gaussx's per-point shift. preconditioner="fitc" is gaussx's FITCPreconditioner, the Nyström approximation at rank training inputs drawn by the key plus the prior variance it misses on the diagonal, so that \(P\) matches \(A\) there; it reads the kernel part and the diagonal from the system, evaluating only the inducing blocks and the diagonal of a matrix_free=True prior. To choose the inducing inputs yourself, pass gaussx.FITCPreconditioner.from_kernel(...) as the prior's preconditioner. From gaussx v0.8.4 the gradient of BBMM's log-determinant, and of a gaussx.SLQLogdet given a preconditioner, carries \(P\) as a control variate (gaussx#826). preconditioned_cg_solver is a deprecated alias of matfree_solver with its old defaults, kept for one release; its shift= is used only for a system that is one dense matrix.
Which of these to pick for a given size and kernel, with the errors and times measured on both likelihoods, is the guide choosing the solver, preconditioner and log-determinant.
GPPrior
¶
Bases: Module
Finite-dimensional GP prior over a fixed training input set.
Holds a kernel, training inputs X, an optional mean function, the
three linear-algebra choices (a solver, a preconditioner and a
log-determinant), and a small diagonal jitter for numerical stability on
otherwise-singular prior covariances.
The three choices are separate fields, composed once by
solver_strategy with gaussx.compose_solver, and every quantity of
the prior uses the result. With the system
\(A = K + (\text{jitter} + \sigma^2) I\):
| Quantity | Solve | Log-determinant |
|---|---|---|
log_marginal, gp_factor, log_prob |
yes | yes |
condition, ConditionedGP.predict |
yes | no |
| pathwise sampling | yes | no |
solver with preconditioner sets the solves, and logdet (or
the solver's own) the determinant. None of the three set is
gaussx.DenseSolver, as before.
Attributes:
| Name | Type | Description |
|---|---|---|
kernel |
Kernel
|
Any |
X |
Float[Array, 'N D']
|
Training inputs of shape |
mean_fn |
Callable[[Float[Array, 'N D']], Float[Array, ' N']] | None
|
Callable |
solver |
AbstractSolverStrategy | None
|
Any |
preconditioner |
AbstractPreconditioner | None
|
Optional |
logdet |
AbstractLogdetStrategy | None
|
Optional |
jitter |
float
|
Diagonal regularization added to the prior covariance
for numerical stability. Not a noise model — use
|
matrix_free |
bool
|
If |
block_size |
int
|
Rows of |
Examples:
BBMM with a preconditioner, or CG with a separate stochastic log-determinant, on \(10^5\) stations:
import gaussx as gx
import jax.random as jr
import pyrox_gp as px
# X: (100_000, 2) station coordinates
preconditioner = gx.NystromPreconditioner.lazy(rank=300, key=jr.key(0))
prior = px.GPPrior(
px.Matern(nu=1.5),
X,
solver=gx.BBMMSolver(num_probes=50),
preconditioner=preconditioner,
matrix_free=True,
)
prior = px.GPPrior(
px.Matern(nu=1.5),
X,
solver=gx.CGSolver(rtol=1e-4),
preconditioner=preconditioner,
logdet=gx.SLQLogdet(num_probes=50),
matrix_free=True,
)
log_marginal = prior.log_marginal(y, noise_var)
mean, variance = prior.condition(y, noise_var).predict(X_star)
Exact GP regression on \(10^5\) stations, hyperparameters by SVI:
import jax.random as jr
import numpyro
import numpyro.distributions as dist
import pyrox_gp as px
# X: (100_000, 2) station coordinates, y: (100_000,) readings
solver = px.matfree_solver(rank=500, key=jr.key(0))
def model(X, y):
kernel = px.Matern(nu=1.5, init_lengthscale=0.1)
prior = px.GPPrior(kernel, X, solver=solver, matrix_free=True)
noise_var = numpyro.param(
"noise_var", 0.1, constraint=dist.constraints.positive
)
px.gp_factor("y", prior, y, noise_var)
# numpyro.infer.SVI(model, lambda X, y: None, optax.adam(1e-2),
# numpyro.infer.Trace_ELBO()).run(key, 500, X, y)
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | |
mean(X: Float[Array, 'N D']) -> Float[Array, ' N']
¶
Evaluate the mean function at X; zero by default.
solver_strategy() -> AbstractSolverStrategy
¶
The solver, preconditioner and logdet fields as one strategy.
Composed by gaussx.compose_solver: none of the three set is
gaussx.DenseSolver, and a solver alone is returned unchanged.
Returns:
| Type | Description |
|---|---|
AbstractSolverStrategy
|
The |
AbstractSolverStrategy
|
uses. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For a combination |
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
log_prob(f: Float[Array, ' N']) -> Float[Array, '']
¶
Marginal log-density of f under the GP prior.
Computes \(\log \mathcal{N}(f \mid \mu(X), K(X, X) + \text{jitter}\,I)\)
using gaussx.log_marginal_likelihood, so any solver strategy
on this prior applies.
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
sample(key: Array, *, method: Literal['cholesky', 'krylov'] = 'cholesky', lanczos_order: int = 100) -> Float[Array, ' N']
¶
Draw f \sim p(f) = \mathcal{N}(\mu(X), K + \text{jitter}\,I).
This is the non-NumPyro analogue of gp_sample — useful for tests,
diagnostics, and prior-sample initialization without registering a
sample site.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
PRNG key. |
required |
method
|
Literal['cholesky', 'krylov']
|
|
'cholesky'
|
lanczos_order
|
int
|
Lanczos steps of |
100
|
Returns:
| Type | Description |
|---|---|
Float[Array, ' N']
|
One draw of |
Raises:
| Type | Description |
|---|---|
ValueError
|
For an unknown |
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
log_marginal(y: Float[Array, ' N'], noise_var: Float[Array, '']) -> Float[Array, '']
¶
Collapsed log marginal likelihood \(\log p(y \mid X, \theta)\).
through gaussx.log_marginal_likelihood with this prior's solver,
the latent function integrated out. The prior's jitter is added
with the noise, so the covariance is the one condition builds.
gp_factor registers this value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, ' N']
|
Observations at the training inputs, shape |
required |
noise_var
|
Float[Array, '']
|
Observation noise variance \(\sigma^2\). |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar log marginal likelihood. |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import GPPrior, RBF
>>> X = jnp.linspace(0.0, 1.0, 8)[:, None]
>>> prior = GPPrior(RBF(init_lengthscale=0.3), X)
>>> log_marg = prior.log_marginal(jnp.sin(6.0 * X[:, 0]), jnp.asarray(0.05))
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
condition(y: Float[Array, ' N'], noise_var: Float[Array, '']) -> ConditionedGP
¶
Condition on Gaussian-likelihood observations y.
Precomputes
alpha = (K + (jitter + noise_var) * I)^{-1} (y - mu(X)) and
caches it in the returned ConditionedGP. The same
jitter regularization configured on this prior is included
alongside noise_var in the conditioned operator and solve, so
every downstream predict / sample call sees the regularized
covariance.
The operator construction and any subsequent hyperparameter
capture share one call_context, so for Pattern B/C
kernels with priors the cached operator and the resolved
hyperparameters on the returned ConditionedGP come from
the same draw. Downstream consumers (notably
pyrox_gp.PathwiseSampler) reuse those values to stay
consistent with the cached operator.
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
condition_nongauss(likelihood: Likelihood, y: Float[Array, ' N'], *, strategy: _NonGaussStrategy, key: Array | None = None) -> ConditionedNonGaussGP
¶
Condition on a non-Gaussian likelihood via a site-based strategy.
Convenience that forwards to strategy.fit(self, likelihood, y),
with key=key when a key is given: the PRNG key of a stochastic
log-determinant in the evidence (CG's SLQ, gaussx.BBMMSolver),
which every pyrox-gp strategy accepts (pyrox#551).
Pick any of the site-based strategies in
pyrox_gp._inference_nongauss:
pyrox_gp.LaplaceInference,
pyrox_gp.GaussNewtonInference,
pyrox_gp.PosteriorLinearization,
pyrox_gp.ExpectationPropagation, or
pyrox_gp.QuasiNewtonInference. Returns a
pyrox_gp.ConditionedNonGaussGP with the same
predict / predict_mean / predict_var API as the
Gaussian-likelihood ConditionedGP.
Examples:
from pyrox_gp import (
BernoulliLikelihood,
ExpectationPropagation,
GPPrior,
RBF,
)
prior = GPPrior(kernel=RBF(), X=X)
cond = prior.condition_nongauss(
BernoulliLikelihood(), y,
strategy=ExpectationPropagation(),
)
mean, var = cond.predict(X_star)
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
ConditionedGP
¶
Bases: Module
GP conditioned on Gaussian-likelihood training observations.
Holds the precomputed training solve alpha (via
gaussx.PredictionCache) and the noisy covariance operator so
predictions at multiple test sets reuse the training solve.
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 | |
predict_mean(X_star: Float[Array, 'M D']) -> Float[Array, ' M']
¶
\(\mu_* = \mu(X_*) + K_{*f}\,\alpha\).
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
predict_var(X_star: Float[Array, 'M D']) -> Float[Array, ' M']
¶
Diagonal predictive variance at X_*.
K_cross and K_diag are computed under one shared kernel
context so Pattern B / C kernels with prior'd hyperparameters
register their NumPyro sites once and reuse them across both
kernel calls (and the cached training solve).
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
predict(X_star: Float[Array, 'M D'], *, include_noise: bool = False) -> tuple[Float[Array, ' M'], Float[Array, ' M']]
¶
Return (mean, variance) at X_* as a tuple.
Both kernel evaluations share a single kernel context; see
predict_var.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_star
|
Float[Array, 'M D']
|
Test inputs, shape |
required |
include_noise
|
bool
|
Add the noise variance \(\sigma^2\) the posterior was conditioned on, giving the variance of a new observation rather than of the latent function. The jitter is not noise and is left out; the mean is unchanged. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, ' M'], Float[Array, ' M']]
|
The predictive mean and variance, each of shape |
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
sample(key: Array, X_star: Float[Array, 'M D'], n_samples: int = 1) -> Float[Array, 'S M']
¶
Sample from the diagonal predictive N(mean, diag(var)).
Returns samples independently per test point; correlated joint
samples from the full predictive covariance are not covered by
the Wave 2 dense surface. For correlated samples, build the full
predictive covariance explicitly and draw from
pyrox_gauss.MultivariateNormal.
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
predict_gradient(X_star: Float[Array, 'M D'], *, cov: Literal['marginal', 'full', 'none'] = 'marginal') -> GradientPosterior
¶
Gaussian posterior over the gradient \(\nabla f(x_*)\) at X_*.
Differentiation is linear, so \(\nabla f\) is jointly Gaussian with \(y\) and conditioning commutes with it (Solak et al. 2003; Rasmussen & Williams 2006, §9.4). With \(\hat K = K(X, X) + (\text{jitter} + \sigma^2) I\), \(\alpha = \hat K^{-1}(y - m(X))\) (the cached training solve) and the cross-covariance \(G(x_*) = \partial_1 K(x_*, X) \in \mathbb{R}^{D \times N}\), \(G_{dn} = \partial k(x_*, x_n) / \partial x_{*,d}\):
which equals \(\nabla_{x_*} \mu_*(x_*)\) exactly (Johnson et al. 2020, §3, with a mean function), and
With the cached factor \(\hat K = L L^\top\) the downdate is
\(V^\top V\), \(V = L^{-1} G^\top\) (triangular solves only); without
one (matrix_free=True / iterative solvers) it is
\(G\,\hat K^{-1} G^\top\) through the prior's solver. The
covariance is symmetrised but not clipped, like predict_var.
k = freeze(kernel) # same draw as the call
G = [Derivative(k, dx=d)(X*, X) for d] # (D*M, N), rows (d m)
mean = rearrange(G @ alpha, "(d m) -> m d") + grad m(X*)
P, Q = whitened_cross(cache, G, G) # G K^-1 G^T = P^T Q
marginal: H_m = d1 d2 k(x_m, x_m) # (M, D, D)
cov = H_m - P_m^T Q_m
full: H = DerivativeIndexed(k)(Xt, Xt) # (D*M, D*M)
cov = rearrange(H - P^T Q, "(i a) (j b) -> a i b j")
The hyperparameters are read once, under one kernel context, so a
kernel with priors registers each site once per call (here
RBF.variance / RBF.lengthscale for pyrox_gp.RBF); the
cached \(\alpha\) comes from the draw taken in GPPrior.condition.
References: Johnson, Laparra, Pérez-Suay, Mahecha & Camps-Valls (2020), PLOS ONE 15(10): e0235885, doi:10.1371/journal.pone.0235885; Solak et al. (2003), NeurIPS 15; Rasmussen & Williams (2006), §9.4.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_star
|
Float[Array, 'M D']
|
Test inputs, shape |
required |
cov
|
Literal['marginal', 'full', 'none']
|
|
'marginal'
|
Returns:
| Type | Description |
|---|---|
GradientPosterior
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
For an unknown |
TypeError
|
For a Gram-only kernellib kernel. |
NotImplementedError
|
For a |
Examples:
Sensitivity map with error bars (Johnson et al. 2020):
import jax.numpy as jnp
import pyrox_gp as px
# X: (N, 2), y: (N,)
cond = px.GPPrior(px.RBF(init_lengthscale=0.5), X).condition(
y, jnp.array(0.01)
)
post = cond.predict_gradient(X_star) # X_star: (M, 2)
post.mean # (M, 2) E[grad f]
post.cov # (M, 2, 2) Cov[grad f] per point
sensitivity = jnp.sqrt(jnp.sum(post.mean**2, axis=-1)) # (M,)
joint = cond.predict_gradient(X_star, cov="full").cov # (M, 2, M, 2)
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 | |
predict_var_gradient(X_star: Float[Array, 'M D']) -> Float[Array, 'M D']
¶
Gradient of the predictive variance, \(\nabla_x \sigma^2_*(x)\).
The acquisition gradient for variance-reduction / uncertainty-sampling active learning. From \(\sigma^2_*(x) = k(x, x) - k(x, X)\,\hat K^{-1} k(X, x)\),
with \(G(x) = \partial_1 K(x, X)\) as in predict_gradient. The first
term vanishes for a stationary kernel. With the cached factor the
second term is \(-2\,(L^{-1} G^\top)^\top (L^{-1} k(X, x))\); it
equals jax.grad of predict_var but reuses the training solve.
The latent variance is differentiated (no observation noise), as in
predict_var.
k = freeze(kernel)
G = d1 K(X*, X) # (D*M, N)
P, Q = whitened_cross(cache, G, K(X*, X))
grad var[m] = grad_x k(x, x)|x_m - 2 P_m^T Q[:, m]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_star
|
Float[Array, 'M D']
|
Test inputs, shape |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'M D']
|
\(\nabla_x \sigma^2_*\) at each test point, shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
For a kernel whose GP is not mean-square
differentiable (see |
NotImplementedError
|
For a |
Examples:
# One gradient-ascent step on the predictive variance
# (uncertainty sampling), X_cand: (M, D)
X_next = X_cand + 0.1 * cond.predict_var_gradient(X_cand)
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
predict_mean_hessian(X_star: Float[Array, 'M D']) -> Float[Array, 'M D D']
¶
Hessian of the predictive mean, \(\nabla \nabla^\top \mu_*(x)\).
by forward-over-reverse autodiff (jax.hessian) of
\(x \mapsto m(x) + k(x, X)\,\alpha\) with the frozen kernel and the
cached \(\alpha\), \(O(N D^2)\) per point. It needs \(k \in C^2\) in its
first argument: fine for pyrox_gp.RBF,
pyrox_gp.RationalQuadratic and Matern(nu=2.5); with
Matern(nu=1.5) it is only defined away from the training
inputs (the Hessian jumps at \(x = x_n\)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_star
|
Float[Array, 'M D']
|
Test inputs, shape |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'M D D']
|
The symmetric |
Raises:
| Type | Description |
|---|---|
ValueError
|
For a kernel whose GP is not mean-square
differentiable (see |
NotImplementedError
|
For a |
Examples:
hess = cond.predict_mean_hessian(X_star) # (M, D, D)
curvature = jnp.trace(hess, axis1=-2, axis2=-1) # Laplacian of mu
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
gp_factor(name: str, prior: GPPrior, y: Float[Array, ' N'], noise_var: Float[Array, '']) -> None
¶
Register the collapsed GP log marginal likelihood with NumPyro.
Adds
log p(y | X, theta) = log N(y | mu, K + (jitter + sigma^2) I)
to the NumPyro trace as numpyro.factor(name, ...). The prior's
jitter is included in addition to the observation noise variance
so the covariance matches what GPPrior.condition builds. Use
this inside a NumPyro model when the likelihood is Gaussian and you
want the latent function marginalized analytically. The value is
GPPrior.log_marginal.
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
gp_laplace_factor(name: str, prior: GPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, strategy: LaplaceInference | GaussNewtonInference | None = None, key: Array | None = None) -> None
¶
Register the Laplace approximate GP evidence with NumPyro.
Adds numpyro.factor(name, strategy.fit(prior, likelihood, y)
.log_marginal_approx), the non-Gaussian analogue of gp_factor: the
latent function is marginalised by the Laplace approximation at the
mode \(\hat f\),
with \(\Lambda\) the site precisions. The Newton loop is
argminax.solve.laplace_mode_covariance with an implicitly
differentiable mode, so the factor traces under NUTS and its gradient in
the kernel hyperparameters \(\theta\) flows through \(\hat f\) without
unrolling the loop. Registers the one factor site name, plus the
kernel's hyperparameter sites, drawn once.
The value is that of a fit that may not have converged; check
strategy.fit(...).converged at the hyperparameters you care about.
The strategy's solver, preconditioner and logdet (or the
prior's) apply, so a matrix-free prior with an iterative solver never
forms the kernel matrix (pyrox#551); with a stochastic log-determinant
the factor is an estimate, and a fixed key makes NUTS target a fixed
approximation of the posterior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
prior
|
GPPrior
|
The |
required |
likelihood
|
Likelihood
|
A scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations, shape |
required |
strategy
|
LaplaceInference | GaussNewtonInference | None
|
|
None
|
key
|
Array | None
|
PRNG key of a stochastic log-determinant in the evidence,
passed to |
None
|
Examples:
>>> import jax.numpy as jnp
>>> import numpyro.distributions as dist
>>> from numpyro import handlers
>>> from pyrox_gp import RBF, BernoulliLikelihood, GPPrior, gp_laplace_factor
>>> X = jnp.linspace(-2.0, 2.0, 10)[:, None]
>>> y = (X[:, 0] > 0.0).astype(X.dtype)
>>> kernel = RBF()
>>> kernel.set_prior("lengthscale", dist.LogNormal(0.0, 0.5))
>>> prior = GPPrior(kernel=kernel, X=X)
>>> def model():
... gp_laplace_factor("y", prior, BernoulliLikelihood(), y)
>>> trace = handlers.trace(handlers.seed(model, 0)).get_trace()
>>> sorted(trace)
['RBF.lengthscale', 'RBF.variance', 'y']
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 | |
gp_sample(name: str, prior: GPPrior, *, whitened: bool = False, guide: object | None = None, method: Literal['cholesky', 'krylov'] = 'cholesky', lanczos_order: int = 100) -> Float[Array, ' N']
¶
Sample a latent function f at the prior's training inputs.
Three mutually exclusive modes:
whitened=False,guide=None(default) — register a singlenumpyro.sample(name, MVN(mu, K + jitter I))site. The latent function is sampled directly from the prior.whitened=True,guide=None— register a unit-normal latent sitef"{name}_u"with shape(N,)and return the deterministic valuef = mu(X) + L uwhereLis the Cholesky factor ofK + jitter I. This reparameterization is the standard fix for mean-field SVI on GP-correlated latents (Murray & Adams, 2010): a NumPyro auto-guide such asnumpyro.infer.autoguide.AutoNormalthen approximates the well-conditioned isotropic posterior overuinstead of the ill-conditioned correlated posterior overf.guideprovided — delegate toguide.register(name, prior). Concrete variational guides (Wave 3) own their own parameterization, so combiningwhitened=Truewithguideis rejected.
Use this inside a NumPyro model for non-conjugate likelihoods, where the latent function cannot be marginalized analytically.
The Cholesky factor of the whitened mode needs the dense kernel
matrix, so whitened=True raises on a matrix-free prior unless
method="krylov", which uses the symmetric root
f = mu(X) + (K + jitter I)^{1/2} u applied by Lanczos
(lanczos_order steps, see GPPrior.sample). The prior over f
is the same, but the posterior over u is rotated relative to the
Cholesky form, and a mean-field guide is not invariant under that
rotation, so a fitted variational posterior differs between the two
methods. method applies to whitened=True only.
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 | |
matfree_solver(*, rank: int = 200, preconditioner: Literal['nystrom', 'rpcholesky', 'fitc'] = 'nystrom', logdet: Literal['nystrom', 'slq'] = 'nystrom', num_probes: int = 50, lanczos_order: int = 30, rtol: float = 0.0001, atol: float | None = None, max_steps: int = 1000, throw: bool = True, key: jax.Array) -> gx.AbstractSolverStrategy
¶
CG and a matfree-backed log-determinant, preconditioned (pyrox#557).
The solve is lineax conjugate gradients, preconditioned by a rank-rank
approximation of the kernel part \(K\) of the system
\(A = K + \mathrm{diag}(d)\), rebuilt from the system at every solve so it
follows the hyperparameters and, in a non-Gaussian fit, the site
variances \(d\). The log-determinant is stochastic Lanczos quadrature
through matfree. The library matfree 0.6.2 has no conjugate gradients,
so "matfree" here means lineax CG plus gaussx's matfree-backed
log-determinant.
The preconditioner reads the system with gaussx.split_diagonal: the
scalar noise of GPPrior(..., matrix_free=True) exactly, or a
per-point \(d\) by gaussx's symmetric scaling. A system that is one dense
matrix does not split, and raises at solve time. Building it costs
\(O(N R^2)\) plus \(R\) kernel matvecs, at every solve; reusing a sketch
across Newton steps is not implemented. Errors, times and memory against
the dense solver, up to \(N = 8000\), are in
the solver guide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rank
|
int
|
Rank \(R\) of the preconditioner (and of the Nyström log-determinant). 200 is a starting point; the rank that lowers the error follows the effective dimension of the system, not \(N\) (see the solver guide). |
200
|
preconditioner
|
Literal['nystrom', 'rpcholesky', 'fitc']
|
|
'nystrom'
|
logdet
|
Literal['nystrom', 'slq']
|
|
'nystrom'
|
num_probes
|
int
|
Probe vectors \(N_\text{probe}\) of the SLQ. |
50
|
lanczos_order
|
int
|
Lanczos steps per probe. |
30
|
rtol
|
float
|
CG relative tolerance. |
0.0001
|
atol
|
float | None
|
CG absolute tolerance; |
None
|
max_steps
|
int
|
CG iteration cap. |
1000
|
throw
|
bool
|
Raise when CG does not converge within |
True
|
key
|
Array
|
PRNG key of the preconditioner's sketch and of the Nyström log-determinant's sketch and probes, so the strategy is a fixed, reproducible function of the hyperparameters. Inside NUTS a fixed key means the sampler targets a fixed approximation of the posterior (pyrox#550). |
required |
Returns:
| Type | Description |
|---|---|
AbstractSolverStrategy
|
One ordinary |
AbstractSolverStrategy
|
for |
AbstractSolverStrategy
|
|
AbstractSolverStrategy
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
For an unknown |
Examples:
import jax.random as jr
import pyrox_gp as px
# X: (100_000, 2); K is never formed
solver = px.matfree_solver(rank=300, key=jr.key(0))
prior = px.GPPrior(px.Matern(nu=1.5), X, solver=solver, matrix_free=True)
log_marginal = prior.log_marginal(y, noise_var)
References
Frangella, Z., Tropp, J. A. & Udell, M. (2023). Randomized Nyström preconditioning. SIAM J. Matrix Anal. Appl. 44(2), 718–752.
Ubaru, S., Chen, J. & Saad, Y. (2017). Fast estimation of tr(f(A)) via stochastic Lanczos quadrature. SIAM J. Matrix Anal. Appl. 38(4), 1075–1099.
Source code in packages/pyrox-gp/src/pyrox_gp/_solvers.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
bbmm_solver(*, rank: int = 200, preconditioner: Literal['nystrom', 'rpcholesky', 'fitc'] = 'nystrom', num_probes: int = 50, lanczos_order: int = 100, rtol: float = 0.0001, max_steps: int = 1000, throw: bool = True, key: jax.Array) -> gx.AbstractSolverStrategy
¶
BBMM with a low-rank preconditioner (pyrox#557).
gaussx.BBMMSolver with a rank-rank preconditioner of the kind
matfree_solver takes (Nyström by default in both): gaussx's lazy
gaussx.NystromPreconditioner or gaussx.PartialCholeskyPreconditioner,
rebuilt from \(A = K + \mathrm{diag}(d)\) at every solve by symmetric
scaling, so its \(P\) is at the scale of \(A\). The solve is CG with
\(P^{-1}\), and the log-determinant comes from one modified batched CG
pass over the right-hand side and probes \(z^{(i)} \sim \mathcal{N}(0, P)\)
drawn from \(P\) itself, so only the near-identity remainder
\(\log \det(P^{-1/2} A P^{-1/2})\) is estimated. A system that is one
dense matrix does not split, and raises at solve time. The probes run to
convergence, not to lanczos_order steps, so the pass can cost more
matvecs than a separate solve and SLQ; errors, times and memory against
the dense solver are in
the solver guide.
The gradient of the log-determinant carries \(P\) as a control variate
(gaussx#826, from gaussx v0.8.4), so its probe noise falls as \(P\)
approaches \(A\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rank
|
int
|
Rank \(R\) of the preconditioner; 200 is a starting point, and the rank that lowers the error follows the effective dimension of the system (see the solver guide). |
200
|
preconditioner
|
Literal['nystrom', 'rpcholesky', 'fitc']
|
|
'nystrom'
|
num_probes
|
int
|
Probe vectors \(N_\text{probe}\). |
50
|
lanczos_order
|
int
|
Lanczos order of the quadrature. |
100
|
rtol
|
float
|
CG relative tolerance. |
0.0001
|
max_steps
|
int
|
CG iteration cap. |
1000
|
throw
|
bool
|
Raise when CG does not converge within |
True
|
key
|
Array
|
PRNG key, split into the preconditioner's sketch and the probes
(bound with |
required |
Returns:
| Type | Description |
|---|---|
AbstractSolverStrategy
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
For an unknown |
Examples:
import jax.random as jr
import pyrox_gp as px
solver = px.bbmm_solver(rank=300, key=jr.key(0))
prior = px.GPPrior(px.Matern(nu=1.5), X, solver=solver, matrix_free=True)
log_marginal = prior.log_marginal(y, noise_var)
References
Gardner, J. R., Pleiss, G., Weinberger, K. Q., Bindel, D. & Wilson, A. G. (2018). GPyTorch: blackbox matrix-matrix Gaussian process inference with GPU acceleration. NeurIPS, arXiv:1809.11165.
Wenger, J., Pleiss, G., Hennig, P., Cunningham, J. P. & Gardner, J. R. (2022). Preconditioning for scalable Gaussian process hyperparameter optimization. ICML, PMLR 162, 23751–23780.
Source code in packages/pyrox-gp/src/pyrox_gp/_solvers.py
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | |
preconditioned_cg_solver(*, shift: float | None = None, preconditioner: Literal['nystrom', 'rpcholesky'] = 'nystrom', rank: int = 200, logdet: Literal['slq', 'nystrom'] = 'slq', key: jax.Array, rtol: float = 1e-06, atol: float = 1e-06, max_steps: int = 1000, num_probes: int = 20, lanczos_order: int = 30) -> gx.AbstractSolverStrategy
¶
Deprecated alias of matfree_solver, with its old arguments and defaults.
Kept for one release (pyrox#557). It builds exactly the strategy it
built before, which is matfree_solver with these defaults, plus
shift: a lower bound on the noise variance, used only for a system
that is one dense matrix. On a sum \(K + \mathrm{diag}(d)\) the diagonal
is read from the system, and a shift passed anyway is ignored with
a warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shift
|
float | None
|
Lower bound \(\mu\) on the noise variance, for a dense system. |
None
|
preconditioner
|
Literal['nystrom', 'rpcholesky']
|
As in |
'nystrom'
|
rank
|
int
|
As in |
200
|
logdet
|
Literal['slq', 'nystrom']
|
As in |
'slq'
|
key
|
Array
|
As in |
required |
rtol
|
float
|
CG relative tolerance. |
1e-06
|
atol
|
float
|
CG absolute tolerance. |
1e-06
|
max_steps
|
int
|
CG iteration cap. |
1000
|
num_probes
|
int
|
SLQ probe vectors. |
20
|
lanczos_order
|
int
|
SLQ Lanczos steps per probe. |
30
|
Returns:
| Type | Description |
|---|---|
AbstractSolverStrategy
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
For a non-positive |
Examples:
import jax.random as jr
import pyrox_gp as px
# before: px.preconditioned_cg_solver(rank=500, key=jr.key(0))
solver = px.matfree_solver(rank=500, logdet="slq", key=jr.key(0))
Source code in packages/pyrox-gp/src/pyrox_gp/_solvers.py
Derivatives¶
The gradient of a GP is a GP, so a ConditionedGP also gives the exact
Gaussian posterior over \(\nabla f(x_*)\), reusing the cached training solve
(no re-solve). With \(\hat K = K(X, X) + (\text{jitter} + \sigma^2) I\),
\(\alpha = \hat K^{-1}(y - m(X))\) and
\(G(x_*) = \partial_1 K(x_*, X) \in \mathbb{R}^{D \times N}\):
The mean is the derivative of the predictive mean used for sensitivity maps
by Johnson et al. (2020, §3); the covariance follows from the joint Gaussian
of values and derivatives (Solak et al. 2003; Rasmussen & Williams 2006,
§9.4). The derivative cross-covariances are kernellib's Derivative /
DerivativeIndexed kernels; the solves go through gaussx (triangular solves
with the cached Cholesky factor, or the prior's solver on the matrix-free
operator).
k = freeze(kernel) # one draw per call
G = [Derivative(k, dx=d)(X*, X) for d] # (D*M, N), kind-major rows
mean = (G @ alpha) as (M, D) + grad m(X*)
G K^-1 G^T = P^T Q # P = Q = L^-1 G^T with a factor
cov = H - P^T Q # marginal: (M, D, D) blocks only
predict_gradient(X_star, cov=...)returns aGradientPosterior(mean,cov);cov="marginal"(default) gives the per-point(M, D, D)blocks,"full"the joint(M, D, M, D),"none"skips the covariance.predict_var_gradient(X_star)gives \(\nabla_x \sigma^2_*(x)\), the acquisition gradient for uncertainty sampling.predict_mean_hessian(X_star)gives \(\nabla \nabla^\top \mu_*(x)\),(M, D, D).
Layout. Internally the derivative rows are kind-major, as
kernellib.derivative_inputs(X_star, values=False) builds them: row
d * M + m is \(\partial_d f(x_{*,m})\). The outputs are point-major:
mean[m, d], cov[m, i, j] (marginal) and cov[a, i, b, j] (full).
Flatten the joint with einx.id("a i b j -> (a i) (b j)", cov).
import jax.numpy as jnp
import pyrox_gp as px
cond = px.GPPrior(px.RBF(init_lengthscale=0.5), X).condition(y, jnp.array(0.01))
post = cond.predict_gradient(X_star) # X_star: (M, D)
sensitivity = jnp.sqrt(jnp.sum(post.mean**2, axis=-1)) # (M,) |E grad f|
std = jnp.sqrt(jnp.diagonal(post.cov, axis1=-2, axis2=-1)) # (M, D)
step = cond.predict_var_gradient(X_star) # (M, D) uncertainty ascent
The kernel must be mean-square differentiable (RBF, RationalQuadratic,
Matern(nu >= 1.5), Periodic); Matern(nu=0.5) raises kernellib's
ValueError. predict_mean_hessian with Matern(nu=1.5) is defined only
away from the training inputs.
References: Johnson, Laparra, Pérez-Suay, Mahecha & Camps-Valls (2020), Kernel methods and their derivatives: Concept and perspectives for the earth system sciences, PLOS ONE 15(10): e0235885, doi:10.1371/journal.pone.0235885; Solak, Murray-Smith, Leithead, Leith & Rasmussen (2003), Derivative observations in Gaussian process models of dynamic systems, NeurIPS 15; Rasmussen & Williams (2006), Gaussian Processes for Machine Learning, §9.4.
GradientPosterior
¶
Bases: NamedTuple
Gaussian posterior over \(\nabla f\) at \(M\) test points (point-major).
Returned by ConditionedGP.predict_gradient. A NamedTuple, so it is
a pytree and passes through jit / vmap.
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
Float[Array, 'M D']
|
\(\mathbb{E}[\nabla f(x_{*,m}) \mid y]\), shape |
cov |
Float[Array, 'M D D'] | Float[Array, 'M D M D'] | None
|
The posterior covariance of the gradient, or |
Examples:
post = cond.predict_gradient(X_star) # X_star: (M, D)
post.mean.shape # (M, D)
post.cov.shape # (M, D, D)
Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
Concrete kernels¶
Each Parameterized kernel registers its hyperparameters with positivity
constraints where appropriate. Attach priors with set_prior, autoguides
with autoguide, and flip set_mode("model" | "guide").
RBF
¶
Bases: _ParameterizedKernel
Radial basis function (squared exponential) kernel.
input_dim: set to the input dimension D to fit a separate
lengthscale per input dimension (ARD). Leave as None for a single
isotropic lengthscale.
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
Matern
¶
Bases: _ParameterizedKernel
Matern kernel with nu in {0.5, 1.5, 2.5}.
nu is a static class attribute — it selects a code path in the
underlying math primitive and is not a trainable parameter.
input_dim: set to the input dimension D to fit a separate
lengthscale per input dimension (ARD). Leave as None for a single
isotropic lengthscale.
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
Periodic
¶
Bases: _ParameterizedKernel
Periodic (MacKay) kernel.
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
Linear
¶
Bases: _ParameterizedKernel
Linear kernel sigma^2 x^T x' + bias.
bias is constrained nonnegative because k = sigma^2 X X^T + b 1 1^T
is only PSD for b >= 0 (e.g. X = 0 gives eigenvalue N*b).
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
RationalQuadratic
¶
Bases: _ParameterizedKernel
Rational quadratic kernel.
input_dim: set to the input dimension D to fit a separate
lengthscale per input dimension (ARD). Leave as None for a single
isotropic lengthscale.
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
Polynomial
¶
Bases: _ParameterizedKernel
Polynomial kernel sigma^2 (x^T x' + bias)^degree.
degree is a static class field (it selects an integer power, not
an optimization target). bias is constrained nonnegative — the
degree=1 case reduces to Linear and has the same
PSD-requires-b>=0 failure mode.
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
Cosine
¶
Bases: _ParameterizedKernel
Cosine kernel sigma^2 cos(2 pi ||x - x'|| / period).
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
White
¶
Bases: _ParameterizedKernel
White-noise kernel sigma^2 delta(x, x').
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
Constant
¶
Bases: _ParameterizedKernel
Constant kernel k(x, x') = sigma^2.
Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
Inducing-point initialisation¶
Pick Z as a subset of the training inputs. "rpcholesky" (the default)
targets the trace error that bounds the SVGP ELBO gap (Burt et al. 2020),
so clusters of rare points still get inducing points.
from pyrox_gp import RBF, SparseGPPrior, init_inducing
kernel = RBF(init_lengthscale=0.3)
Z = init_inducing(X, 64, kernel=kernel, key=jax.random.key(0))
prior = SparseGPPrior(kernel=kernel, Z=Z)
init_inducing(X: Float[Array, 'N D'], n_inducing: int, *, kernel: Kernel | None, method: Literal['uniform', 'rpcholesky', 'greedy', 'leverage'] = 'rpcholesky', key: PRNGKeyArray) -> Float[Array, 'M D']
¶
Inducing inputs (M, D): rows of X picked by kernellib.select_landmarks.
The selection runs once, on kernel frozen at its current
hyperparameters (Kernel.frozen). If they move a long way during
training, call it again with the fitted kernel and refit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Float[Array, 'N D']
|
Training inputs. |
required |
n_inducing
|
int
|
Number of inducing inputs |
required |
kernel
|
Kernel | None
|
The GP's kernel; required by keyword. |
required |
method
|
Literal['uniform', 'rpcholesky', 'greedy', 'leverage']
|
|
'rpcholesky'
|
key
|
PRNGKeyArray
|
PRNG key (unused by |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'M D']
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
import jax.random as jr
import pyrox_gp as px
kernel = px.RBF(init_lengthscale=0.3)
Z = px.init_inducing(X, 64, kernel=kernel, key=jr.key(0))
prior = px.SparseGPPrior(kernel, Z=Z)
# after fitting, if the lengthscale moved a lot:
# Z = px.init_inducing(X, 64, kernel=fitted_kernel, key=jr.key(1))
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing_init.py
Sparse-GP inducing features (#49)¶
Inter-domain inducing-feature families used to build scalable sparse GPs
where the inducing-prior covariance K_uu becomes diagonal. Pass any
of these to SparseGPPrior via the inducing= keyword in
place of a raw point matrix Z.
from pyrox_gp import RBF, FourierInducingFeatures, SparseGPPrior
kernel = RBF(init_lengthscale=0.3, init_variance=1.0)
features = FourierInducingFeatures.init(in_features=1, num_basis_per_dim=64, L=5.0)
prior = SparseGPPrior(kernel=kernel, inducing=features) # K_uu is diagonal!
InducingFeatures
¶
Bases: Protocol
Protocol for inter-domain inducing features.
Implementations expose the inducing-prior covariance K_uu and the
cross-covariance k_ux(X) between data points and inducing
features. Diagonal-friendly concretions return
lineax.DiagonalLinearOperator so the downstream solve dispatches
to elementwise division.
Input shape is family-dependent. k_ux takes a batch of data
points X in whatever representation the family consumes:
FourierInducingFeatures: coordinates(N, D).SphericalHarmonicInducingFeatures: unit vectors(N, 3).LaplacianInducingFeatures: integer node indices(N,).
Each implementation validates its own expected shape and dtype.
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
FourierInducingFeatures
¶
Bases: Module
VFF — Variational Fourier inducing features on \([-L, L]^D\).
For a stationary kernel with spectral density \(S(\cdot)\), the basis \(\{\phi_j\}\) of Laplacian eigenfunctions on the box gives
With this convention \(K_{ux} K_{uu}^{-1} = \phi_j(x)\), so the
SVGP predictive mean reduces to a basis evaluation. K_{uu} is
returned as a lineax.DiagonalLinearOperator to preserve the
O(M) solve dispatch end-to-end.
Attributes:
| Name | Type | Description |
|---|---|---|
in_features |
int
|
Input dimension \(D\). |
num_basis_per_dim |
tuple[int, ...]
|
Per-axis number of 1D eigenfunctions; total
count is |
L |
tuple[float, ...]
|
Per-axis box half-width. |
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
K_uu(kernel: Kernel, *, jitter: float = 1e-06) -> lx.DiagonalLinearOperator
¶
Diagonal \(K_{uu}\) — entries S(sqrt(lambda_j)) plus jitter.
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
k_ux(x: Float[Array, 'N D'], kernel: Kernel) -> Float[Array, 'N M']
¶
Cross-covariance entries \(S(\sqrt{\lambda_j})\,\phi_j(x)\).
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
SphericalHarmonicInducingFeatures
¶
Bases: Module
VISH — inducing harmonics on \(S^2\) (Dutordoir et al. 2020).
For any zonal kernel \(k(x, x') = \kappa(x \cdot x')\) on the unit 2-sphere, the Funk-Hecke theorem gives a diagonal \(K_{uu}\) whose eigenvalues are the kernel's Funk-Hecke coefficients \(a_l\). The cross-covariance is \(a_l\,Y_{lm}(x)\).
Funk-Hecke coefficients are computed by Gauss-Legendre quadrature (arbitrary kernels supported, no closed form required). For kernels that have a closed-form Funk-Hecke series (RBF on S² via Bessel functions etc.), the numerical and analytic answers should agree to the quadrature tolerance.
Attributes:
| Name | Type | Description |
|---|---|---|
l_max |
int
|
Maximum harmonic degree, inclusive. |
num_quadrature |
int
|
Gauss-Legendre nodes for the Funk-Hecke integral. |
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
K_uu(kernel: Kernel, *, jitter: float = 1e-06) -> lx.DiagonalLinearOperator
¶
Diagonal \(K_{uu}\) — Funk-Hecke coefficients per harmonic.
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
k_ux(unit_xyz: Float[Array, 'N 3'], kernel: Kernel) -> Float[Array, 'N M']
¶
Cross-covariance: \(a_l\,Y_{lm}(x)\).
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
SlepianInducingFeatures
¶
Bases: Module
Region-localized Slepian inducing features on \(S^2\).
The retained Slepian functions are linear combinations G = Y C of the
real spherical-harmonic basis evaluated in the cap-centred frame. For a
zonal kernel with Funk-Hecke coefficients a_l this gives dense
inducing covariance K_uu = C.T diag(a_l) C and cross-covariance
K_ux = Y(R x) diag(a_l) C, where R is the rotation aligning the
cap centre with the north pole. The basis (a SlepianCapBasis)
is built once at init time and stored on the module so that
K_uu, k_ux and num_features are cheap matrix multiplies.
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | |
K_uu(kernel: Kernel, *, jitter: float = 1e-06) -> lx.MatrixLinearOperator
¶
Dense Slepian inducing covariance with diagonal jitter.
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
k_ux(unit_xyz: Float[Array, 'N 3'], kernel: Kernel) -> Float[Array, 'N K']
¶
Cross-covariance between unit-sphere inputs and Slepian features.
Spherical harmonics are evaluated in the cap-centred frame to match
SlepianCapBasis.evaluate; without this rotation, two
SlepianInducingFeatures differing only in cap centre would
produce the same cross-covariance.
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
LaplacianInducingFeatures
¶
Bases: Module
Inducing features from low-frequency graph Laplacian eigenvectors.
For a graph Laplacian with smallest eigenpairs \((\lambda_k, \phi_k)\), the inducing variables \(u_k = \phi_k^\top f\) of a graph GP \(f \sim \mathcal{GP}(0, U \Phi(\Lambda) U^\top)\) satisfy
so \(K_{uu}\) is diagonal. \(\Phi\) is the graph heat spectrum for
pyrox_gp.RBF and the graph Matérn spectrum of Borovitskiy et al.
(2021) for pyrox_gp.Matern, normalised so the average marginal
variance over the nodes is the kernel's variance. Eigenpairs come from
kernellib.laplacian_eigpairs, which scales past the dense
eigendecomposition (Kronecker on grid graphs, Lanczos, ARPACK).
Attributes:
| Name | Type | Description |
|---|---|---|
eigvals |
Float[Array, ' M']
|
|
eigvecs |
Float[Array, 'V M']
|
|
Note
X is a vector of node indices (integer-valued), not
coordinates. The returned cross-covariance gathers the relevant
rows of eigvecs.
Examples:
>>> import jax.numpy as jnp
>>> import kernellib as kl
>>> from pyrox_gp import LaplacianInducingFeatures, Matern
>>> features = LaplacianInducingFeatures.fit(kl.grid_graph((10, 10)), 20)
>>> features.K_uu(Matern(nu=1.5)).diagonal.shape
(20,)
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | |
n_nodes: int
property
¶
Number of graph nodes V, used for the variance normalisation.
fit(graph: kl.AbstractGraph | Float[Array, 'V V'], num_basis: int, *, normalization: Literal['unnormalized', 'symmetric'] = 'symmetric', method: Literal['dense', 'kronecker', 'lanczos', 'arpack'] | None = None, key: PRNGKeyArray | None = None, normalized: bool | None = None) -> LaplacianInducingFeatures
classmethod
¶
Take the num_basis smallest Laplacian eigenpairs of graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
AbstractGraph | Float[Array, 'V V']
|
A kernellib graph or a dense symmetric adjacency matrix. |
required |
num_basis
|
int
|
Number of eigenpairs |
required |
normalization
|
Literal['unnormalized', 'symmetric']
|
Laplacian normalisation. |
'symmetric'
|
method
|
Literal['dense', 'kronecker', 'lanczos', 'arpack'] | None
|
Eigensolver, passed to |
None
|
key
|
PRNGKeyArray | None
|
PRNG key for the randomised solvers. |
None
|
normalized
|
bool | None
|
Deprecated alias: |
None
|
Returns:
| Type | Description |
|---|---|
LaplacianInducingFeatures
|
The fitted features. |
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
DecoupledInducingFeatures
¶
Bases: Module
Decoupled mean / covariance inducing-feature bases (Cheng & Boots 2017).
Two independent inducing-feature sets:
mean_features: a largealpha-basis used by the SVGP posterior mean (cheap — predictive mean cost is linear in the mean-basis size).cov_features: a smallbeta-basis used for the posterior covariance (the true bottleneck; keep this small).
The two bases need not share the same family — a common pattern is a large Fourier basis for the mean and a small spherical-harmonic basis for the covariance, or vice versa. The downstream guide consumes both via the standard SVGP machinery.
Attributes:
| Name | Type | Description |
|---|---|---|
mean_features |
InducingFeatures
|
Inducing-feature object backing the predictive mean. |
cov_features |
InducingFeatures
|
Inducing-feature object backing the predictive covariance. |
Note
DecoupledInducingFeatures itself does not implement
InducingFeatures (no single K_uu makes sense for two
bases). Consumers should access .mean_features and
.cov_features directly.
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
funk_hecke_coefficients(kernel: Kernel, l_max: int, *, num_quadrature: int = 256) -> Float[Array, ' l_max_plus_1']
¶
Deprecated: use kernellib.funk_hecke_coefficients on a frozen kernel.
Replace it with
kernellib.funk_hecke_coefficients(pyrox._core.freeze(kernel), l_max),
whose default convention is this function's,
\(a_l = 2\pi \int_{-1}^{1} \kappa(t)\,P_l(t)\,dt\).
Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
Sparse GP prior¶
After fitting a guide over the inducing values (svgp_factor, svgp_elbo or ConjugateVI), prior.condition(guide) returns the ConditionedSparseGP, whose predict(X_star) gives the SVGP predictive mean and variance, mean function included. MultiOutputSparseGPPrior.condition(guide) does the same for the multi-output prior, in the (M, P) layout, and replaces its deprecated predict(guide, X_star).
SparseGPPrior
¶
Bases: Module
GP prior parameterized over inducing inputs Z.
Represents the zero-mean prior over inducing values u = f(Z)
used by sparse variational guides:
The standard SVGP convention is to subtract any global mean function
before forming the prior over u and to add it back at predict
time, so the inducing-prior mean is fixed to zero (this is what the
guides' KL terms assume — see FullRankGuide.kl_divergence,
MeanFieldGuide.kl_divergence, WhitenedGuide.kl_divergence).
The mean_fn attribute on this class is exposed as a
convenience for callers that want to add mu(X_*) back onto the
predictive mean returned by Guide.predict; it is not
incorporated in inducing_operator or in the guides' KL.
Pair with a sparse variational guide that owns q(u) = N(m, S) to
obtain the standard SVGP predictive
Attributes:
| Name | Type | Description |
|---|---|---|
kernel |
Kernel
|
Any |
Z |
Float[Array, 'M D'] | None
|
Inducing inputs of shape |
mean_fn |
Callable[[Float[Array, 'N D']], Float[Array, ' N']] | None
|
Callable |
solver |
AbstractSolverStrategy | None
|
Any |
preconditioner |
AbstractPreconditioner | None
|
Optional |
logdet |
AbstractLogdetStrategy | None
|
Optional |
jitter |
float
|
Diagonal regularization added to |
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | |
num_inducing: int
property
¶
Number of inducing inputs / features M.
mean(X: Float[Array, 'N D']) -> Float[Array, ' N']
¶
Evaluate the mean function at X; zero by default.
inducing_operator() -> lx.AbstractLinearOperator
¶
Return K_{ZZ} + \text{jitter}\,I as a lineax operator.
For point-inducing priors, returns a dense
lineax.MatrixLinearOperator with positive_semidefinite_tag.
For inducing-feature priors, delegates to
InducingFeatures.K_uu — typically a
lineax.DiagonalLinearOperator so the downstream
gaussx.solve dispatches in O(M) instead of O(M^3).
Single kernel call; safe standalone for kernels with priors. For
building several SVGP blocks together, prefer
predictive_blocks, which scopes one shared kernel
context across K_zz, K_xz, and K_xx_diag so
Pattern B / C kernels register their NumPyro hyperparameter
sites once instead of resampling per call.
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
cross_covariance(X: Array) -> Float[Array, 'N M']
¶
\(K_{XZ}\) — covariance between X and the inducing inputs/features.
The expected shape of X is inducing-family-dependent:
- Point-inducing (
Z) orFourierInducingFeatures: coordinates(N, D). SphericalHarmonicInducingFeatures: unit vectors(N, 3).LaplacianInducingFeatures: integer node indices(N,).
See predictive_blocks for the shared-context batch
helper to use when assembling several SVGP blocks together.
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
kernel_diag(X: Float[Array, 'N D']) -> Float[Array, ' N']
¶
Prior diagonal \mathrm{diag}\,K(X, X) — variance at each x.
See predictive_blocks for the shared-context batch
helper to use when assembling several SVGP blocks together.
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
predictive_blocks(X: Array) -> tuple[lx.AbstractLinearOperator, Float[Array, 'N M'], Float[Array, ' N']]
¶
Return (K_zz_op, K_xz, K_xx_diag) under one shared kernel context.
For Pattern B / C kernels with prior'd hyperparameters, the three
kernel evaluations needed for an SVGP predictive must share a
single pyrox.PyroxModule context so the underlying
pyrox_sample sites register once and yield consistent
hyperparameter draws across K_{ZZ}, K_{XZ}, and the
diagonal \mathrm{diag}\,K(X, X). Without this scoping, three
separate calls would draw three independent hyperparameter
samples (under seed) or raise NumPyro duplicate-site errors
(under tracing) — either way invalidating the SVGP math.
For pure equinox.Module kernels (no _get_context),
this is equivalent to calling inducing_operator,
cross_covariance, and kernel_diag independently.
For inducing-feature priors, K_zz_op is a
lineax.DiagonalLinearOperator (jitter folded into the
diagonal vector — never + jnp.eye) so the downstream solve
stays O(M).
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
solver_strategy() -> AbstractSolverStrategy
¶
The solver, preconditioner and logdet fields as one strategy.
Returns:
| Type | Description |
|---|---|
AbstractSolverStrategy
|
The |
AbstractSolverStrategy
|
when none of the three is set. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For a combination |
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
log_prob(u: Float[Array, ' M']) -> Float[Array, '']
¶
Log-density under \(p(u) = \mathcal{N}(0, K_{ZZ} + \text{jitter}\,I)\).
Delegates to gaussx.gaussian_log_prob with the
configured solver so the user-supplied solver controls
the solve / logdet work on K_zz_op. Useful for
scoring inducing values against the SVGP prior in non-NumPyro
contexts (e.g.\ tests, diagnostics).
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
sample(key: Array) -> Float[Array, ' M']
¶
Draw u \sim p(u) from the inducing prior.
Wraps the inducing operator in a
pyrox_gauss.MultivariateNormal with the configured
solver. MultivariateNormal.sample factors the
covariance via gaussx.cholesky and reparameterizes;
the returned draw has shape (M,).
Note: the SVGP variational workflow samples u from the
guide \(q(u)\), not the prior. This method exists so the
prior surface is symmetric with the guide surface and so users
can score / draw inducing values against the prior directly
(e.g.\ for tests or for prior-sample initialization).
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
condition(guide: Guide) -> ConditionedSparseGP
¶
The sparse posterior for a fitted guide.
The observations are already summarised in the fitted guide
\(q(u) = \mathcal{N}(m_q, S_q)\), so condition takes the guide
rather than y; the result is
\(q(f) = \int p(f \mid u)\, q(u)\, du\), whose predict(X_star)
gives the SVGP predictive marginals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guide
|
Guide
|
The fitted guide over the inducing values, any
|
required |
Returns:
| Type | Description |
|---|---|
ConditionedSparseGP
|
The |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import RBF, FullRankGuide, SparseGPPrior
>>> prior = SparseGPPrior(RBF(), Z=jnp.linspace(0.0, 1.0, 5)[:, None])
>>> guide = FullRankGuide.init(prior.num_inducing)
>>> mean, var = prior.condition(guide).predict(jnp.array([[0.3], [2.0]]))
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
ConditionedSparseGP
¶
Bases: Module
A sparse GP conditioned through a fitted guide on its inducing values.
Returned by SparseGPPrior.condition. predict(X_star) is the SVGP
predictive
computed by the guide's own predict on SparseGPPrior.predictive_blocks.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
SparseGPPrior
|
The originating |
guide |
Guide
|
The fitted guide over the inducing values. |
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
predict(X_star: Float[Array, 'M D']) -> tuple[Float[Array, ' M'], Float[Array, ' M']]
¶
Predictive (mean, variance) of f at X_star.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_star
|
Float[Array, 'M D']
|
Test inputs, shape |
required |
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, ' M'], Float[Array, ' M']]
|
|
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import RBF, WhitenedGuide, SparseGPPrior
>>> prior = SparseGPPrior(RBF(), Z=jnp.linspace(0.0, 1.0, 4)[:, None])
>>> cond = prior.condition(WhitenedGuide.init(prior.num_inducing))
>>> mean, var = cond.predict(jnp.linspace(0.0, 1.0, 7)[:, None])
>>> mean.shape
(7,)
Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
Variational guides¶
Variational families q(u) over the inducing values of a
SparseGPPrior. All five expose the same building-block interface —
sample(key), log_prob(u), kl_divergence(prior_cov), and
predict(K_xz, K_zz_op, K_xx_diag) — so they swap freely inside the
SVGP ELBO. WhitenedGuide parameterizes in whitened coordinates
u = L_zz v (the standard choice for stable optimization);
NaturalGuide parameterizes in natural form for natural-gradient / CVI
workflows; DeltaGuide is a point mass for MAP-style training.
A guide's solver is the solver of every solve against \(K_{ZZ}\) in predict and kl_divergence for FullRankGuide, MeanFieldGuide and DeltaGuide (#560): predict forms \(B = K_{ZZ}^{-1} K_{ZX}\) from one matrix right-hand side and needs no root, and the KL of the first two is gaussx.gaussian_kl(..., solver=) (DeltaGuide's \(-\log p(\mathrm{loc})\) already went through gaussx.gaussian_log_prob with it). With solver=None both keep the Cholesky route, and a diagonal \(K_{ZZ}\) of inter-domain features stays \(O(M)\); an explicit solver overrides that structure. An iterative solver's tolerance enters the ELBO, since a relative error \(\delta\) in \(B\) moves each predictive variance by about \(\delta k_{nn}\), and its own log-determinant (stochastic Lanczos for CG and BBMM) moves the KL by half its error, so pass logdet=gaussx.DenseLogdet() through gaussx.compose_solver for an exact KL at moderate \(M\). WhitenedGuide has nothing to choose there: \(u = L_{ZZ} v\) needs the Cholesky factor, and its KL is against \(\mathcal{N}(0, I)\). ConjugateVI.step solves against \(K_{ZZ}\) with the prior's solver when it sets one.
FullRankGuide
¶
Bases: Guide
Full-rank Gaussian variational posterior over inducing values u.
parameterized by the mean mean of shape (M,) and the
lower-triangular Cholesky factor scale_tril of shape (M, M).
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
Float[Array, ' M']
|
Variational mean |
scale_tril |
Float[Array, 'M M']
|
Lower-triangular Cholesky factor of the variational
covariance, shape |
solver |
AbstractSolverStrategy | None
|
Optional |
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
init(num_inducing: int, *, scale: float = 1.0, solver: AbstractSolverStrategy | None = None) -> FullRankGuide
classmethod
¶
Construct a guide initialized to N(0, scale^2 I).
Uses JAX's default float dtype — set
jax.config.update("jax_enable_x64", True) once at the top of
your script if you want float64 inducing parameters.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
sample(key: Array) -> Float[Array, ' M']
¶
Draw u = m + L_S \epsilon with \epsilon ~ N(0, I).
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
log_prob(u: Float[Array, ' ...']) -> Float[Array, '']
¶
Variational log density \log q(u) via gaussx.gaussian_log_prob.
Delegates the solve and logdet work to the configured
solver so the user-supplied solver actually controls the
numerical path.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
kl_divergence(prior_cov: lx.AbstractLinearOperator) -> Float[Array, '']
¶
KL(q(u) || p(u)) against an inducing prior with zero mean.
gaussx.gaussian_kl, whose solves and log-determinant against
prior_cov go through solver (structural dispatch when
None).
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
predict(K_xz: Float[Array, 'N M'], K_zz_op: lx.AbstractLinearOperator, K_xx_diag: Float[Array, ' N']) -> tuple[Float[Array, ' N'], Float[Array, ' N']]
¶
Predictive (mean, variance) at points with cross-cov K_xz.
With solver=None it reduces to the whitened predictive with a
Cholesky factor of K_zz_op (gaussx.whitened_svgp_predict);
with a solver, every solve against \(K_{ZZ}\) goes through it and
no root is formed (_svgp_predict_with_solver).
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
MeanFieldGuide
¶
Bases: Guide
Diagonal Gaussian variational posterior over inducing values u.
parameterized by the mean mean and the per-coordinate standard
deviations scale.
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
Float[Array, ' M']
|
Variational mean |
scale |
Float[Array, ' M']
|
Per-coordinate standard deviations |
solver |
AbstractSolverStrategy | None
|
Optional |
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
init(num_inducing: int, *, scale: float = 1.0, solver: AbstractSolverStrategy | None = None) -> MeanFieldGuide
classmethod
¶
Construct a guide initialized to N(0, scale^2 I) — see
FullRankGuide.init for the dtype convention.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
sample(key: Array) -> Float[Array, ' M']
¶
Draw u = m + s \odot \epsilon with \epsilon ~ N(0, I).
log_prob(u: Float[Array, ' ...']) -> Float[Array, '']
¶
Variational log density \log q(u) via gaussx.gaussian_log_prob.
The covariance operator is built from the per-coordinate scales
as a lineax.MatrixLinearOperator tagged
positive_semidefinite_tag; structural dispatch routes
through the configured solver.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
kl_divergence(prior_cov: lx.AbstractLinearOperator) -> Float[Array, '']
¶
KL(q(u) || p(u)) against an inducing prior with zero mean.
Through solver against prior_cov, as in
FullRankGuide.kl_divergence.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
predict(K_xz: Float[Array, 'N M'], K_zz_op: lx.AbstractLinearOperator, K_xx_diag: Float[Array, ' N']) -> tuple[Float[Array, ' N'], Float[Array, ' N']]
¶
Predictive (mean, variance) at the points whose cross-cov is K_xz.
Through solver when one is set, as in FullRankGuide.predict.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
WhitenedGuide
¶
Bases: Guide
Whitened-coordinate Gaussian variational posterior over inducing values.
Parameterizes q(v) = N(m_v, L_v L_v^T) in whitened coordinates,
so the inducing values are u = L_{ZZ} v with
L_{ZZ} = chol(K_{ZZ} + jitter I). In whitened coordinates the
prior is p(v) = N(0, I) and the KL term has a simple closed form
that is independent of the kernel — the standard reparameterization
for numerically stable SVGP optimization (Hensman et al., 2015).
Attributes:
| Name | Type | Description |
|---|---|---|
mean |
Float[Array, ' M']
|
Variational mean |
scale_tril |
Float[Array, 'M M']
|
Lower-triangular Cholesky factor of the whitened
variational covariance, shape |
solver |
AbstractSolverStrategy | None
|
Optional |
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 | |
init(num_inducing: int, *, scale: float = 1.0, solver: AbstractSolverStrategy | None = None) -> WhitenedGuide
classmethod
¶
Construct a guide initialized to N(0, scale^2 I) in whitened
space — see FullRankGuide.init for the dtype convention.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
sample(key: Array) -> Float[Array, ' M']
¶
Draw a single whitened sample v = m_v + L_v \epsilon.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
log_prob(v: Float[Array, ' ...']) -> Float[Array, '']
¶
Whitened \log q(v) via gaussx.gaussian_log_prob.
Delegates solve and logdet to the configured solver so
the user-supplied solver controls the numerical path
(the KL(q(v) \| N(0, I)) term remains the kernel-free
closed form).
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
kl_divergence(prior_cov: lx.AbstractLinearOperator | None = None) -> Float[Array, '']
¶
KL(q(v) || N(0, I)) — kernel-free closed form.
Computes
The prior_cov argument is accepted for signature parity with
FullRankGuide.kl_divergence and
MeanFieldGuide.kl_divergence, but is ignored — the
whitened prior is the standard normal regardless of K_{ZZ}.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
predict(K_xz: Float[Array, 'N M'], K_zz_op: lx.AbstractLinearOperator, K_xx_diag: Float[Array, ' N']) -> tuple[Float[Array, ' N'], Float[Array, ' N']]
¶
Predictive (mean, variance) via gaussx.whitened_svgp_predict.
Always on the Cholesky factor of K_zz_op, which the whitened
coordinates are defined by; solver does not apply here.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
NaturalGuide
¶
Bases: Guide
Natural-parameter Gaussian variational posterior over inducing values.
Parameterizes \(q(u) = \mathcal{N}(m, S)\) in natural form with parameters
The moments are recovered on demand via mean and
covariance, which delegate to gaussx.natural_to_mean_cov.
The natural form is the parameterization of choice for natural-
gradient and conjugate-computation variational inference (CVI)
workflows: when the true posterior is in the same exponential family
as the prior, the natural-gradient direction equals the difference
in natural parameters. natural_update exposes that step
with a damping factor rho and delegates to
gaussx.damped_natural_update so the same primitive is shared
with future natural-gradient EP / VI / Newton workflows.
Attributes:
| Name | Type | Description |
|---|---|---|
nat1 |
Float[Array, ' M']
|
First natural parameter |
nat2 |
Float[Array, 'M M']
|
Second natural parameter |
solver |
AbstractSolverStrategy | None
|
Optional |
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 | |
covariance: Float[Array, 'M M']
property
¶
Recover the moment-form covariance S = (-2 nat2)^{-1}.
mean: Float[Array, ' M']
property
¶
Recover the moment-form mean m = S nat1.
init(num_inducing: int, *, scale: float = 1.0, solver: AbstractSolverStrategy | None = None) -> NaturalGuide
classmethod
¶
Construct a guide initialized to N(0, scale^2 I) in moment space.
Mapped to natural form this is eta_1 = 0 and
eta_2 = -1 / (2 scale^2) * I — see FullRankGuide.init
for the dtype convention.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
sample(key: Array) -> Float[Array, ' M']
¶
Draw u \sim q via pyrox_gauss.MultivariateNormalPrecision.
Uses the precision Cholesky directly: L = chol(\Lambda),
y = L^{-T} \epsilon, u = m + y. No moment-space
Cholesky and no \Sigma materialization.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
log_prob(u: Float[Array, ' ...']) -> Float[Array, '']
¶
Variational log density \log q(u) via the precision MVN.
Avoids the moment-space \Sigma^{-1} solve: the quadratic
form is one matvec \Lambda (u - m), and the log-determinant
comes from the configured solver on \Lambda.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
kl_divergence(prior_cov: lx.AbstractLinearOperator) -> Float[Array, '']
¶
KL(q(u) || p(u)) against an inducing prior with zero mean.
gaussx.gaussian_kl in moment form, with structural dispatch
against prior_cov: this guide's solver is the solver of
its precision \(\Lambda\), not of \(K_{ZZ}\).
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
predict(K_xz: Float[Array, 'N M'], K_zz_op: lx.AbstractLinearOperator, K_xx_diag: Float[Array, ' N']) -> tuple[Float[Array, ' N'], Float[Array, ' N']]
¶
Predictive (mean, variance) at points with cross-cov K_xz.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
natural_update(nat1_hat: Float[Array, ' M'], nat2_hat: Float[Array, 'M M'], rho: float | Float[Array, ''] = 1.0) -> NaturalGuide
¶
Damped natural-parameter update via gaussx.damped_natural_update.
Returns a new NaturalGuide whose natural parameters are
the convex combination
The damping factor rho interpolates between the current
guide (rho=0) and the candidate update
(nat1_hat, nat2_hat) (rho=1). Convex combinations in
natural-parameter space preserve membership in the Gaussian
exponential family — in particular rho * nat2_hat + (1 - rho)
* self.nat2 stays symmetric negative-definite when both
endpoints are. CVI-style site updates rely on exactly this
property.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
DeltaGuide
¶
Bases: Guide
Point-mass (MAP-style) variational posterior over inducing values.
so all the variational mass concentrates on a single point. Pairs
with the same SVGP ELBO infrastructure as the Gaussian guides but
reduces it to MAP estimation: when ELL - kl_divergence is the
objective, kl_divergence returns the loc-dependent
\(-\log p(\text{loc})\) so the objective becomes the joint
log-density log p(y, loc) = ELL(loc) + log p(loc), recovering
standard MAP estimation of the inducing values.
Attributes:
| Name | Type | Description |
|---|---|---|
loc |
Float[Array, ' M']
|
The point at which the variational mass concentrates,
shape |
solver |
AbstractSolverStrategy | None
|
Optional |
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 | |
init(num_inducing: int, *, solver: AbstractSolverStrategy | None = None) -> DeltaGuide
classmethod
¶
Construct a guide initialized to loc = 0 — see
FullRankGuide.init for the dtype convention.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
sample(key: Array) -> Float[Array, ' M']
¶
log_prob(u: Float[Array, ' ...']) -> Float[Array, '']
¶
Variational log density — constant 0 by convention.
The strict density of a Dirac delta is +inf at loc and
-inf everywhere else, which carries no useful gradient
information. Returning 0 matches the Pyro / NumPyro
AutoDelta convention: the differentiable MAP signal lives
entirely in kl_divergence.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
kl_divergence(prior_cov: lx.AbstractLinearOperator) -> Float[Array, '']
¶
Return the loc-dependent -log p(loc) for the MAP objective.
The strict KL of a Dirac delta against a continuous prior is
+inf, but the only loc-dependent piece is the negative log
prior density at loc,
so we return that. With this convention the standard ELBO
ELL - kl_divergence reduces to the joint log-density
log p(y, loc), which is exactly the MAP objective. Computed
via gaussx.gaussian_log_prob so the same solver / logdet
primitives back this path as the rest of the GP surface.
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
predict(K_xz: Float[Array, 'N M'], K_zz_op: lx.AbstractLinearOperator, K_xx_diag: Float[Array, ' N']) -> tuple[Float[Array, ' N'], Float[Array, ' N']]
¶
Predictive (mean, variance) conditioning on u = loc.
With u = loc deterministically, the predictive is the prior
conditional p(f_* | u = loc): the mean is
K_{xZ} K_{ZZ}^{-1} loc and the variance is the prior
reduction k(x, x) - K_{xZ} K_{ZZ}^{-1} K_{Zx} exactly —
no posterior-uncertainty contribution and no Cholesky jitter.
Implemented by calling gaussx.whitened_svgp_predict
directly with the whitened mean L_{ZZ}^{-1} loc and a zero
whitened Cholesky factor. The shared
_svgp_predict_unwhitened helper would route the zero
variational covariance through gaussx.safe_cholesky,
which injects jitter to make the input PD and would add a tiny
spurious variance term. Bypassing that path keeps the
DeltaGuide predictive numerically equal to the prior
conditional. With a solver the same moments come from
\(K_{ZZ}^{-1} K_{ZX}\) through it, with no root
(_svgp_predict_with_solver).
Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
Likelihoods¶
Observation models for latent-GP workflows. Each maps latent function
values to a summed log-density log_prob(f, y); DistLikelihood wraps
any numpyro.distributions.Distribution factory for one-off models.
GaussianLikelihood
¶
Bases: _GPObservation, GaussianLikelihood
Gaussian observation model \(p(y \mid f) = N(y \mid f, \sigma^2)\), over
gaussx.GaussianLikelihood.
The only likelihood with a closed-form expected log-likelihood, so
svgp_elbo and ConjugateVI take the analytical Titsias path for it. It
subclasses pyrox.likelihoods.GaussianLikelihood, so every closed-form
path that dispatches on the core class takes it too.
Attributes:
| Name | Type | Description |
|---|---|---|
noise_var |
float | Float[Array, '']
|
Observation noise variance \(\sigma^2\). |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import GaussianLikelihood
>>> lik = GaussianLikelihood(noise_var=1.0)
>>> type(lik.build(jnp.zeros(2), {}, {})).__name__
'GaussianLikelihood'
>>> float(lik.log_prob(jnp.zeros(1), jnp.zeros(1)))
-0.918...
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> gx.GaussianLikelihood
¶
gaussx.GaussianLikelihood holding y at noise_var.
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
HeteroscedasticGaussianLikelihood
¶
Bases: _GPObservation
Gaussian regression with input-dependent noise, over
gaussx.HeteroscedasticGaussianLikelihood.
Each observation consumes two latents — the mean and the log-noise-standard-deviation: \(p(y_n | f_n^{(0)}, f_n^{(1)}) = N(y_n | f_n^{(0)}, e^{2 f_n^{(1)}})\).
gaussx's likelihood takes the noise standard deviation as \(\mathrm{softplus}(g_n)\) and the two latent columns concatenated, so the second column enters it as \(g_n = \mathrm{softplus}^{-1}(e^{f_n^{(1)}})\): the same density, with gaussx's numerics.
Multi-latent (latent_dim = 2). The scalar-latent advanced
inference strategies reject this likelihood; use SVGP for now.
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import HeteroscedasticGaussianLikelihood
>>> lik = HeteroscedasticGaussianLikelihood()
>>> lp = lik.log_prob(jnp.zeros((1, 2)), jnp.zeros(1))
>>> bool(jnp.allclose(lp, -0.5 * jnp.log(2.0 * jnp.pi)))
True
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> gx.HeteroscedasticGaussianLikelihood
¶
gaussx.HeteroscedasticGaussianLikelihood holding y.
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
BernoulliLikelihood
¶
Bases: _GPObservation
Binary classification likelihood with logit link, over
gaussx.BernoulliLikelihood.
\(p(y \mid f) = \mathrm{Bernoulli}(\sigma(f))\) where \(\sigma\) is the
logistic function. Targets y are {0, 1} valued. Scalar latent
(latent_dim = 1).
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import BernoulliLikelihood
>>> lik = BernoulliLikelihood()
>>> site = lik.build(jnp.array([1.0, 0.0]), {}, {})
>>> bool(jnp.allclose(site.log_prob(jnp.zeros(2)), 2.0 * jnp.log(0.5)))
True
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> gx.BernoulliLikelihood
¶
gaussx.BernoulliLikelihood holding y.
PoissonLikelihood
¶
Bases: _GPObservation
Count likelihood with log link, over gaussx.PoissonLikelihood.
\(p(y \mid f) = \mathrm{Poisson}(\exp(f))\). Targets y are non-negative
integers. Scalar latent (latent_dim = 1).
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import PoissonLikelihood
>>> float(PoissonLikelihood().log_prob(jnp.zeros(3), jnp.zeros(3)))
-3.0
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> gx.PoissonLikelihood
¶
gaussx.PoissonLikelihood holding y.
SoftmaxLikelihood
¶
Bases: _GPObservation
Multi-class classification likelihood with softmax link, over
gaussx.SoftmaxLikelihood.
Each observation has one latent function value per class:
f has shape (N, num_classes) and
\(p(y_n \mid f_n) = \mathrm{Categorical}(\mathrm{softmax}(f_n))\).
Targets y are integer class indices in [0, num_classes). The
gaussx likelihood takes the latents flattened site by site
(f.reshape(-1)).
Multi-latent (latent_dim = num_classes). The scalar-latent
advanced inference strategies in pyrox_gp._inference_nongauss
reject this likelihood with a clear error; use SVGP / MAP for now,
or wait for the multi-latent inference follow-up.
Attributes:
| Name | Type | Description |
|---|---|---|
num_classes |
int
|
Number of output classes \(C \geq 2\). |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import SoftmaxLikelihood
>>> lik = SoftmaxLikelihood(num_classes=3)
>>> lik.latent_dim
3
>>> lp = lik.log_prob(jnp.zeros((2, 3)), jnp.array([0, 2]))
>>> bool(jnp.allclose(lp, 2.0 * jnp.log(1.0 / 3.0)))
True
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
StudentTLikelihood
¶
Bases: _GPObservation
Heavy-tailed regression \(p(y \mid f) = \mathrm{StudentT}(\nu, f, \sigma)\), over
gaussx.StudentTLikelihood.
Robust to outliers — the heavier-than-Gaussian tails downweight
observations that are far from the latent. Scalar latent
(latent_dim = 1). Both df and scale are positive.
Attributes:
| Name | Type | Description |
|---|---|---|
df |
float | Float[Array, '']
|
Degrees of freedom \(\nu > 0\). Smaller values give
heavier tails. |
scale |
float | Float[Array, '']
|
Scale parameter \(\sigma > 0\). |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import StudentTLikelihood
>>> lik = StudentTLikelihood(df=1.0, scale=1.0)
>>> lp = lik.log_prob(jnp.zeros(1), jnp.zeros(1))
>>> bool(jnp.allclose(lp, -jnp.log(jnp.pi)))
True
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> gx.StudentTLikelihood
¶
gaussx.StudentTLikelihood holding y at df and scale.
Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
DistLikelihood
¶
Bases: AbstractObservation, Likelihood
Observation model over any NumPyro distribution, \(p(y_i \mid \eta_i, \theta)\).
The user's make_dist(eta_i, theta, data_i) returns site \(i\)'s
distribution, and its log_prob is the per-site log density
so a likelihood gaussx has no class for (zero-inflated Poisson, Beta, a censored Gaussian) gets Laplace, EP and the Markov strategies.
The core imports no gaussx, so build does not return a gaussx
likelihood, unlike other observation models: it returns the pair
(log_density, data) that gaussx.CallableLikelihood takes, where
log_density(eta_i, d_i) is \(\ell\) and data is
{"y": y, "data": data}, every leaf with a leading site axis of
length \(N\). pyrox-gp's inference and pyrox-ssm's strategies recognise a
DistLikelihood and wrap the pair as
gaussx.CallableLikelihood(*lik.build(y, theta, data)), which gives
the per-site derivatives and expectations. log_prob(f, y, X) and the
per-site diagnostics (site_distribution) call make_dist on every
site at once, so make_dist must broadcast over a leading site axis,
as NumPyro distributions do; index inputs from the end
(data_i["X"][..., 0]).
The hyperparameters \(\theta\) that make_dist reads are the theta
field, updated key by key by the theta passed to build (pyrox-gp
and pyrox-ssm pass none). They are array leaves of the module, so they
receive gradients and may be NumPyro sample values. pyrox-gp and
pyrox-ssm pass the inputs as data_i = {"X": x_i}. pyrox_lgm.inla
does not take a DistLikelihood yet: it uses what build returns as a
gaussx likelihood. The class registers no NumPyro sites.
The old one-argument link DistLikelihood(lambda f: dist.Bernoulli(logits=f))
still works: a callable with exactly one required positional argument is
wrapped to ignore theta and data_i, keeping the defaults of any
optional ones (lambda f, df=3.0: ...), so a make_dist must take
theta and data_i without defaults. DistLikelihood(dist_fn=...)
warns and always does the same.
The callable cannot carry trainable parameters
make_dist is a static field, so anything it closes over is
invisible to eqx.filter_grad and silently never trains. Put
scalar hyperparameters in theta; for a parameterized link (a
warp, a network), write a Likelihood subclass holding it as a
child module.
Attributes:
| Name | Type | Description |
|---|---|---|
make_dist |
Callable[..., Distribution]
|
|
theta |
dict[str, Array]
|
Hyperparameter values |
name |
str
|
Prefix of the hyperparameter names ( |
Examples:
A zero-inflated Poisson with gate \(\pi\), and the gaussx likelihood a gaussx-backed package wraps it into:
>>> import gaussx as gx
>>> import jax.numpy as jnp
>>> import numpyro.distributions as dist
>>> from pyrox.likelihoods import DistLikelihood
>>> zip_lik = DistLikelihood(
... lambda eta, th, d: dist.ZeroInflatedPoisson(
... gate=th["pi"], rate=jnp.exp(eta)
... ),
... theta={"pi": 0.2},
... )
>>> y = jnp.array([0.0, 2.0, 1.0])
>>> site_lik = gx.CallableLikelihood(*zip_lik.build(y, {}, {}))
>>> g, h = site_lik.site_derivatives(jnp.zeros(3))
>>> g.shape, h.shape
((3,), (3,))
The old one-argument link:
>>> lik = DistLikelihood(lambda f: dist.Bernoulli(logits=f))
>>> float(lik.log_prob(jnp.zeros(2), jnp.array([1.0, 0.0])))
-1.386...
Source code in packages/pyrox/src/pyrox/likelihoods.py
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 | |
dist_fn: Callable[[Array], nd.Distribution]
property
¶
Deprecated: the one-argument link f -> Distribution; use make_dist.
The old one-argument callable when one was passed, else make_dist
at the theta field with empty data.
build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> tuple[Callable[[Float[Array, ''], PyTree], Float[Array, '']], PyTree]
¶
The per-site log density and data that gaussx.CallableLikelihood takes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Array
|
Observations, |
required |
theta
|
dict[str, Array]
|
Hyperparameters, overriding the |
required |
data
|
Mapping[str, ArrayLike]
|
Per-site data other than |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Float[Array, ''], PyTree], Float[Array, '']]
|
|
PyTree
|
\(\log p(y_i \mid \eta_i, \theta, \mathrm{data}_i)\) for a scalar |
tuple[Callable[[Float[Array, ''], PyTree], Float[Array, '']], PyTree]
|
|
tuple[Callable[[Float[Array, ''], PyTree], Float[Array, '']], PyTree]
|
|
Source code in packages/pyrox/src/pyrox/likelihoods.py
site_distribution(eta: Float[Array, ' N'], theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> nd.Distribution
¶
make_dist on every site at once (batched in eta).
Source code in packages/pyrox/src/pyrox/likelihoods.py
log_prob(f: Float[Array, ' ...'], y: Float[Array, ' ...'], X: Float[Array, ' ...'] | None = None) -> Float[Array, '']
¶
\(\sum_i \log p(y_i \mid f_i)\), with the inputs in data["X"].
Source code in packages/pyrox/src/pyrox/likelihoods.py
Warped (transformed-GP) likelihood¶
A transformed Gaussian process (Maronas et al., AISTATS 2021) is an SVGP
whose likelihood composes an elementwise monotone warp G; the warp
never appears in the KL term, so every existing inference path composes
with it unchanged. Needs an integrator (Gauss-Hermite recommended) and,
for the smooth recommended warp MixtureGaussianCDF, the
pyrox-gp[flows] extra.
The warp may also be input-dependent (G_{phi(x)}) — a
non-stationary process from a stationary kernel. Pass a conditional
bijection (e.g. gauss_flows.Conditioner wrapping an unconditional
warp); svgp_elbo threads the inputs through
Likelihood.log_prob(f, y, X) automatically. Cost note: the expected
log-likelihood evaluates the warp at every quadrature node, so a
conditional warp pays order conditioner forward passes per point.
Only svgp_elbo threads the inputs through. The CVI / natural-gradient
strategies, pyrox_ssm.sparse_markov_elbo and the multi-output ELBO do not,
so a conditional warp raises there rather than silently dropping the
condition — use an unconditional warp on those paths.
WarpedGaussianLikelihood
¶
Bases: Likelihood
\(p(y \mid f) = N(y \mid G(f), \sigma^2)\) -- the transformed-GP model.
The warp is a child module, so its parameters are ordinary trainable
leaves. Passing a warp through a lambda to
DistLikelihood does not work: its
make_dist is a static field, so the warp is silently frozen and never
trains.
The expected log-likelihood has no closed form, so
svgp_elbo requires an integrator.
Prefer Gauss-Hermite, and prefer a smooth warp
The warped integrand has heavy tails, so Monte Carlo integration is
high variance -- roughly 4M samples to match Gauss-Hermite at order
20. Gauss-Hermite in turn converges spectrally only for analytic
warps: piecewise ones such as RationalQuadraticSpline stall
around a 3e-3 error floor and their error is non-monotone in
quadrature order, so raising the order is not a valid convergence
check. gauss_flows.MixtureGaussianCDF is smooth and reaches
machine precision.
Note eqx.filter_jit is required over plain jax.jit when jitting
around this likelihood -- flowjax spline pytrees carry string leaves.
Attributes:
| Name | Type | Description |
|---|---|---|
warp |
AbstractBijection
|
Any |
noise_var |
Float[Array, '']
|
Observation noise variance \(\sigma^2\). |
Examples:
>>> import jax.numpy as jnp
>>> from flowjax.bijections import RationalQuadraticSpline
>>> lik = WarpedGaussianLikelihood(
... warp=RationalQuadraticSpline(knots=8, interval=4.0),
... noise_var=jnp.asarray(0.1),
... )
>>> float(lik.log_prob(jnp.zeros(3), jnp.zeros(3))) < 0.0
True
Source code in packages/pyrox-gp/src/pyrox_gp/_warped.py
log_prob(f: Float[Array, ' ...'], y: Float[Array, ' ...'], X: Float[Array, ' ...'] | None = None) -> Float[Array, '']
¶
Sum of per-point Gaussian log-densities about \(G(f)\).
X is required when the warp is conditional (cond_shape
set) and ignored otherwise. Note the cost: the expected
log-likelihood evaluates the warp at every quadrature node, so a
conditional warp pays order conditioner forward passes per
data point.
Source code in packages/pyrox-gp/src/pyrox_gp/_warped.py
warped_predictive_moments(lik: WarpedGaussianLikelihood, f_loc: Float[Array, ' N'], f_var: Float[Array, ' N'], X: Float[Array, 'N D'] | None = None, *, order: int = 32) -> tuple[Float[Array, ' N'], Float[Array, ' N']]
¶
Moments of \(y = G(f) + \epsilon\) under \(q(f)\), by quadrature.
Note \(m_1 \neq G(\mathbb{E}[f])\) whenever \(G\) is nonlinear -- warping the posterior mean is the natural-looking mistake and is badly biased for a skewed warp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lik
|
WarpedGaussianLikelihood
|
The warped likelihood. |
required |
f_loc
|
Float[Array, ' N']
|
Posterior means of the base GP, shape |
required |
f_var
|
Float[Array, ' N']
|
Posterior marginal variances of the base GP, shape |
required |
X
|
Float[Array, 'N D'] | None
|
Inputs of shape |
None
|
order
|
int
|
Gauss-Hermite nodes; at least 2, since one node carries no
spread. Values above ~256 are numerically unreliable
(the rule overflows to |
32
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, ' N'], Float[Array, ' N']]
|
Tuple of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/pyrox-gp/src/pyrox_gp/_warped.py
SVGP inference¶
The structured SVGP ELBO as a differentiable scalar (svgp_elbo), its
NumPyro registration (svgp_factor), and the natural-gradient / CVI
update loop (ConjugateVI) that exploits the NaturalGuide
parameterization for conjugate-style coordinate ascent.
svgp_elbo(prior: SparseGPPrior, guide: Guide, likelihood: Likelihood, X: Float[Array, 'N D'], y: Float[Array, ' N'], *, integrator: GaussxIntegrator | None = None) -> Float[Array, '']
¶
Structured SVGP ELBO as a differentiable scalar.
For GaussianLikelihood the expected log-likelihood has a
closed form and no integrator is needed:
loss = svgp_elbo(prior, guide, GaussianLikelihood(0.1), X, y)
grad = eqx.filter_grad(lambda g: -svgp_elbo(prior, g, ...))(guide)
For non-conjugate likelihoods supply a gaussx integrator:
from gaussx import GaussHermiteIntegrator
loss = svgp_elbo(
prior, guide,
DistLikelihood(lambda f: dist.Bernoulli(logits=f)),
X, y, integrator=GaussHermiteIntegrator(order=20),
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
SparseGPPrior
|
Sparse GP prior (kernel + inducing inputs). |
required |
guide
|
Guide
|
Variational guide over inducing values. |
required |
likelihood
|
Likelihood
|
Observation model. |
required |
X
|
Float[Array, 'N D']
|
Training inputs, shape |
required |
y
|
Float[Array, ' N']
|
Training targets, shape |
required |
integrator
|
AbstractIntegrator | None
|
gaussx integrator for the per-point ELL. Required
for non-conjugate likelihoods; ignored for
|
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar ELBO value (higher is better). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a non-conjugate likelihood is used without an integrator. |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
svgp_factor(name: str, prior: SparseGPPrior, guide: Guide, likelihood: Likelihood, X: Float[Array, 'N D'], y: Float[Array, ' N'], *, integrator: GaussxIntegrator | None = None) -> None
¶
Register the structured SVGP ELBO as a NumPyro factor site.
Wraps svgp_elbo in numpyro.factor so it plugs into
numpyro.infer.SVI + Trace_ELBO. NumPyro sees one
deterministic factor site — the actual ELBO uses the efficient
closed-form KL + structured ELL computation.
def model(X, y):
svgp_factor("elbo", prior, guide, lik, X, y)
svi = SVI(model, lambda X, y: None, Adam(1e-3), Trace_ELBO())
Source code in packages/pyrox-gp/src/pyrox_gp/_inference.py
ConjugateVI
¶
Natural-gradient / CVI update for sparse variational GPs.
Operates in natural-parameter space: each step computes the
per-point expected gradients and Hessians of the log-likelihood
under \(q(f_n)\), projects them into the inducing-value natural
parameters, and applies a damped update via
NaturalGuide.natural_update.
For GaussianLikelihood the gradients and Hessians are
analytical. For non-conjugate likelihoods an integrator is required
to evaluate the expectations numerically.
guide = NaturalGuide.init(num_inducing=M)
cvi = ConjugateVI(damping=0.5)
for epoch in range(100):
guide = cvi.step(prior, guide, GaussianLikelihood(0.1), X, y)
Attributes:
| Name | Type | Description |
|---|---|---|
damping |
float
|
Learning rate / damping factor \(\rho \in (0, 1]\).
|
integrator |
AbstractIntegrator | None
|
gaussx integrator for non-conjugate expected
gradients. |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | |
step(prior: SparseGPPrior, guide: NaturalGuide, likelihood: Likelihood, X: Float[Array, 'N D'], y: Float[Array, ' N']) -> NaturalGuide
¶
One CVI step: compute sites, project, update.
- Predict
(f_loc, f_var) = guide.predict(...) - Compute per-point natural-gradient targets \((\lambda_n^{(1)}, \Lambda_n^{(2)})\).
- Project into inducing space:
- Damped update via
NaturalGuide.natural_update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
SparseGPPrior
|
Sparse GP prior. |
required |
guide
|
NaturalGuide
|
Current natural-parameter guide. |
required |
likelihood
|
Likelihood
|
Observation model. |
required |
X
|
Float[Array, 'N D']
|
Training inputs, shape |
required |
y
|
Float[Array, ' N']
|
Training targets, shape |
required |
Returns:
| Type | Description |
|---|---|
NaturalGuide
|
Updated |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference.py
Non-Gaussian inference strategies¶
Site-based Gaussian approximations q(f) = N(m, V) of the posterior
under a non-conjugate likelihood. All five strategies share the same
diagonal-site view and differ only in where the per-site curvature
comes from: exact Hessian at the mode (Laplace), PSD-projected
Gauss-Newton curvature, statistical linearization under the cavity
(posterior linearization / CVI), moment matching against the tilted
distribution (EP), or L-BFGS to the MAP with a Laplace covariance at
convergence (quasi-Newton). Each fit(prior, likelihood, y) returns a
ConditionedNonGaussGP that quacks like ConditionedGP.
The Laplace and Gauss-Newton loops run on argminax.solve.laplace_mode_covariance, the quasi-Newton one on optimistix.LBFGS, and the posterior-linearisation and EP loops on argminax.solve.site_fixed_point, so all five fits run under jax.jit and jax.vmap (over datasets, say) and their n_iter and converged are arrays. Close over the prior rather than passing it through the transform, since its kernel's priors live in a registry that a rebuilt module loses.
PosteriorLinearization and ExpectationPropagation build the posterior of their sites with gaussx.site_posterior and report gaussx.site_log_evidence, the Laplace-type evidence at the posterior mean (not the EP evidence). They take solver, preconditioner and logdet, and each one left None comes from the prior, so they work on a matrix_free=True prior with an iterative solver. Unlike Laplace, they need the posterior marginal variances at every iteration, because each cavity removes its site from its marginal: with a dense solver that is one Cholesky of \(K + \mathrm{diag}(1 / \Lambda)\) per iteration, and with an iterative one it is \(N\) solves per iteration, batch_size at a time, so the exact route suits a moderate \(N\). For a large \(N\) they take the stochastic variances of gaussx's SitePosterior.variance_and_error (gaussx#827), num_probes solves per iteration whatever \(N\): variance="stochastic", or variance="auto" with an iterative solver above \(N = 2048\). The key of fit is then required, and one key serves every iteration, so the update is a fixed function of the sites and converged refers to that surrogate. Each estimate is clamped for its cavity to at most \((1 - 10^{-3}) / \lambda_n\), so that every cavity precision stays positive, and to at least \(10^{-6} K_{nn}\). The estimator defaults to SBPV, which draws from the prior and the sites, on a dense prior, and to SPV, which needs only products with \(K\), on a matrix-free one, since SBPV would densify the prior for its draws. SPV is much the noisier: on a 200-point Bernoulli problem with 200 probes its standard error was about 4.7 times the variance it estimates, against 0.67 for SBPV, so it needs many more probes. CG's own log-determinant is stochastic Lanczos, so pass logdet=gaussx.DenseLogdet() beside it for an exact evidence at moderate \(N\).
LaplaceInference and GaussNewtonInference take the same solver, preconditioner and logdet, each falling back to the prior's (#551). Every Newton step solves against \(A = K + \mathrm{diag}(1 / \Lambda)\) through that solver on the prior's own operator, so a matrix_free=True prior with CG or BBMM never forms the \(N \times N\) kernel matrix, and unlike the cavity loops they need no marginal variances until q_var is read. Their variance, estimator, num_probes and batch_size mean what they mean for the cavity loops, and only q_var uses them: a stochastic q_var of a fit given no key raises. Give the solver a tolerance at least ten times tighter than the strategy's tol; an inner solve that misses its tolerance makes converged false, and inside a sampler the solver should be built with throw=False. With a stochastic log-determinant the evidence is an estimate whose probes come from the key of fit, condition_nongauss or gp_laplace_factor. QuasiNewtonInference still raises a ValueError on a matrix-free prior, since it whitens its search with a Cholesky root of the kernel matrix.
Every fit keeps its posterior as a gaussx.SitePosterior (site_posterior), with q_mean, site_nat1 and site_nat2 read from it, and predicts from its weights with the hyperparameters the fit used: a kernel with priors is drawn once per fit, and predict registers no new site (before #551 it drew again). Refit to resample.
LaplaceInference
¶
Bases: Module
Laplace approximation via Newton iteration on the log posterior.
Iterates the standard GP-Laplace fixed-point loop (Rasmussen &
Williams Algorithm 3.1): at each iteration evaluate per-point
gradient \(g\) and Hessian diagonal \(h\) of \(\log p(y \mid f)\), set the
sites \(\lambda_n = \max(-h_n, \epsilon)\) and
\(\lambda_n \mu_{\text{site},n} = g_n + \lambda_n f_n\) (floor \(\epsilon\),
precision_floor), and move \(f\) towards the posterior mean of those
sites, \(\mu_f + K A^{-1} (\mu_\text{site} - \mu_f)\) with
\(A = K + \mathrm{diag}(1 / \lambda)\).
The loop is argminax.solve.laplace_mode_covariance, a
lax.while_loop with an implicitly differentiable mode, so fit
runs under jax.jit and jax.vmap; close over the prior, whose
kernel registry does not survive being passed through a transform.
Every solve against \(A\), in the loop, at the mode and in predict, goes
through the solver composed from solver, preconditioner and
logdet (each unset one taken from the prior), on the prior's own
operator, so GPPrior(matrix_free=True) with an iterative solver
never forms the \(N \times N\) kernel matrix (pyrox#551).
The reported log_marginal_approx is the Laplace evidence
gaussx.site_log_evidence at the mode,
with \(m\) the posterior mean of the sites at the mode, computed without
\(K^{-1}\). A dense solver (the default) gives it exactly; a stochastic
log-determinant (CG's own SLQ, gaussx.BBMMSolver) gives the equal
pseudo-observation form, an estimate whose probes come from the key
of fit. Pass logdet=gaussx.DenseLogdet() beside CG for an exact
evidence at moderate \(N\).
With an iterative solver, give it a tolerance at least ten times tighter
than tol (the loop cannot resolve a step below the solves'
residual). An inner solve that misses its tolerance makes converged
false; the variances and the evidence solve through the solver itself,
which raises at max_steps when built with throw=True, so inside
a sampler build it with throw=False.
Attributes:
| Name | Type | Description |
|---|---|---|
max_iter |
int
|
Newton iterations. Default |
tol |
float
|
|
damping |
float
|
Step-size in (0, 1] applied to each Newton update:
|
precision_floor |
float
|
Lower bound on the diagonal precision to keep
|
solver |
AbstractSolverStrategy | None
|
The solve of \(A\); |
preconditioner |
AbstractPreconditioner | None
|
The preconditioner of an iterative |
logdet |
AbstractLogdetStrategy | None
|
The log-determinant of the evidence; |
adjoint |
ImplicitAdjoint | None
|
How the mode is differentiated, an
|
variance |
_VarianceMethod
|
How |
estimator |
_VarianceEstimator
|
The stochastic estimator, |
num_probes |
int
|
Draws or probes of the stochastic variance, one solve
each. Default |
batch_size |
int
|
Solves vectorised together for the exact variances of
an iterative solver. Default |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 | |
fit(prior: GPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, key: Array | None = None) -> ConditionedNonGaussGP
¶
Fit the Laplace approximation at the mode of \(p(f \mid y)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
GPPrior
|
The |
required |
likelihood
|
Likelihood
|
A scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations, shape |
required |
key
|
Array | None
|
PRNG key of a stochastic log-determinant in the evidence
(CG's SLQ, |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussGP
|
The |
Examples:
>>> import gaussx as gx
>>> import jax
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from pyrox_gp import RBF, BernoulliLikelihood, GPPrior
>>> from pyrox_gp import LaplaceInference
>>> X = jnp.linspace(-2.0, 2.0, 10)[:, None]
>>> y = (X[:, 0] > 0.0).astype(X.dtype)
>>> # CG on a matrix-free prior: K is never formed, and the
>>> # evidence is CG's stochastic Lanczos estimate from the key
>>> prior = GPPrior(kernel=RBF(), X=X, matrix_free=True)
>>> strategy = LaplaceInference(solver=gx.CGSolver(rtol=1e-10, atol=1e-10))
>>> fit = jax.jit(
... lambda labels: strategy.fit(
... prior, BernoulliLikelihood(), labels, key=jr.key(0)
... )
... )(y)
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
GaussNewtonInference
¶
Bases: Module
Gauss-Newton inference: Newton loop with PSD-projected curvature.
Identical to LaplaceInference for log-concave likelihoods,
where -d^2 log p / df^2 is already positive. For non-log-concave
likelihoods (e.g. StudentTLikelihood, where the Hessian
becomes positive in the tails) GN aggressively floors the curvature
to a strictly-positive value via precision_floor, guaranteeing a
PSD site precision and stable Newton steps. Laplace uses the same
floor but typically with a smaller default.
For Bernoulli / Poisson the Fisher information equals the negative
Hessian, so GGN ≡ Laplace; for StudentT the floor matters. The loop is
the same argminax.solve.laplace_mode_covariance call, so fit runs
under jax.jit and jax.vmap, and it takes the same solver,
preconditioner and logdet as LaplaceInference, falling back to
the prior's, so a matrix-free prior with an iterative solver never forms
the kernel matrix (pyrox#551).
Attributes:
| Name | Type | Description |
|---|---|---|
max_iter |
int
|
Iterations. Default |
tol |
float
|
|
damping |
float
|
Step-size in (0, 1] applied to each Newton update.
Default |
precision_floor |
float
|
Lower bound on the diagonal precision. Default
|
solver |
AbstractSolverStrategy | None
|
As in |
preconditioner |
AbstractPreconditioner | None
|
As in |
logdet |
AbstractLogdetStrategy | None
|
As in |
adjoint |
ImplicitAdjoint | None
|
As in |
variance |
_VarianceMethod
|
As in |
estimator |
_VarianceEstimator
|
As in |
num_probes |
int
|
As in |
batch_size |
int
|
As in |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 | |
fit(prior: GPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, key: Array | None = None) -> ConditionedNonGaussGP
¶
Fit the Gauss-Newton approximation; as LaplaceInference.fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
GPPrior
|
The |
required |
likelihood
|
Likelihood
|
A scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations, shape |
required |
key
|
Array | None
|
PRNG key of a stochastic log-determinant in the evidence,
ignored by an exact one, and of stochastic marginal
variances, as in |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussGP
|
The |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
PosteriorLinearization
¶
Bases: Module
Iterated statistical-linearization site updates.
At each iteration: form the cavity q_n^\\(¬n) = N(m^c_n, v^c_n)
by removing the current site, then under the cavity compute
statistical-linearization moments
\(\bar g = E_{\rm cav}[\partial_f \log p]\) and
\(\bar h = E_{\rm cav}[\partial^2_f \log p]\) via the integrator,
update the site naturals via gaussx.newton_update with
a damping factor, recompute the global posterior, repeat. This is
PL/CVI in the sense of Adam/Garcia-Fernandez/Sarkka — equivalent
in the Gaussian-cavity limit to taking one EP-style step but using
derivative expectations instead of moment matching.
The posterior of the sites is gaussx.site_posterior through the
strategy's solver, and the loop is argminax.solve.site_fixed_point, so
fit runs under jax.jit and jax.vmap and its gradient in the
kernel hyperparameters is implicit at the fixed point; close over the
prior, whose kernel registry does not survive being passed through a
transform. The cavities need the posterior marginal variances at every
iteration, not only at the end: one Cholesky of
\(A = K + \mathrm{diag}(1 / \Lambda)\) with a dense solver, \(N\) solves
with an iterative one, or num_probes solves for the stochastic
estimate (variance). The reported log_marginal_approx is the
Laplace-type approximation gaussx.site_log_evidence at the posterior
mean, not the EP evidence.
Attributes:
| Name | Type | Description |
|---|---|---|
integrator |
AbstractIntegrator
|
Cavity integrator. Default
|
max_iter |
int
|
Iterations. Default |
damping |
float
|
Step size in (0, 1]. Default |
tol |
float
|
Convergence tolerance: the loop stops at the first iteration
where every site natural changed by less than
|
precision_floor |
float
|
Lower bound on the diagonal precision. |
solver |
AbstractSolverStrategy | None
|
The solve of \(A\); |
preconditioner |
AbstractPreconditioner | None
|
The preconditioner of an iterative |
logdet |
AbstractLogdetStrategy | None
|
The log-determinant of the evidence; |
variance |
_VarianceMethod
|
How the marginal variances are computed, |
estimator |
_VarianceEstimator
|
The stochastic estimator, |
num_probes |
int
|
Draws or probes of the stochastic variance, one solve
each. Default |
adjoint |
AbstractAdjoint | None
|
How gradients pass through the loop; |
batch_size |
int
|
Solves vectorised together for the exact variances of
an iterative solver. Default |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 | |
fit(prior: GPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, key: Array | None = None) -> ConditionedNonGaussGP
¶
Fit the sites by posterior linearisation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
GPPrior
|
The |
required |
likelihood
|
Likelihood
|
A scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations, shape |
required |
key
|
Array | None
|
PRNG key of a stochastic log-determinant in the evidence
(for example |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussGP
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the marginal variances are stochastic (see
|
Examples:
>>> import gaussx as gx
>>> import jax
>>> import jax.numpy as jnp
>>> from pyrox_gp import RBF, BernoulliLikelihood, GPPrior
>>> from pyrox_gp import PosteriorLinearization
>>> X = jnp.linspace(-2.0, 2.0, 10)[:, None]
>>> y = (X[:, 0] > 0.0).astype(X.dtype)
>>> prior = GPPrior(kernel=RBF(), X=X)
>>> strategy = PosteriorLinearization(solver=gx.CGSolver())
>>> # return arrays: a fit passed out of a transform rebuilds its
>>> # kernel without the parameter registry, so predict outside it
>>> q_mean = jax.jit(
... lambda labels: strategy.fit(
... prior, BernoulliLikelihood(), labels
... ).q_mean
... )(y)
>>> q_mean.shape
(10,)
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
ExpectationPropagation
¶
Bases: Module
Parallel expectation propagation (Minka 2001) with damping.
Per outer iteration: for every site simultaneously, form the
cavity, compute the tilted moments
E_{q^c(f) p(y|f)}[1, f, f^2] via the integrator, match them to
a Gaussian, and update site naturals (damped). Parallel-EP is
embarrassingly vectorizable and converges for well-behaved
log-concave likelihoods; for problematic models reduce damping.
On a non-log-concave likelihood EP can cycle, and converged is the
only signal of it.
The posterior of the sites is gaussx.site_posterior through the
strategy's solver, and the loop is argminax.solve.site_fixed_point, so
fit runs under jax.jit and jax.vmap and its gradient is
implicit at the fixed point. As for PosteriorLinearization, the
cavities need the marginal variances at every iteration (one Cholesky
with a dense solver, \(N\) solves with an iterative one, num_probes
for the stochastic estimate), and
log_marginal_approx is the Laplace-type gaussx.site_log_evidence
at the EP mean, not the EP evidence with the cavity normalisers.
Attributes:
| Name | Type | Description |
|---|---|---|
integrator |
AbstractIntegrator
|
Cavity integrator. Default
|
max_iter |
int
|
Iterations. Default |
damping |
float
|
Damping in (0, 1]. Default |
tol |
float
|
Convergence tolerance on the site naturals, as in
|
precision_floor |
float
|
Lower bound on the diagonal precision. |
solver |
AbstractSolverStrategy | None
|
As in |
preconditioner |
AbstractPreconditioner | None
|
As in |
logdet |
AbstractLogdetStrategy | None
|
As in |
variance |
_VarianceMethod
|
As in |
num_probes |
int
|
As in |
adjoint |
AbstractAdjoint | None
|
As in |
batch_size |
int
|
As in |
estimator |
_VarianceEstimator
|
As in |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 | |
fit(prior: GPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, key: Array | None = None) -> ConditionedNonGaussGP
¶
Fit the sites by parallel expectation propagation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
GPPrior
|
The |
required |
likelihood
|
Likelihood
|
A scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations, shape |
required |
key
|
Array | None
|
PRNG key of a stochastic log-determinant in the evidence
(for example |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussGP
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the marginal variances are stochastic (see
|
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> from pyrox_gp import RBF, ExpectationPropagation, GPPrior
>>> from pyrox_gp import StudentTLikelihood
>>> X = jnp.linspace(-2.0, 2.0, 10)[:, None]
>>> y = jnp.sin(X[:, 0]).at[3].set(4.0)
>>> prior = GPPrior(kernel=RBF(), X=X)
>>> strategy = ExpectationPropagation(damping=0.3)
>>> # return arrays: a fit passed out of a transform rebuilds its
>>> # kernel without the parameter registry, so predict outside it
>>> q_means = jax.jit(jax.vmap(
... lambda labels: strategy.fit(
... prior, StudentTLikelihood(df=4.0, scale=0.5), labels
... ).q_mean
... ))(jnp.stack([y, -y]))
>>> q_means.shape
(2, 10)
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
QuasiNewtonInference
¶
Bases: Module
MAP optimization via L-BFGS, Laplace covariance at convergence.
Optimizes the unnormalized log posterior
\(\log p(y | f) - \tfrac12 (f - \mu)^\top K^{-1} (f - \mu)\)
with optimistix.LBFGS in the whitened coordinates \(v\) of
\(f = \mu + L v\), \(L L^\top = K\), where the prior term is
\(\tfrac12 v^\top v\) and the problem is far better conditioned than in
\(f\); then it forms a Laplace-style Gaussian
approximation centered at the optimum using the exact per-point
Hessian. The optimization is the cheap path for very high N where
you cannot afford dense Hessians per iteration; the final Laplace
covariance is computed once.
For full low-rank posterior covariance from L-BFGS history (without the final Hessian solve) see the follow-up issue — this class delivers the simpler "QN optimization, Laplace covariance" contract.
The L-BFGS loop is optimistix.minimise, so fit runs under
jax.jit and jax.vmap.
Dense only: the whitening needs a Cholesky root of the N × N kernel
matrix, and the prior's solver is not used, so a
GPPrior(matrix_free=True) raises ValueError, permanently
(pyrox#549); LaplaceInference with an iterative solver is the
matrix-free route (pyrox#551).
Attributes:
| Name | Type | Description |
|---|---|---|
max_iter |
int
|
L-BFGS iterations. Default |
tol |
float
|
The |
precision_floor |
float
|
Lower bound on the diagonal precision. |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 | |
fit(prior: GPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, key: Array | None = None) -> ConditionedNonGaussGP
¶
Fit by L-BFGS to the mode, then the Laplace Gaussian there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
GPPrior
|
A dense |
required |
likelihood
|
Likelihood
|
A scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations, shape |
required |
key
|
Array | None
|
Accepted so that every strategy takes the keyword of
|
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussGP
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
For |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 | |
ConditionedNonGaussGP
¶
Bases: Module
GP conditioned on a non-Gaussian likelihood via an advanced strategy.
Equivalent role to pyrox_gp.ConditionedGP but the posterior over
training latents is the Gaussian of diagonal sites, a
gaussx.SitePosterior: any site-based approximation of \(p(f \mid y)\)
looks like a Gaussian-likelihood regression with per-point noise
variance \(d_n = 1 / \lambda_n\) and targets
\(\mu_{\text{site},n} = \lambda^{(1)}_n / \lambda_n\), so with
\(A = K + \mathrm{diag}(d)\) the fit keeps the weights
\(w = A^{-1} (\mu_\text{site} - \mu_f)\) and predicts with
through the solver of the fit: triangular solves with the Cholesky factor of \(A\) kept from the fit on the dense path, one solve per test point with an iterative solver, so a matrix-free prior stays matrix-free.
The kernel's hyperparameters are those the fit used (pyrox#551): the fit
resolves them once, and predict reuses them. Before pyrox#551 each
predict evaluated the prior's kernel again, so a kernel with priors
drew new hyperparameters there; refit to resample.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
GPPrior
|
The |
y |
Float[Array, ' N']
|
Training targets (kept for round-trip / diagnostics). |
site_posterior |
SitePosterior
|
The |
log_marginal_approx |
Float[Array, '']
|
Approximate log marginal likelihood (the scalar each strategy reports — interpretation is strategy-specific; see the per-class docstring). |
n_iter |
Int[Array, '']
|
Iterations used by the strategy, a scalar integer array,
so a fit runs under |
converged |
Bool[Array, '']
|
Whether the convergence tolerance was met, a scalar boolean array; with an iterative solver it is also false when an inner solve of a Newton fit missed its tolerance. |
kernel |
Kernel
|
The prior's kernel with the hyperparameters of the fit, a
plain kernellib kernel ( |
marginal_variance |
_MarginalVariance
|
How |
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | |
batch_size: int
property
¶
Solves vectorised together for the exact variances of an iterative fit.
site_nat1: Float[Array, ' N']
property
¶
The site information \(\lambda^{(1)} = \lambda \odot \mu_\text{site}\).
site_nat2: Float[Array, ' N']
property
¶
The site precisions \(\lambda\), all positive.
q_mean: Float[Array, ' N']
property
¶
The posterior mean \(\mu_f + K w\) at the training inputs.
solver: AbstractSolverStrategy | None
property
¶
The iterative solver the fit used; None for a dense fit.
A dense fit predicts by the Cholesky factor of \(A\) kept from the fit, an iterative one by one solve per test point through this solver.
q_var: Float[Array, ' N']
property
¶
The posterior marginal variances \(\mathrm{diag}(K - K A^{-1} K)\).
Computed when read, so a fit that needs only the mean or the
evidence does no extra solves: triangular solves with the kept
factor on the dense path, \(N\) solves (batch_size at a time) with
an iterative solver, or, for a fit whose variance resolved to
"stochastic", num_probes solves and the estimate of
gaussx.SitePosterior.variance, clamped at zero.
Raises:
| Type | Description |
|---|---|
ValueError
|
For stochastic variances of a fit given no |
predict_mean(X_star: Float[Array, 'M D']) -> Float[Array, ' M']
¶
\(\mu_* = \mu(X_*) + K_{*X} w\), from the weights of the fit.
predict_var(X_star: Float[Array, 'M D']) -> Float[Array, ' M']
¶
\(k_{**} - k_*^\top (K + \mathrm{diag}(1/\lambda))^{-1} k_*\).
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
predict(X_star: Float[Array, 'M D']) -> tuple[Float[Array, ' M'], Float[Array, ' M']]
¶
Joint mean / marginal-variance prediction at X_star.
Both use the hyperparameters of the fit, so the pair is self-consistent and a kernel with priors registers no new site.
Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
Multi-output GPs¶
Vector-valued GPs via coregionalization: the linear model of
coregionalization (LMC) mixes Q independent latent processes through
a learned matrix, the intrinsic coregionalization model (ICM) shares
one latent kernel, and the orthogonal instantaneous linear mixing model
(OILMM) constrains the mixing to be orthogonal so inference decouples
per latent process (the projections delegate to gaussx.oilmm_project
/ gaussx.oilmm_back_project).
LMCKernel
¶
Bases: Module
Linear model of coregionalization for vector-valued GPs.
Each output is a linear combination of latent scalar GPs:
f_p(x) = sum_q W[p, q] g_q(x). The cross-output covariance is
Cov[f_p(x), f_{p'}(x')] = sum_q (w_q w_q^T)[p, p'] k_q(x, x').
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
num_outputs: int
property
¶
Number of observed output channels P.
num_latents: int
property
¶
Number of latent scalar GPs Q.
coregionalization_matrix(q: int) -> Float[Array, 'P P']
¶
Return the rank-1 coregionalization matrix w_q w_q^T.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
kronecker_factors(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> tuple[tuple[Float[Array, 'P P'], Float[Array, 'N1 N2']], ...]
¶
Return (B_q, K_q(X1, X2)) factors for each latent process.
All latent kernel evaluations share one per-call context per unique kernel instance, so reusing the same kernel across latents (for hyperparameter tying) registers each sample site exactly once.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
output_covariance(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> Float[Array, 'P P N1 N2']
¶
Return output-pair covariance blocks with shape (P, P, N1, N2).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
cross_covariance_operator(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> lx.AbstractLinearOperator
¶
Return Cov[vec(F(X1)), vec(F(X2))] as a sum-of-Kroneckers operator.
The returned operator preserves the per-latent Kronecker structure
so structure-aware solvers can avoid materializing the full
(P*N1, P*N2) matrix.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
cross_covariance(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> Float[Array, 'PN1 PN2']
¶
Return the dense covariance of vec(F(X1)) and vec(F(X2)).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
full_covariance_operator(X: Float[Array, 'N D']) -> lx.AbstractLinearOperator
¶
Return the Gram operator for isotopic multi-output observations.
full_covariance(X: Float[Array, 'N D']) -> Float[Array, 'PN PN']
¶
Return the dense Gram matrix for isotopic multi-output observations.
diag(X: Float[Array, 'N D']) -> Float[Array, 'N P']
¶
Return per-input, per-output marginal variances with shape (N, P).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
ICMKernel
¶
Bases: Module
Intrinsic coregionalization model with one shared latent kernel.
The cross-output covariance is kron(B, k(X1, X2)) with
B = W W^T + diag(kappa). When kappa is None the extra diagonal
term is omitted.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |
num_outputs: int
property
¶
Number of observed output channels P.
num_latents: int
property
¶
Number of latent scalar GPs Q.
coregionalization_matrix() -> Float[Array, 'P P']
¶
Return B = W W^T + diag(kappa).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
kronecker_factors(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> tuple[Float[Array, 'P P'], Float[Array, 'N1 N2']]
¶
Return the shared (B, K(X1, X2)) Kronecker factors.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
output_covariance(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> Float[Array, 'P P N1 N2']
¶
Return output-pair covariance blocks with shape (P, P, N1, N2).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
cross_covariance_operator(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> Kronecker
¶
Return Cov[vec(F(X1)), vec(F(X2))] as a Kronecker operator.
The kron(B, K) structure lets downstream solvers apply
gaussx.kronecker_mll and related Kronecker-exact routines
instead of materializing a (P*N1, P*N2) matrix.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
cross_covariance(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> Float[Array, 'PN1 PN2']
¶
Return the dense covariance of vec(F(X1)) and vec(F(X2)).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
full_covariance_operator(X: Float[Array, 'N D']) -> Kronecker
¶
Return the Gram operator for isotopic multi-output observations.
full_covariance(X: Float[Array, 'N D']) -> Float[Array, 'PN PN']
¶
Return the dense Gram matrix for isotopic multi-output observations.
diag(X: Float[Array, 'N D']) -> Float[Array, 'N P']
¶
Return per-input, per-output marginal variances with shape (N, P).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
OILMMKernel
¶
Bases: Module
Orthogonal instantaneous linear mixing model.
The latent GP kernels stay independent. Orthogonal mixing makes it
possible to project observations into latent space and run Q scalar
GP problems instead of one monolithic multi-output solve. Observation
noise lives in a separate pyrox_gp.Likelihood; this class
returns noise-free signal covariance, matching the LMC/ICM convention.
Pass check_orthogonal=True to verify W^T W ≈ I at
construction — useful as a defensive check when W comes from
an external computation that may drift off the Stiefel manifold.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 | |
num_outputs: int
property
¶
Number of observed output channels P.
num_latents: int
property
¶
Number of latent scalar GPs Q.
is_orthogonal(*, atol: float = 1e-06, rtol: float = 1e-06) -> bool
¶
Whether the current mixing matrix satisfies W^T W ≈ I.
Returns a Python bool via a host sync; not usable inside
jax.jit / jax.vmap.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
project(Y: Float[Array, 'N P'], noise_var: Float[Array, ' P'] | float) -> tuple[Float[Array, 'N Q'], Float[Array, ' Q']]
¶
Project observations to latent space + per-latent noise variances.
Delegates to gaussx.oilmm_project. Returns
(Y_latent, noise_latent) with shapes (N, Q) and (Q,);
the per-latent noise is noise_latent = (W**2).T @ noise_var.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
back_project(f_means: Float[Array, 'N Q'], f_vars: Float[Array, 'N Q']) -> tuple[Float[Array, 'N P'], Float[Array, 'N P']]
¶
Back-project latent GP predictive (means, vars) to output space.
Delegates to gaussx.oilmm_back_project.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
independent_gps() -> tuple[Kernel, ...]
¶
signal_factors(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> tuple[tuple[Float[Array, 'P P'], Float[Array, 'N1 N2']], ...]
¶
Return the latent signal factors before any observation noise.
All latent kernel evaluations share one per-call context per
unique kernel instance, mirroring LMCKernel.kronecker_factors.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
signal_covariance_operator(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> lx.AbstractLinearOperator
¶
Return the noise-free signal covariance as a structured operator.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
signal_covariance(X1: Float[Array, 'N1 D'], X2: Float[Array, 'N2 D']) -> Float[Array, 'PN1 PN2']
¶
Return the dense noise-free signal covariance matrix.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
full_covariance_operator(X: Float[Array, 'N D']) -> lx.AbstractLinearOperator
¶
Return the noise-free Gram operator for isotopic observations.
full_covariance(X: Float[Array, 'N D']) -> Float[Array, 'PN PN']
¶
diag(X: Float[Array, 'N D']) -> Float[Array, 'N P']
¶
Return per-input, per-output marginal signal variances.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
oilmm_factor(name: str, prior: OILMMGPPrior, Y: Float[Array, 'N P'], noise_var: Float[Array, '']) -> None
¶
Register the OILMM collapsed log marginal likelihood with NumPyro.
Adds numpyro.factor(name, prior.log_marginal(Y, noise_var)): the
exact log marginal of the orthogonal-mixing model at the projected
cost of OILMMGPPrior.log_marginal, the OILMM analogue of
mo_gp_factor. Registers the one site name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
prior
|
OILMMGPPrior
|
The |
required |
Y
|
Float[Array, 'N P']
|
Observations, shape |
required |
noise_var
|
Float[Array, '']
|
The isotropic noise variance, a scalar. |
required |
Examples:
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> from pyrox_gp import RBF, OILMMGPPrior, OILMMKernel, oilmm_factor
>>> X = jnp.linspace(0.0, 1.0, 6)[:, None]
>>> W = jnp.array([[0.6], [0.8]])
>>> Y = jnp.stack([jnp.sin(4 * X[:, 0]), jnp.cos(4 * X[:, 0])], -1)
>>> def model():
... noise = numpyro.sample("noise_var", dist.LogNormal(-3.0, 1.0))
... prior = OILMMGPPrior(OILMMKernel(kernels=(RBF(),), mixing=W), X)
... oilmm_factor("y", prior, Y, noise)
>>> trace = numpyro.handlers.trace(numpyro.handlers.seed(model, 0)).get_trace()
>>> sorted(trace)
['RBF.lengthscale', 'RBF.variance', 'noise_var', 'y']
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output_models.py
MultiOutputInducingVariables
¶
Bases: Module
Shared inducing-point structure for LMC-style sparse workflows.
mixing[p, q] is the weight with which latent process q enters
output p; the block layout of K_uf matches that convention.
ICMKernel with non-zero kappa cannot be represented here —
the extra diagonal does not fit the per-latent factorization.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 | |
num_outputs: int
property
¶
Number of observed output channels P.
num_latents: int
property
¶
Number of latent scalar GPs Q.
from_kernel(kernel: LMCKernel | ICMKernel, inducing: SharedInducingPoints) -> MultiOutputInducingVariables
classmethod
¶
Construct from a kernel, sharing its mixing matrix.
Avoids the footgun of maintaining two independent mixing
copies that can silently disagree between K_ff and K_uf.
Only LMCKernel and ICMKernel are accepted;
OILMMKernel is rejected because the sparse inducing
workflow does not currently exploit orthogonal projection.
ICMKernel with non-zero kappa is rejected: the
sparse blocks assembled downstream (K_uu / K_uf)
do not carry the diag(kappa) contribution that is present
in ICMKernel.K_ff, so accepting it here would silently
produce inconsistent covariance terms and underestimate output
variance. Users who need the kappa contribution should use
the dense multi-output solve.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
K_uu_operator(kernels: tuple[Kernel, ...]) -> BlockDiag
¶
Return the block-diagonal inducing covariance as a BlockDiag.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
K_uu(kernels: tuple[Kernel, ...]) -> Float[Array, 'QM QM']
¶
Return the block-diagonal inducing covariance over latent processes.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
K_uf(X: Float[Array, 'N D'], kernels: tuple[Kernel, ...]) -> Float[Array, 'QM PN']
¶
Return the inducing-to-output cross-covariance for isotopic outputs.
The block layout is
K_uf[q*M:(q+1)*M, p*N:(p+1)*N] = mixing[p, q] * k_q(Z, X).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
inducing_blocks(X: Float[Array, 'N D'], kernels: tuple[Kernel, ...]) -> tuple[BlockDiag, Float[Array, 'QM PN']]
¶
Return (K_uu_op, K_uf) under one shared kernel context.
Use this in place of separate K_uu_operator /
K_uf calls when assembling an SVGP-style sparse
predictive: it shares one per-call context per unique kernel
instance across both blocks, so Pattern B/C kernels with priored
hyperparameters register their pyrox_sample sites
exactly once and the two blocks see the same hyperparameter
draw. Sequential calls would close the per-call context between
K_uu and K_uf, which would re-register sites under a
NumPyro trace (or resample inconsistent hyperparameters under
numpyro.handlers.seed).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
SharedInducingPoints
¶
Bases: Module
Shared inducing inputs for multi-output latent GP collections.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 | |
num_inducing: int
property
¶
Number of inducing inputs M shared by all latent processes.
latent_covariances(kernels: tuple[Kernel, ...]) -> tuple[Float[Array, 'M M'], ...]
¶
Return one inducing covariance block per latent kernel.
Shares a per-call context per unique kernel instance so a kernel reused across latents registers its sample sites once.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
K_uu_operator(kernels: tuple[Kernel, ...]) -> BlockDiag
¶
Return the block-diagonal inducing covariance as a BlockDiag.
Downstream solvers decompose a (Q*M, Q*M) solve into Q
independent (M, M) solves via the block_diagonal_tag.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
K_uu(kernels: tuple[Kernel, ...]) -> Float[Array, 'QM QM']
¶
Materialize the block-diagonal inducing covariance over all latents.
cross_covariances(X: Float[Array, 'N D'], kernels: tuple[Kernel, ...]) -> tuple[Float[Array, 'M N'], ...]
¶
Return one K(Z, X) block per latent kernel.
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
inducing_blocks(X: Float[Array, 'N D'], kernels: tuple[Kernel, ...]) -> tuple[tuple[Float[Array, 'M M'], ...], tuple[Float[Array, 'M N'], ...]]
¶
Return (K_uu_blocks, K_uf_blocks) under one shared context.
Pairs the per-latent K(Z, Z) and K(Z, X) evaluations so
Pattern B/C kernels with priored hyperparameters register their
pyrox_sample sites once across the K_uu/K_uf pair.
Calling latent_covariances and cross_covariances
sequentially would close and reopen each kernel's per-call
context between the two calls, clearing the sample-site cache
and tripping duplicate-site registration under a NumPyro trace
(or resampling inconsistent hyperparameters under
numpyro.handlers.seed).
Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
Latent factor¶
Collapsed latent-factor regression: the linear decoder (mixing matrix)
carries a fixed unit-normal prior and is marginalized analytically, so
the likelihood factorizes only a Q x Q capacitance matrix and costs
O(NQP) in the output dimension. Contrast the coregionalization
kernels above, which hold the mixing matrix as a concrete array.
LatentFactorGPPrior
¶
Bases: Module
GP latent factors with an analytically marginalized linear decoder.
Unlike pyrox_gp.OILMMKernel, the mixing matrix is not a field of
this module. It is a random variable with a fixed \(\mathcal{N}(0,1)\)
prior, integrated out in
collapsed_lfr_log_prob and recovered
in closed form by
decoder_posterior. There is therefore no
orthogonality requirement and no Q <= P constraint, and the output
dimension P is not fixed at construction — it is read from Y at
condition time.
Caveats to keep in mind:
- Only the span of
Zis identified. The \(\mathcal{N}(0, I)\) prior on the decoder is rotation-invariant, so any orthogonal \(Z \to ZA\), \(W \to A^\top W\) leaves the objective unchanged. Individual latent factors carry no physical meaning without an extra rotation criterion. - The kernel amplitude is identifiable (unlike the rotation above).
\(Z \to cZ\), \(W \to W/c\) is degenerate only when \(W\) is a free
parameter; here \(W\) carries a fixed \(\mathcal{N}(0, I)\) prior and is
marginalized, so scaling \(Z\) changes the collapsed covariance
\(ZZ^\top + \sigma^2 I\) and the amplitude has a finite,
data-dependent optimum. Fixing
variance = 1.0per latent is a legitimate modelling choice (it makes the factors comparable), not a requirement for a valid fit. predict_latentsvariance understates uncertainty. It treats the MAPZas noiseless observations of the latent processes, so it captures input-space extrapolation but not uncertainty in the point estimate itself.z_*andWare assumed independent inpredict. They are not — both depend on the training data through the fittedZ. Reasonable whenPis large; understates variance for smallP.- This is a low-data model.
ZisN x Qfree parameters, does not amortize, does not minibatch overN, and carriesO(Q N^3)through the latent priors. The reference experiments top out atN = 800.
Warp-specific caveats (ignore when warp is None):
Ymust sit inside the warp's support.gauss_flows.RQSplineMarginalis linear outside[-interval, interval]; scaleYsensibly or the warp degenerates to affine.- Identifiability gets worse. A per-channel affine warp is
degenerate with \(\sigma\) and with the columns of \(W\). Identity
init plus a distinct learning-rate group
(
param_group_optimizer) is the mitigation. - The warp is fitted to the marginals of
Y, not the residuals. A warp that Gaussianizes raw channel marginals is not necessarily the one that Gaussianizes the noise — a genuine modelling approximation, not a bug. - Invertibility is mandatory. The change of variables requires a bijection, unlike warped-likelihood GPs where a bound holds for any monotone link.
Attributes:
| Name | Type | Description |
|---|---|---|
kernels |
tuple[Kernel, ...]
|
One |
X |
Float[Array, 'N D']
|
Training inputs of shape |
warp |
AbstractBijection | None
|
Optional bijection with event shape |
latent_noise |
float
|
Model nugget added to each latent GP covariance. A
modelling choice that controls how tightly the latent GP
interpolates the MAP factors — distinct from |
jitter |
float
|
Numerical diagonal regularization for Cholesky stability. |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | |
num_latents: int
property
¶
Number of latent scalar GPs Q.
latent_priors() -> tuple[GPPrior, ...]
¶
Return one scalar pyrox_gp.GPPrior per latent process.
latent_cholesky() -> Float[Array, 'Q N N']
¶
Batched Cholesky factors of the Q latent GP covariances.
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
condition(Y: Float[Array, 'N P'], Z: Float[Array, 'N Q'], noise_var: Float[Array, '']) -> ConditionedLatentFactorGP
¶
Recover the decoder posterior for MAP latents Z.
Returns a pyrox_gp.ConditionedLatentFactorGP holding the
closed-form matrix-normal decoder posterior alongside the latents,
with each latent GP conditioned once so repeated predict calls
do not repeat the O(Q N^3) training solve.
Call this under the same context you fitted in
The kernels resolve their hyperparameters when this method
evaluates them. Outside a NumPyro substitution context they
resolve to their initial values, so predictions would come
from different kernels than the fit. Wrap the call in
numpyro.handlers.substitute(fn, result.params) — see the
module docstring for the end-to-end pattern.
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
ConditionedLatentFactorGP
¶
Bases: Module
Latent-factor posterior — MAP latents plus the decoder posterior.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
LatentFactorGPPrior
|
The |
Z |
Float[Array, 'N Q']
|
MAP latent factor values at the training inputs, |
mu_W |
Float[Array, 'Q P']
|
Decoder posterior mean, |
Sigma_W |
Float[Array, 'Q Q']
|
Decoder posterior row covariance, |
noise_var |
Float[Array, '']
|
Scalar isotropic observation noise variance. |
latents |
tuple[ConditionedGP, ...]
|
One conditioned scalar GP per latent process, built once
by |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | |
predict_latents(X_new: Float[Array, 'T D']) -> tuple[Float[Array, 'T Q'], Float[Array, 'T Q']]
¶
Per-latent GP conditional means and marginal variances at X_new.
The MAP latents are treated as observations of the latent processes
with latent_noise as their noise, so the returned variance
reflects input-space extrapolation only — not uncertainty in the
point estimate Z itself.
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
predict(X_new: Float[Array, 'T D'], *, include_noise: bool = False, quad_order: int = 32) -> tuple[Float[Array, 'T P'], Float[Array, 'T P']]
¶
Posterior predictive mean and variance over all P outputs.
Composes the latent GP conditional with the decoder posterior via
lfr_predictive_moments. The
variance decomposes into a decoder term, a latent term, and an
interaction term; the first and third are output-independent.
With a warp, the warped-space moments are pushed through \(G\)
(transform) by Gauss-Hermite quadrature. The returned mean is
\(\mathbb{E}[G(f)]\), not \(G(\mathbb{E}[f])\) — the latter is the
pushforward median for a monotone warp and is badly biased for a
skewed one.
The warped predictive is an approximation
\(f = z_*^\top W\) is a product of two independent Gaussians,
which is not itself Gaussian;
lfr_predictive_moments
gives its exact first two moments, and the quadrature below
builds Gaussian nodes from them. The observation-space moments
are therefore moment-matched, not exact, and the error grows
with the product of the latent and decoder variances relative
to the mean. The unwarped path (warp=None) is unaffected —
it returns the exact moments directly.
The latent variance includes the model's latent_noise
nugget, matching the prior lfr_model fits. include_noise
additionally adds the observation noise, a separate quantity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_new
|
Float[Array, 'T D']
|
Test inputs, shape |
required |
include_noise
|
bool
|
Add the observation noise variance. With a warp, the noise lives in the warped space, so it is added before the pushforward. |
False
|
quad_order
|
int
|
Gauss-Hermite order for the warped pushforward, in
|
32
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'T P'], Float[Array, 'T P']]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
lfr_model(X: Float[Array, 'N D'], Y: Float[Array, 'N P'], prior: LatentFactorGPPrior, *, beta: float | None = None, noise_prior_scale: float = 0.5) -> None
¶
MAP-over-latents collapsed latent-factor regression model.
Pair with numpyro.infer.autoguide.AutoDelta — the latents are a
point estimate, not a marginalized quantity. Latents are stored
transposed, as (Q, N), so the Q independent GP priors form a
batch dimension of one batched multivariate normal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Float[Array, 'N D']
|
Training inputs, |
required |
Y
|
Float[Array, 'N P']
|
Centered observations, |
required |
prior
|
LatentFactorGPPrior
|
The |
required |
beta
|
float | None
|
Inverse temperature forwarded to
|
None
|
noise_prior_scale
|
float
|
Scale of the half-normal prior on the noise standard deviation. |
0.5
|
With a warp on the prior, the warp's array leaves are registered as a
single pytree-valued numpyro.param site ("warp_params") so all
four blocks — latents, noise, kernel hyperparameters, and the warp —
fit jointly under SVI. After fitting, rebuild the warp for prediction
with eqx.combine(result.params["warp_params"],
eqx.partition(prior.warp, eqx.is_inexact_array)[1]) and pass it via
eqx.tree_at (or reconstruct the prior) before calling condition.
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
lfr_factor(*args, **kwargs) -> None
¶
Register the collapsed latent-factor log-likelihood with NumPyro.
Called as lfr_factor(name, prior, Y, Z, noise_var, *, beta=None),
the order of every other factor (gp_factor, mo_gp_factor, …).
Registers the one factor site name: the collapsed likelihood
collapsed_lfr_log_prob, or warped_lfr_log_prob when the prior has
a warp.
The likelihood term grows as \(O(NP)\) while the GP prior on \(Z\) grows
as \(O(NQ)\), so for \(P \gg Q\) an untempered MAP drives \(Z\) to
interpolate noise. The likelihood is therefore scaled by an inverse
temperature beta; priors are left at unit weight.
The old form lfr_factor(Y, Z, noise_var, *, warp=None, beta=None,
name="collapsed_lfr") still works and registers the same factor, with
a DeprecationWarning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
NumPyro factor site name. |
required | |
prior
|
The |
required | |
Y
|
Observations, |
required | |
Z
|
Latent factor values, |
required | |
noise_var
|
Scalar isotropic observation noise variance (in the warped space when the prior has a warp). |
required | |
beta
|
Inverse temperature on the likelihood. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from numpyro import handlers
>>> from pyrox_gp import RBF, LatentFactorGPPrior, lfr_factor
>>> X = jnp.linspace(0.0, 1.0, 5)[:, None]
>>> prior = LatentFactorGPPrior(kernels=(RBF(),), X=X)
>>> Y = jr.normal(jr.key(0), (5, 4))
>>> Z = jr.normal(jr.key(1), (5, 1))
>>> def model():
... lfr_factor("y", prior, Y, Z, jnp.asarray(0.1))
>>> trace = handlers.trace(handlers.seed(model, 0)).get_trace()
>>> float(trace["y"]["scale"]) # beta = Q / P
0.25
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
latent_total_correlation(Z: Float[Array, 'N Q']) -> Float[Array, '']
¶
Total correlation of the fitted latent factors.
The model places an independent GP prior on each of the \(Q\) latent
factors. A large value here means that assumption is violated in the
fit — usually because \(Q\) is larger than the data supports, or because
the optimizer landed in a badly rotated gauge (only the span of \(Z\) is
identified; see pyrox_gp.LatentFactorGPPrior).
Diagnostic only — this does not enter the objective. Requires the
flows optional dependency (pip install 'pyrox-gp[flows]').
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Z
|
Float[Array, 'N Q']
|
MAP latent factor values, shape |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar total correlation, zero for exactly independent factors. |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
latent_init(Y: Float[Array, 'N D'], n_latent: int, *, method: Literal['pca', 'kernel_pca', 'laplacian_eigenmaps'] = 'pca', kernel: kl.AbstractKernel | None = None, n_neighbors: int = 10, standardize: bool = True) -> Float[Array, 'N Q']
¶
Initial latents (N, n_latent) for a GPLVM or latent-factor model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
Float[Array, 'N D']
|
Observations, one row per point. |
required |
n_latent
|
int
|
Latent dimension \(Q\). |
required |
method
|
Literal['pca', 'kernel_pca', 'laplacian_eigenmaps']
|
|
'pca'
|
kernel
|
AbstractKernel | None
|
The kernel for |
None
|
n_neighbors
|
int
|
Graph degree for |
10
|
standardize
|
bool
|
Scale each column to unit variance, matching the GPLVM prior \(X \sim \mathcal N(0, I_Q)\). |
True
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'N Q']
|
The latents. Deterministic: each column's sign is fixed so that its |
Float[Array, 'N Q']
|
largest-magnitude entry is positive. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For an unknown method, or |
Examples:
Start a latent-factor model's latents Z_T (stored transposed,
(Q, N)) on the data manifold:
from numpyro.infer.autoguide import AutoDelta
from numpyro.infer.initialization import init_to_value
Z0 = latent_init(Y, 6, method="laplacian_eigenmaps")
guide = AutoDelta(lfr_model, init_loc_fn=init_to_value(values={"Z_T": Z0.T}))
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_init.py
collapsed_lfr_log_prob(Y: Float[Array, 'N P'], Z: Float[Array, 'N Q'], noise_var: Float[Array, ''], *, jitter: float = 1e-12) -> Float[Array, '']
¶
Log-likelihood with the linear decoder marginalized analytically.
Evaluates
via the Woodbury identity in the \(Q \times Q\) capacitance matrix \(\Psi = I_Q + \sigma^{-2} Z^\top Z\), so no \((N, N)\) matrix is ever formed. Cost is \(O(NQ^2 + NQP + Q^3)\); the output dimension \(P\) enters only through \(\lVert Y \rVert_F^2\) and \(Z^\top Y\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
Float[Array, 'N P']
|
Observations of shape |
required |
Z
|
Float[Array, 'N Q']
|
Latent factor values at the training inputs, shape |
required |
noise_var
|
Float[Array, '']
|
Scalar isotropic observation noise variance. Per-output noise is not supported — it breaks the shared-covariance identity the derivation rests on. |
required |
jitter
|
float
|
Added to |
1e-12
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar log-likelihood. |
Examples:
>>> import jax.numpy as jnp
>>> Y = jnp.zeros((5, 100))
>>> Z = jnp.ones((5, 2))
>>> float(collapsed_lfr_log_prob(Y, Z, 0.1)) < 0.0
True
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
decoder_posterior(Y: Float[Array, 'N P'], Z: Float[Array, 'N Q'], noise_var: Float[Array, ''], *, jitter: float = 1e-12) -> tuple[Float[Array, 'Q P'], Float[Array, 'Q Q']]
¶
Closed-form matrix-normal posterior over the decoder.
The row covariance is shared across all \(P\) columns and the column covariance is the identity, so the full \(QP \times QP\) posterior covariance is exactly \(\Psi^{-1} \otimes I_P\) and is never built.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
Float[Array, 'N P']
|
Observations of shape |
required |
Z
|
Float[Array, 'N Q']
|
Latent factor values, shape |
required |
noise_var
|
Float[Array, '']
|
Scalar isotropic observation noise variance. |
required |
jitter
|
float
|
Added to |
1e-12
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'Q P'], Float[Array, 'Q Q']]
|
Tuple of |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
lfr_predictive_moments(z_mean: Float[Array, 'T Q'], z_var: Float[Array, 'T Q'], mu_W: Float[Array, 'Q P'], Sigma_W: Float[Array, 'Q Q'], noise_var: Float[Array, ''] | None = None) -> tuple[Float[Array, 'T P'], Float[Array, 'T P']]
¶
Exact moments of the product of two independent Gaussians.
For \(z \sim \mathcal{N}(m, \mathrm{diag}(v))\) independent of \(W \sim \mathcal{MN}(\mu_W, \Sigma_W, I_P)\), the predictive \(f = z^\top W\) has
The first and third terms do not depend on the output index, so they are
computed once as (T, 1) columns and broadcast over P. Predictive
variance for very wide outputs therefore costs barely more than the mean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z_mean
|
Float[Array, 'T Q']
|
Latent predictive means, shape |
required |
z_var
|
Float[Array, 'T Q']
|
Latent predictive marginal variances, shape |
required |
mu_W
|
Float[Array, 'Q P']
|
Decoder posterior mean, shape |
required |
Sigma_W
|
Float[Array, 'Q Q']
|
Decoder posterior row covariance, shape |
required |
noise_var
|
Float[Array, ''] | None
|
If given, added to the variance for the observation-noise predictive rather than the signal predictive. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'T P'], Float[Array, 'T P']]
|
Tuple of |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
warp_to_base(warp: AbstractBijection, Y: Float[Array, 'N P']) -> tuple[Float[Array, 'N P'], Float[Array, '']]
¶
Map observations into the space where the factor model is linear.
The warp has event shape (P,) -- one marginal transform per output
channel -- and is applied independently to each of the N rows.
The warp must be elementwise
The event shape check below cannot tell a per-channel bijection
from a coupled one (a triangular affine transform has the same
(P,) event shape and passes). A coupled warp trains and
conditions without complaint, but prediction keeps only per-channel
marginal moments and evaluates every channel at the same scalar
quadrature node, which silently imposes perfect standardized
correlation. Pass a genuinely marginal transform such as
gauss_flows.RQSplineMarginal; a coupled one would need the full
joint covariance and multidimensional integration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
warp
|
AbstractBijection
|
Elementwise bijection with event shape |
required |
Y
|
Float[Array, 'N P']
|
Observations of shape |
required |
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'N P'], Float[Array, '']]
|
Tuple of |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
warped_lfr_log_prob(Y: Float[Array, 'N P'], Z: Float[Array, 'N Q'], noise_var: Float[Array, ''], warp: AbstractBijection, *, jitter: float = 1e-12) -> Float[Array, '']
¶
Collapsed latent-factor log-likelihood on warped observations.
Models \(G^{-1}(y_j) = Z w_j + \epsilon\), so
The Jacobian term is free of \(Z\), \(W\) and \(\sigma\), so the analytic
decoder marginalization of
collapsed_lfr_log_prob is
unchanged and the cost stays linear in \(P\).
Warp direction is a performance cliff
This evaluates G^{-1} (inverse) on every step, so a warp
that is cheap forward and expensive backward costs dearly:
MixtureGaussianCDF.inverse runs a bisection solver and is ~40x
its own forward cost, ~459x slower end-to-end than the
alternative. Prefer gauss_flows.RQSplineMarginal — closed-form
in both directions and the exact identity at initialization.
Wrapping a mixture-CDF warp in flowjax.bijections.Invert is
cheap, but it is a different model, not a faster route to the
same one: this function applies warp.inverse, which is
M.inverse for M and M.transform for Invert(M), so
the two map Y to different base values and define different
likelihoods. Choose it because the flipped map is the warp you
want, never as a drop-in speedup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
Float[Array, 'N P']
|
Observations of shape |
required |
Z
|
Float[Array, 'N Q']
|
Latent factor values at the training inputs, shape |
required |
noise_var
|
Float[Array, '']
|
Scalar isotropic observation noise variance, in the warped space. |
required |
warp
|
AbstractBijection
|
Bijection with event shape |
required |
jitter
|
float
|
Added to |
1e-12
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar log-likelihood. |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
warped_decoder_posterior(Y: Float[Array, 'N P'], Z: Float[Array, 'N Q'], noise_var: Float[Array, ''], warp: AbstractBijection, *, jitter: float = 1e-12) -> tuple[Float[Array, 'Q P'], Float[Array, 'Q Q']]
¶
Matrix-normal decoder posterior, read in the warped space.
Identical to decoder_posterior applied
to G^{-1}(Y) -- the warp does not change the conjugacy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
Float[Array, 'N P']
|
Observations of shape |
required |
Z
|
Float[Array, 'N Q']
|
Latent factor values, shape |
required |
noise_var
|
Float[Array, '']
|
Scalar isotropic observation noise variance, in the warped space. |
required |
warp
|
AbstractBijection
|
Bijection with event shape |
required |
jitter
|
float
|
Added to |
1e-12
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'Q P'], Float[Array, 'Q Q']]
|
Tuple of |
Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
Pathwise posterior samplers (#39)¶
Callable posterior function draws via Matheron's rule. Each sampled
path is a PathwiseFunction that evaluates in
O(N_* · F · D + N_* · N_corr) per path — N_* · F · D for the
RFF prior draw and N_* · N_corr for the kernel correction against
the N_corr training (exact) or inducing (decoupled) points — so the
same draw can be reused at arbitrary test sets without rebuilding a
test-set covariance. Standard enabler for Thompson sampling, Bayesian
optimization, and posterior visualization.
from pyrox_gp import (
RBF,
GPPrior,
PathwiseSampler,
DecoupledPathwiseSampler,
FullRankGuide,
SparseGPPrior,
)
import jax
import jax.numpy as jnp
# Exact GP:
posterior = GPPrior(kernel=RBF(), X=X).condition(y, jnp.array(0.05))
paths = PathwiseSampler(posterior, n_features=512).sample_paths(
jax.random.PRNGKey(0), n_paths=32
)
draws = paths(X_star) # (32, N_star)
# Sparse / decoupled:
sparse = SparseGPPrior(kernel=RBF(), Z=Z)
guide = FullRankGuide.init(Z.shape[0])
paths = DecoupledPathwiseSampler(sparse, guide).sample_paths(key, n_paths=16)
samples = paths(X_star)
Currently supports RBF and Matern kernels. Point-inducing
SparseGPPrior only — inducing-feature priors raise at construction.
PathwiseSampler
¶
Bases: Module
Exact-GP pathwise posterior sampler using Matheron's rule.
Given a ConditionedGP, draws a zero-mean RFF prior path
f_tilde and an iid noise draw eps_tilde at the training
inputs, forms the residual y - mu(X) - f_tilde(X) - eps_tilde,
solves it against the cached noisy operator K + (jitter + sigma^2)I,
and stores the result as posterior correction weights. The returned
PathwiseFunction is callable at any X_* in
\(\mathcal{O}(N_* \cdot F \cdot D + N_* \cdot N)\) per path,
where N is the number of training (correction) points: the RFF
prior term recomputes features over X_* each call
(N_* · F · D), and the correction term forms a fresh
K(X_*, X) block (N_* · N).
The correction solve uses the prior's solver, the strategy that
built the cached solve in GPPrior.condition, so a
GPPrior(matrix_free=True) with an iterative solver never forms
\(K_{XX}\). Its tolerance is that solver's own rtol and atol
(1e-6 each for pyrox_gp.preconditioned_cg_solver); the residual
of an iterative solve enters every path as an error that does not
shrink with the number of paths. A prior without a solver keeps
gaussx's structural dispatch, a dense Cholesky solve.
Examples:
>>> posterior = GPPrior(kernel=RBF(), X=X).condition(y, jnp.array(0.05))
>>> sampler = PathwiseSampler(posterior, n_features=512)
>>> paths = sampler.sample_paths(key, n_paths=32)
>>> draws = paths(X_star)
Examples:
>>> sampler = PathwiseSampler(posterior, n_features=1024)
>>> thompson = sampler.sample_paths(key, n_paths=1)
>>> values = thompson(X_candidates)
Source code in packages/pyrox-gp/src/pyrox_gp/_pathwise.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
sample_paths(key: Array, n_paths: int = 1) -> PathwiseFunction
¶
Sample callable posterior paths.
key is split into three subkeys: one for the RFF basis,
one for the iid training-noise draw, and one reserved for
future extensions.
Source code in packages/pyrox-gp/src/pyrox_gp/_pathwise.py
DecoupledPathwiseSampler
¶
Bases: Module
Sparse/decoupled pathwise sampler with RFF prior + inducing update.
The prior draw uses random features while the correction is represented in the inducing-point basis, so each sampled path stays callable at arbitrary inputs after a one-time inducing solve.
Supported for point-inducing SparseGPPrior (Z=...);
inducing-feature priors (inducing=...) are rejected at
construction with a clear error.
Handles WhitenedGuide automatically: whitened guide draws
v ~ q(v) are unwhitened to inducing values u = L_ZZ v via
gaussx.unwhiten before forming the inducing-space residual.
The inducing-space correction solve uses the prior's solver
(structural dispatch when it is None); the Cholesky factor for
unwhitening stays, since it is only inducing × inducing.
Examples:
>>> prior = SparseGPPrior(kernel=RBF(), Z=Z)
>>> guide = FullRankGuide.init(Z.shape[0])
>>> sampler = DecoupledPathwiseSampler(prior, guide, n_features=512)
>>> paths = sampler.sample_paths(key, n_paths=16)
>>> draws = paths(X_star)
Source code in packages/pyrox-gp/src/pyrox_gp/_pathwise.py
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
sample_paths(key: Array, n_paths: int = 1) -> PathwiseFunction
¶
Sample callable sparse posterior paths.
key is split into three subkeys: one for the RFF basis, one
for n_paths independent guide draws, and one for the
jitter-augmentation of the prior inducing draw. The RFF basis
draw and the \(K_{zz}\) assembly share a single
call_context so kernels with hyperparameter priors
(Pattern B / C) sample (variance, lengthscale) once.
The Matheron correction needs Cov(u_tilde) = K_{zz} + \text{jitter}\,I so it matches the operator that the
correction is solved against. The bare RFF draw at Z
produces only the K_{zz} part; we add an iid Gaussian
with variance jitter per inducing index to close the gap —
without this, paths are under-dispersed when jitter is bumped
up for stability.
Source code in packages/pyrox-gp/src/pyrox_gp/_pathwise.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | |
PathwiseFunction
¶
Bases: Module
Callable posterior function draw(s) produced by a pathwise sampler.
Carries the random-feature prior basis (omega, phase,
feature_weights) and the posterior correction weights evaluated
against either the training inputs (exact) or the inducing inputs
(sparse). Calling the instance on test points X_star evaluates
where \(\tilde f\) is the stored RFF prior draw and \(X_{\mathrm{corr}}\) is either the training set (exact) or the inducing set (sparse).
The kernel enters only as a frozen (X1, X2) -> K callable with
the sample-time variance and lengthscale baked in, so
repeated evaluations stay consistent with the original RFF draw
even for Pattern B/C kernels that register hyperparameter priors.
Examples:
>>> prior = GPPrior(kernel=RBF(), X=X)
>>> posterior = prior.condition(y, noise_var=jnp.array(0.05))
>>> sampler = PathwiseSampler(posterior, n_features=512)
>>> paths = sampler.sample_paths(key, n_paths=8)
>>> samples = paths(X_star)
Examples:
>>> sparse_prior = SparseGPPrior(kernel=RBF(), Z=Z)
>>> guide = FullRankGuide.init(Z.shape[0])
>>> paths = DecoupledPathwiseSampler(sparse_prior, guide).sample_paths(key)
>>> thompson_values = paths(X_candidates)
Source code in packages/pyrox-gp/src/pyrox_gp/_pathwise.py
Component protocols¶
Abstract pyrox-local bases for the orthogonal component stack — the
contracts that the concrete kernels, guides, and likelihoods above
implement. Cubature integrators (Gauss-Hermite,
Monte Carlo) come from gaussx.AbstractIntegrator and its concrete
subclasses; solver strategies live in
gaussx.
Kernel = AbstractKernel
module-attribute
¶
Guide
¶
Bases: Module
Abstract base for variational posterior families.
Concrete guides (DeltaGuide, MeanFieldGuide, LowRankGuide,
FullRankGuide, etc.) live in pyrox-gp. The whitening principle keeps
optimization geometry well-conditioned — sample from a unit-scale latent
and unwhiten with the prior Cholesky.
Two distinct entry points:
sample/log_prob— pure variational draws and densities.sample(self, key)returns a draw fromq(f);log_prob(self, f)evaluateslog q(f). Neither touches the NumPyro trace.register(name, prior)(optional) — the NumPyro-integration hook invoked bypyrox_gp.gp_samplewhen a guide is supplied. Use it to register a sample / param site (or compose one out of guide state) undernameand return the latent function value. Concrete guides that participate ingp_sampleshould implement this; the protocol leaves it unspecified so guides usable purely outside NumPyro stay valid.
Examples:
A point-mass guide at a fixed vector:
>>> import jax.numpy as jnp
>>> from pyrox.likelihoods import Guide
>>> class PointGuide(Guide):
... loc: jnp.ndarray
... def sample(self, key):
... return self.loc
... def log_prob(self, f):
... return jnp.asarray(0.0)
>>> PointGuide(jnp.zeros(3)).sample(None).shape
(3,)
Source code in packages/pyrox/src/pyrox/likelihoods.py
Likelihood
¶
Bases: Module
Abstract base for observation models.
Implements the conditional p(y | f), summed over points. The advanced
inference strategies in pyrox-gp integrate log p(y | f) against a
Gaussian cavity via any gaussx.AbstractIntegrator. Concrete
scalar-latent likelihoods (GaussianLikelihood here;
BernoulliLikelihood, PoissonLikelihood, StudentTLikelihood in
pyrox-gp) and multi-latent ones (SoftmaxLikelihood,
HeteroscedasticGaussianLikelihood) subclass it.
Multi-latent likelihoods declare latent_dim: int as a static
field (e.g. latent_dim = num_classes for softmax). Scalar
likelihoods may omit the field; consumers should read
getattr(lik, "latent_dim", 1).
Examples:
A Laplace observation model with unit scale:
>>> import jax.numpy as jnp
>>> from pyrox.likelihoods import Likelihood
>>> class LaplaceLikelihood(Likelihood):
... def log_prob(self, f, y, X=None):
... return jnp.sum(-jnp.abs(y - f) - jnp.log(2.0))
>>> float(LaplaceLikelihood().log_prob(jnp.zeros(2), jnp.zeros(2)))
-1.386...
Source code in packages/pyrox/src/pyrox/likelihoods.py
log_prob(f: Float[Array, ' ...'], y: Float[Array, ' ...'], X: Float[Array, ' ...'] | None = None) -> Float[Array, '']
abstractmethod
¶
Conditional p(y | f), optionally conditioned on inputs.
X is consumed only by likelihoods whose parameters are
functions of the input (see pyrox_gp.WarpedGaussianLikelihood
with a conditional warp). Scalar observation models ignore it.
Source code in packages/pyrox/src/pyrox/likelihoods.py
Math primitives¶
The pure JAX kernel functions (rbf_kernel, matern_kernel, ...) live in
kernellib's functional API: from kernellib.functional import rbf_kernel.
Stateless, differentiable, composable — (Array, ..., hyperparams) -> Gram.
See the kernellib documentation
for the reference.