Skip to content

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 pyrox_gp.Kernel — evaluated on X.

X Float[Array, 'N D']

Training inputs of shape (N, D).

mean_fn Callable[[Float[Array, 'N D']], Float[Array, ' N']] | None

Callable X -> (N,) or None for the zero mean.

solver AbstractSolverStrategy | None

Any gaussx.AbstractSolverStrategy. Defaults to gaussx.DenseSolver() — swap for CGSolver, BBMMSolver, ComposedSolver(solve=..., logdet=...), etc. Every gaussx solver runs on the matrix-free operator, but the system is symmetric positive definite, so CG (pyrox_gp.matfree_solver, pyrox_gp.bbmm_solver, CGSolver, PreconditionedCGSolver, BBMMSolver) is the sensible choice; MINRESSolver and LSMRSolver also converge, and LSMR works on the squared condition number, so it is slower. Which solver, preconditioner and log-determinant to pick for a size and a kernel, with measured errors and times, is the guide Choosing the solver.

preconditioner AbstractPreconditioner | None

Optional gaussx.AbstractPreconditioner for the solve, and for the log-determinant of a BBMMSolver, whose shared pass uses \(P\) itself. Keyword only. A lazy one (gaussx.NystromPreconditioner.lazy(rank, key=key)) is rebuilt from the system at every solve, so it follows the kernel's hyperparameters; gaussx stops its gradient, so a stale one changes the iteration count and not the result. It needs an iterative solver: with solver=None (DenseSolver) the prior raises at construction. A lazy preconditioner reads the system as \(K + \mathrm{diag}(d)\) (gaussx.split_diagonal), so it needs matrix_free=True; a dense prior takes one built with from_operator.

logdet AbstractLogdetStrategy | None

Optional gaussx.AbstractLogdetStrategy for \(\log \det A\) in place of the solver's own (for example gaussx.SLQLogdet or gaussx.DenseLogdet next to a CG solve). Keyword only. A stochastic estimator without a key reuses its probes at every call, so NUTS then samples a fixed approximation of the posterior and not the posterior; wrap it in gaussx.KeyedSolver with a key per step to vary them.

jitter float

Diagonal regularization added to the prior covariance for numerical stability. Not a noise model — use noise_var on condition for that.

matrix_free bool

If True, never form K. The covariance is the lineax.AddLinearOperator of a matrix-free kernel operator (row blocks of K evaluated per matvec, O(block_size N) memory, gradients included) and (jitter + noise_var) I. Pair it with an iterative solver, normally pyrox_gp.matfree_solver or pyrox_gp.bbmm_solver, which read the noise from the sum; a dense solver materialises K again. NumPyro-aware kernels are resolved once per call through frozen(). Matrix-free entry points: log_prob, log_marginal, condition and its predictions, gp_factor, pyrox_gp.PathwiseSampler on the conditioned GP, and prior draws with method="krylov" (sample, gp_sample(whitened=True)), and, with an iterative solver, the non-Gaussian strategies other than quasi-Newton (condition_nongauss with Laplace, Gauss-Newton, posterior linearisation or EP, and gp_laplace_factor; pyrox#551, pyrox#552). The default Cholesky draws and pyrox_gp.QuasiNewtonInference form K and raise ValueError on a matrix-free prior.

block_size int

Rows of K per matvec step when matrix_free.

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
class GPPrior(eqx.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:
        kernel: Any `pyrox_gp.Kernel` — evaluated on ``X``.
        X: Training inputs of shape ``(N, D)``.
        mean_fn: Callable ``X -> (N,)`` or ``None`` for the zero mean.
        solver: Any ``gaussx.AbstractSolverStrategy``. Defaults to
            ``gaussx.DenseSolver()`` — swap for ``CGSolver``,
            ``BBMMSolver``, ``ComposedSolver(solve=..., logdet=...)``, etc.
            Every gaussx solver runs on the matrix-free operator, but the
            system is symmetric positive definite, so CG
            (`pyrox_gp.matfree_solver`, `pyrox_gp.bbmm_solver`, ``CGSolver``,
            ``PreconditionedCGSolver``, ``BBMMSolver``) is the sensible
            choice; ``MINRESSolver`` and ``LSMRSolver`` also converge, and
            LSMR works on the squared condition number, so it is slower.
            Which solver, preconditioner and log-determinant to pick for a
            size and a kernel, with measured errors and times, is the guide
            [Choosing the solver](https://jejjohnson.github.io/pyrox/gp-solver-choices/).
        preconditioner: Optional ``gaussx.AbstractPreconditioner`` for the
            solve, and for the log-determinant of a ``BBMMSolver``, whose
            shared pass uses $P$ itself. Keyword only. A lazy one
            (``gaussx.NystromPreconditioner.lazy(rank, key=key)``) is
            rebuilt from the system at every solve, so it follows the
            kernel's hyperparameters; gaussx stops its gradient, so a
            stale one changes the iteration count and not the result. It
            needs an iterative ``solver``: with ``solver=None``
            (``DenseSolver``) the prior raises at construction. A lazy
            preconditioner reads the system as $K + \\mathrm{diag}(d)$
            (`gaussx.split_diagonal`), so it needs ``matrix_free=True``; a
            dense prior takes one built with ``from_operator``.
        logdet: Optional ``gaussx.AbstractLogdetStrategy`` for
            $\\log \\det A$ in place of the solver's own (for example
            ``gaussx.SLQLogdet`` or ``gaussx.DenseLogdet`` next to a CG
            solve). Keyword only. A stochastic estimator without a key
            reuses its probes at every call, so NUTS then samples a fixed
            approximation of the posterior and not the posterior; wrap it in
            ``gaussx.KeyedSolver`` with a key per step to vary them.
        jitter: Diagonal regularization added to the prior covariance
            for numerical stability. Not a noise model — use
            ``noise_var`` on `condition` for that.
        matrix_free: If ``True``, never form ``K``. The covariance is the
            `lineax.AddLinearOperator` of a matrix-free kernel operator
            (row blocks of ``K`` evaluated per matvec, ``O(block_size N)``
            memory, gradients included) and ``(jitter + noise_var) I``. Pair
            it with an iterative solver, normally `pyrox_gp.matfree_solver`
            or `pyrox_gp.bbmm_solver`, which read the noise from the sum; a
            dense solver materialises ``K`` again. NumPyro-aware
            kernels are resolved once per call through ``frozen()``.
            Matrix-free entry points: `log_prob`, `log_marginal`,
            `condition` and its predictions, `gp_factor`,
            `pyrox_gp.PathwiseSampler` on the conditioned GP, and prior
            draws with ``method="krylov"`` (`sample`,
            ``gp_sample(whitened=True)``), and, with an iterative solver,
            the non-Gaussian strategies other than quasi-Newton
            (`condition_nongauss` with Laplace, Gauss-Newton, posterior
            linearisation or EP, and `gp_laplace_factor`; pyrox#551,
            pyrox#552). The default Cholesky draws and
            `pyrox_gp.QuasiNewtonInference` form ``K`` and raise
            ``ValueError`` on a matrix-free prior.
        block_size: Rows of ``K`` per matvec step when ``matrix_free``.

    Examples:
        BBMM with a preconditioner, or CG with a separate stochastic
        log-determinant, on $10^5$ stations:

        ```python
        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:

        ```python
        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)
        ```
    """

    kernel: Kernel
    X: Float[Array, "N D"]
    mean_fn: Callable[[Float[Array, "N D"]], Float[Array, " N"]] | None = None
    solver: AbstractSolverStrategy | None = None
    jitter: float = 1e-6
    matrix_free: bool = eqx.field(static=True, default=False)
    block_size: int = eqx.field(static=True, default=256)
    # keyword only, so positional calls up to block_size keep working
    preconditioner: AbstractPreconditioner | None = eqx.field(
        default=None, kw_only=True
    )
    logdet: AbstractLogdetStrategy | None = eqx.field(default=None, kw_only=True)

    def __check_init__(self) -> None:
        # rejected combinations raise here, naming the fields (type checks only)
        self.solver_strategy()

    def mean(self, X: Float[Array, "N D"]) -> Float[Array, " N"]:
        """Evaluate the mean function at ``X``; zero by default."""
        if self.mean_fn is None:
            return jnp.zeros(X.shape[0], dtype=X.dtype)
        return self.mean_fn(X)

    def _matrix_free_operator(
        self, diagonal: Float[Array, ""]
    ) -> lx.AbstractLinearOperator:
        return matrix_free_operator(
            freeze_kernel(self.kernel), self.X, diagonal, block_size=self.block_size
        )

    def _prior_operator(self) -> lx.AbstractLinearOperator:
        if self.matrix_free:
            return self._matrix_free_operator(jnp.asarray(self.jitter))
        K = self.kernel(self.X, self.X)
        K = K.at[jnp.diag_indices_from(K)].add(self.jitter)
        return _psd_operator(K)

    def _noisy_operator(self, noise_var: Float[Array, ""]) -> lx.AbstractLinearOperator:
        if self.matrix_free:
            return self._matrix_free_operator(self.jitter + noise_var)
        K = self.kernel(self.X, self.X)
        K = K.at[jnp.diag_indices_from(K)].add(self.jitter + noise_var)
        return _psd_operator(K)

    def solver_strategy(self) -> 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:
            The `gaussx.AbstractSolverStrategy` every quantity of the prior
            uses.

        Raises:
            ValueError: For a combination `gaussx.compose_solver` rejects,
                naming the three fields.
        """
        return compose_solver_fields(
            "GPPrior", self.solver, self.preconditioner, self.logdet
        )

    def _resolved_solver(self) -> AbstractSolverStrategy:
        return self.solver_strategy()

    def log_prob(self, f: Float[Array, " N"]) -> Float[Array, ""]:
        r"""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.
        """
        return log_marginal_likelihood(
            self.mean(self.X),
            self._prior_operator(),
            f,
            solver=self._resolved_solver(),
        )

    def sample(
        self,
        key: Array,
        *,
        method: Literal["cholesky", "krylov"] = "cholesky",
        lanczos_order: int = 100,
    ) -> Float[Array, " N"]:
        r"""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.

        Args:
            key: PRNG key.
            method: ``"cholesky"`` (default) wraps the prior in a
                `pyrox_gauss.MultivariateNormal` with the configured
                `solver`, which factorises the dense ``K``, so it raises on
                a matrix-free prior. ``"krylov"`` draws
                $f = \mu + \hat K^{1/2} v$, $v \sim \mathcal{N}(0, I)$,
                with the symmetric root applied by Lanczos
                (`gaussx.sqrt` with ``lanczos_order``): matrix-free, and
                exact up to the Lanczos error.
            lanczos_order: Lanczos steps of ``method="krylov"``. The error
                falls with the condition number of $K + \text{jitter}\,I$,
                so the jitter sets the cost: at $N = 1000$, 100 steps gave
                a relative error of the draws below $10^{-5}$ for an RBF
                and a Matérn-1/2 kernel (condition numbers $2 \cdot 10^8$
                and $2 \cdot 10^4$), and 30 steps about $10^{-2}$.

        Returns:
            One draw of ``f`` at the training inputs, shape ``(N,)``.

        Raises:
            ValueError: For an unknown ``method``, or for
                ``method="cholesky"`` on a matrix-free prior.
        """
        _check_draw_method(method)
        op = self._prior_operator()
        loc = self.mean(self.X)
        if method == "krylov":
            # v ~ N(0, I)
            normals = jax.random.normal(key, loc.shape, dtype=self.X.dtype)
            # f = μ + K̂^½ v, the root applied by Lanczos
            return loc + sqrt(op, lanczos_order=lanczos_order).mv(normals)
        if self.matrix_free:
            raise ValueError(_dense_draw_message("GPPrior.sample"))
        mvn = MultivariateNormal(loc, op, solver=self._resolved_solver())
        return mvn.sample(key)

    def log_marginal(
        self,
        y: Float[Array, " N"],
        noise_var: Float[Array, ""],
    ) -> Float[Array, ""]:
        r"""Collapsed log marginal likelihood $\log p(y \mid X, \theta)$.

        $$
        \log p(y \mid X, \theta)
          = \log \mathcal{N}\!\left(y \mid \mu(X),\,
            K + (\text{jitter} + \sigma^2) I\right),
        $$

        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.

        Args:
            y: Observations at the training inputs, shape ``(N,)``.
            noise_var: Observation noise variance $\sigma^2$.

        Returns:
            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))
        """
        return log_marginal_likelihood(
            self.mean(self.X),
            self._noisy_operator(noise_var),
            y,
            solver=self._resolved_solver(),
        )

    def condition(
        self,
        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.
        """
        with call_context(self.kernel):
            operator = self._noisy_operator(noise_var)
            resolved_hyperparams = _resolve_kernel_hyperparams(self.kernel)
        residual = y - self.mean(self.X)
        cache = build_prediction_cache(
            operator, residual, solver=self._resolved_solver()
        )
        return ConditionedGP(
            prior=self,
            y=y,
            noise_var=noise_var,
            cache=cache,
            operator=operator,
            resolved_hyperparams=resolved_hyperparams,
        )

    def condition_nongauss(
        self,
        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)
        """
        if key is None:
            return strategy.fit(self, likelihood, y)
        fit_with_key = cast(Any, strategy).fit
        return fit_with_key(self, likelihood, y, key=key)

mean(X: Float[Array, 'N D']) -> Float[Array, ' N']

Evaluate the mean function at X; zero by default.

Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
def mean(self, X: Float[Array, "N D"]) -> Float[Array, " N"]:
    """Evaluate the mean function at ``X``; zero by default."""
    if self.mean_fn is None:
        return jnp.zeros(X.shape[0], dtype=X.dtype)
    return self.mean_fn(X)

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 gaussx.AbstractSolverStrategy every quantity of the prior

AbstractSolverStrategy

uses.

Raises:

Type Description
ValueError

For a combination gaussx.compose_solver rejects, naming the three fields.

Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
def solver_strategy(self) -> 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:
        The `gaussx.AbstractSolverStrategy` every quantity of the prior
        uses.

    Raises:
        ValueError: For a combination `gaussx.compose_solver` rejects,
            naming the three fields.
    """
    return compose_solver_fields(
        "GPPrior", self.solver, self.preconditioner, self.logdet
    )

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
def log_prob(self, f: Float[Array, " N"]) -> Float[Array, ""]:
    r"""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.
    """
    return log_marginal_likelihood(
        self.mean(self.X),
        self._prior_operator(),
        f,
        solver=self._resolved_solver(),
    )

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" (default) wraps the prior in a pyrox_gauss.MultivariateNormal with the configured solver, which factorises the dense K, so it raises on a matrix-free prior. "krylov" draws \(f = \mu + \hat K^{1/2} v\), \(v \sim \mathcal{N}(0, I)\), with the symmetric root applied by Lanczos (gaussx.sqrt with lanczos_order): matrix-free, and exact up to the Lanczos error.

'cholesky'
lanczos_order int

Lanczos steps of method="krylov". The error falls with the condition number of \(K + \text{jitter}\,I\), so the jitter sets the cost: at \(N = 1000\), 100 steps gave a relative error of the draws below \(10^{-5}\) for an RBF and a Matérn-1/2 kernel (condition numbers \(2 \cdot 10^8\) and \(2 \cdot 10^4\)), and 30 steps about \(10^{-2}\).

100

Returns:

Type Description
Float[Array, ' N']

One draw of f at the training inputs, shape (N,).

Raises:

Type Description
ValueError

For an unknown method, or for method="cholesky" on a matrix-free prior.

Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
def sample(
    self,
    key: Array,
    *,
    method: Literal["cholesky", "krylov"] = "cholesky",
    lanczos_order: int = 100,
) -> Float[Array, " N"]:
    r"""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.

    Args:
        key: PRNG key.
        method: ``"cholesky"`` (default) wraps the prior in a
            `pyrox_gauss.MultivariateNormal` with the configured
            `solver`, which factorises the dense ``K``, so it raises on
            a matrix-free prior. ``"krylov"`` draws
            $f = \mu + \hat K^{1/2} v$, $v \sim \mathcal{N}(0, I)$,
            with the symmetric root applied by Lanczos
            (`gaussx.sqrt` with ``lanczos_order``): matrix-free, and
            exact up to the Lanczos error.
        lanczos_order: Lanczos steps of ``method="krylov"``. The error
            falls with the condition number of $K + \text{jitter}\,I$,
            so the jitter sets the cost: at $N = 1000$, 100 steps gave
            a relative error of the draws below $10^{-5}$ for an RBF
            and a Matérn-1/2 kernel (condition numbers $2 \cdot 10^8$
            and $2 \cdot 10^4$), and 30 steps about $10^{-2}$.

    Returns:
        One draw of ``f`` at the training inputs, shape ``(N,)``.

    Raises:
        ValueError: For an unknown ``method``, or for
            ``method="cholesky"`` on a matrix-free prior.
    """
    _check_draw_method(method)
    op = self._prior_operator()
    loc = self.mean(self.X)
    if method == "krylov":
        # v ~ N(0, I)
        normals = jax.random.normal(key, loc.shape, dtype=self.X.dtype)
        # f = μ + K̂^½ v, the root applied by Lanczos
        return loc + sqrt(op, lanczos_order=lanczos_order).mv(normals)
    if self.matrix_free:
        raise ValueError(_dense_draw_message("GPPrior.sample"))
    mvn = MultivariateNormal(loc, op, solver=self._resolved_solver())
    return mvn.sample(key)

log_marginal(y: Float[Array, ' N'], noise_var: Float[Array, '']) -> Float[Array, '']

Collapsed log marginal likelihood \(\log p(y \mid X, \theta)\).

\[ \log p(y \mid X, \theta) = \log \mathcal{N}\!\left(y \mid \mu(X),\, K + (\text{jitter} + \sigma^2) I\right), \]

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 (N,).

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
def log_marginal(
    self,
    y: Float[Array, " N"],
    noise_var: Float[Array, ""],
) -> Float[Array, ""]:
    r"""Collapsed log marginal likelihood $\log p(y \mid X, \theta)$.

    $$
    \log p(y \mid X, \theta)
      = \log \mathcal{N}\!\left(y \mid \mu(X),\,
        K + (\text{jitter} + \sigma^2) I\right),
    $$

    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.

    Args:
        y: Observations at the training inputs, shape ``(N,)``.
        noise_var: Observation noise variance $\sigma^2$.

    Returns:
        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))
    """
    return log_marginal_likelihood(
        self.mean(self.X),
        self._noisy_operator(noise_var),
        y,
        solver=self._resolved_solver(),
    )

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
def condition(
    self,
    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.
    """
    with call_context(self.kernel):
        operator = self._noisy_operator(noise_var)
        resolved_hyperparams = _resolve_kernel_hyperparams(self.kernel)
    residual = y - self.mean(self.X)
    cache = build_prediction_cache(
        operator, residual, solver=self._resolved_solver()
    )
    return ConditionedGP(
        prior=self,
        y=y,
        noise_var=noise_var,
        cache=cache,
        operator=operator,
        resolved_hyperparams=resolved_hyperparams,
    )

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
def condition_nongauss(
    self,
    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)
    """
    if key is None:
        return strategy.fit(self, likelihood, y)
    fit_with_key = cast(Any, strategy).fit
    return fit_with_key(self, likelihood, y, key=key)

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
class ConditionedGP(eqx.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.
    """

    prior: GPPrior
    y: Float[Array, " N"]
    noise_var: Float[Array, ""]
    cache: PredictionCache
    operator: lx.AbstractLinearOperator
    resolved_hyperparams: tuple[Float[Array, ""], Float[Array, ""]] | None = None

    def predict_mean(self, X_star: Float[Array, "M D"]) -> Float[Array, " M"]:
        r"""$\mu_* = \mu(X_*) + K_{*f}\,\alpha$."""
        with call_context(self.prior.kernel):
            K_cross = self.prior.kernel(X_star, self.prior.X)
        return self.prior.mean(X_star) + predict_mean(self.cache, K_cross)

    def predict_var(self, X_star: Float[Array, "M D"]) -> Float[Array, " M"]:
        r"""Diagonal predictive variance at ``X_*``.

        $$
        \sigma^2_{*,i} = k(x_{*,i}, x_{*,i})
            - K_{*f}[i,:] \cdot (K + \sigma^2 I)^{-1} K_{f*}[:,i]
        $$

        ``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).
        """
        with call_context(self.prior.kernel):
            K_cross = self.prior.kernel(X_star, self.prior.X)
            K_diag = self.prior.kernel.diag(X_star)
        return predict_variance(
            self.cache,
            K_cross,
            K_diag,
            solver=self.prior._resolved_solver(),
        )

    def predict(
        self, X_star: Float[Array, "M D"], *, include_noise: bool = False
    ) -> tuple[Float[Array, " M"], Float[Array, " M"]]:
        r"""Return ``(mean, variance)`` at ``X_*`` as a tuple.

        Both kernel evaluations share a single kernel context; see
        `predict_var`.

        Args:
            X_star: Test inputs, shape ``(M, D)``.
            include_noise: 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.

        Returns:
            The predictive mean and variance, each of shape ``(M,)``.
        """
        with call_context(self.prior.kernel):
            mean, var = self.predict_mean(X_star), self.predict_var(X_star)
        if include_noise:
            var = var + jnp.asarray(self.noise_var, dtype=var.dtype)
        return mean, var

    def sample(
        self,
        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`.
        """
        with call_context(self.prior.kernel):
            mean = self.predict_mean(X_star)
            var = self.predict_var(X_star)
        std = jnp.sqrt(jnp.clip(var, min=0.0))
        eps = jax.random.normal(key, (n_samples, X_star.shape[0]), dtype=mean.dtype)
        # Scale per-point std across the S sample rows: (M,) ⊙ (S, M) → (S, M).
        return einx.multiply("m, s m -> s m", std, eps) + mean

    def predict_gradient(
        self,
        X_star: Float[Array, "M D"],
        *,
        cov: Literal["marginal", "full", "none"] = "marginal",
    ) -> GradientPosterior:
        r"""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}$:

        $$
        \mathbb{E}[\nabla f(x_*) \mid y] = \nabla m(x_*) + G(x_*)\,\alpha ,
        $$

        which equals $\nabla_{x_*} \mu_*(x_*)$ exactly (Johnson et al.
        2020, §3, with a mean function), and

        $$
        \operatorname{Cov}[\partial_i f(x_a), \partial_j f(x_b) \mid y]
        = \partial_{1,i} \partial_{2,j} k(x_a, x_b)
          - \partial_{1,i} K(x_a, X)\,\hat K^{-1}\,
            \partial_{1,j} K(x_b, X)^\top .
        $$

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

        ```text
        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.

        Args:
            X_star: Test inputs, shape ``(M, D)``.
            cov: ``"marginal"`` (default) for the per-point ``(M, D, D)``
                blocks, ``"full"`` for the joint ``(M, D, M, D)`` and
                ``"none"`` for the mean only (skips the ``N x DM`` solve).

        Returns:
            A `GradientPosterior` ``(mean, cov)`` in point-major layout.

        Raises:
            ValueError: For an unknown ``cov``, or a kernel whose GP is not
                mean-square differentiable (``Matern(nu=0.5)``, ``White``;
                kernellib's check).
            TypeError: For a Gram-only kernellib kernel.
            NotImplementedError: For a `pyrox_gp` kernel without a
                kernellib counterpart (no ``frozen()``).

        Examples:
            Sensitivity map with error bars (Johnson et al. 2020):

            ```python
            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)
            ```
        """
        if cov not in ("marginal", "full", "none"):
            raise ValueError(f"cov must be 'marginal', 'full' or 'none', got {cov!r}.")
        D = X_star.shape[-1]
        with call_context(self.prior.kernel):
            k = _derivative_kernel(self.prior.kernel)
            G = _cross_gradient(k, X_star, self.prior.X)
        mean = einx.id(
            "(d m) -> m d", einx.dot("k n, n -> k", G, self.cache.alpha), d=D
        ) + _mean_fn_gradient(self.prior.mean_fn, X_star)
        if cov == "none":
            return GradientPosterior(mean, None)
        P, Q = _whitened_cross(self.cache, G, G, solver=self.prior._resolved_solver())
        if cov == "marginal":
            H = jax.vmap(lambda x: jax.jacfwd(jax.grad(k.pairwise, 0), 1)(x, x))(X_star)
            Pm = einx.id("n (d m) -> m n d", P, d=D)
            Qm = einx.id("n (d m) -> m n d", Q, d=D)
            S = H - einx.dot("m n i, m n j -> m i j", Pm, Qm)
            return GradientPosterior(mean, 0.5 * (S + einx.id("m i j -> m j i", S)))
        Xt = kl.derivative_inputs(X_star, values=False)
        S = kl.DerivativeIndexed(k)(Xt, Xt) - einx.dot("n k, n l -> k l", P, Q)
        S = 0.5 * (S + einx.id("k l -> l k", S))
        return GradientPosterior(mean, einx.id("(i a) (j b) -> a i b j", S, i=D, j=D))

    def predict_var_gradient(self, X_star: Float[Array, "M D"]) -> Float[Array, "M D"]:
        r"""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)$,

        $$
        \nabla_x \sigma^2_*(x) = \big[\partial_1 k + \partial_2 k\big](x, x)
            - 2\,G(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`.

        ```text
        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]
        ```

        Args:
            X_star: Test inputs, shape ``(M, D)``.

        Returns:
            $\nabla_x \sigma^2_*$ at each test point, shape ``(M, D)``.

        Raises:
            ValueError: For a kernel whose GP is not mean-square
                differentiable (see `predict_gradient`).
            NotImplementedError: For a `pyrox_gp` kernel without
                ``frozen()``.

        Examples:
            ```python
            # 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)
            ```
        """
        D = X_star.shape[-1]
        with call_context(self.prior.kernel):
            k = _derivative_kernel(self.prior.kernel)
            G = _cross_gradient(k, X_star, self.prior.X)
            K_cross = k(X_star, self.prior.X)
        prior_term = jax.vmap(jax.grad(lambda x: k.pairwise(x, x)))(X_star)
        P, Q = _whitened_cross(
            self.cache, G, K_cross, solver=self.prior._resolved_solver()
        )
        Pm = einx.id("n (d m) -> m n d", P, d=D)
        return prior_term - 2.0 * einx.dot("m n d, n m -> m d", Pm, Q)

    def predict_mean_hessian(
        self, X_star: Float[Array, "M D"]
    ) -> Float[Array, "M D D"]:
        r"""Hessian of the predictive mean, $\nabla \nabla^\top \mu_*(x)$.

        $$
        \nabla \nabla^\top \mu_*(x) = \nabla^2 m(x)
            + \sum_n \alpha_n\, \nabla_x^2 k(x, x_n),
        $$

        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$).

        Args:
            X_star: Test inputs, shape ``(M, D)``.

        Returns:
            The symmetric ``(M, D, D)`` Hessians.

        Raises:
            ValueError: For a kernel whose GP is not mean-square
                differentiable (see `predict_gradient`).
            NotImplementedError: For a `pyrox_gp` kernel without
                ``frozen()``.

        Examples:
            ```python
            hess = cond.predict_mean_hessian(X_star)  # (M, D, D)
            curvature = jnp.trace(hess, axis1=-2, axis2=-1)  # Laplacian of mu
            ```
        """
        with call_context(self.prior.kernel):
            k = _derivative_kernel(self.prior.kernel)
        kl.DerivativeIndexed(k)  # kernellib's mean-square differentiability check
        X, alpha, mean_fn = self.prior.X, self.cache.alpha, self.prior.mean_fn

        def mu(x: Float[Array, " D"]) -> Float[Array, ""]:
            value = einx.dot("n, n ->", k(x[None], X)[0], alpha)
            if mean_fn is not None:
                value = value + mean_fn(x[None])[0]
            return value

        return jax.vmap(jax.hessian(mu))(X_star)

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
def predict_mean(self, X_star: Float[Array, "M D"]) -> Float[Array, " M"]:
    r"""$\mu_* = \mu(X_*) + K_{*f}\,\alpha$."""
    with call_context(self.prior.kernel):
        K_cross = self.prior.kernel(X_star, self.prior.X)
    return self.prior.mean(X_star) + predict_mean(self.cache, K_cross)

predict_var(X_star: Float[Array, 'M D']) -> Float[Array, ' M']

Diagonal predictive variance at X_*.

\[ \sigma^2_{*,i} = k(x_{*,i}, x_{*,i}) - K_{*f}[i,:] \cdot (K + \sigma^2 I)^{-1} K_{f*}[:,i] \]

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
def predict_var(self, X_star: Float[Array, "M D"]) -> Float[Array, " M"]:
    r"""Diagonal predictive variance at ``X_*``.

    $$
    \sigma^2_{*,i} = k(x_{*,i}, x_{*,i})
        - K_{*f}[i,:] \cdot (K + \sigma^2 I)^{-1} K_{f*}[:,i]
    $$

    ``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).
    """
    with call_context(self.prior.kernel):
        K_cross = self.prior.kernel(X_star, self.prior.X)
        K_diag = self.prior.kernel.diag(X_star)
    return predict_variance(
        self.cache,
        K_cross,
        K_diag,
        solver=self.prior._resolved_solver(),
    )

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 (M, D).

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 (M,).

Source code in packages/pyrox-gp/src/pyrox_gp/_models.py
def predict(
    self, X_star: Float[Array, "M D"], *, include_noise: bool = False
) -> tuple[Float[Array, " M"], Float[Array, " M"]]:
    r"""Return ``(mean, variance)`` at ``X_*`` as a tuple.

    Both kernel evaluations share a single kernel context; see
    `predict_var`.

    Args:
        X_star: Test inputs, shape ``(M, D)``.
        include_noise: 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.

    Returns:
        The predictive mean and variance, each of shape ``(M,)``.
    """
    with call_context(self.prior.kernel):
        mean, var = self.predict_mean(X_star), self.predict_var(X_star)
    if include_noise:
        var = var + jnp.asarray(self.noise_var, dtype=var.dtype)
    return mean, var

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
def sample(
    self,
    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`.
    """
    with call_context(self.prior.kernel):
        mean = self.predict_mean(X_star)
        var = self.predict_var(X_star)
    std = jnp.sqrt(jnp.clip(var, min=0.0))
    eps = jax.random.normal(key, (n_samples, X_star.shape[0]), dtype=mean.dtype)
    # Scale per-point std across the S sample rows: (M,) ⊙ (S, M) → (S, M).
    return einx.multiply("m, s m -> s m", std, eps) + mean

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}\):

\[ \mathbb{E}[\nabla f(x_*) \mid y] = \nabla m(x_*) + G(x_*)\,\alpha , \]

which equals \(\nabla_{x_*} \mu_*(x_*)\) exactly (Johnson et al. 2020, §3, with a mean function), and

\[ \operatorname{Cov}[\partial_i f(x_a), \partial_j f(x_b) \mid y] = \partial_{1,i} \partial_{2,j} k(x_a, x_b) - \partial_{1,i} K(x_a, X)\,\hat K^{-1}\, \partial_{1,j} K(x_b, X)^\top . \]

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 (M, D).

required
cov Literal['marginal', 'full', 'none']

"marginal" (default) for the per-point (M, D, D) blocks, "full" for the joint (M, D, M, D) and "none" for the mean only (skips the N x DM solve).

'marginal'

Returns:

Type Description
GradientPosterior

A GradientPosterior (mean, cov) in point-major layout.

Raises:

Type Description
ValueError

For an unknown cov, or a kernel whose GP is not mean-square differentiable (Matern(nu=0.5), White; kernellib's check).

TypeError

For a Gram-only kernellib kernel.

NotImplementedError

For a pyrox_gp kernel without a kernellib counterpart (no frozen()).

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
def predict_gradient(
    self,
    X_star: Float[Array, "M D"],
    *,
    cov: Literal["marginal", "full", "none"] = "marginal",
) -> GradientPosterior:
    r"""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}$:

    $$
    \mathbb{E}[\nabla f(x_*) \mid y] = \nabla m(x_*) + G(x_*)\,\alpha ,
    $$

    which equals $\nabla_{x_*} \mu_*(x_*)$ exactly (Johnson et al.
    2020, §3, with a mean function), and

    $$
    \operatorname{Cov}[\partial_i f(x_a), \partial_j f(x_b) \mid y]
    = \partial_{1,i} \partial_{2,j} k(x_a, x_b)
      - \partial_{1,i} K(x_a, X)\,\hat K^{-1}\,
        \partial_{1,j} K(x_b, X)^\top .
    $$

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

    ```text
    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.

    Args:
        X_star: Test inputs, shape ``(M, D)``.
        cov: ``"marginal"`` (default) for the per-point ``(M, D, D)``
            blocks, ``"full"`` for the joint ``(M, D, M, D)`` and
            ``"none"`` for the mean only (skips the ``N x DM`` solve).

    Returns:
        A `GradientPosterior` ``(mean, cov)`` in point-major layout.

    Raises:
        ValueError: For an unknown ``cov``, or a kernel whose GP is not
            mean-square differentiable (``Matern(nu=0.5)``, ``White``;
            kernellib's check).
        TypeError: For a Gram-only kernellib kernel.
        NotImplementedError: For a `pyrox_gp` kernel without a
            kernellib counterpart (no ``frozen()``).

    Examples:
        Sensitivity map with error bars (Johnson et al. 2020):

        ```python
        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)
        ```
    """
    if cov not in ("marginal", "full", "none"):
        raise ValueError(f"cov must be 'marginal', 'full' or 'none', got {cov!r}.")
    D = X_star.shape[-1]
    with call_context(self.prior.kernel):
        k = _derivative_kernel(self.prior.kernel)
        G = _cross_gradient(k, X_star, self.prior.X)
    mean = einx.id(
        "(d m) -> m d", einx.dot("k n, n -> k", G, self.cache.alpha), d=D
    ) + _mean_fn_gradient(self.prior.mean_fn, X_star)
    if cov == "none":
        return GradientPosterior(mean, None)
    P, Q = _whitened_cross(self.cache, G, G, solver=self.prior._resolved_solver())
    if cov == "marginal":
        H = jax.vmap(lambda x: jax.jacfwd(jax.grad(k.pairwise, 0), 1)(x, x))(X_star)
        Pm = einx.id("n (d m) -> m n d", P, d=D)
        Qm = einx.id("n (d m) -> m n d", Q, d=D)
        S = H - einx.dot("m n i, m n j -> m i j", Pm, Qm)
        return GradientPosterior(mean, 0.5 * (S + einx.id("m i j -> m j i", S)))
    Xt = kl.derivative_inputs(X_star, values=False)
    S = kl.DerivativeIndexed(k)(Xt, Xt) - einx.dot("n k, n l -> k l", P, Q)
    S = 0.5 * (S + einx.id("k l -> l k", S))
    return GradientPosterior(mean, einx.id("(i a) (j b) -> a i b j", S, i=D, j=D))

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)\),

\[ \nabla_x \sigma^2_*(x) = \big[\partial_1 k + \partial_2 k\big](x, x) - 2\,G(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 (M, D).

required

Returns:

Type Description
Float[Array, 'M D']

\(\nabla_x \sigma^2_*\) at each test point, shape (M, D).

Raises:

Type Description
ValueError

For a kernel whose GP is not mean-square differentiable (see predict_gradient).

NotImplementedError

For a pyrox_gp kernel without frozen().

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
def predict_var_gradient(self, X_star: Float[Array, "M D"]) -> Float[Array, "M D"]:
    r"""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)$,

    $$
    \nabla_x \sigma^2_*(x) = \big[\partial_1 k + \partial_2 k\big](x, x)
        - 2\,G(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`.

    ```text
    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]
    ```

    Args:
        X_star: Test inputs, shape ``(M, D)``.

    Returns:
        $\nabla_x \sigma^2_*$ at each test point, shape ``(M, D)``.

    Raises:
        ValueError: For a kernel whose GP is not mean-square
            differentiable (see `predict_gradient`).
        NotImplementedError: For a `pyrox_gp` kernel without
            ``frozen()``.

    Examples:
        ```python
        # 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)
        ```
    """
    D = X_star.shape[-1]
    with call_context(self.prior.kernel):
        k = _derivative_kernel(self.prior.kernel)
        G = _cross_gradient(k, X_star, self.prior.X)
        K_cross = k(X_star, self.prior.X)
    prior_term = jax.vmap(jax.grad(lambda x: k.pairwise(x, x)))(X_star)
    P, Q = _whitened_cross(
        self.cache, G, K_cross, solver=self.prior._resolved_solver()
    )
    Pm = einx.id("n (d m) -> m n d", P, d=D)
    return prior_term - 2.0 * einx.dot("m n d, n m -> m d", Pm, Q)

predict_mean_hessian(X_star: Float[Array, 'M D']) -> Float[Array, 'M D D']

Hessian of the predictive mean, \(\nabla \nabla^\top \mu_*(x)\).

\[ \nabla \nabla^\top \mu_*(x) = \nabla^2 m(x) + \sum_n \alpha_n\, \nabla_x^2 k(x, x_n), \]

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 (M, D).

required

Returns:

Type Description
Float[Array, 'M D D']

The symmetric (M, D, D) Hessians.

Raises:

Type Description
ValueError

For a kernel whose GP is not mean-square differentiable (see predict_gradient).

NotImplementedError

For a pyrox_gp kernel without frozen().

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
def predict_mean_hessian(
    self, X_star: Float[Array, "M D"]
) -> Float[Array, "M D D"]:
    r"""Hessian of the predictive mean, $\nabla \nabla^\top \mu_*(x)$.

    $$
    \nabla \nabla^\top \mu_*(x) = \nabla^2 m(x)
        + \sum_n \alpha_n\, \nabla_x^2 k(x, x_n),
    $$

    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$).

    Args:
        X_star: Test inputs, shape ``(M, D)``.

    Returns:
        The symmetric ``(M, D, D)`` Hessians.

    Raises:
        ValueError: For a kernel whose GP is not mean-square
            differentiable (see `predict_gradient`).
        NotImplementedError: For a `pyrox_gp` kernel without
            ``frozen()``.

    Examples:
        ```python
        hess = cond.predict_mean_hessian(X_star)  # (M, D, D)
        curvature = jnp.trace(hess, axis1=-2, axis2=-1)  # Laplacian of mu
        ```
    """
    with call_context(self.prior.kernel):
        k = _derivative_kernel(self.prior.kernel)
    kl.DerivativeIndexed(k)  # kernellib's mean-square differentiability check
    X, alpha, mean_fn = self.prior.X, self.cache.alpha, self.prior.mean_fn

    def mu(x: Float[Array, " D"]) -> Float[Array, ""]:
        value = einx.dot("n, n ->", k(x[None], X)[0], alpha)
        if mean_fn is not None:
            value = value + mean_fn(x[None])[0]
        return value

    return jax.vmap(jax.hessian(mu))(X_star)

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
def 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`.
    """
    numpyro.factor(name, prior.log_marginal(y, noise_var))

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\),

\[ \log p(y \mid \theta) \approx \sum_n \log p(y_n \mid \hat f_n) - \tfrac12 (\hat f - \mu)^\top K^{-1} (\hat f - \mu) - \tfrac12 \log \lvert I + \Lambda^{1/2} K \Lambda^{1/2} \rvert , \]

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

required
likelihood Likelihood

A scalar-latent Likelihood.

required
y Float[Array, ' N']

Observations, shape (N,).

required
strategy LaplaceInference | GaussNewtonInference | None

LaplaceInference (the default) or GaussNewtonInference.

None
key Array | None

PRNG key of a stochastic log-determinant in the evidence, passed to strategy.fit; None uses the solver's own seed.

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
def gp_laplace_factor(
    name: str,
    prior: GPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    strategy: LaplaceInference | GaussNewtonInference | None = None,
    key: Array | None = None,
) -> None:
    r"""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$,

    $$
    \log p(y \mid \theta) \approx \sum_n \log p(y_n \mid \hat f_n)
      - \tfrac12 (\hat f - \mu)^\top K^{-1} (\hat f - \mu)
      - \tfrac12 \log \lvert I + \Lambda^{1/2} K \Lambda^{1/2} \rvert ,
    $$

    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.

    Args:
        name: The factor site name.
        prior: The `GPPrior`.
        likelihood: A scalar-latent `Likelihood`.
        y: Observations, shape ``(N,)``.
        strategy: `LaplaceInference` (the default) or `GaussNewtonInference`.
        key: PRNG key of a stochastic log-determinant in the evidence,
            passed to ``strategy.fit``; ``None`` uses the solver's own seed.

    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']
    """
    strategy = LaplaceInference() if strategy is None else strategy
    fit = strategy.fit(prior, likelihood, y, key=key)
    numpyro.factor(name, fit.log_marginal_approx)

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 single numpyro.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 site f"{name}_u" with shape (N,) and return the deterministic value f = mu(X) + L u where L is the Cholesky factor of K + jitter I. This reparameterization is the standard fix for mean-field SVI on GP-correlated latents (Murray & Adams, 2010): a NumPyro auto-guide such as numpyro.infer.autoguide.AutoNormal then approximates the well-conditioned isotropic posterior over u instead of the ill-conditioned correlated posterior over f.
  • guide provided — delegate to guide.register(name, prior). Concrete variational guides (Wave 3) own their own parameterization, so combining whitened=True with guide is 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
def 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"]:
    r"""Sample a latent function ``f`` at the prior's training inputs.

    Three mutually exclusive modes:

    * ``whitened=False``, ``guide=None`` (default) — register a single
      ``numpyro.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
      site ``f"{name}_u"`` with shape ``(N,)`` and return the
      deterministic value ``f = mu(X) + L u`` where ``L`` is the
      Cholesky factor of ``K + jitter I``. This reparameterization is the
      standard fix for mean-field SVI on GP-correlated latents
      (Murray & Adams, 2010): a NumPyro auto-guide such as
      `numpyro.infer.autoguide.AutoNormal` then approximates the
      well-conditioned isotropic posterior over ``u`` instead of the
      ill-conditioned correlated posterior over ``f``.
    * ``guide`` provided — delegate to ``guide.register(name, prior)``.
      Concrete variational guides (Wave 3) own their own
      parameterization, so combining ``whitened=True`` with ``guide`` is
      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.
    """
    _check_draw_method(method)
    if method != "cholesky" and not whitened:
        raise ValueError(
            'gp_sample: method="krylov" applies to whitened=True only; the '
            "unwhitened site is a MultivariateNormal on the prior's solver."
        )
    if guide is not None:
        if whitened:
            raise ValueError(
                "gp_sample: cannot combine `whitened=True` with `guide=...`. "
                "Provide one or the other; concrete guides own their own "
                "parameterization."
            )
        return guide.register(name, prior)  # type: ignore[attr-defined]  # ty: ignore[unresolved-attribute]

    if whitened:
        if method == "cholesky" and prior.matrix_free:
            raise ValueError(_dense_draw_message("gp_sample(whitened=True)"))
        # the kernel's sites register before f_u, in the same order as ever
        operator = prior._prior_operator()
        if method == "krylov":
            root = sqrt(operator, lanczos_order=lanczos_order)
        else:
            root = cholesky(operator)
        n = prior.X.shape[0]
        dtype = prior.X.dtype
        u = numpyro.sample(
            f"{name}_u",
            dist.Normal(jnp.zeros(n, dtype=dtype), jnp.ones((), dtype=dtype)).to_event(
                1
            ),
        )
        if method == "krylov":
            # f = μ + K̂^½ u, the symmetric root applied by Lanczos
            f = prior.mean(prior.X) + root.mv(jnp.asarray(u))
        else:
            # f = μ + L u, L Lᵀ = K̂
            f = prior.mean(prior.X) + unwhiten(jnp.asarray(u), root)
        return numpyro.deterministic(name, f)  # ty: ignore[invalid-return-type]

    return numpyro.sample(  # ty: ignore[invalid-return-type]
        name,
        MultivariateNormal(
            prior.mean(prior.X),
            prior._prior_operator(),
            solver=prior._resolved_solver(),
        ),
    )

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" (randomized Nyström, one batched matvec per build), "rpcholesky" (randomly pivoted partial Cholesky, one matvec per pivot) or "fitc" (gaussx.FITCPreconditioner: the Nyström approximation at rank training inputs drawn by key, plus the prior variance it misses on the diagonal, so \(P\) matches \(A\) there; only \(K_{ZZ}\), \(K_{XZ}\) and \(\mathrm{diag}(K)\) are evaluated). To choose the inducing inputs yourself, pass gaussx.FITCPreconditioner.from_kernel(...) as the prior's preconditioner instead.

'nystrom'
logdet Literal['nystrom', 'slq']

"nystrom" (the default, gaussx.NystromLogdet with the same shift: the exact \(\log \det P\) plus SLQ on the near-identity \(P^{-1/2} A P^{-1/2}\), the more accurate at equal rank) or "slq" (CG's own SLQ on the system, with probes from its fixed seed).

'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 is gaussx's default.

None
max_steps int

CG iteration cap.

1000
throw bool

Raise when CG does not converge within max_steps.

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 gaussx.AbstractSolverStrategy (a gaussx.CGSolver

AbstractSolverStrategy

for logdet="slq", a gaussx.ComposedSolver for

AbstractSolverStrategy

logdet="nystrom"), so gaussx.compose_solver and

AbstractSolverStrategy

gaussx.KeyedSolver work on it.

Raises:

Type Description
ValueError

For an unknown preconditioner or logdet.

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
def 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 = 1e-4,
    atol: float | None = None,
    max_steps: int = 1000,
    throw: bool = True,
    key: jax.Array,
) -> gx.AbstractSolverStrategy:
    r"""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](https://jejjohnson.github.io/pyrox/gp-solver-choices/).

    Args:
        rank: 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).
        preconditioner: ``"nystrom"`` (randomized Nyström, one batched
            matvec per build), ``"rpcholesky"`` (randomly pivoted partial
            Cholesky, one matvec per pivot) or ``"fitc"``
            (`gaussx.FITCPreconditioner`: the Nyström approximation at
            ``rank`` training inputs drawn by ``key``, plus the prior
            variance it misses on the diagonal, so $P$ matches $A$ there;
            only $K_{ZZ}$, $K_{XZ}$ and $\mathrm{diag}(K)$ are evaluated).
            To choose the inducing inputs yourself, pass
            ``gaussx.FITCPreconditioner.from_kernel(...)`` as the prior's
            ``preconditioner`` instead.
        logdet: ``"nystrom"`` (the default, `gaussx.NystromLogdet` with the
            same shift: the exact $\log \det P$ plus SLQ on the
            near-identity $P^{-1/2} A P^{-1/2}$, the more accurate at equal
            rank) or ``"slq"`` (CG's own SLQ on the system, with probes from
            its fixed seed).
        num_probes: Probe vectors $N_\text{probe}$ of the SLQ.
        lanczos_order: Lanczos steps per probe.
        rtol: CG relative tolerance.
        atol: CG absolute tolerance; ``None`` is gaussx's default.
        max_steps: CG iteration cap.
        throw: Raise when CG does not converge within ``max_steps``.
        key: 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).

    Returns:
        One ordinary `gaussx.AbstractSolverStrategy` (a `gaussx.CGSolver`
        for ``logdet="slq"``, a `gaussx.ComposedSolver` for
        ``logdet="nystrom"``), so `gaussx.compose_solver` and
        `gaussx.KeyedSolver` work on it.

    Raises:
        ValueError: For an unknown ``preconditioner`` or ``logdet``.

    Examples:
        ```python
        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.
    """
    return _matfree_solver(
        rank=rank,
        preconditioner=preconditioner,
        logdet=logdet,
        num_probes=num_probes,
        lanczos_order=lanczos_order,
        rtol=rtol,
        atol=atol,
        max_steps=max_steps,
        throw=throw,
        shift=None,
        key=key,
    )

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", "rpcholesky" or "fitc", as in matfree_solver.

'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 max_steps.

True
key Array

PRNG key, split into the preconditioner's sketch and the probes (bound with gaussx.KeyedSolver), so the estimate 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

A gaussx.KeyedSolver around the preconditioned gaussx.BBMMSolver.

Raises:

Type Description
ValueError

For an unknown preconditioner.

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
def bbmm_solver(
    *,
    rank: int = 200,
    preconditioner: Literal["nystrom", "rpcholesky", "fitc"] = "nystrom",
    num_probes: int = 50,
    lanczos_order: int = 100,
    rtol: float = 1e-4,
    max_steps: int = 1000,
    throw: bool = True,
    key: jax.Array,
) -> gx.AbstractSolverStrategy:
    r"""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](https://jejjohnson.github.io/pyrox/gp-solver-choices/).
    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$.

    Args:
        rank: 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).
        preconditioner: ``"nystrom"``, ``"rpcholesky"`` or ``"fitc"``, as in
            `matfree_solver`.
        num_probes: Probe vectors $N_\text{probe}$.
        lanczos_order: Lanczos order of the quadrature.
        rtol: CG relative tolerance.
        max_steps: CG iteration cap.
        throw: Raise when CG does not converge within ``max_steps``.
        key: PRNG key, split into the preconditioner's sketch and the probes
            (bound with `gaussx.KeyedSolver`), so the estimate 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).

    Returns:
        A `gaussx.KeyedSolver` around the preconditioned `gaussx.BBMMSolver`.

    Raises:
        ValueError: For an unknown ``preconditioner``.

    Examples:
        ```python
        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.
    """
    _check_preconditioner(preconditioner)
    sketch_key, probe_key = jr.split(key)
    # gaussx's lazy preconditioners, which read A = K + diag(d) per solve and
    # give P at the scale of A (the shared pass draws its probes from P)
    built: gx.AbstractPreconditioner
    if preconditioner == "nystrom":
        built = gx.NystromPreconditioner.lazy(rank, key=sketch_key)
    elif preconditioner == "fitc":
        # P = U Uᵀ + diag(r + d) matches A on the diagonal, at its scale
        built = _SystemFITCPreconditioner(rank, sketch_key)
    else:
        built = gx.PartialCholeskyPreconditioner(
            rank=rank, shift=None, pivoting="random", key=sketch_key
        )
    bbmm = gx.BBMMSolver(
        rtol=rtol,
        max_steps=max_steps,
        lanczos_order=lanczos_order,
        num_probes=num_probes,
        throw=throw,
    )
    return gx.KeyedSolver(gx.compose_solver(bbmm, preconditioner=built), probe_key)

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

'nystrom'
rank int

As in matfree_solver.

200
logdet Literal['slq', 'nystrom']

As in matfree_solver, with "slq" the old default.

'slq'
key Array

As in matfree_solver.

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 matfree_solver strategy.

Raises:

Type Description
ValueError

For a non-positive shift, and as matfree_solver.

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
def 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-6,
    atol: float = 1e-6,
    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.

    Args:
        shift: Lower bound $\\mu$ on the noise variance, for a dense system.
        preconditioner: As in `matfree_solver`.
        rank: As in `matfree_solver`.
        logdet: As in `matfree_solver`, with ``"slq"`` the old default.
        key: As in `matfree_solver`.
        rtol: CG relative tolerance.
        atol: CG absolute tolerance.
        max_steps: CG iteration cap.
        num_probes: SLQ probe vectors.
        lanczos_order: SLQ Lanczos steps per probe.

    Returns:
        The `matfree_solver` strategy.

    Raises:
        ValueError: For a non-positive ``shift``, and as `matfree_solver`.

    Examples:
        ```python
        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))
        ```
    """
    warnings.warn(
        "preconditioned_cg_solver is deprecated and will be removed in the "
        "next release; use pyrox_gp.matfree_solver (or pyrox_gp.bbmm_solver) "
        "instead (pyrox#557).",
        DeprecationWarning,
        stacklevel=2,
    )
    if shift is not None and not shift > 0:
        raise ValueError(f"shift must be positive, got {shift}")
    return _matfree_solver(
        rank=rank,
        preconditioner=preconditioner,
        logdet=logdet,
        num_probes=num_probes,
        lanczos_order=lanczos_order,
        rtol=rtol,
        atol=atol,
        max_steps=max_steps,
        throw=True,
        shift=shift,
        key=key,
    )

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}\):

\[ \mathbb{E}[\nabla f(x_*) \mid y] = \nabla m(x_*) + G(x_*)\,\alpha , \qquad \operatorname{Cov}[\nabla f \mid y] = \nabla_x \nabla_{x'}^\top k(X_*, X_*) - G\,\hat K^{-1} G^\top . \]

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 a GradientPosterior (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 (M, D).

cov Float[Array, 'M D D'] | Float[Array, 'M D M D'] | None

The posterior covariance of the gradient, or None. With cov="marginal" the per-point blocks, shape (M, D, D): cov[m] is \(\operatorname{Cov}[\nabla f(x_{*,m}) \mid y]\). With cov="full" the joint, shape (M, D, M, D): cov[a, i, b, j] is \(\operatorname{Cov}[\partial_i f(x_{*,a}), \partial_j f(x_{*,b}) \mid y]\); flatten it with einx.id("a i b j -> (a i) (b j)", cov). None with cov="none".

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
class GradientPosterior(NamedTuple):
    r"""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:
        mean: $\mathbb{E}[\nabla f(x_{*,m}) \mid y]$, shape ``(M, D)``.
        cov: The posterior covariance of the gradient, or ``None``.
            With ``cov="marginal"`` the per-point blocks, shape
            ``(M, D, D)``: ``cov[m]`` is
            $\operatorname{Cov}[\nabla f(x_{*,m}) \mid y]$. With
            ``cov="full"`` the joint, shape ``(M, D, M, D)``:
            ``cov[a, i, b, j]`` is
            $\operatorname{Cov}[\partial_i f(x_{*,a}), \partial_j f(x_{*,b}) \mid y]$;
            flatten it with
            ``einx.id("a i b j -> (a i) (b j)", cov)``. ``None``
            with ``cov="none"``.

    Examples:
        ```python
        post = cond.predict_gradient(X_star)  # X_star: (M, D)
        post.mean.shape  # (M, D)
        post.cov.shape  # (M, D, D)
        ```
    """

    mean: Float[Array, "M D"]
    cov: Float[Array, "M D D"] | Float[Array, "M D M D"] | None

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
class RBF(_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.
    """

    _frozen_cls = kl.RBF
    _frozen_params = ("variance", "lengthscale")

    pyrox_name: str = "RBF"
    init_variance: float = 1.0
    init_lengthscale: float = 1.0
    input_dim: int | None = None

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )
        lengthscale = (
            jnp.asarray(self.init_lengthscale)
            if self.input_dim is None
            else jnp.full((self.input_dim,), self.init_lengthscale)
        )
        self.register_param(
            "lengthscale",
            lengthscale,
            constraint=dist.constraints.positive,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.rbf_kernel(
            X1, X2, self.get_param("variance"), self.get_param("lengthscale")
        )

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
class Matern(_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.
    """

    _frozen_cls = kl.Matern
    _frozen_params = ("variance", "lengthscale")
    _frozen_static = ("nu",)

    pyrox_name: str = "Matern"
    init_variance: float = 1.0
    init_lengthscale: float = 1.0
    nu: float = 2.5
    input_dim: int | None = None

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )
        lengthscale = (
            jnp.asarray(self.init_lengthscale)
            if self.input_dim is None
            else jnp.full((self.input_dim,), self.init_lengthscale)
        )
        self.register_param(
            "lengthscale",
            lengthscale,
            constraint=dist.constraints.positive,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.matern_kernel(
            X1,
            X2,
            self.get_param("variance"),
            self.get_param("lengthscale"),
            self.nu,
        )

Periodic

Bases: _ParameterizedKernel

Periodic (MacKay) kernel.

Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
class Periodic(_ParameterizedKernel):
    """Periodic (MacKay) kernel."""

    _frozen_cls = kl.Periodic
    _frozen_params = ("variance", "lengthscale", "period")

    pyrox_name: str = "Periodic"
    init_variance: float = 1.0
    init_lengthscale: float = 1.0
    init_period: float = 1.0

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )
        self.register_param(
            "lengthscale",
            jnp.asarray(self.init_lengthscale),
            constraint=dist.constraints.positive,
        )
        self.register_param(
            "period",
            jnp.asarray(self.init_period),
            constraint=dist.constraints.positive,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.periodic_kernel(
            X1,
            X2,
            self.get_param("variance"),
            self.get_param("lengthscale"),
            self.get_param("period"),
        )

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
class Linear(_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``).
    """

    _frozen_cls = kl.Linear
    _frozen_params = ("variance", "bias")

    pyrox_name: str = "Linear"
    init_variance: float = 1.0
    init_bias: float = 0.0

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )
        self.register_param(
            "bias",
            jnp.asarray(self.init_bias),
            constraint=dist.constraints.nonnegative,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.linear_kernel(
            X1, X2, self.get_param("variance"), self.get_param("bias")
        )

    def diag(self, X: Float[Array, "N D"]) -> Float[Array, " N"]:
        # Non-stationary: diagonal depends on |X[i]|^2.
        v = self.get_param("variance")
        b = self.get_param("bias")
        return v * jnp.sum(X * X, axis=-1) + b

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
class RationalQuadratic(_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.
    """

    _frozen_cls = kl.RationalQuadratic
    _frozen_params = ("variance", "lengthscale", "alpha")

    pyrox_name: str = "RationalQuadratic"
    init_variance: float = 1.0
    init_lengthscale: float = 1.0
    init_alpha: float = 1.0
    input_dim: int | None = None

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )
        lengthscale = (
            jnp.asarray(self.init_lengthscale)
            if self.input_dim is None
            else jnp.full((self.input_dim,), self.init_lengthscale)
        )
        self.register_param(
            "lengthscale",
            lengthscale,
            constraint=dist.constraints.positive,
        )
        self.register_param(
            "alpha",
            jnp.asarray(self.init_alpha),
            constraint=dist.constraints.positive,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.rational_quadratic_kernel(
            X1,
            X2,
            self.get_param("variance"),
            self.get_param("lengthscale"),
            self.get_param("alpha"),
        )

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
class Polynomial(_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.
    """

    _frozen_cls = kl.Polynomial
    _frozen_params = ("variance", "bias")
    _frozen_static = ("degree",)

    pyrox_name: str = "Polynomial"
    init_variance: float = 1.0
    init_bias: float = 0.0
    degree: int = 2

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )
        self.register_param(
            "bias",
            jnp.asarray(self.init_bias),
            constraint=dist.constraints.nonnegative,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.polynomial_kernel(
            X1,
            X2,
            self.get_param("variance"),
            self.get_param("bias"),
            self.degree,
        )

    def diag(self, X: Float[Array, "N D"]) -> Float[Array, " N"]:
        v = self.get_param("variance")
        b = self.get_param("bias")
        return v * (jnp.sum(X * X, axis=-1) + b) ** self.degree

Cosine

Bases: _ParameterizedKernel

Cosine kernel sigma^2 cos(2 pi ||x - x'|| / period).

Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
class Cosine(_ParameterizedKernel):
    """Cosine kernel ``sigma^2 cos(2 pi ||x - x'|| / period)``."""

    _frozen_cls = kl.Cosine
    _frozen_params = ("variance", "period")

    pyrox_name: str = "Cosine"
    init_variance: float = 1.0
    init_period: float = 1.0

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )
        self.register_param(
            "period",
            jnp.asarray(self.init_period),
            constraint=dist.constraints.positive,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.cosine_kernel(
            X1, X2, self.get_param("variance"), self.get_param("period")
        )

White

Bases: _ParameterizedKernel

White-noise kernel sigma^2 delta(x, x').

Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
class White(_ParameterizedKernel):
    """White-noise kernel ``sigma^2 delta(x, x')``."""

    _frozen_cls = kl.White
    _frozen_params = ("variance",)

    pyrox_name: str = "White"
    init_variance: float = 1.0

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.white_kernel(X1, X2, self.get_param("variance"))

Constant

Bases: _ParameterizedKernel

Constant kernel k(x, x') = sigma^2.

Source code in packages/pyrox-gp/src/pyrox_gp/_kernels.py
class Constant(_ParameterizedKernel):
    """Constant kernel ``k(x, x') = sigma^2``."""

    _frozen_cls = kl.Constant
    _frozen_params = ("variance",)

    pyrox_name: str = "Constant"
    init_variance: float = 1.0

    def setup(self) -> None:
        self.register_param(
            "variance",
            jnp.asarray(self.init_variance),
            constraint=dist.constraints.positive,
        )

    @pyrox_method
    def __call__(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "N1 N2"]:
        return _k.constant_kernel(X1, X2, self.get_param("variance"))

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

required
kernel Kernel | None

The GP's kernel; required by keyword. None only with method="uniform", which does not look at it.

required
method Literal['uniform', 'rpcholesky', 'greedy', 'leverage']

"rpcholesky" (default: kernel-aware, no tuning), "greedy" (largest conditional variance; deterministic, but drawn to outliers), "leverage" (approximate ridge leverage) or "uniform".

'rpcholesky'
key PRNGKeyArray

PRNG key (unused by "greedy").

required

Returns:

Type Description
Float[Array, 'M D']

X[indices], distinct rows of X.

Raises:

Type Description
ValueError

If kernel is None with a kernel-aware method.

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

    Args:
        X: Training inputs.
        n_inducing: Number of inducing inputs ``M``.
        kernel: The GP's kernel; required by keyword. ``None`` only with
            ``method="uniform"``, which does not look at it.
        method: ``"rpcholesky"`` (default: kernel-aware, no tuning),
            ``"greedy"`` (largest conditional variance; deterministic, but
            drawn to outliers), ``"leverage"`` (approximate ridge leverage)
            or ``"uniform"``.
        key: PRNG key (unused by ``"greedy"``).

    Returns:
        ``X[indices]``, distinct rows of ``X``.

    Raises:
        ValueError: If ``kernel`` is None with a kernel-aware method.

    Examples:
        ```python
        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))
        ```
    """
    if kernel is None:
        if method != "uniform":
            raise ValueError(
                f"method={method!r} needs the kernel; "
                'kernel=None only works with "uniform"'
            )
        frozen: kl.AbstractKernel = kl.RBF()  # never evaluated by "uniform"
    else:
        if isinstance(kernel, _ParameterizedKernel):
            with call_context(kernel):
                frozen = kernel.frozen()
        else:  # already a plain kernellib kernel
            frozen = kernel
    idx = kl.select_landmarks(frozen, X, n_inducing, method=method, key=key)
    return X[idx]

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
@runtime_checkable
class InducingFeatures(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.
    """

    @property
    def num_features(self) -> int: ...

    def K_uu(
        self, kernel: Kernel, *, jitter: float = 1e-6
    ) -> lx.AbstractLinearOperator: ...

    def k_ux(self, x: Array, kernel: Kernel) -> Float[Array, "N M"]: ...

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

\[ K_{uu} = \mathrm{diag}\!\big(S(\sqrt{\lambda_j})\big), \qquad K_{ux}(x)_j = S(\sqrt{\lambda_j})\,\phi_j(x). \]

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 prod(num_basis_per_dim).

L tuple[float, ...]

Per-axis box half-width.

Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
class FourierInducingFeatures(eqx.Module):
    r"""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

    $$
    K_{uu} = \mathrm{diag}\!\big(S(\sqrt{\lambda_j})\big),
    \qquad
    K_{ux}(x)_j = S(\sqrt{\lambda_j})\,\phi_j(x).
    $$

    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:
        in_features: Input dimension $D$.
        num_basis_per_dim: Per-axis number of 1D eigenfunctions; total
            count is ``prod(num_basis_per_dim)``.
        L: Per-axis box half-width.
    """

    in_features: int = eqx.field(static=True)
    num_basis_per_dim: tuple[int, ...] = eqx.field(static=True)
    L: tuple[float, ...] = eqx.field(static=True)

    @classmethod
    def init(
        cls,
        in_features: int,
        num_basis_per_dim: int | tuple[int, ...],
        L: float | tuple[float, ...],
    ) -> FourierInducingFeatures:
        M_per = _to_tuple(num_basis_per_dim, in_features, "num_basis_per_dim")
        L_per = _to_tuple(L, in_features, "L")
        if any(L_d <= 0 for L_d in L_per):
            raise ValueError(f"L must be all positive; got {L_per}.")
        if any(M_d < 1 for M_d in M_per):
            raise ValueError(f"num_basis_per_dim must be all >= 1; got {M_per}.")
        return cls(
            in_features=in_features,
            num_basis_per_dim=M_per,
            L=tuple(float(L_d) for L_d in L_per),
        )

    @property
    def num_features(self) -> int:
        n = 1
        for m in self.num_basis_per_dim:
            n *= m
        return n

    def _check_stationary(self, kernel: Kernel) -> None:
        if not _is_stationary(kernel):
            raise ValueError(
                f"FourierInducingFeatures requires a stationary kernel with a "
                f"registered spectral density (RBF or Matern); got "
                f"{type(kernel).__name__}."
            )

    def K_uu(
        self, kernel: Kernel, *, jitter: float = 1e-6
    ) -> lx.DiagonalLinearOperator:
        """Diagonal $K_{uu}$ — entries ``S(sqrt(lambda_j))`` plus jitter."""
        self._check_stationary(kernel)
        with call_context(kernel):
            lam = fourier_eigenvalues(self.num_basis_per_dim, self.L, self.in_features)
            S = _isotropic_spectral_density(kernel, lam, D=self.in_features)
        return _diagonal_with_jitter(S, jitter)

    def k_ux(self, x: Float[Array, "N D"], kernel: Kernel) -> Float[Array, "N M"]:
        """Cross-covariance entries $S(\\sqrt{\\lambda_j})\\,\\phi_j(x)$."""
        self._check_stationary(kernel)
        if x.ndim != 2 or x.shape[-1] != self.in_features:
            raise ValueError(f"x must be (N, {self.in_features}); got shape {x.shape}.")
        with call_context(kernel):
            Phi, lam = fourier_basis(x, self.num_basis_per_dim, self.L)
            S = _isotropic_spectral_density(kernel, lam, D=self.in_features)
        return Phi * S[None, :]

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
def K_uu(
    self, kernel: Kernel, *, jitter: float = 1e-6
) -> lx.DiagonalLinearOperator:
    """Diagonal $K_{uu}$ — entries ``S(sqrt(lambda_j))`` plus jitter."""
    self._check_stationary(kernel)
    with call_context(kernel):
        lam = fourier_eigenvalues(self.num_basis_per_dim, self.L, self.in_features)
        S = _isotropic_spectral_density(kernel, lam, D=self.in_features)
    return _diagonal_with_jitter(S, jitter)

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
def k_ux(self, x: Float[Array, "N D"], kernel: Kernel) -> Float[Array, "N M"]:
    """Cross-covariance entries $S(\\sqrt{\\lambda_j})\\,\\phi_j(x)$."""
    self._check_stationary(kernel)
    if x.ndim != 2 or x.shape[-1] != self.in_features:
        raise ValueError(f"x must be (N, {self.in_features}); got shape {x.shape}.")
    with call_context(kernel):
        Phi, lam = fourier_basis(x, self.num_basis_per_dim, self.L)
        S = _isotropic_spectral_density(kernel, lam, D=self.in_features)
    return Phi * S[None, :]

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
class SphericalHarmonicInducingFeatures(eqx.Module):
    r"""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:
        l_max: Maximum harmonic degree, inclusive.
        num_quadrature: Gauss-Legendre nodes for the Funk-Hecke integral.
    """

    l_max: int = eqx.field(static=True)
    num_quadrature: int = eqx.field(static=True, default=256)

    @classmethod
    def init(
        cls, l_max: int, *, num_quadrature: int = 256
    ) -> SphericalHarmonicInducingFeatures:
        if l_max < 0:
            raise ValueError(f"l_max must be >= 0; got {l_max}.")
        if num_quadrature < 1:
            raise ValueError(f"num_quadrature must be >= 1; got {num_quadrature}.")
        return cls(l_max=l_max, num_quadrature=num_quadrature)

    @property
    def num_features(self) -> int:
        return (self.l_max + 1) ** 2

    def _per_feature_coeffs(self, kernel: Kernel) -> Float[Array, " M"]:
        a = kl.funk_hecke_coefficients(
            freeze(kernel), self.l_max, num_quadrature=self.num_quadrature
        )
        # Each l contributes 2l+1 features with the same coefficient.
        return jnp.concatenate(
            [jnp.full((2 * ell + 1,), a[ell]) for ell in range(self.l_max + 1)]
        )

    def K_uu(
        self, kernel: Kernel, *, jitter: float = 1e-6
    ) -> lx.DiagonalLinearOperator:
        """Diagonal $K_{uu}$ — Funk-Hecke coefficients per harmonic."""
        diag = self._per_feature_coeffs(kernel)
        return _diagonal_with_jitter(diag, jitter)

    def k_ux(
        self,
        unit_xyz: Float[Array, "N 3"],
        kernel: Kernel,
    ) -> Float[Array, "N M"]:
        r"""Cross-covariance: $a_l\,Y_{lm}(x)$."""
        if unit_xyz.ndim != 2 or unit_xyz.shape[-1] != 3:
            raise ValueError(f"unit_xyz must be (N, 3); got {unit_xyz.shape}.")
        Y = real_spherical_harmonics(unit_xyz, self.l_max)
        a_per_feature = self._per_feature_coeffs(kernel)
        return Y * a_per_feature[None, :]

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
def K_uu(
    self, kernel: Kernel, *, jitter: float = 1e-6
) -> lx.DiagonalLinearOperator:
    """Diagonal $K_{uu}$ — Funk-Hecke coefficients per harmonic."""
    diag = self._per_feature_coeffs(kernel)
    return _diagonal_with_jitter(diag, jitter)

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
def k_ux(
    self,
    unit_xyz: Float[Array, "N 3"],
    kernel: Kernel,
) -> Float[Array, "N M"]:
    r"""Cross-covariance: $a_l\,Y_{lm}(x)$."""
    if unit_xyz.ndim != 2 or unit_xyz.shape[-1] != 3:
        raise ValueError(f"unit_xyz must be (N, 3); got {unit_xyz.shape}.")
    Y = real_spherical_harmonics(unit_xyz, self.l_max)
    a_per_feature = self._per_feature_coeffs(kernel)
    return Y * a_per_feature[None, :]

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
class SlepianInducingFeatures(eqx.Module):
    r"""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.
    """

    l_max: int = eqx.field(static=True)
    cap_radius_deg: float = eqx.field(static=True)
    cap_centre_lonlat_deg: tuple[float, float] = eqx.field(static=True)
    eig_threshold: float = eqx.field(static=True)
    n_modes: int | None = eqx.field(static=True)
    num_quadrature: int = eqx.field(static=True)
    basis_num_quadrature: int | None = eqx.field(static=True)
    basis: SlepianCapBasis

    @classmethod
    def init(
        cls,
        *,
        l_max: int,
        cap_radius_deg: float,
        cap_centre_lonlat_deg: tuple[float, float],
        eig_threshold: float = 0.05,
        n_modes: int | None = None,
        num_quadrature: int = 256,
        basis_num_quadrature: int | None = None,
    ) -> SlepianInducingFeatures:
        if l_max < 0:
            raise ValueError(f"l_max must be >= 0; got {l_max}.")
        if cap_radius_deg <= 0.0 or cap_radius_deg > 180.0:
            raise ValueError(
                f"cap_radius_deg must lie in (0, 180]; got {cap_radius_deg}."
            )
        if num_quadrature < 1:
            raise ValueError(f"num_quadrature must be >= 1; got {num_quadrature}.")
        if n_modes is not None and n_modes < 1:
            raise ValueError(f"n_modes must be >= 1; got {n_modes}.")
        if len(cap_centre_lonlat_deg) != 2:
            raise ValueError(
                "cap_centre_lonlat_deg must contain (lon, lat); "
                f"got {cap_centre_lonlat_deg}."
            )
        lon, lat = cap_centre_lonlat_deg
        # Build the basis once at construction so K_uu / k_ux are matrix
        # multiplies; cap geometry is static, so the eigensolve does not
        # rerun per call.
        basis = slepian_cap_basis(
            l_max,
            jnp.deg2rad(cap_radius_deg),
            n_modes=n_modes,
            eig_threshold=eig_threshold,
            lonlat_centre=jnp.deg2rad(jnp.asarray((float(lon), float(lat)))),
            num_quadrature=basis_num_quadrature,
        )
        return cls(
            l_max=l_max,
            cap_radius_deg=float(cap_radius_deg),
            cap_centre_lonlat_deg=(float(lon), float(lat)),
            eig_threshold=float(eig_threshold),
            n_modes=n_modes,
            num_quadrature=num_quadrature,
            basis_num_quadrature=basis_num_quadrature,
            basis=basis,
        )

    @property
    def num_features(self) -> int:
        return self.basis.num_modes

    def _per_feature_coeffs(self, kernel: Kernel) -> Float[Array, " M"]:
        a = kl.funk_hecke_coefficients(
            freeze(kernel), self.l_max, num_quadrature=self.num_quadrature
        )
        return a[jnp.asarray(harmonic_degrees(self.l_max))]

    def K_uu(self, kernel: Kernel, *, jitter: float = 1e-6) -> lx.MatrixLinearOperator:
        """Dense Slepian inducing covariance with diagonal jitter."""
        a_per_feature = self._per_feature_coeffs(kernel)
        # Scale each feature row by its Funk-Hecke coefficient, then form the
        # Gram K = Φᵀ diag(a) Φ by contracting the feature axis f.
        weighted_coeffs = einx.multiply(
            "f m, f -> f m", self.basis.coeffs, a_per_feature
        )
        K = einx.dot("f i, f j -> i j", self.basis.coeffs, weighted_coeffs)
        K = K.at[jnp.diag_indices_from(K)].add(jitter)
        return lx.MatrixLinearOperator(K, lx.positive_semidefinite_tag)

    def k_ux(
        self,
        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.
        """
        if unit_xyz.ndim != 2 or unit_xyz.shape[-1] != 3:
            raise ValueError(f"unit_xyz must be (N, 3); got {unit_xyz.shape}.")
        centred = self.basis.centred_coordinates(unit_xyz)
        Y = real_spherical_harmonics(centred, self.l_max)
        a_per_feature = self._per_feature_coeffs(kernel)
        # Weight each harmonic by its Funk-Hecke coefficient, then project
        # onto the Slepian modes by contracting the feature axis f.
        Y_weighted = einx.multiply("n f, f -> n f", Y, a_per_feature)
        return einx.dot("n f, f m -> n m", Y_weighted, self.basis.coeffs)

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
def K_uu(self, kernel: Kernel, *, jitter: float = 1e-6) -> lx.MatrixLinearOperator:
    """Dense Slepian inducing covariance with diagonal jitter."""
    a_per_feature = self._per_feature_coeffs(kernel)
    # Scale each feature row by its Funk-Hecke coefficient, then form the
    # Gram K = Φᵀ diag(a) Φ by contracting the feature axis f.
    weighted_coeffs = einx.multiply(
        "f m, f -> f m", self.basis.coeffs, a_per_feature
    )
    K = einx.dot("f i, f j -> i j", self.basis.coeffs, weighted_coeffs)
    K = K.at[jnp.diag_indices_from(K)].add(jitter)
    return lx.MatrixLinearOperator(K, lx.positive_semidefinite_tag)

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
def k_ux(
    self,
    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.
    """
    if unit_xyz.ndim != 2 or unit_xyz.shape[-1] != 3:
        raise ValueError(f"unit_xyz must be (N, 3); got {unit_xyz.shape}.")
    centred = self.basis.centred_coordinates(unit_xyz)
    Y = real_spherical_harmonics(centred, self.l_max)
    a_per_feature = self._per_feature_coeffs(kernel)
    # Weight each harmonic by its Funk-Hecke coefficient, then project
    # onto the Slepian modes by contracting the feature axis f.
    Y_weighted = einx.multiply("n f, f -> n f", Y, a_per_feature)
    return einx.dot("n f, f m -> n m", Y_weighted, self.basis.coeffs)

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

\[ \operatorname{Cov}(u_k, u_l) = \Phi(\lambda_k)\,\delta_{kl}, \qquad \operatorname{Cov}(u_k, f(v)) = \Phi(\lambda_k)\,\phi_k(v), \]

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']

(M,) Laplacian eigenvalues.

eigvecs Float[Array, 'V M']

(V, M) Laplacian eigenvectors.

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
class LaplacianInducingFeatures(eqx.Module):
    r"""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

    $$
    \operatorname{Cov}(u_k, u_l) = \Phi(\lambda_k)\,\delta_{kl}, \qquad
    \operatorname{Cov}(u_k, f(v)) = \Phi(\lambda_k)\,\phi_k(v),
    $$

    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:
        eigvals: ``(M,)`` Laplacian eigenvalues.
        eigvecs: ``(V, M)`` Laplacian eigenvectors.

    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,)
    """

    eigvals: Float[Array, " M"]
    eigvecs: Float[Array, "V M"]

    @classmethod
    def fit(
        cls,
        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:
        """Take the ``num_basis`` smallest Laplacian eigenpairs of ``graph``.

        Args:
            graph: A kernellib graph or a dense symmetric adjacency matrix.
            num_basis: Number of eigenpairs ``M``.
            normalization: Laplacian normalisation.
            method: Eigensolver, passed to `kernellib.laplacian_eigpairs`
                (``None`` picks one from the graph).
            key: PRNG key for the randomised solvers.
            normalized: Deprecated alias: ``True`` is ``"symmetric"``,
                ``False`` is ``"unnormalized"``. Removed in 0.3.

        Returns:
            The fitted features.
        """
        if normalized is not None:
            warnings.warn(
                "normalized= is deprecated; use normalization="
                '"symmetric" or "unnormalized". It is removed in 0.3.',
                DeprecationWarning,
                stacklevel=2,
            )
            normalization = "symmetric" if normalized else "unnormalized"
        eigvals, eigvecs = kl.laplacian_eigpairs(
            graph, num_basis, normalization=normalization, method=method, key=key
        )
        return cls(eigvals=eigvals, eigvecs=eigvecs)

    @property
    def num_features(self) -> int:
        return int(self.eigvals.shape[0])

    @property
    def n_nodes(self) -> int:
        """Number of graph nodes ``V``, used for the variance normalisation."""
        return int(self.eigvecs.shape[0])

    def K_uu(
        self, kernel: Kernel, *, jitter: float = 1e-6
    ) -> lx.DiagonalLinearOperator:
        S = _graph_spectrum(kernel, self.eigvals, self.n_nodes)
        return _diagonal_with_jitter(S, jitter)

    def k_ux(
        self, node_indices: Int[Array, " N"], kernel: Kernel
    ) -> Float[Array, "N M"]:
        if node_indices.ndim != 1:
            raise ValueError(
                "node_indices must be a 1D integer array; got shape "
                f"{node_indices.shape}."
            )
        S = _graph_spectrum(kernel, self.eigvals, self.n_nodes)
        rows = self.eigvecs[node_indices]
        return rows * S[None, :]

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

required
normalization Literal['unnormalized', 'symmetric']

Laplacian normalisation.

'symmetric'
method Literal['dense', 'kronecker', 'lanczos', 'arpack'] | None

Eigensolver, passed to kernellib.laplacian_eigpairs (None picks one from the graph).

None
key PRNGKeyArray | None

PRNG key for the randomised solvers.

None
normalized bool | None

Deprecated alias: True is "symmetric", False is "unnormalized". Removed in 0.3.

None

Returns:

Type Description
LaplacianInducingFeatures

The fitted features.

Source code in packages/pyrox-gp/src/pyrox_gp/_inducing.py
@classmethod
def fit(
    cls,
    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:
    """Take the ``num_basis`` smallest Laplacian eigenpairs of ``graph``.

    Args:
        graph: A kernellib graph or a dense symmetric adjacency matrix.
        num_basis: Number of eigenpairs ``M``.
        normalization: Laplacian normalisation.
        method: Eigensolver, passed to `kernellib.laplacian_eigpairs`
            (``None`` picks one from the graph).
        key: PRNG key for the randomised solvers.
        normalized: Deprecated alias: ``True`` is ``"symmetric"``,
            ``False`` is ``"unnormalized"``. Removed in 0.3.

    Returns:
        The fitted features.
    """
    if normalized is not None:
        warnings.warn(
            "normalized= is deprecated; use normalization="
            '"symmetric" or "unnormalized". It is removed in 0.3.',
            DeprecationWarning,
            stacklevel=2,
        )
        normalization = "symmetric" if normalized else "unnormalized"
    eigvals, eigvecs = kl.laplacian_eigpairs(
        graph, num_basis, normalization=normalization, method=method, key=key
    )
    return cls(eigvals=eigvals, eigvecs=eigvecs)

DecoupledInducingFeatures

Bases: Module

Decoupled mean / covariance inducing-feature bases (Cheng & Boots 2017).

Two independent inducing-feature sets:

  • mean_features: a large alpha-basis used by the SVGP posterior mean (cheap — predictive mean cost is linear in the mean-basis size).
  • cov_features: a small beta-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
class DecoupledInducingFeatures(eqx.Module):
    r"""Decoupled mean / covariance inducing-feature bases (Cheng & Boots 2017).

    Two independent inducing-feature sets:

    - ``mean_features``: a large ``alpha``-basis used by the SVGP
      posterior *mean* (cheap — predictive mean cost is linear in the
      mean-basis size).
    - ``cov_features``: a small ``beta``-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:
        mean_features: Inducing-feature object backing the predictive mean.
        cov_features: 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.
    """

    mean_features: InducingFeatures
    cov_features: InducingFeatures

    @property
    def num_mean_features(self) -> int:
        return self.mean_features.num_features

    @property
    def num_cov_features(self) -> int:
        return self.cov_features.num_features

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
def funk_hecke_coefficients(
    kernel: Kernel,
    l_max: int,
    *,
    num_quadrature: int = 256,
) -> Float[Array, " l_max_plus_1"]:
    r"""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$.
    """
    warnings.warn(
        "pyrox_gp.funk_hecke_coefficients is deprecated; use "
        "kernellib.funk_hecke_coefficients(pyrox._core.freeze(kernel), l_max).",
        DeprecationWarning,
        stacklevel=2,
    )
    return kl.funk_hecke_coefficients(
        freeze(kernel), l_max, num_quadrature=num_quadrature
    )

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:

\[ p(u) = \mathcal{N}(0,\, K_{ZZ} + \mathrm{jitter}\,I). \]

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

\[ \mu_*(x) = K_{xZ} K_{ZZ}^{-1} m, \qquad \sigma_*^2(x) = k(x, x) - K_{xZ} K_{ZZ}^{-1} K_{Zx} + K_{xZ} K_{ZZ}^{-1} S K_{ZZ}^{-1} K_{Zx}. \]

Attributes:

Name Type Description
kernel Kernel

Any pyrox_gp.Kernel — evaluated on Z.

Z Float[Array, 'M D'] | None

Inducing inputs of shape (M, D).

mean_fn Callable[[Float[Array, 'N D']], Float[Array, ' N']] | None

Callable X -> (N,) or None for the zero mean. Convenience accessor; not folded into the inducing prior.

solver AbstractSolverStrategy | None

Any gaussx.AbstractSolverStrategy. Defaults to gaussx.DenseSolver(). Used by guides that need to solve against K_zz (e.g.\ for KL or unwhitening).

preconditioner AbstractPreconditioner | None

Optional gaussx.AbstractPreconditioner, composed with solver by gaussx.compose_solver (see pyrox_gp.GPPrior). Keyword only.

logdet AbstractLogdetStrategy | None

Optional gaussx.AbstractLogdetStrategy in place of the solver's own log-determinant. Keyword only.

jitter float

Diagonal regularization added to K_zz for numerical stability. Not a noise model — sparse SVGP does not put observation noise on the inducing-value prior.

Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
class SparseGPPrior(eqx.Module):
    r"""GP prior parameterized over inducing inputs ``Z``.

    Represents the *zero-mean* prior over inducing values ``u = f(Z)``
    used by sparse variational guides:

    $$
    p(u) = \mathcal{N}(0,\, K_{ZZ} + \mathrm{jitter}\,I).
    $$

    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

    $$
    \mu_*(x) = K_{xZ} K_{ZZ}^{-1} m, \qquad
    \sigma_*^2(x) = k(x, x) - K_{xZ} K_{ZZ}^{-1} K_{Zx}
                   + K_{xZ} K_{ZZ}^{-1} S K_{ZZ}^{-1} K_{Zx}.
    $$

    Attributes:
        kernel: Any `pyrox_gp.Kernel` — evaluated on ``Z``.
        Z: Inducing inputs of shape ``(M, D)``.
        mean_fn: Callable ``X -> (N,)`` or ``None`` for the zero mean.
            Convenience accessor; not folded into the inducing prior.
        solver: Any ``gaussx.AbstractSolverStrategy``. Defaults to
            ``gaussx.DenseSolver()``. Used by guides that need to solve
            against ``K_zz`` (e.g.\ for KL or unwhitening).
        preconditioner: Optional ``gaussx.AbstractPreconditioner``, composed
            with ``solver`` by `gaussx.compose_solver` (see
            `pyrox_gp.GPPrior`). Keyword only.
        logdet: Optional ``gaussx.AbstractLogdetStrategy`` in place of the
            solver's own log-determinant. Keyword only.
        jitter: Diagonal regularization added to ``K_zz`` for numerical
            stability. Not a noise model — sparse SVGP does not put
            observation noise on the inducing-value prior.
    """

    kernel: Kernel
    Z: Float[Array, "M D"] | None = None
    inducing: InducingFeatures | None = None
    mean_fn: Callable[[Float[Array, "N D"]], Float[Array, " N"]] | None = None
    solver: AbstractSolverStrategy | None = None
    jitter: float = 1e-6
    # keyword only, so positional calls keep working
    preconditioner: AbstractPreconditioner | None = eqx.field(
        default=None, kw_only=True
    )
    logdet: AbstractLogdetStrategy | None = eqx.field(default=None, kw_only=True)

    def __check_init__(self) -> None:
        self.solver_strategy()
        if (self.Z is None) == (self.inducing is None):
            raise ValueError(
                "SparseGPPrior must be constructed with exactly one of `Z` "
                "(point inducing) or `inducing` (inducing features)."
            )

    @property
    def num_inducing(self) -> int:
        """Number of inducing inputs / features ``M``."""
        if self.inducing is not None:
            return self.inducing.num_features
        assert self.Z is not None
        return self.Z.shape[0]

    def mean(self, X: Float[Array, "N D"]) -> Float[Array, " N"]:
        """Evaluate the mean function at ``X``; zero by default."""
        if self.mean_fn is None:
            return jnp.zeros(X.shape[0], dtype=X.dtype)
        return self.mean_fn(X)

    def inducing_operator(self) -> lx.AbstractLinearOperator:
        r"""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.
        """
        if self.inducing is not None:
            with call_context(self.kernel):
                return self.inducing.K_uu(self.kernel, jitter=self.jitter)
        assert self.Z is not None
        with call_context(self.kernel):
            K = self.kernel(self.Z, self.Z)
        K = K.at[jnp.diag_indices_from(K)].add(self.jitter)
        return _psd_operator(K)

    def cross_covariance(self, X: Array) -> Float[Array, "N M"]:
        r"""$K_{XZ}$ — covariance between ``X`` and the inducing inputs/features.

        The expected shape of ``X`` is inducing-family-dependent:

        - Point-inducing (``Z``) or `FourierInducingFeatures`:
          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.
        """
        if self.inducing is not None:
            with call_context(self.kernel):
                return self.inducing.k_ux(X, self.kernel)
        assert self.Z is not None
        with call_context(self.kernel):
            return self.kernel(X, self.Z)

    def kernel_diag(self, X: Float[Array, "N D"]) -> Float[Array, " N"]:
        r"""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.
        """
        with call_context(self.kernel):
            return self.kernel.diag(X)

    def predictive_blocks(
        self, X: Array
    ) -> tuple[
        lx.AbstractLinearOperator,
        Float[Array, "N M"],
        Float[Array, " N"],
    ]:
        r"""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).
        """
        with call_context(self.kernel):
            if self.inducing is not None:
                K_zz_op = self.inducing.K_uu(self.kernel, jitter=self.jitter)
                K_xz = self.inducing.k_ux(X, self.kernel)
            else:
                assert self.Z is not None
                K_zz_raw = self.kernel(self.Z, self.Z)
                K_xz = self.kernel(X, self.Z)
                K_zz = K_zz_raw.at[jnp.diag_indices_from(K_zz_raw)].add(self.jitter)
                K_zz_op = _psd_operator(K_zz)
            K_xx_diag = self.kernel.diag(X)
        return K_zz_op, K_xz, K_xx_diag

    def solver_strategy(self) -> AbstractSolverStrategy:
        """The ``solver``, ``preconditioner`` and ``logdet`` fields as one strategy.

        Returns:
            The `gaussx.compose_solver` composition; `gaussx.DenseSolver`
            when none of the three is set.

        Raises:
            ValueError: For a combination `gaussx.compose_solver` rejects,
                naming the three fields.
        """
        return compose_solver_fields(
            "SparseGPPrior", self.solver, self.preconditioner, self.logdet
        )

    def _resolved_solver(self) -> AbstractSolverStrategy:
        return self.solver_strategy()

    def log_prob(self, u: Float[Array, " M"]) -> Float[Array, ""]:
        r"""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).
        """
        m = jnp.zeros(self.num_inducing, dtype=u.dtype)
        return gaussian_log_prob(
            m, self.inducing_operator(), u, solver=self._resolved_solver()
        )

    def sample(self, key: Array) -> Float[Array, " M"]:
        r"""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).
        """
        n = self.num_inducing
        op = self.inducing_operator()
        loc = jnp.zeros(n, dtype=op.out_structure().dtype)
        mvn = MultivariateNormal(loc, op, solver=self._resolved_solver())
        return mvn.sample(key)

    def condition(self, guide: Guide) -> ConditionedSparseGP:
        r"""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.

        Args:
            guide: The fitted guide over the inducing values, any
                `pyrox_gp.Guide` with ``predict(K_xz, K_zz_op, K_xx_diag)``
                (`FullRankGuide`, `WhitenedGuide`, `NaturalGuide`, …).

        Returns:
            The `ConditionedSparseGP` holding this prior and the guide.

        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]]))
        """
        return ConditionedSparseGP(prior=self, guide=guide)

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.

Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
def mean(self, X: Float[Array, "N D"]) -> Float[Array, " N"]:
    """Evaluate the mean function at ``X``; zero by default."""
    if self.mean_fn is None:
        return jnp.zeros(X.shape[0], dtype=X.dtype)
    return self.mean_fn(X)

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
def inducing_operator(self) -> lx.AbstractLinearOperator:
    r"""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.
    """
    if self.inducing is not None:
        with call_context(self.kernel):
            return self.inducing.K_uu(self.kernel, jitter=self.jitter)
    assert self.Z is not None
    with call_context(self.kernel):
        K = self.kernel(self.Z, self.Z)
    K = K.at[jnp.diag_indices_from(K)].add(self.jitter)
    return _psd_operator(K)

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) or FourierInducingFeatures: 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
def cross_covariance(self, X: Array) -> Float[Array, "N M"]:
    r"""$K_{XZ}$ — covariance between ``X`` and the inducing inputs/features.

    The expected shape of ``X`` is inducing-family-dependent:

    - Point-inducing (``Z``) or `FourierInducingFeatures`:
      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.
    """
    if self.inducing is not None:
        with call_context(self.kernel):
            return self.inducing.k_ux(X, self.kernel)
    assert self.Z is not None
    with call_context(self.kernel):
        return self.kernel(X, self.Z)

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
def kernel_diag(self, X: Float[Array, "N D"]) -> Float[Array, " N"]:
    r"""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.
    """
    with call_context(self.kernel):
        return self.kernel.diag(X)

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
def predictive_blocks(
    self, X: Array
) -> tuple[
    lx.AbstractLinearOperator,
    Float[Array, "N M"],
    Float[Array, " N"],
]:
    r"""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).
    """
    with call_context(self.kernel):
        if self.inducing is not None:
            K_zz_op = self.inducing.K_uu(self.kernel, jitter=self.jitter)
            K_xz = self.inducing.k_ux(X, self.kernel)
        else:
            assert self.Z is not None
            K_zz_raw = self.kernel(self.Z, self.Z)
            K_xz = self.kernel(X, self.Z)
            K_zz = K_zz_raw.at[jnp.diag_indices_from(K_zz_raw)].add(self.jitter)
            K_zz_op = _psd_operator(K_zz)
        K_xx_diag = self.kernel.diag(X)
    return K_zz_op, K_xz, K_xx_diag

solver_strategy() -> AbstractSolverStrategy

The solver, preconditioner and logdet fields as one strategy.

Returns:

Type Description
AbstractSolverStrategy

The gaussx.compose_solver composition; gaussx.DenseSolver

AbstractSolverStrategy

when none of the three is set.

Raises:

Type Description
ValueError

For a combination gaussx.compose_solver rejects, naming the three fields.

Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
def solver_strategy(self) -> AbstractSolverStrategy:
    """The ``solver``, ``preconditioner`` and ``logdet`` fields as one strategy.

    Returns:
        The `gaussx.compose_solver` composition; `gaussx.DenseSolver`
        when none of the three is set.

    Raises:
        ValueError: For a combination `gaussx.compose_solver` rejects,
            naming the three fields.
    """
    return compose_solver_fields(
        "SparseGPPrior", self.solver, self.preconditioner, self.logdet
    )

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
def log_prob(self, u: Float[Array, " M"]) -> Float[Array, ""]:
    r"""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).
    """
    m = jnp.zeros(self.num_inducing, dtype=u.dtype)
    return gaussian_log_prob(
        m, self.inducing_operator(), u, solver=self._resolved_solver()
    )

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
def sample(self, key: Array) -> Float[Array, " M"]:
    r"""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).
    """
    n = self.num_inducing
    op = self.inducing_operator()
    loc = jnp.zeros(n, dtype=op.out_structure().dtype)
    mvn = MultivariateNormal(loc, op, solver=self._resolved_solver())
    return mvn.sample(key)

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 pyrox_gp.Guide with predict(K_xz, K_zz_op, K_xx_diag) (FullRankGuide, WhitenedGuide, NaturalGuide, …).

required

Returns:

Type Description
ConditionedSparseGP

The ConditionedSparseGP holding this prior and the guide.

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
def condition(self, guide: Guide) -> ConditionedSparseGP:
    r"""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.

    Args:
        guide: The fitted guide over the inducing values, any
            `pyrox_gp.Guide` with ``predict(K_xz, K_zz_op, K_xx_diag)``
            (`FullRankGuide`, `WhitenedGuide`, `NaturalGuide`, …).

    Returns:
        The `ConditionedSparseGP` holding this prior and the guide.

    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]]))
    """
    return ConditionedSparseGP(prior=self, guide=guide)

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

\[ \mu_* = K_{*Z} K_{ZZ}^{-1} m_q + \mu(X_*), \qquad \sigma_*^2 = k_{**} - K_{*Z} K_{ZZ}^{-1} K_{Z*} + K_{*Z} K_{ZZ}^{-1} S_q K_{ZZ}^{-1} K_{Z*}, \]

computed by the guide's own predict on SparseGPPrior.predictive_blocks.

Attributes:

Name Type Description
prior SparseGPPrior

The originating SparseGPPrior.

guide Guide

The fitted guide over the inducing values.

Source code in packages/pyrox-gp/src/pyrox_gp/_sparse.py
class ConditionedSparseGP(eqx.Module):
    r"""A sparse GP conditioned through a fitted guide on its inducing values.

    Returned by `SparseGPPrior.condition`. ``predict(X_star)`` is the SVGP
    predictive

    $$
    \mu_* = K_{*Z} K_{ZZ}^{-1} m_q + \mu(X_*), \qquad
    \sigma_*^2 = k_{**} - K_{*Z} K_{ZZ}^{-1} K_{Z*}
      + K_{*Z} K_{ZZ}^{-1} S_q K_{ZZ}^{-1} K_{Z*},
    $$

    computed by the guide's own ``predict`` on `SparseGPPrior.predictive_blocks`.

    Attributes:
        prior: The originating `SparseGPPrior`.
        guide: The fitted guide over the inducing values.
    """

    prior: SparseGPPrior
    guide: Guide

    def predict(
        self, X_star: Float[Array, "M D"]
    ) -> tuple[Float[Array, " M"], Float[Array, " M"]]:
        """Predictive ``(mean, variance)`` of ``f`` at ``X_star``.

        Args:
            X_star: Test inputs, shape ``(M, D)``.

        Returns:
            ``(mean, var)``, each ``(M,)``, mean function included.

        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,)
        """
        K_zz_op, K_xz, K_xx_diag = self.prior.predictive_blocks(X_star)
        mean, var = self.guide.predict(K_xz, K_zz_op, K_xx_diag)  # ty: ignore[unresolved-attribute]
        return mean + self.prior.mean(X_star), var

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 (M, D).

required

Returns:

Type Description
tuple[Float[Array, ' M'], Float[Array, ' M']]

(mean, var), each (M,), mean function included.

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
def predict(
    self, X_star: Float[Array, "M D"]
) -> tuple[Float[Array, " M"], Float[Array, " M"]]:
    """Predictive ``(mean, variance)`` of ``f`` at ``X_star``.

    Args:
        X_star: Test inputs, shape ``(M, D)``.

    Returns:
        ``(mean, var)``, each ``(M,)``, mean function included.

    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,)
    """
    K_zz_op, K_xz, K_xx_diag = self.prior.predictive_blocks(X_star)
    mean, var = self.guide.predict(K_xz, K_zz_op, K_xx_diag)  # ty: ignore[unresolved-attribute]
    return mean + self.prior.mean(X_star), var

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.

\[ q(u) = \mathcal{N}(m,\, L_S L_S^\top), \]

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 m of shape (M,).

scale_tril Float[Array, 'M M']

Lower-triangular Cholesky factor of the variational covariance, shape (M, M). The covariance is S = scale_tril @ scale_tril.T.

solver AbstractSolverStrategy | None

Optional gaussx.AbstractSolverStrategy. log_prob solves against \(S\) with it, and predict and kl_divergence solve against \(K_{ZZ}\) with it (pyrox#560); None keeps a Cholesky factor of \(K_{ZZ}\) in those two and gaussx.DenseSolver in log_prob. An iterative solver's tolerance enters the ELBO: a relative error \(\delta\) in \(K_{ZZ}^{-1} K_{ZX}\) moves each predictive variance by about \(\delta k_{nn}\).

Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
class FullRankGuide(Guide):
    r"""Full-rank Gaussian variational posterior over inducing values ``u``.

    $$
    q(u) = \mathcal{N}(m,\, L_S L_S^\top),
    $$

    parameterized by the mean ``mean`` of shape ``(M,)`` and the
    *lower-triangular* Cholesky factor ``scale_tril`` of shape ``(M, M)``.

    Attributes:
        mean: Variational mean ``m`` of shape ``(M,)``.
        scale_tril: Lower-triangular Cholesky factor of the variational
            covariance, shape ``(M, M)``. The covariance is
            ``S = scale_tril @ scale_tril.T``.
        solver: Optional `gaussx.AbstractSolverStrategy`. ``log_prob``
            solves against $S$ with it, and ``predict`` and
            ``kl_divergence`` solve against $K_{ZZ}$ with it (pyrox#560);
            ``None`` keeps a Cholesky factor of $K_{ZZ}$ in those two and
            `gaussx.DenseSolver` in ``log_prob``. An iterative solver's
            tolerance enters the ELBO: a relative error $\delta$ in
            $K_{ZZ}^{-1} K_{ZX}$ moves each predictive variance by about
            $\delta k_{nn}$.
    """

    mean: Float[Array, " M"]
    scale_tril: Float[Array, "M M"]
    solver: AbstractSolverStrategy | None = None

    @classmethod
    def init(
        cls,
        num_inducing: int,
        *,
        scale: float = 1.0,
        solver: AbstractSolverStrategy | None = None,
    ) -> FullRankGuide:
        """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.
        """
        m = jnp.zeros(num_inducing)
        L = scale * jnp.eye(num_inducing)
        return cls(mean=m, scale_tril=L, solver=solver)

    def sample(self, key: Array) -> Float[Array, " M"]:
        r"""Draw ``u = m + L_S \epsilon`` with ``\epsilon ~ N(0, I)``."""
        eps = jax.random.normal(key, self.mean.shape, dtype=self.mean.dtype)
        return self.mean + einx.dot("i j, j -> i", self.scale_tril, eps)

    def log_prob(self, u: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
        r"""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.
        """
        return gaussian_log_prob(
            self.mean,
            _full_cov_operator(self.scale_tril),
            u,
            solver=_resolve_solver(self.solver),
        )

    def kl_divergence(self, prior_cov: lx.AbstractLinearOperator) -> Float[Array, ""]:
        r"""``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``).
        """
        q_loc = self.mean
        q_cov = _full_cov_operator(self.scale_tril)
        p_loc = jnp.zeros_like(self.mean)
        return gaussian_kl(q_loc, q_cov, p_loc, prior_cov, solver=self.solver)

    def predict(
        self,
        K_xz: Float[Array, "N M"],
        K_zz_op: lx.AbstractLinearOperator,
        K_xx_diag: Float[Array, " N"],
    ) -> tuple[Float[Array, " N"], Float[Array, " N"]]:
        r"""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`).
        """
        if self.solver is not None:
            return _svgp_predict_with_solver(
                K_xz, K_zz_op, K_xx_diag, self.mean, self.scale_tril, self.solver
            )
        u_cov = einx.dot("i j, k j -> i k", self.scale_tril, self.scale_tril)
        return _svgp_predict_unwhitened(K_xz, K_zz_op, K_xx_diag, self.mean, u_cov)

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
@classmethod
def init(
    cls,
    num_inducing: int,
    *,
    scale: float = 1.0,
    solver: AbstractSolverStrategy | None = None,
) -> FullRankGuide:
    """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.
    """
    m = jnp.zeros(num_inducing)
    L = scale * jnp.eye(num_inducing)
    return cls(mean=m, scale_tril=L, solver=solver)

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
def sample(self, key: Array) -> Float[Array, " M"]:
    r"""Draw ``u = m + L_S \epsilon`` with ``\epsilon ~ N(0, I)``."""
    eps = jax.random.normal(key, self.mean.shape, dtype=self.mean.dtype)
    return self.mean + einx.dot("i j, j -> i", self.scale_tril, eps)

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
def log_prob(self, u: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
    r"""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.
    """
    return gaussian_log_prob(
        self.mean,
        _full_cov_operator(self.scale_tril),
        u,
        solver=_resolve_solver(self.solver),
    )

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
def kl_divergence(self, prior_cov: lx.AbstractLinearOperator) -> Float[Array, ""]:
    r"""``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``).
    """
    q_loc = self.mean
    q_cov = _full_cov_operator(self.scale_tril)
    p_loc = jnp.zeros_like(self.mean)
    return gaussian_kl(q_loc, q_cov, p_loc, prior_cov, solver=self.solver)

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
def predict(
    self,
    K_xz: Float[Array, "N M"],
    K_zz_op: lx.AbstractLinearOperator,
    K_xx_diag: Float[Array, " N"],
) -> tuple[Float[Array, " N"], Float[Array, " N"]]:
    r"""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`).
    """
    if self.solver is not None:
        return _svgp_predict_with_solver(
            K_xz, K_zz_op, K_xx_diag, self.mean, self.scale_tril, self.solver
        )
    u_cov = einx.dot("i j, k j -> i k", self.scale_tril, self.scale_tril)
    return _svgp_predict_unwhitened(K_xz, K_zz_op, K_xx_diag, self.mean, u_cov)

MeanFieldGuide

Bases: Guide

Diagonal Gaussian variational posterior over inducing values u.

\[ q(u) = \mathcal{N}(m,\, \mathrm{diag}(s^2)), \]

parameterized by the mean mean and the per-coordinate standard deviations scale.

Attributes:

Name Type Description
mean Float[Array, ' M']

Variational mean m of shape (M,).

scale Float[Array, ' M']

Per-coordinate standard deviations s of shape (M,). Must be strictly positive.

solver AbstractSolverStrategy | None

Optional gaussx.AbstractSolverStrategy, as in FullRankGuide. None by default.

Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
class MeanFieldGuide(Guide):
    r"""Diagonal Gaussian variational posterior over inducing values ``u``.

    $$
    q(u) = \mathcal{N}(m,\, \mathrm{diag}(s^2)),
    $$

    parameterized by the mean ``mean`` and the per-coordinate standard
    deviations ``scale``.

    Attributes:
        mean: Variational mean ``m`` of shape ``(M,)``.
        scale: Per-coordinate standard deviations ``s`` of shape ``(M,)``.
            Must be strictly positive.
        solver: Optional `gaussx.AbstractSolverStrategy`, as in
            `FullRankGuide`. ``None`` by default.
    """

    mean: Float[Array, " M"]
    scale: Float[Array, " M"]
    solver: AbstractSolverStrategy | None = None

    @classmethod
    def init(
        cls,
        num_inducing: int,
        *,
        scale: float = 1.0,
        solver: AbstractSolverStrategy | None = None,
    ) -> MeanFieldGuide:
        """Construct a guide initialized to ``N(0, scale^2 I)`` — see
        `FullRankGuide.init` for the dtype convention."""
        m = jnp.zeros(num_inducing)
        s = jnp.full(num_inducing, scale)
        return cls(mean=m, scale=s, solver=solver)

    def sample(self, key: Array) -> Float[Array, " M"]:
        r"""Draw ``u = m + s \odot \epsilon`` with ``\epsilon ~ N(0, I)``."""
        eps = jax.random.normal(key, self.mean.shape, dtype=self.mean.dtype)
        return self.mean + self.scale * eps

    def log_prob(self, u: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
        r"""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.
        """
        return gaussian_log_prob(
            self.mean,
            _diag_cov_operator(self.scale),
            u,
            solver=_resolve_solver(self.solver),
        )

    def kl_divergence(self, prior_cov: lx.AbstractLinearOperator) -> Float[Array, ""]:
        r"""``KL(q(u) || p(u))`` against an inducing prior with zero mean.

        Through ``solver`` against ``prior_cov``, as in
        `FullRankGuide.kl_divergence`.
        """
        q_loc = self.mean
        q_cov = _diag_cov_operator(self.scale)
        p_loc = jnp.zeros_like(self.mean)
        return gaussian_kl(q_loc, q_cov, p_loc, prior_cov, solver=self.solver)

    def predict(
        self,
        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`.
        """
        if self.solver is not None:
            return _svgp_predict_with_solver(
                K_xz, K_zz_op, K_xx_diag, self.mean, jnp.diag(self.scale), self.solver
            )
        u_cov = jnp.diag(self.scale**2)
        return _svgp_predict_unwhitened(K_xz, K_zz_op, K_xx_diag, self.mean, u_cov)

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
@classmethod
def init(
    cls,
    num_inducing: int,
    *,
    scale: float = 1.0,
    solver: AbstractSolverStrategy | None = None,
) -> MeanFieldGuide:
    """Construct a guide initialized to ``N(0, scale^2 I)`` — see
    `FullRankGuide.init` for the dtype convention."""
    m = jnp.zeros(num_inducing)
    s = jnp.full(num_inducing, scale)
    return cls(mean=m, scale=s, solver=solver)

sample(key: Array) -> Float[Array, ' M']

Draw u = m + s \odot \epsilon with \epsilon ~ N(0, I).

Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
def sample(self, key: Array) -> Float[Array, " M"]:
    r"""Draw ``u = m + s \odot \epsilon`` with ``\epsilon ~ N(0, I)``."""
    eps = jax.random.normal(key, self.mean.shape, dtype=self.mean.dtype)
    return self.mean + self.scale * eps

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
def log_prob(self, u: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
    r"""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.
    """
    return gaussian_log_prob(
        self.mean,
        _diag_cov_operator(self.scale),
        u,
        solver=_resolve_solver(self.solver),
    )

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
def kl_divergence(self, prior_cov: lx.AbstractLinearOperator) -> Float[Array, ""]:
    r"""``KL(q(u) || p(u))`` against an inducing prior with zero mean.

    Through ``solver`` against ``prior_cov``, as in
    `FullRankGuide.kl_divergence`.
    """
    q_loc = self.mean
    q_cov = _diag_cov_operator(self.scale)
    p_loc = jnp.zeros_like(self.mean)
    return gaussian_kl(q_loc, q_cov, p_loc, prior_cov, solver=self.solver)

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
def predict(
    self,
    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`.
    """
    if self.solver is not None:
        return _svgp_predict_with_solver(
            K_xz, K_zz_op, K_xx_diag, self.mean, jnp.diag(self.scale), self.solver
        )
    u_cov = jnp.diag(self.scale**2)
    return _svgp_predict_unwhitened(K_xz, K_zz_op, K_xx_diag, self.mean, u_cov)

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 m_v in whitened coordinates, shape (M,).

scale_tril Float[Array, 'M M']

Lower-triangular Cholesky factor of the whitened variational covariance, shape (M, M). The covariance in whitened space is L_v @ L_v.T.

solver AbstractSolverStrategy | None

Optional gaussx.AbstractSolverStrategy for log_prob, which solves against \(L_v L_v^\top\). It does not apply to predict or kl_divergence (pyrox#560): u = L_{ZZ} v needs the Cholesky factor of \(K_{ZZ}\), which no other solver gives, and the KL against \(\mathcal{N}(0, I)\) has no \(K_{ZZ}\). None by default.

Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
class WhitenedGuide(Guide):
    r"""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:
        mean: Variational mean ``m_v`` in whitened coordinates,
            shape ``(M,)``.
        scale_tril: Lower-triangular Cholesky factor of the whitened
            variational covariance, shape ``(M, M)``. The covariance in
            whitened space is ``L_v @ L_v.T``.
        solver: Optional `gaussx.AbstractSolverStrategy` for ``log_prob``,
            which solves against $L_v L_v^\top$. It does not apply to
            ``predict`` or ``kl_divergence`` (pyrox#560): ``u = L_{ZZ} v``
            needs the Cholesky factor of $K_{ZZ}$, which no other solver
            gives, and the KL against $\mathcal{N}(0, I)$ has no $K_{ZZ}$.
            ``None`` by default.
    """

    mean: Float[Array, " M"]
    scale_tril: Float[Array, "M M"]
    solver: AbstractSolverStrategy | None = None

    @classmethod
    def init(
        cls,
        num_inducing: int,
        *,
        scale: float = 1.0,
        solver: AbstractSolverStrategy | None = None,
    ) -> WhitenedGuide:
        """Construct a guide initialized to ``N(0, scale^2 I)`` in whitened
        space — see `FullRankGuide.init` for the dtype convention."""
        m = jnp.zeros(num_inducing)
        L = scale * jnp.eye(num_inducing)
        return cls(mean=m, scale_tril=L, solver=solver)

    def sample(self, key: Array) -> Float[Array, " M"]:
        """Draw a single whitened sample ``v = m_v + L_v \\epsilon``."""
        eps = jax.random.normal(key, self.mean.shape, dtype=self.mean.dtype)
        return self.mean + einx.dot("i j, j -> i", self.scale_tril, eps)

    def log_prob(self, v: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
        r"""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).
        """
        return gaussian_log_prob(
            self.mean,
            _full_cov_operator(self.scale_tril),
            v,
            solver=_resolve_solver(self.solver),
        )

    def kl_divergence(
        self,
        prior_cov: lx.AbstractLinearOperator | None = None,
    ) -> Float[Array, ""]:
        r"""``KL(q(v) || N(0, I))`` — kernel-free closed form.

        Computes

        $$
        \mathrm{KL}(\mathcal{N}(m_v, L_v L_v^\top) \,\|\,
                   \mathcal{N}(0, I))
        = \tfrac{1}{2} \bigl(
            \|m_v\|^2 + \|L_v\|_F^2 - M
            - 2 \sum_i \log |[L_v]_{ii}|
        \bigr).
        $$

        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}``.
        """
        del prior_cov
        m = self.mean
        L = self.scale_tril
        n = m.shape[0]
        quad = jnp.sum(m**2)
        trace = jnp.sum(L**2)  # ||L||_F^2
        log_det = 2.0 * jnp.sum(jnp.log(jnp.abs(jnp.diag(L))))
        return 0.5 * (quad + trace - n - log_det)

    def predict(
        self,
        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.
        """
        return whitened_svgp_predict(
            K_zz_op, K_xz, self.mean, self.scale_tril, K_xx_diag
        )

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
@classmethod
def init(
    cls,
    num_inducing: int,
    *,
    scale: float = 1.0,
    solver: AbstractSolverStrategy | None = None,
) -> WhitenedGuide:
    """Construct a guide initialized to ``N(0, scale^2 I)`` in whitened
    space — see `FullRankGuide.init` for the dtype convention."""
    m = jnp.zeros(num_inducing)
    L = scale * jnp.eye(num_inducing)
    return cls(mean=m, scale_tril=L, solver=solver)

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
def sample(self, key: Array) -> Float[Array, " M"]:
    """Draw a single whitened sample ``v = m_v + L_v \\epsilon``."""
    eps = jax.random.normal(key, self.mean.shape, dtype=self.mean.dtype)
    return self.mean + einx.dot("i j, j -> i", self.scale_tril, eps)

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
def log_prob(self, v: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
    r"""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).
    """
    return gaussian_log_prob(
        self.mean,
        _full_cov_operator(self.scale_tril),
        v,
        solver=_resolve_solver(self.solver),
    )

kl_divergence(prior_cov: lx.AbstractLinearOperator | None = None) -> Float[Array, '']

KL(q(v) || N(0, I)) — kernel-free closed form.

Computes

\[ \mathrm{KL}(\mathcal{N}(m_v, L_v L_v^\top) \,\|\, \mathcal{N}(0, I)) = \tfrac{1}{2} \bigl( \|m_v\|^2 + \|L_v\|_F^2 - M - 2 \sum_i \log |[L_v]_{ii}| \bigr). \]

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
def kl_divergence(
    self,
    prior_cov: lx.AbstractLinearOperator | None = None,
) -> Float[Array, ""]:
    r"""``KL(q(v) || N(0, I))`` — kernel-free closed form.

    Computes

    $$
    \mathrm{KL}(\mathcal{N}(m_v, L_v L_v^\top) \,\|\,
               \mathcal{N}(0, I))
    = \tfrac{1}{2} \bigl(
        \|m_v\|^2 + \|L_v\|_F^2 - M
        - 2 \sum_i \log |[L_v]_{ii}|
    \bigr).
    $$

    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}``.
    """
    del prior_cov
    m = self.mean
    L = self.scale_tril
    n = m.shape[0]
    quad = jnp.sum(m**2)
    trace = jnp.sum(L**2)  # ||L||_F^2
    log_det = 2.0 * jnp.sum(jnp.log(jnp.abs(jnp.diag(L))))
    return 0.5 * (quad + trace - n - log_det)

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
def predict(
    self,
    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.
    """
    return whitened_svgp_predict(
        K_zz_op, K_xz, self.mean, self.scale_tril, K_xx_diag
    )

NaturalGuide

Bases: Guide

Natural-parameter Gaussian variational posterior over inducing values.

Parameterizes \(q(u) = \mathcal{N}(m, S)\) in natural form with parameters

\[ \eta_1 = S^{-1} m, \qquad \eta_2 = -\tfrac{1}{2} S^{-1}. \]

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 eta_1 of shape (M,).

nat2 Float[Array, 'M M']

Second natural parameter eta_2 of shape (M, M), symmetric negative-definite.

solver AbstractSolverStrategy | None

Optional gaussx.AbstractSolverStrategy used for solve and logdet against the precision operator Lambda = -2 nat2. sample and log_prob route through pyrox_gauss.MultivariateNormalPrecision with this solver — efficient because the precision form avoids ever materializing \(\Sigma\). None defaults to gaussx.DenseSolver.

Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
class NaturalGuide(Guide):
    r"""Natural-parameter Gaussian variational posterior over inducing values.

    Parameterizes $q(u) = \mathcal{N}(m, S)$ in *natural form*
    with parameters

    $$
    \eta_1 = S^{-1} m, \qquad
    \eta_2 = -\tfrac{1}{2} S^{-1}.
    $$

    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:
        nat1: First natural parameter ``eta_1`` of shape ``(M,)``.
        nat2: Second natural parameter ``eta_2`` of shape ``(M, M)``,
            symmetric negative-definite.
        solver: Optional `gaussx.AbstractSolverStrategy` used for
            ``solve`` and ``logdet`` against the precision operator
            ``Lambda = -2 nat2``. ``sample`` and ``log_prob`` route
            through `pyrox_gauss.MultivariateNormalPrecision` with
            this solver — efficient because the precision form avoids
            ever materializing $\Sigma$. ``None`` defaults to
            `gaussx.DenseSolver`.
    """

    nat1: Float[Array, " M"]
    nat2: Float[Array, "M M"]
    solver: AbstractSolverStrategy | None = None

    @classmethod
    def init(
        cls,
        num_inducing: int,
        *,
        scale: float = 1.0,
        solver: AbstractSolverStrategy | None = None,
    ) -> NaturalGuide:
        """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.
        """
        n = num_inducing
        nat1 = jnp.zeros(n)
        nat2 = (-0.5 / (scale**2)) * jnp.eye(n)
        return cls(nat1=nat1, nat2=nat2, solver=solver)

    def _precision_operator(self) -> lx.AbstractLinearOperator:
        """Build the precision operator ``Lambda = -2 nat2`` (PSD)."""
        return _possemi_cov_operator(-2.0 * self.nat2)

    def _moment_mean(self) -> Float[Array, " M"]:
        """Moment-form mean via one structured solve — no covariance build.

        `gaussx.natural_to_mean_cov` returns the covariance as a
        *lazy* inverse operator, so discarding it here is free.
        """
        nat2_op = _negsemi_cov_operator(self.nat2)
        m, _ = natural_to_mean_cov(
            self.nat1, nat2_op, solver=_resolve_solver(self.solver)
        )
        return m

    def _moments(self) -> tuple[Float[Array, " M"], Float[Array, "M M"]]:
        """Return ``(mean, cov_array)`` via `gaussx.natural_to_mean_cov`."""
        nat2_op = _negsemi_cov_operator(self.nat2)
        m, cov_op = natural_to_mean_cov(
            self.nat1, nat2_op, solver=_resolve_solver(self.solver)
        )
        return m, symmetrize(cov_op.as_matrix())

    def _mvn(self) -> MultivariateNormalPrecision:
        """Wrap the natural form as a `pyrox_gauss.MultivariateNormalPrecision`.

        Carries the precision operator directly, so ``sample`` /
        ``log_prob`` never materialize the covariance.
        """
        return MultivariateNormalPrecision(
            loc=self._moment_mean(),
            prec_operator=self._precision_operator(),
            solver=_resolve_solver(self.solver),
        )

    @property
    def covariance(self) -> Float[Array, "M M"]:
        """Recover the moment-form covariance ``S = (-2 nat2)^{-1}``."""
        return self._moments()[1]

    @property
    def mean(self) -> Float[Array, " M"]:
        """Recover the moment-form mean ``m = S nat1``."""
        return self._moment_mean()

    def sample(self, key: Array) -> Float[Array, " M"]:
        r"""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.
        """
        return self._mvn().sample(key)

    def log_prob(self, u: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
        r"""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``.
        """
        return self._mvn().log_prob(u)

    def kl_divergence(self, prior_cov: lx.AbstractLinearOperator) -> Float[Array, ""]:
        r"""``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}$.
        """
        m, cov = self._moments()
        p_loc = jnp.zeros_like(m)
        return gaussian_kl(m, _possemi_cov_operator(cov), p_loc, prior_cov)

    def predict(
        self,
        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``."""
        m, cov = self._moments()
        return _svgp_predict_unwhitened(K_xz, K_zz_op, K_xx_diag, m, cov)

    def natural_update(
        self,
        nat1_hat: Float[Array, " M"],
        nat2_hat: Float[Array, "M M"],
        rho: float | Float[Array, ""] = 1.0,
    ) -> NaturalGuide:
        r"""Damped natural-parameter update via `gaussx.damped_natural_update`.

        Returns a new `NaturalGuide` whose natural parameters are
        the convex combination

        $$
        \eta_i \leftarrow (1 - \rho)\,\eta_i + \rho\,\hat{\eta}_i,
        \quad i \in \{1, 2\}.
        $$

        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.
        """
        new_nat1, new_nat2 = damped_natural_update(
            self.nat1,
            self.nat2,
            nat1_hat,
            nat2_hat,
            lr=rho,
        )
        # gaussx returns Array | AbstractLinearOperator; we always pass Arrays
        # in, so the runtime type is Array.
        assert not isinstance(new_nat2, lx.AbstractLinearOperator)
        return NaturalGuide(nat1=new_nat1, nat2=new_nat2)

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
@classmethod
def init(
    cls,
    num_inducing: int,
    *,
    scale: float = 1.0,
    solver: AbstractSolverStrategy | None = None,
) -> NaturalGuide:
    """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.
    """
    n = num_inducing
    nat1 = jnp.zeros(n)
    nat2 = (-0.5 / (scale**2)) * jnp.eye(n)
    return cls(nat1=nat1, nat2=nat2, solver=solver)

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
def sample(self, key: Array) -> Float[Array, " M"]:
    r"""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.
    """
    return self._mvn().sample(key)

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
def log_prob(self, u: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
    r"""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``.
    """
    return self._mvn().log_prob(u)

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
def kl_divergence(self, prior_cov: lx.AbstractLinearOperator) -> Float[Array, ""]:
    r"""``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}$.
    """
    m, cov = self._moments()
    p_loc = jnp.zeros_like(m)
    return gaussian_kl(m, _possemi_cov_operator(cov), p_loc, prior_cov)

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
def predict(
    self,
    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``."""
    m, cov = self._moments()
    return _svgp_predict_unwhitened(K_xz, K_zz_op, K_xx_diag, m, cov)

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

\[ \eta_i \leftarrow (1 - \rho)\,\eta_i + \rho\,\hat{\eta}_i, \quad i \in \{1, 2\}. \]

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
def natural_update(
    self,
    nat1_hat: Float[Array, " M"],
    nat2_hat: Float[Array, "M M"],
    rho: float | Float[Array, ""] = 1.0,
) -> NaturalGuide:
    r"""Damped natural-parameter update via `gaussx.damped_natural_update`.

    Returns a new `NaturalGuide` whose natural parameters are
    the convex combination

    $$
    \eta_i \leftarrow (1 - \rho)\,\eta_i + \rho\,\hat{\eta}_i,
    \quad i \in \{1, 2\}.
    $$

    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.
    """
    new_nat1, new_nat2 = damped_natural_update(
        self.nat1,
        self.nat2,
        nat1_hat,
        nat2_hat,
        lr=rho,
    )
    # gaussx returns Array | AbstractLinearOperator; we always pass Arrays
    # in, so the runtime type is Array.
    assert not isinstance(new_nat2, lx.AbstractLinearOperator)
    return NaturalGuide(nat1=new_nat1, nat2=new_nat2)

DeltaGuide

Bases: Guide

Point-mass (MAP-style) variational posterior over inducing values.

\[ q(u) = \delta(u - \text{loc}), \]

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 (M,). This is also the MAP estimate of the inducing values when used inside a maximization loop.

solver AbstractSolverStrategy | None

Optional gaussx.AbstractSolverStrategy passed to gaussx.gaussian_log_prob when computing -log p(loc) against the prior covariance in kl_divergence (None is gaussx.DenseSolver there), and the solver of predict against \(K_{ZZ}\) (pyrox#560; None keeps its Cholesky factor).

Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
class DeltaGuide(Guide):
    r"""Point-mass (MAP-style) variational posterior over inducing values.

    $$
    q(u) = \delta(u - \text{loc}),
    $$

    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:
        loc: The point at which the variational mass concentrates,
            shape ``(M,)``. This is also the MAP estimate of the
            inducing values when used inside a maximization loop.
        solver: Optional `gaussx.AbstractSolverStrategy` passed
            to `gaussx.gaussian_log_prob` when computing
            ``-log p(loc)`` against the prior covariance in
            `kl_divergence` (``None`` is `gaussx.DenseSolver` there), and
            the solver of ``predict`` against $K_{ZZ}$ (pyrox#560; ``None``
            keeps its Cholesky factor).
    """

    loc: Float[Array, " M"]
    solver: AbstractSolverStrategy | None = None

    @classmethod
    def init(
        cls,
        num_inducing: int,
        *,
        solver: AbstractSolverStrategy | None = None,
    ) -> DeltaGuide:
        """Construct a guide initialized to ``loc = 0`` — see
        `FullRankGuide.init` for the dtype convention."""
        return cls(loc=jnp.zeros(num_inducing), solver=solver)

    def sample(self, key: Array) -> Float[Array, " M"]:
        """Return ``self.loc`` — the variational draw is deterministic."""
        del key
        return self.loc

    def log_prob(self, u: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
        r"""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`.
        """
        del u
        return jnp.zeros((), dtype=self.loc.dtype)

    def kl_divergence(self, prior_cov: lx.AbstractLinearOperator) -> Float[Array, ""]:
        r"""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``,

        $$
        -\log p(\text{loc}) =
            \tfrac{1}{2} \text{loc}^\top K^{-1} \text{loc}
            + \tfrac{1}{2} \log |K|
            + \tfrac{M}{2} \log(2\pi),
        $$

        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.
        """
        loc = self.loc
        return -gaussian_log_prob(
            jnp.zeros_like(loc), prior_cov, loc, solver=_resolve_solver(self.solver)
        )

    def predict(
        self,
        K_xz: Float[Array, "N M"],
        K_zz_op: lx.AbstractLinearOperator,
        K_xx_diag: Float[Array, " N"],
    ) -> tuple[Float[Array, " N"], Float[Array, " N"]]:
        r"""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`).
        """
        if self.solver is not None:
            return _svgp_predict_with_solver(
                K_xz, K_zz_op, K_xx_diag, self.loc, None, self.solver
            )
        m_size = self.loc.shape[0]
        L_zz = cholesky(K_zz_op)
        u_mean_white = lx.linear_solve(L_zz, self.loc).value
        zero_chol = jnp.zeros((m_size, m_size), dtype=self.loc.dtype)
        return whitened_svgp_predict(K_zz_op, K_xz, u_mean_white, zero_chol, K_xx_diag)

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
@classmethod
def init(
    cls,
    num_inducing: int,
    *,
    solver: AbstractSolverStrategy | None = None,
) -> DeltaGuide:
    """Construct a guide initialized to ``loc = 0`` — see
    `FullRankGuide.init` for the dtype convention."""
    return cls(loc=jnp.zeros(num_inducing), solver=solver)

sample(key: Array) -> Float[Array, ' M']

Return self.loc — the variational draw is deterministic.

Source code in packages/pyrox-gp/src/pyrox_gp/_guides.py
def sample(self, key: Array) -> Float[Array, " M"]:
    """Return ``self.loc`` — the variational draw is deterministic."""
    del key
    return self.loc

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
def log_prob(self, u: Float[Array, " ..."]) -> Float[Array, ""]:  # ty: ignore[invalid-method-override]
    r"""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`.
    """
    del u
    return jnp.zeros((), dtype=self.loc.dtype)

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,

\[ -\log p(\text{loc}) = \tfrac{1}{2} \text{loc}^\top K^{-1} \text{loc} + \tfrac{1}{2} \log |K| + \tfrac{M}{2} \log(2\pi), \]

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
def kl_divergence(self, prior_cov: lx.AbstractLinearOperator) -> Float[Array, ""]:
    r"""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``,

    $$
    -\log p(\text{loc}) =
        \tfrac{1}{2} \text{loc}^\top K^{-1} \text{loc}
        + \tfrac{1}{2} \log |K|
        + \tfrac{M}{2} \log(2\pi),
    $$

    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.
    """
    loc = self.loc
    return -gaussian_log_prob(
        jnp.zeros_like(loc), prior_cov, loc, solver=_resolve_solver(self.solver)
    )

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
def predict(
    self,
    K_xz: Float[Array, "N M"],
    K_zz_op: lx.AbstractLinearOperator,
    K_xx_diag: Float[Array, " N"],
) -> tuple[Float[Array, " N"], Float[Array, " N"]]:
    r"""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`).
    """
    if self.solver is not None:
        return _svgp_predict_with_solver(
            K_xz, K_zz_op, K_xx_diag, self.loc, None, self.solver
        )
    m_size = self.loc.shape[0]
    L_zz = cholesky(K_zz_op)
    u_mean_white = lx.linear_solve(L_zz, self.loc).value
    zero_chol = jnp.zeros((m_size, m_size), dtype=self.loc.dtype)
    return whitened_svgp_predict(K_zz_op, K_xz, u_mean_white, zero_chol, K_xx_diag)

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
class GaussianLikelihood(_GPObservation, _CoreGaussianLikelihood):
    r"""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:
        noise_var: 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...
    """

    name: str = eqx.field(static=True, default="gaussian", repr=False, kw_only=True)

    def build(
        self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
    ) -> gx.GaussianLikelihood:
        """`gaussx.GaussianLikelihood` holding ``y`` at ``noise_var``."""
        return gx.GaussianLikelihood(y, self.noise_var)  # ty: ignore[invalid-argument-type]

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
def build(
    self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
) -> gx.GaussianLikelihood:
    """`gaussx.GaussianLikelihood` holding ``y`` at ``noise_var``."""
    return gx.GaussianLikelihood(y, self.noise_var)  # ty: ignore[invalid-argument-type]

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
class HeteroscedasticGaussianLikelihood(_GPObservation):
    r"""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
    """

    latent_dim: int = eqx.field(static=True, default=2)
    name: str = eqx.field(
        static=True, default="heteroscedastic_gaussian", repr=False, kw_only=True
    )

    def _gaussx_latents(self, f: Float[Array, "N 2"]) -> Float[Array, " 2N"]:
        # σₙ = exp(fₙ⁽¹⁾) = softplus(gₙ), so gₙ = softplus⁻¹(exp(fₙ⁽¹⁾))
        noise_latent = SoftplusTransform().inv(jnp.exp(f[:, 1]))
        # (f⁽⁰⁾, g), the two columns concatenated
        return jnp.concatenate([f[:, 0], noise_latent])

    def build(
        self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
    ) -> gx.HeteroscedasticGaussianLikelihood:
        """`gaussx.HeteroscedasticGaussianLikelihood` holding ``y``."""
        return gx.HeteroscedasticGaussianLikelihood(y)

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
def build(
    self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
) -> gx.HeteroscedasticGaussianLikelihood:
    """`gaussx.HeteroscedasticGaussianLikelihood` holding ``y``."""
    return gx.HeteroscedasticGaussianLikelihood(y)

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
class BernoulliLikelihood(_GPObservation):
    r"""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
    """

    name: str = eqx.field(static=True, default="bernoulli", repr=False, kw_only=True)

    def build(
        self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
    ) -> gx.BernoulliLikelihood:
        """`gaussx.BernoulliLikelihood` holding ``y``."""
        return gx.BernoulliLikelihood(y)

build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> gx.BernoulliLikelihood

gaussx.BernoulliLikelihood holding y.

Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
def build(
    self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
) -> gx.BernoulliLikelihood:
    """`gaussx.BernoulliLikelihood` holding ``y``."""
    return gx.BernoulliLikelihood(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
class PoissonLikelihood(_GPObservation):
    r"""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
    """

    name: str = eqx.field(static=True, default="poisson", repr=False, kw_only=True)

    def build(
        self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
    ) -> gx.PoissonLikelihood:
        """`gaussx.PoissonLikelihood` holding ``y``."""
        return gx.PoissonLikelihood(y)

build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> gx.PoissonLikelihood

gaussx.PoissonLikelihood holding y.

Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
def build(
    self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
) -> gx.PoissonLikelihood:
    """`gaussx.PoissonLikelihood` holding ``y``."""
    return gx.PoissonLikelihood(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
class SoftmaxLikelihood(_GPObservation):
    r"""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:
        num_classes: 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
    """

    num_classes: int = eqx.field(static=True)
    name: str = eqx.field(static=True, default="softmax", repr=False, kw_only=True)

    def __init__(self, num_classes: int) -> None:
        if num_classes < 2:
            msg = f"num_classes must be >= 2, got {num_classes}"
            raise ValueError(msg)
        self.num_classes = num_classes

    @property
    def latent_dim(self) -> int:
        """Latents per site, ``num_classes``."""
        return self.num_classes

    def _gaussx_latents(self, f: Float[Array, "N C"]) -> Float[Array, " NC"]:
        # (N, C) → (N C), site by site
        return jnp.reshape(f, (-1,))

    def build(
        self,
        y: Int[Array, " N"],
        theta: dict[str, Array],
        data: Mapping[str, ArrayLike],
    ) -> gx.SoftmaxLikelihood:
        """`gaussx.SoftmaxLikelihood` holding ``y`` over ``num_classes`` classes."""
        return gx.SoftmaxLikelihood(y, self.num_classes)

latent_dim: int property

Latents per site, num_classes.

build(y: Int[Array, ' N'], theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> gx.SoftmaxLikelihood

gaussx.SoftmaxLikelihood holding y over num_classes classes.

Source code in packages/pyrox-gp/src/pyrox_gp/_likelihoods.py
def build(
    self,
    y: Int[Array, " N"],
    theta: dict[str, Array],
    data: Mapping[str, ArrayLike],
) -> gx.SoftmaxLikelihood:
    """`gaussx.SoftmaxLikelihood` holding ``y`` over ``num_classes`` classes."""
    return gx.SoftmaxLikelihood(y, self.num_classes)

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. df -> infinity recovers the Gaussian.

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
class StudentTLikelihood(_GPObservation):
    r"""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:
        df: Degrees of freedom $\nu > 0$. Smaller values give
            heavier tails. ``df -> infinity`` recovers the Gaussian.
        scale: 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
    """

    df: float | Float[Array, ""]
    scale: float | Float[Array, ""]
    name: str = eqx.field(static=True, default="student_t", repr=False, kw_only=True)

    def build(
        self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
    ) -> gx.StudentTLikelihood:
        """`gaussx.StudentTLikelihood` holding ``y`` at ``df`` and ``scale``."""
        return gx.StudentTLikelihood(y, self.df, self.scale)  # ty: ignore[invalid-argument-type]

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
def build(
    self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
) -> gx.StudentTLikelihood:
    """`gaussx.StudentTLikelihood` holding ``y`` at ``df`` and ``scale``."""
    return gx.StudentTLikelihood(y, self.df, self.scale)  # ty: ignore[invalid-argument-type]

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

\[ \ell(\eta_i, d_i) = \log p(y_i \mid \eta_i, \theta, \mathrm{data}_i), \qquad \log p(y \mid \eta) = \sum_i \ell(\eta_i, d_i), \]

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]

(eta_i, theta, data_i) -> numpyro.distributions.Distribution, site \(i\)'s distribution of \(y_i\).

theta dict[str, Array]

Hyperparameter values make_dist reads, as arrays.

name str

Prefix of the hyperparameter names ("dist").

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
class DistLikelihood(AbstractObservation, Likelihood):
    r"""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

    $$
    \ell(\eta_i, d_i) = \log p(y_i \mid \eta_i, \theta, \mathrm{data}_i),
    \qquad
    \log p(y \mid \eta) = \sum_i \ell(\eta_i, d_i),
    $$

    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.

    !!! warning "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:
        make_dist: ``(eta_i, theta, data_i) -> numpyro.distributions.Distribution``,
            site $i$'s distribution of $y_i$.
        theta: Hyperparameter values ``make_dist`` reads, as arrays.
        name: Prefix of the hyperparameter names (``"dist"``).

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

    # (eta_i, theta, data_i) -> Distribution
    make_dist: Callable[..., nd.Distribution] = eqx.field(static=True)
    theta: dict[str, Array]
    name: str = eqx.field(static=True)

    def __init__(
        self,
        make_dist: Callable[..., nd.Distribution] | None = None,
        theta: Mapping[str, ArrayLike] | None = None,
        *,
        name: str = "dist",
        dist_fn: Callable[[Array], nd.Distribution] | None = None,
    ) -> None:
        if dist_fn is not None:
            if make_dist is not None:
                msg = "pass make_dist or the deprecated dist_fn, not both"
                raise TypeError(msg)
            warnings.warn(
                "DistLikelihood(dist_fn=...) is deprecated; pass the callable "
                "as make_dist: DistLikelihood(make_dist=...) or positionally.",
                DeprecationWarning,
                stacklevel=2,
                # equinox's metaclass calls __init__; point at the caller
                skip_file_prefixes=(str(Path(eqx.__file__).parent),),
            )
            # dist_fn was always the one-argument link f -> Distribution
            make_dist = _LatentOnly(dist_fn)
        if make_dist is None:
            msg = "DistLikelihood needs make_dist(eta_i, theta, data_i)"
            raise TypeError(msg)
        if not isinstance(make_dist, _LatentOnly) and _takes_latent_only(make_dist):
            make_dist = _LatentOnly(make_dist)
        self.make_dist = make_dist
        self.theta = {key: jnp.asarray(value) for key, value in (theta or {}).items()}
        self.name = name

    @property
    def dist_fn(self) -> Callable[[Array], nd.Distribution]:
        """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``.
        """
        warnings.warn(
            "DistLikelihood.dist_fn is deprecated; use make_dist(eta_i, theta, "
            "data_i), or keep the one-argument callable you passed in.",
            DeprecationWarning,
            stacklevel=2,
        )
        if isinstance(self.make_dist, _LatentOnly):
            return self.make_dist.dist_fn
        make_dist, theta = self.make_dist, self.theta
        return lambda f: make_dist(f, theta, {})

    def _theta(self, theta: Mapping[str, Array]) -> dict[str, Array]:
        """The ``theta`` field, updated by the caller's ``theta``."""
        return {**self.theta, **theta}

    def build(
        self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
    ) -> tuple[Callable[[Float[Array, ""], PyTree], Float[Array, ""]], PyTree]:
        r"""The per-site log density and data that `gaussx.CallableLikelihood` takes.

        Args:
            y: Observations, ``(N,)``.
            theta: Hyperparameters, overriding the ``theta`` field key by key.
            data: Per-site data other than ``y``, every leaf with a leading
                site axis of length ``N``.

        Returns:
            ``(log_density, site_data)``: ``log_density(eta_i, d_i)`` is
            $\log p(y_i \mid \eta_i, \theta, \mathrm{data}_i)$ for a scalar
            ``eta_i`` and one site's slice ``d_i`` of
            ``site_data = {"y": y, "data": data}``.
        """
        log_density = _DistSiteLogDensity(self.make_dist, self._theta(theta))
        site_data = {
            "y": jnp.asarray(y),
            "data": {key: jnp.asarray(value) for key, value in data.items()},
        }
        return log_density, site_data

    def site_distribution(
        self,
        eta: Float[Array, " N"],
        theta: dict[str, Array],
        data: Mapping[str, ArrayLike],
    ) -> nd.Distribution:
        """``make_dist`` on every site at once (batched in eta)."""
        return self.make_dist(eta, self._theta(theta), data)

    def log_prob(
        self,
        f: Float[Array, " ..."],
        y: Float[Array, " ..."],
        X: Float[Array, " ..."] | None = None,
    ) -> Float[Array, ""]:
        r"""$\sum_i \log p(y_i \mid f_i)$, with the inputs in ``data["X"]``."""
        data = {} if X is None else {"X": X}
        return self.site_log_prob(y, f, {}, data).sum()

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, (N,).

required
theta dict[str, Array]

Hyperparameters, overriding the theta field key by key.

required
data Mapping[str, ArrayLike]

Per-site data other than y, every leaf with a leading site axis of length N.

required

Returns:

Type Description
Callable[[Float[Array, ''], PyTree], Float[Array, '']]

(log_density, site_data): log_density(eta_i, d_i) is

PyTree

\(\log p(y_i \mid \eta_i, \theta, \mathrm{data}_i)\) for a scalar

tuple[Callable[[Float[Array, ''], PyTree], Float[Array, '']], PyTree]

eta_i and one site's slice d_i of

tuple[Callable[[Float[Array, ''], PyTree], Float[Array, '']], PyTree]

site_data = {"y": y, "data": data}.

Source code in packages/pyrox/src/pyrox/likelihoods.py
def build(
    self, y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]
) -> tuple[Callable[[Float[Array, ""], PyTree], Float[Array, ""]], PyTree]:
    r"""The per-site log density and data that `gaussx.CallableLikelihood` takes.

    Args:
        y: Observations, ``(N,)``.
        theta: Hyperparameters, overriding the ``theta`` field key by key.
        data: Per-site data other than ``y``, every leaf with a leading
            site axis of length ``N``.

    Returns:
        ``(log_density, site_data)``: ``log_density(eta_i, d_i)`` is
        $\log p(y_i \mid \eta_i, \theta, \mathrm{data}_i)$ for a scalar
        ``eta_i`` and one site's slice ``d_i`` of
        ``site_data = {"y": y, "data": data}``.
    """
    log_density = _DistSiteLogDensity(self.make_dist, self._theta(theta))
    site_data = {
        "y": jnp.asarray(y),
        "data": {key: jnp.asarray(value) for key, value in data.items()},
    }
    return log_density, site_data

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
def site_distribution(
    self,
    eta: Float[Array, " N"],
    theta: dict[str, Array],
    data: Mapping[str, ArrayLike],
) -> nd.Distribution:
    """``make_dist`` on every site at once (batched in eta)."""
    return self.make_dist(eta, self._theta(theta), data)

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
def log_prob(
    self,
    f: Float[Array, " ..."],
    y: Float[Array, " ..."],
    X: Float[Array, " ..."] | None = None,
) -> Float[Array, ""]:
    r"""$\sum_i \log p(y_i \mid f_i)$, with the inputs in ``data["X"]``."""
    data = {} if X is None else {"X": X}
    return self.site_log_prob(y, f, {}, data).sum()

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 flowjax.bijections.AbstractBijection with event shape () or (1,).

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
class WarpedGaussianLikelihood(Likelihood):
    r"""$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`][pyrox_gp.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`][pyrox_gp.svgp_elbo] requires an integrator.

    !!! warning "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:
        warp: Any ``flowjax.bijections.AbstractBijection`` with event shape
            ``()`` or ``(1,)``.
        noise_var: 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
    """

    warp: AbstractBijection
    noise_var: Float[Array, ""]

    def log_prob(
        self,
        f: Float[Array, " ..."],
        y: Float[Array, " ..."],
        X: Float[Array, " ..."] | None = None,
    ) -> Float[Array, ""]:
        r"""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.
        """
        g = _apply_warp(self.warp, f, X)
        return nd.Normal(g, jnp.sqrt(self.noise_var)).log_prob(y).sum()

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
def log_prob(
    self,
    f: Float[Array, " ..."],
    y: Float[Array, " ..."],
    X: Float[Array, " ..."] | None = None,
) -> Float[Array, ""]:
    r"""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.
    """
    g = _apply_warp(self.warp, f, X)
    return nd.Normal(g, jnp.sqrt(self.noise_var)).log_prob(y).sum()

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.

\[ m_1 = \mathbb{E}_{q(f)}[G(f)], \qquad m_2 = \sigma^2 + \mathbb{E}_{q(f)}[(G(f) - m_1)^2] \]

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 (N,).

required
f_var Float[Array, ' N']

Posterior marginal variances of the base GP, shape (N,).

required
X Float[Array, 'N D'] | None

Inputs of shape (N, D); required when the warp is conditional, ignored otherwise. Broadcast over the quadrature nodes.

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 NaN by order 512).

32

Returns:

Type Description
tuple[Float[Array, ' N'], Float[Array, ' N']]

Tuple of (mean, variance) in observation space, both (N,).

Raises:

Type Description
ValueError

If order is outside [2, 256].

Source code in packages/pyrox-gp/src/pyrox_gp/_warped.py
def 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"]]:
    r"""Moments of $y = G(f) + \epsilon$ under $q(f)$, by quadrature.

    $$
    m_1 = \mathbb{E}_{q(f)}[G(f)], \qquad
    m_2 = \sigma^2 + \mathbb{E}_{q(f)}[(G(f) - m_1)^2]
    $$

    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.

    Args:
        lik: The warped likelihood.
        f_loc: Posterior means of the base GP, shape ``(N,)``.
        f_var: Posterior marginal variances of the base GP, shape ``(N,)``.
        X: Inputs of shape ``(N, D)``; required when the warp is
            conditional, ignored otherwise. Broadcast over the quadrature
            nodes.
        order: Gauss-Hermite nodes; at least 2, since one node carries no
            spread. Values above ~256 are numerically unreliable
            (the rule overflows to ``NaN`` by order 512).

    Returns:
        Tuple of ``(mean, variance)`` in observation space, both ``(N,)``.

    Raises:
        ValueError: If ``order`` is outside ``[2, 256]``.
    """
    # _apply_warp broadcasts the (N, D) inputs across one node's (N,) values.
    first_moment, variance = _pushforward_moments(
        lambda f: _apply_warp(lik.warp, f, X), f_loc, f_var, order=order
    )
    return first_moment, lik.noise_var + variance

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.

\[ \mathcal{L} = \sum_n \mathbb{E}_{q(f_n)} [\log p(y_n \mid f_n)] - \mathrm{KL}[q(u) \| p(u)] \]

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 (N, D).

required
y Float[Array, ' N']

Training targets, shape (N,).

required
integrator AbstractIntegrator | None

gaussx integrator for the per-point ELL. Required for non-conjugate likelihoods; ignored for GaussianLikelihood.

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
def svgp_elbo(
    prior: SparseGPPrior,
    guide: Guide,
    likelihood: Likelihood,
    X: Float[Array, "N D"],
    y: Float[Array, " N"],
    *,
    integrator: GaussxIntegrator | None = None,
) -> Float[Array, ""]:
    r"""Structured SVGP ELBO as a differentiable scalar.

    $$
    \mathcal{L} = \sum_n \mathbb{E}_{q(f_n)}
                  [\log p(y_n \mid f_n)]
                - \mathrm{KL}[q(u) \| p(u)]
    $$

    For `GaussianLikelihood` the expected log-likelihood has a
    closed form and no integrator is needed:

    ```python
    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:

    ```python
    from gaussx import GaussHermiteIntegrator
    loss = svgp_elbo(
        prior, guide,
        DistLikelihood(lambda f: dist.Bernoulli(logits=f)),
        X, y, integrator=GaussHermiteIntegrator(order=20),
    )
    ```

    Args:
        prior: Sparse GP prior (kernel + inducing inputs).
        guide: Variational guide over inducing values.
        likelihood: Observation model.
        X: Training inputs, shape ``(N, D)``.
        y: Training targets, shape ``(N,)``.
        integrator: gaussx integrator for the per-point ELL. Required
            for non-conjugate likelihoods; ignored for
            `GaussianLikelihood`.

    Returns:
        Scalar ELBO value (higher is better).

    Raises:
        ValueError: If a non-conjugate likelihood is used without an
            integrator.
    """
    with call_context(prior.kernel):
        K_zz_op, K_xz, K_xx_diag = prior.predictive_blocks(X)

    f_loc, f_var = guide.predict(K_xz, K_zz_op, K_xx_diag)  # ty: ignore[unresolved-attribute]
    f_loc = f_loc + prior.mean(X)

    kl = guide.kl_divergence(K_zz_op)  # ty: ignore[unresolved-attribute]

    if isinstance(likelihood, GaussianLikelihood):
        return variational_elbo_gaussian(
            y,
            f_loc,
            f_var,
            likelihood.noise_var,  # ty: ignore[invalid-argument-type]
            kl,
        )

    if integrator is None:
        raise ValueError(
            "Non-conjugate likelihoods require an integrator "
            "(e.g. gaussx.GaussHermiteIntegrator). "
            "Pass integrator=GaussHermiteIntegrator(order=20)."
        )
    ell = _ell_numerical(likelihood, y, f_loc, f_var, integrator, X)
    return ell - kl

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

    ```python
    def model(X, y):
        svgp_factor("elbo", prior, guide, lik, X, y)

    svi = SVI(model, lambda X, y: None, Adam(1e-3), Trace_ELBO())
    ```
    """
    numpyro.factor(
        name,
        svgp_elbo(prior, guide, likelihood, X, y, integrator=integrator),
    )

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]\). 1.0 replaces the natural parameters with the target; < 1 interpolates for stability.

integrator AbstractIntegrator | None

gaussx integrator for non-conjugate expected gradients. None is fine for GaussianLikelihood.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference.py
class ConjugateVI:
    r"""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.

    ```python
    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:
        damping: Learning rate / damping factor $\rho \in (0, 1]$.
            ``1.0`` replaces the natural parameters with the target;
            ``< 1`` interpolates for stability.
        integrator: gaussx integrator for non-conjugate expected
            gradients. ``None`` is fine for `GaussianLikelihood`.
    """

    damping: float
    integrator: GaussxIntegrator | None

    def __init__(
        self,
        damping: float = 1.0,
        integrator: GaussxIntegrator | None = None,
    ) -> None:
        if not 0.0 <= damping <= 1.0:
            raise ValueError(f"damping must be in [0, 1], got {damping}.")
        self.damping = damping
        self.integrator = integrator

    def step(
        self,
        prior: SparseGPPrior,
        guide: NaturalGuide,
        likelihood: Likelihood,
        X: Float[Array, "N D"],
        y: Float[Array, " N"],
    ) -> NaturalGuide:
        r"""One CVI step: compute sites, project, update.

        1. Predict ``(f_loc, f_var) = guide.predict(...)``
        2. Compute per-point natural-gradient targets
           $(\lambda_n^{(1)}, \Lambda_n^{(2)})$.
        3. Project into inducing space:

        $$
        \begin{aligned}
        \hat{\eta}_1 &= \eta_1^{\text{prior}}
            + K_{ZZ}^{-1} K_{ZX}\, \lambda^{(1)}, \\
        \hat{\eta}_2 &= \eta_2^{\text{prior}}
            + K_{ZZ}^{-1} K_{ZX}\,
              \mathrm{diag}(\Lambda^{(2)})\, K_{XZ} K_{ZZ}^{-1}.
        \end{aligned}
        $$

        4. Damped update via `NaturalGuide.natural_update`.

        Args:
            prior: Sparse GP prior.
            guide: Current natural-parameter guide.
            likelihood: Observation model.
            X: Training inputs, shape ``(N, D)``.
            y: Training targets, shape ``(N,)``.

        Returns:
            Updated `NaturalGuide`.
        """
        with call_context(prior.kernel):
            K_zz_op, K_xz, K_xx_diag = prior.predictive_blocks(X)

        f_loc, f_var = guide.predict(K_xz, K_zz_op, K_xx_diag)
        f_loc = f_loc + prior.mean(X)

        grad1, grad2 = self._site_gradients(likelihood, y, f_loc, f_var, X)

        # B = K_zz^{-1} K_zx via gaussx.solve_matrix: one Cholesky
        # factorization shared across the matrix RHS for dense PSD
        # K_zz, structured dispatch (O(M) diagonal) otherwise, unless the
        # prior sets a solver, which then does every solve (pyrox#560).
        solver = _prior_solver(prior)
        K_zx = einx.id("n m -> m n", K_xz)  # (N, M) → (M, N)
        B = solve_matrix(K_zz_op, K_zx, solver=solver)

        # Prior natural parameters: p(u) = N(0, K_zz)
        # => eta1_prior = 0, eta2_prior = -0.5 K_zz^{-1}
        # K_zz^{-1} must be dense here (it seeds the dense nat2), so
        # solve against I and re-symmetrize.
        M = K_zz_op.in_size()
        nat1_prior = jnp.zeros_like(guide.nat1)
        eye = jnp.eye(M, dtype=guide.nat2.dtype)
        nat2_prior = -0.5 * symmetrize(solve_matrix(K_zz_op, eye, solver=solver))

        # Project per-point site natural parameters into inducing
        # space. The site λ₁ = grad1 - f_loc * grad2 (not just grad1);
        # omitting the f_loc correction makes the update depend on the
        # current guide mean instead of being a fixed-point update.
        site_lambda1 = grad1 - f_loc * grad2
        # η̂₁ = η₁ᵖʳⁱᵒʳ + B λ⁽¹⁾,  with B: (M, N), λ⁽¹⁾: (N,) → (M,).
        nat1_hat = nat1_prior + einx.dot("m n, n -> m", B, site_lambda1)
        # η̂₂ = η₂ᵖʳⁱᵒʳ + B diag(½ grad2) Bᵀ. Fold the per-point scale into
        # B then contract the shared n axis: (M, N)·(K, N) → (M, K).
        scaled_B = einx.multiply("n, m n -> m n", 0.5 * grad2, B)
        nat2_hat = nat2_prior + einx.dot("m n, k n -> m k", scaled_B, B)

        return guide.natural_update(nat1_hat, nat2_hat, rho=self.damping)

    def _site_gradients(
        self,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        f_loc: Float[Array, " N"],
        f_var: Float[Array, " N"],
        X: Float[Array, "N D"] | None = None,
    ) -> tuple[Float[Array, " N"], Float[Array, " N"]]:
        r"""Per-point ELL gradients w.r.t. the marginal mean.

        Returns ``(grad1, grad2)`` where ``grad1[n]`` is
        $\partial / \partial \mu_n \,
        \mathbb{E}_{q(f_n)}[\log p(y_n \mid f_n)]$ and ``grad2[n]``
        is the second derivative.

        For `GaussianLikelihood` these are analytical. For
        non-conjugate likelihoods they are computed via JAX autodiff
        through the per-point ELL: an observation model's from the one-site
        gaussx likelihood it builds (``X`` in ``data["X"]``), any other
        `Likelihood`'s from ``log_prob`` without ``X``.
        """
        if isinstance(likelihood, GaussianLikelihood):
            noise_var = likelihood.noise_var
            grad1 = (y - f_loc) / noise_var
            grad2 = jnp.full_like(f_loc, -1.0 / noise_var)
            return grad1, grad2

        if self.integrator is None:
            raise ValueError(
                "Non-conjugate likelihoods require an integrator for "
                "CVI. Pass integrator=GaussHermiteIntegrator(order=20)."
            )

        lik = likelihood
        if isinstance(lik, AbstractObservation):
            observation = lik
            sites: PyTree = (y, _input_data(X))

            def site_log_prob(f_n: Float[Array, ""], site: PyTree) -> Float[Array, ""]:
                return _site_log_prob(observation, f_n, site[0], site[1])

        else:
            sites = y

            def site_log_prob(f_n: Float[Array, ""], site: PyTree) -> Float[Array, ""]:
                return lik.log_prob(f_n[None], site[None])

        def _per_point_ell(
            mu_n: Float[Array, ""],
            var_n: Float[Array, ""],
            y_n: PyTree,
        ) -> Float[Array, ""]:
            return _site_expectation(
                self.integrator,  # type: ignore[arg-type]  # ty: ignore[invalid-argument-type]
                site_log_prob,
                mu_n,
                var_n,
                y_n,
            )

        grad1 = jax.vmap(jax.grad(lambda mu, v, yn: _per_point_ell(mu, v, yn)))(
            f_loc, f_var, sites
        )
        grad2 = jax.vmap(
            jax.grad(jax.grad(lambda mu, v, yn: _per_point_ell(mu, v, yn)))
        )(f_loc, f_var, sites)
        return grad1, grad2

step(prior: SparseGPPrior, guide: NaturalGuide, likelihood: Likelihood, X: Float[Array, 'N D'], y: Float[Array, ' N']) -> NaturalGuide

One CVI step: compute sites, project, update.

  1. Predict (f_loc, f_var) = guide.predict(...)
  2. Compute per-point natural-gradient targets \((\lambda_n^{(1)}, \Lambda_n^{(2)})\).
  3. Project into inducing space:
\[ \begin{aligned} \hat{\eta}_1 &= \eta_1^{\text{prior}} + K_{ZZ}^{-1} K_{ZX}\, \lambda^{(1)}, \\ \hat{\eta}_2 &= \eta_2^{\text{prior}} + K_{ZZ}^{-1} K_{ZX}\, \mathrm{diag}(\Lambda^{(2)})\, K_{XZ} K_{ZZ}^{-1}. \end{aligned} \]
  1. 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 (N, D).

required
y Float[Array, ' N']

Training targets, shape (N,).

required

Returns:

Type Description
NaturalGuide

Updated NaturalGuide.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference.py
def step(
    self,
    prior: SparseGPPrior,
    guide: NaturalGuide,
    likelihood: Likelihood,
    X: Float[Array, "N D"],
    y: Float[Array, " N"],
) -> NaturalGuide:
    r"""One CVI step: compute sites, project, update.

    1. Predict ``(f_loc, f_var) = guide.predict(...)``
    2. Compute per-point natural-gradient targets
       $(\lambda_n^{(1)}, \Lambda_n^{(2)})$.
    3. Project into inducing space:

    $$
    \begin{aligned}
    \hat{\eta}_1 &= \eta_1^{\text{prior}}
        + K_{ZZ}^{-1} K_{ZX}\, \lambda^{(1)}, \\
    \hat{\eta}_2 &= \eta_2^{\text{prior}}
        + K_{ZZ}^{-1} K_{ZX}\,
          \mathrm{diag}(\Lambda^{(2)})\, K_{XZ} K_{ZZ}^{-1}.
    \end{aligned}
    $$

    4. Damped update via `NaturalGuide.natural_update`.

    Args:
        prior: Sparse GP prior.
        guide: Current natural-parameter guide.
        likelihood: Observation model.
        X: Training inputs, shape ``(N, D)``.
        y: Training targets, shape ``(N,)``.

    Returns:
        Updated `NaturalGuide`.
    """
    with call_context(prior.kernel):
        K_zz_op, K_xz, K_xx_diag = prior.predictive_blocks(X)

    f_loc, f_var = guide.predict(K_xz, K_zz_op, K_xx_diag)
    f_loc = f_loc + prior.mean(X)

    grad1, grad2 = self._site_gradients(likelihood, y, f_loc, f_var, X)

    # B = K_zz^{-1} K_zx via gaussx.solve_matrix: one Cholesky
    # factorization shared across the matrix RHS for dense PSD
    # K_zz, structured dispatch (O(M) diagonal) otherwise, unless the
    # prior sets a solver, which then does every solve (pyrox#560).
    solver = _prior_solver(prior)
    K_zx = einx.id("n m -> m n", K_xz)  # (N, M) → (M, N)
    B = solve_matrix(K_zz_op, K_zx, solver=solver)

    # Prior natural parameters: p(u) = N(0, K_zz)
    # => eta1_prior = 0, eta2_prior = -0.5 K_zz^{-1}
    # K_zz^{-1} must be dense here (it seeds the dense nat2), so
    # solve against I and re-symmetrize.
    M = K_zz_op.in_size()
    nat1_prior = jnp.zeros_like(guide.nat1)
    eye = jnp.eye(M, dtype=guide.nat2.dtype)
    nat2_prior = -0.5 * symmetrize(solve_matrix(K_zz_op, eye, solver=solver))

    # Project per-point site natural parameters into inducing
    # space. The site λ₁ = grad1 - f_loc * grad2 (not just grad1);
    # omitting the f_loc correction makes the update depend on the
    # current guide mean instead of being a fixed-point update.
    site_lambda1 = grad1 - f_loc * grad2
    # η̂₁ = η₁ᵖʳⁱᵒʳ + B λ⁽¹⁾,  with B: (M, N), λ⁽¹⁾: (N,) → (M,).
    nat1_hat = nat1_prior + einx.dot("m n, n -> m", B, site_lambda1)
    # η̂₂ = η₂ᵖʳⁱᵒʳ + B diag(½ grad2) Bᵀ. Fold the per-point scale into
    # B then contract the shared n axis: (M, N)·(K, N) → (M, K).
    scaled_B = einx.multiply("n, m n -> m n", 0.5 * grad2, B)
    nat2_hat = nat2_prior + einx.dot("m n, k n -> m k", scaled_B, B)

    return guide.natural_update(nat1_hat, nat2_hat, rho=self.damping)

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,

\[ \log p(y) \approx \sum_n \log p(y_n \mid m_n) - \tfrac12 (m - \mu_f)^\top K^{-1} (m - \mu_f) - \tfrac12 \log \lvert I + \Lambda^{1/2} K \Lambda^{1/2} \rvert , \]

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

tol float

inf-norm convergence tolerance on f. Default 1e-6.

damping float

Step-size in (0, 1] applied to each Newton update: f_{k+1} = (1 - alpha) f_k + alpha f_k^{Newton}. Default 1.0 (full Newton step). Drop below 1 for non-log-concave likelihoods where pure Newton oscillates.

precision_floor float

Lower bound on the diagonal precision to keep K + 1/Λ well-conditioned even for log-concave-but-flat likelihoods (e.g. Bernoulli at extreme logits). Default 1e-6.

solver AbstractSolverStrategy | None

The solve of \(A\); None takes the prior's solver.

preconditioner AbstractPreconditioner | None

The preconditioner of an iterative solver; None takes the prior's. A lazy one (gaussx.NystromPreconditioner.lazy) reads the site variances from the system at every Newton step.

logdet AbstractLogdetStrategy | None

The log-determinant of the evidence; None takes the prior's (and, if that is unset too, the solver's own). The three are composed by gaussx.compose_solver; none set on either side is gaussx.DenseSolver.

adjoint ImplicitAdjoint | None

How the mode is differentiated, an optimistix.ImplicitAdjoint; None is argminax's matrix-free GMRES tangent solve.

variance _VarianceMethod

How ConditionedNonGaussGP.q_var computes the marginal variances, "auto", "exact" or "stochastic". "auto" is exact for a dense solver, and for an iterative one up to \(N = 2048\); above, it is the stochastic estimate of gaussx.SitePosterior.variance (gaussx#827), which needs the key of fit. The Newton loop itself needs no variances.

estimator _VarianceEstimator

The stochastic estimator, "auto", "sbpv" or "spv". "auto" is SBPV (draws from the prior and the sites, the more accurate) on a dense prior and SPV (sign probes, products with \(K\) only) on any other, so a matrix-free prior is never densified.

num_probes int

Draws or probes of the stochastic variance, one solve each. Default 100.

batch_size int

Solves vectorised together for the exact variances of an iterative solver. Default 32.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
class LaplaceInference(eqx.Module):
    r"""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,

    $$
    \log p(y) \approx \sum_n \log p(y_n \mid m_n)
      - \tfrac12 (m - \mu_f)^\top K^{-1} (m - \mu_f)
      - \tfrac12 \log \lvert I + \Lambda^{1/2} K \Lambda^{1/2} \rvert ,
    $$

    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:
        max_iter: Newton iterations. Default ``20``.
        tol: ``inf``-norm convergence tolerance on ``f``. Default ``1e-6``.
        damping: Step-size in (0, 1] applied to each Newton update:
            ``f_{k+1} = (1 - alpha) f_k + alpha f_k^{Newton}``. Default
            ``1.0`` (full Newton step). Drop below 1 for non-log-concave
            likelihoods where pure Newton oscillates.
        precision_floor: Lower bound on the diagonal precision to keep
            ``K + 1/Λ`` well-conditioned even for log-concave-but-flat
            likelihoods (e.g. Bernoulli at extreme logits). Default
            ``1e-6``.
        solver: The solve of $A$; ``None`` takes the prior's ``solver``.
        preconditioner: The preconditioner of an iterative ``solver``;
            ``None`` takes the prior's. A lazy one
            (``gaussx.NystromPreconditioner.lazy``) reads the site variances
            from the system at every Newton step.
        logdet: The log-determinant of the evidence; ``None`` takes the
            prior's (and, if that is unset too, the solver's own). The three
            are composed by `gaussx.compose_solver`; none set on either side
            is `gaussx.DenseSolver`.
        adjoint: How the mode is differentiated, an
            ``optimistix.ImplicitAdjoint``; ``None`` is argminax's
            matrix-free GMRES tangent solve.
        variance: How `ConditionedNonGaussGP.q_var` computes the marginal
            variances, ``"auto"``, ``"exact"`` or ``"stochastic"``.
            ``"auto"`` is exact for a dense solver, and for an iterative one
            up to $N = 2048$; above, it is the stochastic estimate of
            `gaussx.SitePosterior.variance` (gaussx#827), which needs the
            ``key`` of `fit`. The Newton loop itself needs no variances.
        estimator: The stochastic estimator, ``"auto"``, ``"sbpv"`` or
            ``"spv"``. ``"auto"`` is SBPV (draws from the prior and the
            sites, the more accurate) on a dense prior and SPV (sign probes,
            products with $K$ only) on any other, so a matrix-free prior is
            never densified.
        num_probes: Draws or probes of the stochastic variance, one solve
            each. Default ``100``.
        batch_size: Solves vectorised together for the exact variances of
            an iterative solver. Default ``32``.
    """

    max_iter: int = eqx.field(static=True, default=20)
    tol: float = eqx.field(static=True, default=1e-6)
    damping: float = eqx.field(static=True, default=1.0)
    precision_floor: float = eqx.field(static=True, default=1e-6)
    solver: AbstractSolverStrategy | None = None
    preconditioner: AbstractPreconditioner | None = None
    logdet: AbstractLogdetStrategy | None = None
    adjoint: optx.ImplicitAdjoint | None = None
    variance: _VarianceMethod = eqx.field(static=True, default="auto")
    estimator: _VarianceEstimator = eqx.field(static=True, default="auto")
    num_probes: int = eqx.field(static=True, default=100)
    batch_size: int = eqx.field(static=True, default=32)

    def __check_init__(self) -> None:
        _check_variance_options("LaplaceInference", self.variance, self.estimator)

    def fit(
        self,
        prior: GPPrior,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        *,
        key: Array | None = None,
    ) -> ConditionedNonGaussGP:
        r"""Fit the Laplace approximation at the mode of $p(f \mid y)$.

        Args:
            prior: The `GPPrior`, dense or ``matrix_free=True``.
            likelihood: A scalar-latent `Likelihood`.
            y: Observations, shape ``(N,)``.
            key: PRNG key of a stochastic log-determinant in the evidence
                (CG's SLQ, `gaussx.BBMMSolver`); ``None`` uses the solver's
                own seed. Ignored by an exact log-determinant. Stochastic
                marginal variances use ``fold_in(key, 1)``, and without a
                key `ConditionedNonGaussGP.q_var` raises for them.

        Returns:
            The `ConditionedNonGaussGP` at the mode.

        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)
        """
        return _newton_fit(self, prior, likelihood, y, key)

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 GPPrior, dense or matrix_free=True.

required
likelihood Likelihood

A scalar-latent Likelihood.

required
y Float[Array, ' N']

Observations, shape (N,).

required
key Array | None

PRNG key of a stochastic log-determinant in the evidence (CG's SLQ, gaussx.BBMMSolver); None uses the solver's own seed. Ignored by an exact log-determinant. Stochastic marginal variances use fold_in(key, 1), and without a key ConditionedNonGaussGP.q_var raises for them.

None

Returns:

Type Description
ConditionedNonGaussGP

The ConditionedNonGaussGP at the mode.

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
def fit(
    self,
    prior: GPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    key: Array | None = None,
) -> ConditionedNonGaussGP:
    r"""Fit the Laplace approximation at the mode of $p(f \mid y)$.

    Args:
        prior: The `GPPrior`, dense or ``matrix_free=True``.
        likelihood: A scalar-latent `Likelihood`.
        y: Observations, shape ``(N,)``.
        key: PRNG key of a stochastic log-determinant in the evidence
            (CG's SLQ, `gaussx.BBMMSolver`); ``None`` uses the solver's
            own seed. Ignored by an exact log-determinant. Stochastic
            marginal variances use ``fold_in(key, 1)``, and without a
            key `ConditionedNonGaussGP.q_var` raises for them.

    Returns:
        The `ConditionedNonGaussGP` at the mode.

    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)
    """
    return _newton_fit(self, prior, likelihood, y, key)

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

tol float

inf-norm convergence tolerance on f. Default 1e-6.

damping float

Step-size in (0, 1] applied to each Newton update. Default 1.0 (full Newton step). Drop below 1 for non-log-concave likelihoods where pure Newton oscillates.

precision_floor float

Lower bound on the diagonal precision. Default 1e-3 — larger than LaplaceInference to ensure stable updates on non-log-concave likelihoods.

solver AbstractSolverStrategy | None

As in LaplaceInference; None takes the prior's.

preconditioner AbstractPreconditioner | None

As in LaplaceInference.

logdet AbstractLogdetStrategy | None

As in LaplaceInference.

adjoint ImplicitAdjoint | None

As in LaplaceInference.

variance _VarianceMethod

As in LaplaceInference.

estimator _VarianceEstimator

As in LaplaceInference.

num_probes int

As in LaplaceInference.

batch_size int

As in LaplaceInference.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
class GaussNewtonInference(eqx.Module):
    r"""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:
        max_iter: Iterations. Default ``20``.
        tol: ``inf``-norm convergence tolerance on ``f``. Default ``1e-6``.
        damping: Step-size in (0, 1] applied to each Newton update.
            Default ``1.0`` (full Newton step). Drop below 1 for
            non-log-concave likelihoods where pure Newton oscillates.
        precision_floor: Lower bound on the diagonal precision. Default
            ``1e-3`` — larger than `LaplaceInference` to ensure
            stable updates on non-log-concave likelihoods.
        solver: As in `LaplaceInference`; ``None`` takes the prior's.
        preconditioner: As in `LaplaceInference`.
        logdet: As in `LaplaceInference`.
        adjoint: As in `LaplaceInference`.
        variance: As in `LaplaceInference`.
        estimator: As in `LaplaceInference`.
        num_probes: As in `LaplaceInference`.
        batch_size: As in `LaplaceInference`.
    """

    max_iter: int = eqx.field(static=True, default=20)
    tol: float = eqx.field(static=True, default=1e-6)
    damping: float = eqx.field(static=True, default=1.0)
    precision_floor: float = eqx.field(static=True, default=1e-3)
    solver: AbstractSolverStrategy | None = None
    preconditioner: AbstractPreconditioner | None = None
    logdet: AbstractLogdetStrategy | None = None
    adjoint: optx.ImplicitAdjoint | None = None
    variance: _VarianceMethod = eqx.field(static=True, default="auto")
    estimator: _VarianceEstimator = eqx.field(static=True, default="auto")
    num_probes: int = eqx.field(static=True, default=100)
    batch_size: int = eqx.field(static=True, default=32)

    def __check_init__(self) -> None:
        _check_variance_options("GaussNewtonInference", self.variance, self.estimator)

    def fit(
        self,
        prior: GPPrior,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        *,
        key: Array | None = None,
    ) -> ConditionedNonGaussGP:
        """Fit the Gauss-Newton approximation; as `LaplaceInference.fit`.

        Args:
            prior: The `GPPrior`, dense or ``matrix_free=True``.
            likelihood: A scalar-latent `Likelihood`.
            y: Observations, shape ``(N,)``.
            key: PRNG key of a stochastic log-determinant in the evidence,
                ignored by an exact one, and of stochastic marginal
                variances, as in `LaplaceInference.fit`.

        Returns:
            The `ConditionedNonGaussGP` at the mode.
        """
        return _newton_fit(self, prior, likelihood, y, key)

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 GPPrior, dense or matrix_free=True.

required
likelihood Likelihood

A scalar-latent Likelihood.

required
y Float[Array, ' N']

Observations, shape (N,).

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 LaplaceInference.fit.

None

Returns:

Type Description
ConditionedNonGaussGP

The ConditionedNonGaussGP at the mode.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
def fit(
    self,
    prior: GPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    key: Array | None = None,
) -> ConditionedNonGaussGP:
    """Fit the Gauss-Newton approximation; as `LaplaceInference.fit`.

    Args:
        prior: The `GPPrior`, dense or ``matrix_free=True``.
        likelihood: A scalar-latent `Likelihood`.
        y: Observations, shape ``(N,)``.
        key: PRNG key of a stochastic log-determinant in the evidence,
            ignored by an exact one, and of stochastic marginal
            variances, as in `LaplaceInference.fit`.

    Returns:
        The `ConditionedNonGaussGP` at the mode.
    """
    return _newton_fit(self, prior, likelihood, y, key)

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 gaussx.GaussHermiteIntegrator(order=20).

max_iter int

Iterations. Default 40 (20 before pyrox#552, whose stopping test on the posterior mean let a fit stop a few iterations earlier: on a 16-point Bernoulli problem the site test needs 23 where the mean test stopped at 20).

damping float

Step size in (0, 1]. Default 0.5.

tol float

Convergence tolerance: the loop stops at the first iteration where every site natural changed by less than 0.1 * tol * (1 + |new value|). Default 1e-6.

precision_floor float

Lower bound on the diagonal precision.

solver AbstractSolverStrategy | None

The solve of \(A\); None takes the prior's solver.

preconditioner AbstractPreconditioner | None

The preconditioner of an iterative solver; None takes the prior's.

logdet AbstractLogdetStrategy | None

The log-determinant of the evidence; None takes the prior's (and, if that is unset too, the solver's own). The three are composed by gaussx.compose_solver; none set on either side is gaussx.DenseSolver.

variance _VarianceMethod

How the marginal variances are computed, "auto", "exact" or "stochastic". "auto" is exact for a dense solver, and for an iterative one up to \(N = 2048\); above, it is the stochastic estimate of gaussx.SitePosterior.variance_and_error (gaussx#827), \(N\)-independent in its solve count, which needs the key of fit. A stochastic estimate is clamped for the cavities to \([10^{-6} K_{nn}, (1 - 10^{-3}) / \lambda_n]\), so every cavity precision stays positive.

estimator _VarianceEstimator

The stochastic estimator, "auto", "sbpv" or "spv". "auto" is SBPV (draws from the prior and the sites, the more accurate) on a dense prior and SPV (sign probes, products with \(K\) only) on any other, so a matrix-free prior is never densified.

num_probes int

Draws or probes of the stochastic variance, one solve each. Default 100.

adjoint AbstractAdjoint | None

How gradients pass through the loop; None is the matrix-free implicit adjoint of argminax.solve.site_fixed_point.

batch_size int

Solves vectorised together for the exact variances of an iterative solver. Default 32.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
class PosteriorLinearization(eqx.Module):
    r"""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:
        integrator: Cavity integrator. Default
            ``gaussx.GaussHermiteIntegrator(order=20)``.
        max_iter: Iterations. Default ``40`` (``20`` before pyrox#552,
            whose stopping test on the posterior mean let a fit stop a few
            iterations earlier: on a 16-point Bernoulli problem the site test
            needs 23 where the mean test stopped at 20).
        damping: Step size in (0, 1]. Default ``0.5``.
        tol: Convergence tolerance: the loop stops at the first iteration
            where every site natural changed by less than
            ``0.1 * tol * (1 + |new value|)``. Default ``1e-6``.
        precision_floor: Lower bound on the diagonal precision.
        solver: The solve of $A$; ``None`` takes the prior's ``solver``.
        preconditioner: The preconditioner of an iterative ``solver``;
            ``None`` takes the prior's.
        logdet: The log-determinant of the evidence; ``None`` takes the
            prior's (and, if that is unset too, the solver's own). The three
            are composed by `gaussx.compose_solver`; none set on either side
            is `gaussx.DenseSolver`.
        variance: How the marginal variances are computed, ``"auto"``,
            ``"exact"`` or ``"stochastic"``. ``"auto"`` is exact for a dense
            solver, and for an iterative one up to $N = 2048$; above, it is
            the stochastic estimate of `gaussx.SitePosterior.variance_and_error`
            (gaussx#827), $N$-independent in its solve count, which needs the
            ``key`` of `fit`. A stochastic estimate is clamped for the
            cavities to $[10^{-6} K_{nn}, (1 - 10^{-3}) / \lambda_n]$, so
            every cavity precision stays positive.
        estimator: The stochastic estimator, ``"auto"``, ``"sbpv"`` or
            ``"spv"``. ``"auto"`` is SBPV (draws from the prior and the
            sites, the more accurate) on a dense prior and SPV (sign probes,
            products with $K$ only) on any other, so a matrix-free prior is
            never densified.
        num_probes: Draws or probes of the stochastic variance, one solve
            each. Default ``100``.
        adjoint: How gradients pass through the loop; ``None`` is the
            matrix-free implicit adjoint of `argminax.solve.site_fixed_point`.
        batch_size: Solves vectorised together for the exact variances of
            an iterative solver. Default ``32``.
    """

    integrator: AbstractIntegrator = eqx.field(
        default_factory=lambda: GaussHermiteIntegrator(order=20)
    )
    max_iter: int = eqx.field(static=True, default=40)
    damping: float = eqx.field(static=True, default=0.5)
    tol: float = eqx.field(static=True, default=1e-6)
    precision_floor: float = eqx.field(static=True, default=1e-6)
    solver: AbstractSolverStrategy | None = None
    preconditioner: AbstractPreconditioner | None = None
    logdet: AbstractLogdetStrategy | None = None
    variance: _VarianceMethod = eqx.field(static=True, default="auto")
    num_probes: int = eqx.field(static=True, default=100)
    adjoint: optx.AbstractAdjoint | None = None
    batch_size: int = eqx.field(static=True, default=32)
    estimator: _VarianceEstimator = eqx.field(static=True, default="auto")

    def __check_init__(self) -> None:
        _check_variance_options("PosteriorLinearization", self.variance, self.estimator)

    def _update(
        self,
        sites: _SiteNaturals,
        mean: Float[Array, " N"],
        variance: Float[Array, " N"],
        likelihood: Likelihood,
        site_data: PyTree,
    ) -> _SiteNaturals:
        """The damped PL sites from the marginals ``(mean, variance)``."""
        nat1, nat2 = sites
        log_prob_per_point = _log_prob_per_point_factory(likelihood)

        def grad_at(f_n: Float[Array, ""], y_n: PyTree) -> Float[Array, ""]:
            return jax.grad(lambda f: log_prob_per_point(f[None], _one_site(y_n))[0])(
                f_n
            )

        def hess_at(f_n: Float[Array, ""], y_n: PyTree) -> Float[Array, ""]:
            return jax.grad(
                jax.grad(lambda f: log_prob_per_point(f[None], _one_site(y_n))[0])
            )(f_n)

        # q₋ₙ(fₙ) = q(fₙ) / siteₙ(fₙ)
        cav_mean, cav_var = cavity_distribution(
            mean, variance, nat1, nat2, precision_floor=self.precision_floor
        )
        assert isinstance(cav_var, jax.Array)  # diagonal path in, diagonal out
        # ḡₙ = 𝔼_{cav}[∂f log p(yₙ | f)], h̄ₙ = 𝔼_{cav}[∂²f log p(yₙ | f)]
        E_grad = _per_site_expectation(
            self.integrator, grad_at, cav_mean, cav_var, site_data
        )
        E_hess = _per_site_expectation(
            self.integrator, hess_at, cav_mean, cav_var, site_data
        )
        # λₙ ← max(−h̄ₙ, ε),  λₙ μ_site,n ← ḡₙ + λₙ μ_cav,n; damped
        nat1_target, nat2_target = newton_update(
            cav_mean, E_grad, E_hess, precision_floor=self.precision_floor
        )
        nat1, nat2 = damped_natural_update(
            nat1, nat2, nat1_target, nat2_target, lr=self.damping
        )
        assert isinstance(nat2, jax.Array)  # pyrox sites are diagonal arrays
        return nat1, jnp.maximum(nat2, self.precision_floor)

    def _step(self, sites: _SiteNaturals, args: PyTree) -> _SiteNaturals:
        return _cavity_step(self, sites, args)

    def fit(
        self,
        prior: GPPrior,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        *,
        key: Array | None = None,
    ) -> ConditionedNonGaussGP:
        r"""Fit the sites by posterior linearisation.

        Args:
            prior: The `GPPrior`, dense or ``matrix_free=True``.
            likelihood: A scalar-latent `Likelihood`.
            y: Observations, shape ``(N,)``.
            key: PRNG key of a stochastic log-determinant in the evidence
                (for example `gaussx.BBMMSolver`) and, as
                ``fold_in(key, 1)``, of stochastic marginal variances, one
                key for every iteration; ignored otherwise.

        Returns:
            The `ConditionedNonGaussGP` of the fitted sites.

        Raises:
            ValueError: If the marginal variances are stochastic (see
                ``variance``) and ``key`` is ``None``.

        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,)
        """
        return _fit_cavity_sites(self, prior, likelihood, y, key)

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 GPPrior, dense or matrix_free=True.

required
likelihood Likelihood

A scalar-latent Likelihood.

required
y Float[Array, ' N']

Observations, shape (N,).

required
key Array | None

PRNG key of a stochastic log-determinant in the evidence (for example gaussx.BBMMSolver) and, as fold_in(key, 1), of stochastic marginal variances, one key for every iteration; ignored otherwise.

None

Returns:

Type Description
ConditionedNonGaussGP

The ConditionedNonGaussGP of the fitted sites.

Raises:

Type Description
ValueError

If the marginal variances are stochastic (see variance) and key is None.

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
def fit(
    self,
    prior: GPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    key: Array | None = None,
) -> ConditionedNonGaussGP:
    r"""Fit the sites by posterior linearisation.

    Args:
        prior: The `GPPrior`, dense or ``matrix_free=True``.
        likelihood: A scalar-latent `Likelihood`.
        y: Observations, shape ``(N,)``.
        key: PRNG key of a stochastic log-determinant in the evidence
            (for example `gaussx.BBMMSolver`) and, as
            ``fold_in(key, 1)``, of stochastic marginal variances, one
            key for every iteration; ignored otherwise.

    Returns:
        The `ConditionedNonGaussGP` of the fitted sites.

    Raises:
        ValueError: If the marginal variances are stochastic (see
            ``variance``) and ``key`` is ``None``.

    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,)
    """
    return _fit_cavity_sites(self, prior, likelihood, y, key)

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 gaussx.GaussHermiteIntegrator(order=20). EP reads only its order, for gaussx.ep_tilted_moments, so any other rule raises TypeError.

max_iter int

Iterations. Default 40.

damping float

Damping in (0, 1]. Default 0.5.

tol float

Convergence tolerance on the site naturals, as in PosteriorLinearization. Default 1e-6.

precision_floor float

Lower bound on the diagonal precision.

solver AbstractSolverStrategy | None

As in PosteriorLinearization; None takes the prior's.

preconditioner AbstractPreconditioner | None

As in PosteriorLinearization.

logdet AbstractLogdetStrategy | None

As in PosteriorLinearization.

variance _VarianceMethod

As in PosteriorLinearization.

num_probes int

As in PosteriorLinearization.

adjoint AbstractAdjoint | None

As in PosteriorLinearization.

batch_size int

As in PosteriorLinearization.

estimator _VarianceEstimator

As in PosteriorLinearization.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
class ExpectationPropagation(eqx.Module):
    r"""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:
        integrator: Cavity integrator. Default
            ``gaussx.GaussHermiteIntegrator(order=20)``. EP reads only its
            ``order``, for `gaussx.ep_tilted_moments`, so any other rule
            raises ``TypeError``.
        max_iter: Iterations. Default ``40``.
        damping: Damping in (0, 1]. Default ``0.5``.
        tol: Convergence tolerance on the site naturals, as in
            `PosteriorLinearization`. Default ``1e-6``.
        precision_floor: Lower bound on the diagonal precision.
        solver: As in `PosteriorLinearization`; ``None`` takes the prior's.
        preconditioner: As in `PosteriorLinearization`.
        logdet: As in `PosteriorLinearization`.
        variance: As in `PosteriorLinearization`.
        num_probes: As in `PosteriorLinearization`.
        adjoint: As in `PosteriorLinearization`.
        batch_size: As in `PosteriorLinearization`.
        estimator: As in `PosteriorLinearization`.
    """

    integrator: AbstractIntegrator = eqx.field(
        default_factory=lambda: GaussHermiteIntegrator(order=20)
    )
    max_iter: int = eqx.field(static=True, default=40)
    damping: float = eqx.field(static=True, default=0.5)
    tol: float = eqx.field(static=True, default=1e-6)
    precision_floor: float = eqx.field(static=True, default=1e-6)
    solver: AbstractSolverStrategy | None = None
    preconditioner: AbstractPreconditioner | None = None
    logdet: AbstractLogdetStrategy | None = None
    variance: _VarianceMethod = eqx.field(static=True, default="auto")
    num_probes: int = eqx.field(static=True, default=100)
    adjoint: optx.AbstractAdjoint | None = None
    batch_size: int = eqx.field(static=True, default=32)
    estimator: _VarianceEstimator = eqx.field(static=True, default="auto")

    def __check_init__(self) -> None:
        _require_gauss_hermite(self.integrator)
        _check_variance_options("ExpectationPropagation", self.variance, self.estimator)

    def _update(
        self,
        sites: _SiteNaturals,
        mean: Float[Array, " N"],
        variance: Float[Array, " N"],
        likelihood: Likelihood,
        site_data: PyTree,
    ) -> _SiteNaturals:
        """The damped EP sites from the marginals ``(mean, variance)``."""
        nat1, nat2 = sites
        log_prob_per_point = _log_prob_per_point_factory(likelihood)
        order = _require_gauss_hermite(self.integrator).order

        def _per_site_tilted(
            m_n: Float[Array, ""],
            v_n: Float[Array, ""],
            y_n: PyTree,
        ) -> tuple[Float[Array, ""], Float[Array, ""]]:
            def lp(f: Float[Array, ""]) -> Float[Array, ""]:
                return log_prob_per_point(f[None], _one_site(y_n))[0]

            return ep_tilted_moments(lp, m_n, v_n, order=order)

        # q₋ₙ(fₙ) = q(fₙ) / siteₙ(fₙ)
        cav_mean, cav_var = cavity_distribution(
            mean, variance, nat1, nat2, precision_floor=self.precision_floor
        )
        assert isinstance(cav_var, jax.Array)  # diagonal path in, diagonal out
        # The tilted moments of q₋ₙ(fₙ) p(yₙ ∣ fₙ), one site at a time.
        tilted_mean, tilted_var = jax.vmap(_per_site_tilted)(
            cav_mean, cav_var, site_data
        )
        # λₙ ← max(1 / σ̂ₙ² − 1 / σ²_cav,n, ε), and the matching information
        new_prec = jnp.reciprocal(tilted_var) - jnp.reciprocal(cav_var)
        new_prec = jnp.maximum(new_prec, self.precision_floor)
        new_nat1 = tilted_mean / tilted_var - cav_mean / cav_var
        nat1, nat2 = damped_natural_update(
            nat1, nat2, new_nat1, new_prec, lr=self.damping
        )
        assert isinstance(nat2, jax.Array)  # pyrox sites are diagonal arrays
        return nat1, jnp.maximum(nat2, self.precision_floor)

    def _step(self, sites: _SiteNaturals, args: PyTree) -> _SiteNaturals:
        return _cavity_step(self, sites, args)

    def fit(
        self,
        prior: GPPrior,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        *,
        key: Array | None = None,
    ) -> ConditionedNonGaussGP:
        r"""Fit the sites by parallel expectation propagation.

        Args:
            prior: The `GPPrior`, dense or ``matrix_free=True``.
            likelihood: A scalar-latent `Likelihood`.
            y: Observations, shape ``(N,)``.
            key: PRNG key of a stochastic log-determinant in the evidence
                (for example `gaussx.BBMMSolver`) and, as
                ``fold_in(key, 1)``, of stochastic marginal variances, one
                key for every iteration; ignored otherwise.

        Returns:
            The `ConditionedNonGaussGP` of the fitted sites.

        Raises:
            ValueError: If the marginal variances are stochastic (see
                ``variance``) and ``key`` is ``None``.

        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)
        """
        return _fit_cavity_sites(self, prior, likelihood, y, key)

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 GPPrior, dense or matrix_free=True.

required
likelihood Likelihood

A scalar-latent Likelihood.

required
y Float[Array, ' N']

Observations, shape (N,).

required
key Array | None

PRNG key of a stochastic log-determinant in the evidence (for example gaussx.BBMMSolver) and, as fold_in(key, 1), of stochastic marginal variances, one key for every iteration; ignored otherwise.

None

Returns:

Type Description
ConditionedNonGaussGP

The ConditionedNonGaussGP of the fitted sites.

Raises:

Type Description
ValueError

If the marginal variances are stochastic (see variance) and key is None.

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
def fit(
    self,
    prior: GPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    key: Array | None = None,
) -> ConditionedNonGaussGP:
    r"""Fit the sites by parallel expectation propagation.

    Args:
        prior: The `GPPrior`, dense or ``matrix_free=True``.
        likelihood: A scalar-latent `Likelihood`.
        y: Observations, shape ``(N,)``.
        key: PRNG key of a stochastic log-determinant in the evidence
            (for example `gaussx.BBMMSolver`) and, as
            ``fold_in(key, 1)``, of stochastic marginal variances, one
            key for every iteration; ignored otherwise.

    Returns:
        The `ConditionedNonGaussGP` of the fitted sites.

    Raises:
        ValueError: If the marginal variances are stochastic (see
            ``variance``) and ``key`` is ``None``.

    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)
    """
    return _fit_cavity_sites(self, prior, likelihood, y, key)

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

tol float

The rtol and atol of optimistix.LBFGS, which stops when both the step in v and the change in the objective are within atol + rtol * |.|. Default 1e-6.

precision_floor float

Lower bound on the diagonal precision.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
class QuasiNewtonInference(eqx.Module):
    r"""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:
        max_iter: L-BFGS iterations. Default ``50``.
        tol: The ``rtol`` and ``atol`` of `optimistix.LBFGS`, which stops
            when both the step in ``v`` and the change in the objective are
            within ``atol + rtol * |.|``. Default ``1e-6``.
        precision_floor: Lower bound on the diagonal precision.
    """

    max_iter: int = eqx.field(static=True, default=50)
    tol: float = eqx.field(static=True, default=1e-6)
    precision_floor: float = eqx.field(static=True, default=1e-6)

    def fit(
        self,
        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.

        Args:
            prior: A dense `GPPrior`.
            likelihood: A scalar-latent `Likelihood`.
            y: Observations, shape ``(N,)``.
            key: Accepted so that every strategy takes the keyword of
                `GPPrior.condition_nongauss`; the evidence here is exact,
                so it is ignored.

        Returns:
            The `ConditionedNonGaussGP` at the mode.

        Raises:
            ValueError: For ``GPPrior(matrix_free=True)``.
        """
        del key  # the dense evidence needs no probes
        _reject_matrix_free(prior)
        _check_scalar_latent(likelihood)
        # one hyperparameter draw for K, the mean and the predictions
        with call_context(prior.kernel):
            K = _prior_K(prior)
            prior_mean = jnp.asarray(prior.mean(prior.X))
            kernel = _fitted_kernel(prior)
        log_prob_per_point = _log_prob_per_point_factory(likelihood)
        sites = _site_data(likelihood, y, prior.X)
        L_K = _psd_safe_cholesky(K)

        def latent(v: Float[Array, " N"]) -> Float[Array, " N"]:
            # f = μ + L v, the whitened coordinates of the prior
            return prior_mean + einx.dot("i j, j -> i", L_K, v)

        def neg_log_post(v: Float[Array, " N"], args: None) -> Float[Array, ""]:
            del args
            # −log p(y | f) + ½ vᵀv, the negative log posterior in v
            return -log_prob_per_point(latent(v), sites).sum() + 0.5 * jnp.dot(v, v)

        # optimistix keeps the L-BFGS history in the default float dtype, so
        # float32 data under x64 runs the search in float64 and casts back.
        dtype = jnp.promote_types(prior_mean.dtype, jnp.result_type(float))
        solution = optx.minimise(
            neg_log_post,
            optx.LBFGS(rtol=self.tol, atol=self.tol),
            jnp.zeros(prior_mean.shape, dtype),
            max_steps=self.max_iter,
            throw=False,
        )
        mode = latent(solution.value).astype(prior_mean.dtype)
        # the Newton sites at the mode: λ = max(−h, ε), λ μ_site = g + λ f̂
        g, h = _per_point_grad_hess(log_prob_per_point, mode, sites)
        information, precision = newton_update(
            mode, g, h, precision_floor=self.precision_floor
        )
        posterior = site_posterior(
            prior_mean,
            _psd_operator(K),
            information,
            precision,
            solver=DenseSolver(),
        )
        # ∑ₙ log p(yₙ ∣ mₙ) at the posterior mean of the sites
        log_lik = log_prob_per_point(posterior.mean, sites).sum()
        return ConditionedNonGaussGP(
            prior=prior,
            y=y,
            site_posterior=posterior,
            log_marginal_approx=site_log_evidence(posterior, log_lik),
            n_iter=jnp.asarray(solution.stats["num_steps"]),
            converged=solution.result == optx.RESULTS.successful,
            kernel=kernel,
        )

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

required
likelihood Likelihood

A scalar-latent Likelihood.

required
y Float[Array, ' N']

Observations, shape (N,).

required
key Array | None

Accepted so that every strategy takes the keyword of GPPrior.condition_nongauss; the evidence here is exact, so it is ignored.

None

Returns:

Type Description
ConditionedNonGaussGP

The ConditionedNonGaussGP at the mode.

Raises:

Type Description
ValueError

For GPPrior(matrix_free=True).

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
def fit(
    self,
    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.

    Args:
        prior: A dense `GPPrior`.
        likelihood: A scalar-latent `Likelihood`.
        y: Observations, shape ``(N,)``.
        key: Accepted so that every strategy takes the keyword of
            `GPPrior.condition_nongauss`; the evidence here is exact,
            so it is ignored.

    Returns:
        The `ConditionedNonGaussGP` at the mode.

    Raises:
        ValueError: For ``GPPrior(matrix_free=True)``.
    """
    del key  # the dense evidence needs no probes
    _reject_matrix_free(prior)
    _check_scalar_latent(likelihood)
    # one hyperparameter draw for K, the mean and the predictions
    with call_context(prior.kernel):
        K = _prior_K(prior)
        prior_mean = jnp.asarray(prior.mean(prior.X))
        kernel = _fitted_kernel(prior)
    log_prob_per_point = _log_prob_per_point_factory(likelihood)
    sites = _site_data(likelihood, y, prior.X)
    L_K = _psd_safe_cholesky(K)

    def latent(v: Float[Array, " N"]) -> Float[Array, " N"]:
        # f = μ + L v, the whitened coordinates of the prior
        return prior_mean + einx.dot("i j, j -> i", L_K, v)

    def neg_log_post(v: Float[Array, " N"], args: None) -> Float[Array, ""]:
        del args
        # −log p(y | f) + ½ vᵀv, the negative log posterior in v
        return -log_prob_per_point(latent(v), sites).sum() + 0.5 * jnp.dot(v, v)

    # optimistix keeps the L-BFGS history in the default float dtype, so
    # float32 data under x64 runs the search in float64 and casts back.
    dtype = jnp.promote_types(prior_mean.dtype, jnp.result_type(float))
    solution = optx.minimise(
        neg_log_post,
        optx.LBFGS(rtol=self.tol, atol=self.tol),
        jnp.zeros(prior_mean.shape, dtype),
        max_steps=self.max_iter,
        throw=False,
    )
    mode = latent(solution.value).astype(prior_mean.dtype)
    # the Newton sites at the mode: λ = max(−h, ε), λ μ_site = g + λ f̂
    g, h = _per_point_grad_hess(log_prob_per_point, mode, sites)
    information, precision = newton_update(
        mode, g, h, precision_floor=self.precision_floor
    )
    posterior = site_posterior(
        prior_mean,
        _psd_operator(K),
        information,
        precision,
        solver=DenseSolver(),
    )
    # ∑ₙ log p(yₙ ∣ mₙ) at the posterior mean of the sites
    log_lik = log_prob_per_point(posterior.mean, sites).sum()
    return ConditionedNonGaussGP(
        prior=prior,
        y=y,
        site_posterior=posterior,
        log_marginal_approx=site_log_evidence(posterior, log_lik),
        n_iter=jnp.asarray(solution.stats["num_steps"]),
        converged=solution.result == optx.RESULTS.successful,
        kernel=kernel,
    )

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

\[ \mu_* = \mu(X_*) + K_{*X} w, \qquad \sigma_*^2 = k_{**} - k_*^\top A^{-1} k_* , \]

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 GPPrior the fit was given.

y Float[Array, ' N']

Training targets (kept for round-trip / diagnostics).

site_posterior SitePosterior

The gaussx.SitePosterior of the fitted sites: the prior covariance, the sites, the weights \(w\), the posterior mean and the solver (with the Cholesky factor of \(A\) on the dense path).

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 jax.jit and jax.vmap.

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 (frozen()); a kernel that cannot be frozen is kept as it is and evaluated once per predict.

marginal_variance _MarginalVariance

How q_var is computed: exactly, or by the stochastic estimate of gaussx.SitePosterior.variance with the fit's estimator, probes and key (gaussx#827).

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
class ConditionedNonGaussGP(eqx.Module):
    r"""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

    $$
    \mu_* = \mu(X_*) + K_{*X} w, \qquad
    \sigma_*^2 = k_{**} - k_*^\top A^{-1} k_* ,
    $$

    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:
        prior: The `GPPrior` the fit was given.
        y: Training targets (kept for round-trip / diagnostics).
        site_posterior: The `gaussx.SitePosterior` of the fitted sites: the
            prior covariance, the sites, the weights $w$, the posterior mean
            and the solver (with the Cholesky factor of $A$ on the dense
            path).
        log_marginal_approx: Approximate log marginal likelihood
            (the scalar each strategy reports — interpretation is
            strategy-specific; see the per-class docstring).
        n_iter: Iterations used by the strategy, a scalar integer array,
            so a fit runs under ``jax.jit`` and ``jax.vmap``.
        converged: 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: The prior's kernel with the hyperparameters of the fit, a
            plain kernellib kernel (``frozen()``); a kernel that cannot be
            frozen is kept as it is and evaluated once per ``predict``.
        marginal_variance: How `q_var` is computed: exactly, or by the
            stochastic estimate of `gaussx.SitePosterior.variance` with the
            fit's estimator, probes and key (gaussx#827).
    """

    prior: GPPrior
    y: Float[Array, " N"]
    site_posterior: SitePosterior
    log_marginal_approx: Float[Array, ""]
    n_iter: Int[Array, ""]
    converged: Bool[Array, ""]
    kernel: Kernel
    marginal_variance: _MarginalVariance = eqx.field(
        default_factory=lambda: _MarginalVariance()
    )

    @property
    def batch_size(self) -> int:
        """Solves vectorised together for the exact variances of an iterative fit."""
        return self.marginal_variance.batch_size

    @property
    def site_nat1(self) -> Float[Array, " N"]:
        r"""The site information $\lambda^{(1)} = \lambda \odot \mu_\text{site}$."""
        return self.site_posterior.site_information

    @property
    def site_nat2(self) -> Float[Array, " N"]:
        r"""The site precisions $\lambda$, all positive."""
        return self.site_posterior.site_precision

    @property
    def q_mean(self) -> Float[Array, " N"]:
        r"""The posterior mean $\mu_f + K w$ at the training inputs."""
        return self.site_posterior.mean

    @property
    def solver(self) -> AbstractSolverStrategy | None:
        """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.
        """
        solver = self.site_posterior.solver
        return None if isinstance(solver, DenseSolver) else solver

    @property
    def q_var(self) -> Float[Array, " N"]:
        r"""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:
            ValueError: For stochastic variances of a fit given no ``key``.
        """
        return self.marginal_variance(self.site_posterior)

    def _predict(
        self, X_star: Float[Array, "M D"], *, variance: bool
    ) -> tuple[Float[Array, " M"], Float[Array, " M"] | None]:
        """The predictive mean and, if asked, the marginal variances."""
        kernel = self.kernel
        posterior = self.site_posterior
        # a no-op for a frozen kernel; one draw for one that could not be
        with call_context(kernel):
            K_cross = kernel(X_star, self.prior.X)
            K_diag = kernel.diag(X_star) if variance else None
            prior_mean_test = self.prior.mean(X_star)
        # μ_* = μ(X_*) + K_{*X} w,  K_{*X}: (M, N), w: (N,) → (M,)
        mean = prior_mean_test + einx.dot("m n, n -> m", K_cross, posterior.weights)
        if K_diag is None:
            return mean, None
        cache = PredictionCache(
            alpha=posterior.weights,
            operator=posterior.system,
            factor=posterior.factor,
        )
        # σ²_* = k_** − k_*ᵀ A⁻¹ k_*
        var = predict_variance(cache, K_cross, K_diag, solver=posterior.solver)
        return mean, jnp.maximum(var, 0.0)

    def predict_mean(self, X_star: Float[Array, "M D"]) -> Float[Array, " M"]:
        r"""$\mu_* = \mu(X_*) + K_{*X} w$, from the weights of the fit."""
        return self._predict(X_star, variance=False)[0]

    def predict_var(self, X_star: Float[Array, "M D"]) -> Float[Array, " M"]:
        r"""$k_{**} - k_*^\top (K + \mathrm{diag}(1/\lambda))^{-1} k_*$."""
        var = self._predict(X_star, variance=True)[1]
        assert var is not None
        return var

    def predict(
        self, 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.
        """
        mean, var = self._predict(X_star, variance=True)
        assert var is not None
        return mean, var

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

predict_mean(X_star: Float[Array, 'M D']) -> Float[Array, ' M']

\(\mu_* = \mu(X_*) + K_{*X} w\), from the weights of the fit.

Source code in packages/pyrox-gp/src/pyrox_gp/_inference_nongauss.py
def predict_mean(self, X_star: Float[Array, "M D"]) -> Float[Array, " M"]:
    r"""$\mu_* = \mu(X_*) + K_{*X} w$, from the weights of the fit."""
    return self._predict(X_star, variance=False)[0]

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
def predict_var(self, X_star: Float[Array, "M D"]) -> Float[Array, " M"]:
    r"""$k_{**} - k_*^\top (K + \mathrm{diag}(1/\lambda))^{-1} k_*$."""
    var = self._predict(X_star, variance=True)[1]
    assert var is not None
    return var

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
def predict(
    self, 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.
    """
    mean, var = self._predict(X_star, variance=True)
    assert var is not None
    return mean, var

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
class LMCKernel(eqx.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')``.
    """

    kernels: tuple[Kernel, ...]
    mixing: Float[Array, "P Q"]

    def __check_init__(self) -> None:
        _validate_mixing(self.mixing)
        _validate_kernel_count(self.kernels, self.mixing.shape[1])
        _validate_kernel_scopes_unique(self.kernels)

    @property
    def num_outputs(self) -> int:
        """Number of observed output channels ``P``."""
        return self.mixing.shape[0]

    @property
    def num_latents(self) -> int:
        """Number of latent scalar GPs ``Q``."""
        return self.mixing.shape[1]

    def coregionalization_matrix(self, q: int) -> Float[Array, "P P"]:
        """Return the rank-1 coregionalization matrix ``w_q w_q^T``."""
        if not 0 <= q < self.num_latents:
            raise IndexError(f"latent index out of range: {q}")
        column = self.mixing[:, q]
        return einx.dot("i, j -> i j", column, column)

    def kronecker_factors(
        self,
        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.
        """
        with call_contexts(self.kernels):
            return tuple(
                (self.coregionalization_matrix(q), kernel(X1, X2))
                for q, kernel in enumerate(self.kernels)
            )

    def output_covariance(
        self,
        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)``."""
        # Per-latent outer product B_q ⊗ K_q → (P, P, N1, N2).
        terms = [
            einx.multiply("p1 p2, n1 n2 -> p1 p2 n1 n2", B_q, K_q)
            for B_q, K_q in self.kronecker_factors(X1, X2)
        ]
        return functools.reduce(jnp.add, terms)

    def cross_covariance_operator(
        self,
        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.
        """
        psd_K = X1 is X2
        terms = [
            _kron_block_op(B_q, K_q, psd_K=psd_K)
            for B_q, K_q in self.kronecker_factors(X1, X2)
        ]
        if len(terms) == 1:
            return terms[0]
        return sum_operator(*terms)

    def cross_covariance(
        self,
        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))``."""
        return self.cross_covariance_operator(X1, X2).as_matrix()

    def full_covariance_operator(
        self, X: Float[Array, "N D"]
    ) -> lx.AbstractLinearOperator:
        """Return the Gram operator for isotopic multi-output observations."""
        return self.cross_covariance_operator(X, X)

    def full_covariance(self, X: Float[Array, "N D"]) -> Float[Array, "PN PN"]:
        """Return the dense Gram matrix for isotopic multi-output observations."""
        return self.full_covariance_operator(X).as_matrix()

    def diag(self, X: Float[Array, "N D"]) -> Float[Array, "N P"]:
        """Return per-input, per-output marginal variances with shape ``(N, P)``."""
        with call_contexts(self.kernels):
            # Per-latent variance kₙ ⊗ wₚ² → (N, P), summed over latents.
            terms = [
                einx.multiply(
                    "n, p -> n p", kernel.diag(X), jnp.square(self.mixing[:, q])
                )
                for q, kernel in enumerate(self.kernels)
            ]
        return functools.reduce(jnp.add, terms)

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
def coregionalization_matrix(self, q: int) -> Float[Array, "P P"]:
    """Return the rank-1 coregionalization matrix ``w_q w_q^T``."""
    if not 0 <= q < self.num_latents:
        raise IndexError(f"latent index out of range: {q}")
    column = self.mixing[:, q]
    return einx.dot("i, j -> i j", column, column)

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
def kronecker_factors(
    self,
    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.
    """
    with call_contexts(self.kernels):
        return tuple(
            (self.coregionalization_matrix(q), kernel(X1, X2))
            for q, kernel in enumerate(self.kernels)
        )

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
def output_covariance(
    self,
    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)``."""
    # Per-latent outer product B_q ⊗ K_q → (P, P, N1, N2).
    terms = [
        einx.multiply("p1 p2, n1 n2 -> p1 p2 n1 n2", B_q, K_q)
        for B_q, K_q in self.kronecker_factors(X1, X2)
    ]
    return functools.reduce(jnp.add, terms)

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
def cross_covariance_operator(
    self,
    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.
    """
    psd_K = X1 is X2
    terms = [
        _kron_block_op(B_q, K_q, psd_K=psd_K)
        for B_q, K_q in self.kronecker_factors(X1, X2)
    ]
    if len(terms) == 1:
        return terms[0]
    return sum_operator(*terms)

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
def cross_covariance(
    self,
    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))``."""
    return self.cross_covariance_operator(X1, X2).as_matrix()

full_covariance_operator(X: Float[Array, 'N D']) -> lx.AbstractLinearOperator

Return the Gram operator for isotopic multi-output observations.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
def full_covariance_operator(
    self, X: Float[Array, "N D"]
) -> lx.AbstractLinearOperator:
    """Return the Gram operator for isotopic multi-output observations."""
    return self.cross_covariance_operator(X, X)

full_covariance(X: Float[Array, 'N D']) -> Float[Array, 'PN PN']

Return the dense Gram matrix for isotopic multi-output observations.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
def full_covariance(self, X: Float[Array, "N D"]) -> Float[Array, "PN PN"]:
    """Return the dense Gram matrix for isotopic multi-output observations."""
    return self.full_covariance_operator(X).as_matrix()

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
def diag(self, X: Float[Array, "N D"]) -> Float[Array, "N P"]:
    """Return per-input, per-output marginal variances with shape ``(N, P)``."""
    with call_contexts(self.kernels):
        # Per-latent variance kₙ ⊗ wₚ² → (N, P), summed over latents.
        terms = [
            einx.multiply(
                "n, p -> n p", kernel.diag(X), jnp.square(self.mixing[:, q])
            )
            for q, kernel in enumerate(self.kernels)
        ]
    return functools.reduce(jnp.add, terms)

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
class ICMKernel(eqx.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.
    """

    kernel: Kernel
    mixing: Float[Array, "P Q"]
    kappa: Float[Array, " P"] | None = None

    def __check_init__(self) -> None:
        _validate_mixing(self.mixing)
        if self.kappa is not None:
            if self.kappa.shape != (self.mixing.shape[0],):
                raise ValueError(
                    "kappa must have shape (num_outputs,) when provided; "
                    f"got {self.kappa.shape}."
                )
            # ``B = W W^T + diag(kappa)`` is downstream wrapped with the
            # PSD tag (``_psd_matrix_op``). ``W W^T`` is PSD by
            # construction, but a negative ``kappa`` entry can pull
            # ``B`` out of PSD and silently break Cholesky-based solver
            # paths. Reject at construction when the value is concrete;
            # under ``jax.jit`` the check is a no-op (see
            # `_check_nonnegative_concrete`).
            _check_nonnegative_concrete(self.kappa, name="ICMKernel.kappa")

    @property
    def num_outputs(self) -> int:
        """Number of observed output channels ``P``."""
        return self.mixing.shape[0]

    @property
    def num_latents(self) -> int:
        """Number of latent scalar GPs ``Q``."""
        return self.mixing.shape[1]

    def coregionalization_matrix(self) -> Float[Array, "P P"]:
        """Return ``B = W W^T + diag(kappa)``."""
        # B = W Wᵀ: contract the shared latent axis q.
        B = einx.dot("p q, r q -> p r", self.mixing, self.mixing)
        if self.kappa is None:
            return B
        return B + jnp.diag(self.kappa)

    def kronecker_factors(
        self,
        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."""
        with call_context(self.kernel):
            return self.coregionalization_matrix(), self.kernel(X1, X2)

    def output_covariance(
        self,
        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)``."""
        B, K = self.kronecker_factors(X1, X2)
        # Outer product B ⊗ K → (P, P, N1, N2).
        return einx.multiply("p1 p2, n1 n2 -> p1 p2 n1 n2", B, K)

    def cross_covariance_operator(
        self,
        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.
        """
        B, K = self.kronecker_factors(X1, X2)
        return _kron_block_op(B, K, psd_K=X1 is X2)  # ty: ignore[invalid-return-type]

    def cross_covariance(
        self,
        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))``."""
        return self.cross_covariance_operator(X1, X2).as_matrix()

    def full_covariance_operator(self, X: Float[Array, "N D"]) -> Kronecker:
        """Return the Gram operator for isotopic multi-output observations."""
        return self.cross_covariance_operator(X, X)

    def full_covariance(self, X: Float[Array, "N D"]) -> Float[Array, "PN PN"]:
        """Return the dense Gram matrix for isotopic multi-output observations."""
        return self.full_covariance_operator(X).as_matrix()

    def diag(self, X: Float[Array, "N D"]) -> Float[Array, "N P"]:
        """Return per-input, per-output marginal variances with shape ``(N, P)``."""
        with call_context(self.kernel):
            # kₙ ⊗ diag(B)ₚ → (N, P) marginal variances.
            return einx.multiply(
                "n, p -> n p",
                self.kernel.diag(X),
                jnp.diag(self.coregionalization_matrix()),
            )

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
def coregionalization_matrix(self) -> Float[Array, "P P"]:
    """Return ``B = W W^T + diag(kappa)``."""
    # B = W Wᵀ: contract the shared latent axis q.
    B = einx.dot("p q, r q -> p r", self.mixing, self.mixing)
    if self.kappa is None:
        return B
    return B + jnp.diag(self.kappa)

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
def kronecker_factors(
    self,
    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."""
    with call_context(self.kernel):
        return self.coregionalization_matrix(), self.kernel(X1, X2)

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
def output_covariance(
    self,
    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)``."""
    B, K = self.kronecker_factors(X1, X2)
    # Outer product B ⊗ K → (P, P, N1, N2).
    return einx.multiply("p1 p2, n1 n2 -> p1 p2 n1 n2", B, K)

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
def cross_covariance_operator(
    self,
    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.
    """
    B, K = self.kronecker_factors(X1, X2)
    return _kron_block_op(B, K, psd_K=X1 is X2)  # ty: ignore[invalid-return-type]

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
def cross_covariance(
    self,
    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))``."""
    return self.cross_covariance_operator(X1, X2).as_matrix()

full_covariance_operator(X: Float[Array, 'N D']) -> Kronecker

Return the Gram operator for isotopic multi-output observations.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
def full_covariance_operator(self, X: Float[Array, "N D"]) -> Kronecker:
    """Return the Gram operator for isotopic multi-output observations."""
    return self.cross_covariance_operator(X, X)

full_covariance(X: Float[Array, 'N D']) -> Float[Array, 'PN PN']

Return the dense Gram matrix for isotopic multi-output observations.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
def full_covariance(self, X: Float[Array, "N D"]) -> Float[Array, "PN PN"]:
    """Return the dense Gram matrix for isotopic multi-output observations."""
    return self.full_covariance_operator(X).as_matrix()

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
def diag(self, X: Float[Array, "N D"]) -> Float[Array, "N P"]:
    """Return per-input, per-output marginal variances with shape ``(N, P)``."""
    with call_context(self.kernel):
        # kₙ ⊗ diag(B)ₚ → (N, P) marginal variances.
        return einx.multiply(
            "n, p -> n p",
            self.kernel.diag(X),
            jnp.diag(self.coregionalization_matrix()),
        )

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
class OILMMKernel(eqx.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.
    """

    kernels: tuple[Kernel, ...]
    mixing: Float[Array, "P Q"]
    check_orthogonal: bool = eqx.field(static=True, default=False)

    def __check_init__(self) -> None:
        _validate_mixing(self.mixing)
        _validate_kernel_count(self.kernels, self.mixing.shape[1])
        if self.mixing.shape[1] > self.mixing.shape[0]:
            raise ValueError(
                "orthogonal mixing requires num_latents <= num_outputs to form "
                "a valid semi-orthogonal mixing matrix; "
                f"got {self.mixing.shape[1]} latents and "
                f"{self.mixing.shape[0]} outputs."
            )
        if self.check_orthogonal and not self.is_orthogonal():
            raise ValueError(
                "mixing must satisfy W^T W ≈ I when check_orthogonal=True. "
                "Project via `jnp.linalg.qr(W)[0]` before construction, or "
                "pass check_orthogonal=False to bypass."
            )
        _validate_kernel_scopes_unique(self.kernels)

    @property
    def num_outputs(self) -> int:
        """Number of observed output channels ``P``."""
        return self.mixing.shape[0]

    @property
    def num_latents(self) -> int:
        """Number of latent scalar GPs ``Q``."""
        return self.mixing.shape[1]

    def is_orthogonal(self, *, atol: float = 1e-6, rtol: float = 1e-6) -> 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``.
        """
        # Wᵀ W: contract the shared output axis p.
        gram = einx.dot("p q, p r -> q r", self.mixing, self.mixing)
        eye = jnp.eye(self.num_latents, dtype=self.mixing.dtype)
        return bool(jnp.allclose(gram, eye, atol=atol, rtol=rtol))

    def project(
        self,
        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``.
        """
        if Y.ndim != 2 or Y.shape[1] != self.num_outputs:
            raise ValueError(
                f"Y must have shape (N, {self.num_outputs}); got {Y.shape}."
            )
        return oilmm_project(Y, self.mixing, noise_var)

    def back_project(
        self,
        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`.
        """
        return oilmm_back_project(f_means, f_vars, self.mixing)

    def independent_gps(self) -> tuple[Kernel, ...]:
        """Return the latent scalar GP kernels used after projection."""
        return self.kernels

    def signal_factors(
        self,
        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`.
        """
        with call_contexts(self.kernels):
            return tuple(
                (
                    einx.dot("i, j -> i j", self.mixing[:, q], self.mixing[:, q]),
                    kernel(X1, X2),
                )
                for q, kernel in enumerate(self.kernels)
            )

    def signal_covariance_operator(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> lx.AbstractLinearOperator:
        """Return the noise-free signal covariance as a structured operator."""
        psd_K = X1 is X2
        terms = [
            _kron_block_op(B_q, K_q, psd_K=psd_K)
            for B_q, K_q in self.signal_factors(X1, X2)
        ]
        if len(terms) == 1:
            return terms[0]
        return sum_operator(*terms)

    def signal_covariance(
        self,
        X1: Float[Array, "N1 D"],
        X2: Float[Array, "N2 D"],
    ) -> Float[Array, "PN1 PN2"]:
        """Return the dense noise-free signal covariance matrix."""
        return self.signal_covariance_operator(X1, X2).as_matrix()

    # LMC / ICM-parity aliases — OILMM's "signal covariance" is the
    # noise-free vec-cross covariance, same semantics as
    # ``LMCKernel.cross_covariance`` since noise is no longer kernel-side.
    cross_covariance_operator = signal_covariance_operator
    cross_covariance = signal_covariance

    def full_covariance_operator(
        self, X: Float[Array, "N D"]
    ) -> lx.AbstractLinearOperator:
        """Return the noise-free Gram operator for isotopic observations."""
        return self.signal_covariance_operator(X, X)

    def full_covariance(self, X: Float[Array, "N D"]) -> Float[Array, "PN PN"]:
        """Return the dense noise-free Gram matrix."""
        return self.full_covariance_operator(X).as_matrix()

    def diag(self, X: Float[Array, "N D"]) -> Float[Array, "N P"]:
        """Return per-input, per-output marginal signal variances."""
        with call_contexts(self.kernels):
            # Per-latent variance kₙ ⊗ wₚ² → (N, P), summed over latents.
            terms = [
                einx.multiply(
                    "n, p -> n p", kernel.diag(X), jnp.square(self.mixing[:, q])
                )
                for q, kernel in enumerate(self.kernels)
            ]
        return functools.reduce(jnp.add, terms)

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
def is_orthogonal(self, *, atol: float = 1e-6, rtol: float = 1e-6) -> 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``.
    """
    # Wᵀ W: contract the shared output axis p.
    gram = einx.dot("p q, p r -> q r", self.mixing, self.mixing)
    eye = jnp.eye(self.num_latents, dtype=self.mixing.dtype)
    return bool(jnp.allclose(gram, eye, atol=atol, rtol=rtol))

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
def project(
    self,
    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``.
    """
    if Y.ndim != 2 or Y.shape[1] != self.num_outputs:
        raise ValueError(
            f"Y must have shape (N, {self.num_outputs}); got {Y.shape}."
        )
    return oilmm_project(Y, self.mixing, noise_var)

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
def back_project(
    self,
    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`.
    """
    return oilmm_back_project(f_means, f_vars, self.mixing)

independent_gps() -> tuple[Kernel, ...]

Return the latent scalar GP kernels used after projection.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
def independent_gps(self) -> tuple[Kernel, ...]:
    """Return the latent scalar GP kernels used after projection."""
    return self.kernels

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
def signal_factors(
    self,
    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`.
    """
    with call_contexts(self.kernels):
        return tuple(
            (
                einx.dot("i, j -> i j", self.mixing[:, q], self.mixing[:, q]),
                kernel(X1, X2),
            )
            for q, kernel in enumerate(self.kernels)
        )

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
def signal_covariance_operator(
    self,
    X1: Float[Array, "N1 D"],
    X2: Float[Array, "N2 D"],
) -> lx.AbstractLinearOperator:
    """Return the noise-free signal covariance as a structured operator."""
    psd_K = X1 is X2
    terms = [
        _kron_block_op(B_q, K_q, psd_K=psd_K)
        for B_q, K_q in self.signal_factors(X1, X2)
    ]
    if len(terms) == 1:
        return terms[0]
    return sum_operator(*terms)

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
def signal_covariance(
    self,
    X1: Float[Array, "N1 D"],
    X2: Float[Array, "N2 D"],
) -> Float[Array, "PN1 PN2"]:
    """Return the dense noise-free signal covariance matrix."""
    return self.signal_covariance_operator(X1, X2).as_matrix()

full_covariance_operator(X: Float[Array, 'N D']) -> lx.AbstractLinearOperator

Return the noise-free Gram operator for isotopic observations.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
def full_covariance_operator(
    self, X: Float[Array, "N D"]
) -> lx.AbstractLinearOperator:
    """Return the noise-free Gram operator for isotopic observations."""
    return self.signal_covariance_operator(X, X)

full_covariance(X: Float[Array, 'N D']) -> Float[Array, 'PN PN']

Return the dense noise-free Gram matrix.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
def full_covariance(self, X: Float[Array, "N D"]) -> Float[Array, "PN PN"]:
    """Return the dense noise-free Gram matrix."""
    return self.full_covariance_operator(X).as_matrix()

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
def diag(self, X: Float[Array, "N D"]) -> Float[Array, "N P"]:
    """Return per-input, per-output marginal signal variances."""
    with call_contexts(self.kernels):
        # Per-latent variance kₙ ⊗ wₚ² → (N, P), summed over latents.
        terms = [
            einx.multiply(
                "n, p -> n p", kernel.diag(X), jnp.square(self.mixing[:, q])
            )
            for q, kernel in enumerate(self.kernels)
        ]
    return functools.reduce(jnp.add, terms)

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

required
Y Float[Array, 'N P']

Observations, shape (N, P).

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
def 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``.

    Args:
        name: The factor site name.
        prior: The `OILMMGPPrior`.
        Y: Observations, shape ``(N, P)``.
        noise_var: The isotropic noise variance, a scalar.

    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']
    """
    numpyro.factor(name, prior.log_marginal(Y, noise_var))

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
class MultiOutputInducingVariables(eqx.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.
    """

    inducing: SharedInducingPoints
    mixing: Float[Array, "P Q"]

    def __check_init__(self) -> None:
        _validate_mixing(self.mixing)

    @classmethod
    def from_kernel(
        cls,
        kernel: LMCKernel | ICMKernel,
        inducing: SharedInducingPoints,
    ) -> MultiOutputInducingVariables:
        """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.
        """
        if isinstance(kernel, (LMCKernel, ICMKernel)):
            if isinstance(kernel, ICMKernel) and kernel.kappa is not None:
                _require_all_zero_concrete(kernel.kappa, name="ICMKernel.kappa")
            return cls(inducing=inducing, mixing=kernel.mixing)
        raise TypeError(
            "from_kernel only accepts LMCKernel or ICMKernel; "
            f"got {type(kernel).__name__}."
        )

    @property
    def num_outputs(self) -> int:
        """Number of observed output channels ``P``."""
        return self.mixing.shape[0]

    @property
    def num_latents(self) -> int:
        """Number of latent scalar GPs ``Q``."""
        return self.mixing.shape[1]

    def K_uu_operator(self, kernels: tuple[Kernel, ...]) -> BlockDiag:
        """Return the block-diagonal inducing covariance as a ``BlockDiag``."""
        _validate_kernel_count(kernels, self.num_latents)
        return self.inducing.K_uu_operator(kernels)

    def K_uu(self, kernels: tuple[Kernel, ...]) -> Float[Array, "QM QM"]:
        """Return the block-diagonal inducing covariance over latent processes."""
        _validate_kernel_count(kernels, self.num_latents)
        return self.inducing.K_uu(kernels)

    def K_uf(
        self,
        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)``.
        """
        _validate_kernel_count(kernels, self.num_latents)
        latent_blocks = self.inducing.cross_covariances(X, kernels)
        return self._assemble_K_uf(latent_blocks)

    def _assemble_K_uf(
        self, latent_blocks: tuple[Float[Array, "M N"], ...]
    ) -> Float[Array, "QM PN"]:
        """Stack per-latent ``K(Z, X)`` blocks into the ``(Q*M, P*N)`` ``K_uf``."""
        rows = []
        for q, K_zx in enumerate(latent_blocks):
            # Scale K(Z, X) by each output weight, then interleave the output
            # axis into the columns: (P,) ⊙ (M, N) → (M, P·N).
            scaled = einx.multiply("p, m n -> p m n", self.mixing[:, q], K_zx)
            row = einx.id("p m n -> m (p n)", scaled)
            rows.append(row)
        return jnp.concatenate(rows, axis=0)

    def inducing_blocks(
        self,
        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`).
        """
        _validate_kernel_count(kernels, self.num_latents)
        K_uu_blocks, K_uf_blocks = self.inducing.inducing_blocks(X, kernels)
        K_uu_op = BlockDiag(*(_psd_matrix_op(B) for B in K_uu_blocks))
        K_uf = self._assemble_K_uf(K_uf_blocks)
        return K_uu_op, K_uf

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
@classmethod
def from_kernel(
    cls,
    kernel: LMCKernel | ICMKernel,
    inducing: SharedInducingPoints,
) -> MultiOutputInducingVariables:
    """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.
    """
    if isinstance(kernel, (LMCKernel, ICMKernel)):
        if isinstance(kernel, ICMKernel) and kernel.kappa is not None:
            _require_all_zero_concrete(kernel.kappa, name="ICMKernel.kappa")
        return cls(inducing=inducing, mixing=kernel.mixing)
    raise TypeError(
        "from_kernel only accepts LMCKernel or ICMKernel; "
        f"got {type(kernel).__name__}."
    )

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
def K_uu_operator(self, kernels: tuple[Kernel, ...]) -> BlockDiag:
    """Return the block-diagonal inducing covariance as a ``BlockDiag``."""
    _validate_kernel_count(kernels, self.num_latents)
    return self.inducing.K_uu_operator(kernels)

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
def K_uu(self, kernels: tuple[Kernel, ...]) -> Float[Array, "QM QM"]:
    """Return the block-diagonal inducing covariance over latent processes."""
    _validate_kernel_count(kernels, self.num_latents)
    return self.inducing.K_uu(kernels)

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
def K_uf(
    self,
    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)``.
    """
    _validate_kernel_count(kernels, self.num_latents)
    latent_blocks = self.inducing.cross_covariances(X, kernels)
    return self._assemble_K_uf(latent_blocks)

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
def inducing_blocks(
    self,
    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`).
    """
    _validate_kernel_count(kernels, self.num_latents)
    K_uu_blocks, K_uf_blocks = self.inducing.inducing_blocks(X, kernels)
    K_uu_op = BlockDiag(*(_psd_matrix_op(B) for B in K_uu_blocks))
    K_uf = self._assemble_K_uf(K_uf_blocks)
    return K_uu_op, K_uf

SharedInducingPoints

Bases: Module

Shared inducing inputs for multi-output latent GP collections.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
class SharedInducingPoints(eqx.Module):
    """Shared inducing inputs for multi-output latent GP collections."""

    locations: Float[Array, "M D"]

    def __check_init__(self) -> None:
        if self.locations.ndim != 2:
            raise ValueError("locations must have shape (num_inducing, input_dim).")

    @property
    def num_inducing(self) -> int:
        """Number of inducing inputs ``M`` shared by all latent processes."""
        return self.locations.shape[0]

    def latent_covariances(
        self, 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.
        """
        if not kernels:
            raise ValueError("kernels must be non-empty.")
        _validate_kernel_scopes_unique(kernels)
        with call_contexts(kernels):
            return tuple(kernel(self.locations, self.locations) for kernel in kernels)

    def K_uu_operator(self, 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``.
        """
        if not kernels:
            raise ValueError("kernels must be non-empty.")
        _validate_kernel_scopes_unique(kernels)
        with call_contexts(kernels):
            blocks = tuple(
                _psd_matrix_op(kernel(self.locations, self.locations))
                for kernel in kernels
            )
        return BlockDiag(*blocks)

    def K_uu(self, kernels: tuple[Kernel, ...]) -> Float[Array, "QM QM"]:
        """Materialize the block-diagonal inducing covariance over all latents."""
        return self.K_uu_operator(kernels).as_matrix()

    def cross_covariances(
        self,
        X: Float[Array, "N D"],
        kernels: tuple[Kernel, ...],
    ) -> tuple[Float[Array, "M N"], ...]:
        """Return one ``K(Z, X)`` block per latent kernel."""
        if not kernels:
            raise ValueError("kernels must be non-empty.")
        _validate_kernel_scopes_unique(kernels)
        with call_contexts(kernels):
            return tuple(kernel(self.locations, X) for kernel in kernels)

    def inducing_blocks(
        self,
        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`).
        """
        if not kernels:
            raise ValueError("kernels must be non-empty.")
        _validate_kernel_scopes_unique(kernels)
        with call_contexts(kernels):
            K_uu_blocks = tuple(
                kernel(self.locations, self.locations) for kernel in kernels
            )
            K_uf_blocks = tuple(kernel(self.locations, X) for kernel in kernels)
        return K_uu_blocks, K_uf_blocks

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
def latent_covariances(
    self, 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.
    """
    if not kernels:
        raise ValueError("kernels must be non-empty.")
    _validate_kernel_scopes_unique(kernels)
    with call_contexts(kernels):
        return tuple(kernel(self.locations, self.locations) for kernel in kernels)

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
def K_uu_operator(self, 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``.
    """
    if not kernels:
        raise ValueError("kernels must be non-empty.")
    _validate_kernel_scopes_unique(kernels)
    with call_contexts(kernels):
        blocks = tuple(
            _psd_matrix_op(kernel(self.locations, self.locations))
            for kernel in kernels
        )
    return BlockDiag(*blocks)

K_uu(kernels: tuple[Kernel, ...]) -> Float[Array, 'QM QM']

Materialize the block-diagonal inducing covariance over all latents.

Source code in packages/pyrox-gp/src/pyrox_gp/_multi_output.py
def K_uu(self, kernels: tuple[Kernel, ...]) -> Float[Array, "QM QM"]:
    """Materialize the block-diagonal inducing covariance over all latents."""
    return self.K_uu_operator(kernels).as_matrix()

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
def cross_covariances(
    self,
    X: Float[Array, "N D"],
    kernels: tuple[Kernel, ...],
) -> tuple[Float[Array, "M N"], ...]:
    """Return one ``K(Z, X)`` block per latent kernel."""
    if not kernels:
        raise ValueError("kernels must be non-empty.")
    _validate_kernel_scopes_unique(kernels)
    with call_contexts(kernels):
        return tuple(kernel(self.locations, X) for kernel in kernels)

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
def inducing_blocks(
    self,
    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`).
    """
    if not kernels:
        raise ValueError("kernels must be non-empty.")
    _validate_kernel_scopes_unique(kernels)
    with call_contexts(kernels):
        K_uu_blocks = tuple(
            kernel(self.locations, self.locations) for kernel in kernels
        )
        K_uf_blocks = tuple(kernel(self.locations, X) for kernel in kernels)
    return K_uu_blocks, K_uf_blocks

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 Z is 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.0 per latent is a legitimate modelling choice (it makes the factors comparable), not a requirement for a valid fit.
  • predict_latents variance understates uncertainty. It treats the MAP Z as noiseless observations of the latent processes, so it captures input-space extrapolation but not uncertainty in the point estimate itself.
  • z_* and W are assumed independent in predict. They are not — both depend on the training data through the fitted Z. Reasonable when P is large; understates variance for small P.
  • This is a low-data model. Z is N x Q free parameters, does not amortize, does not minibatch over N, and carries O(Q N^3) through the latent priors. The reference experiments top out at N = 800.

Warp-specific caveats (ignore when warp is None):

  • Y must sit inside the warp's support. gauss_flows.RQSplineMarginal is linear outside [-interval, interval]; scale Y sensibly 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 pyrox_gp.Kernel per latent process; len is Q. Distinct pyrox.PyroxModule kernels must carry distinct pyrox_name values or their NumPyro sites collide.

X Float[Array, 'N D']

Training inputs of shape (N, D).

warp AbstractBijection | None

Optional bijection with event shape (P,) — one marginal transform per output channel. The warped observations \(G^{-1}(Y)\) are modelled as the linear factor model, which handles skewed / heavy-tailed / positive channels without breaking the analytic decoder marginalization (the log-det Jacobian is free of \(Z\), \(W\), and \(\sigma\)). None keeps the plain Gaussian factor model. Prefer gauss_flows.RQSplineMarginal — closed-form in both directions and the exact identity at initialization, so a warped fit starts precisely at the unwarped fit. Conditional (input-dependent) warps are rejected.

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.

jitter float

Numerical diagonal regularization for Cholesky stability.

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
class LatentFactorGPPrior(eqx.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`][pyrox_gp.collapsed_lfr_log_prob] and recovered
    in closed form by
    [`decoder_posterior`][pyrox_gp.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 ``Z`` is 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.0`` per latent is a
      legitimate modelling choice (it makes the factors comparable), not a
      requirement for a valid fit.
    - **`predict_latents` variance understates uncertainty.** It treats the
      MAP ``Z`` as noiseless observations of the latent processes, so it
      captures input-space extrapolation but not uncertainty in the point
      estimate itself.
    - **``z_*`` and ``W`` are assumed independent** in `predict`. They are
      not — both depend on the training data through the fitted ``Z``.
      Reasonable when ``P`` is large; understates variance for small ``P``.
    - **This is a low-data model.** ``Z`` is ``N x Q`` free parameters, does
      not amortize, does not minibatch over ``N``, and carries ``O(Q N^3)``
      through the latent priors. The reference experiments top out at
      ``N = 800``.

    Warp-specific caveats (ignore when ``warp is None``):

    - **``Y`` must sit inside the warp's support.**
      ``gauss_flows.RQSplineMarginal`` is linear outside
      ``[-interval, interval]``; scale ``Y`` sensibly 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`][pyrox.inference.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:
        kernels: One `pyrox_gp.Kernel` per latent process; ``len`` is ``Q``.
            Distinct `pyrox.PyroxModule` kernels must carry distinct
            ``pyrox_name`` values or their NumPyro sites collide.
        X: Training inputs of shape ``(N, D)``.
        warp: Optional bijection with event shape ``(P,)`` — one marginal
            transform per output channel. The *warped* observations
            $G^{-1}(Y)$ are modelled as the linear factor model, which
            handles skewed / heavy-tailed / positive channels without
            breaking the analytic decoder marginalization (the log-det
            Jacobian is free of $Z$, $W$, and $\\sigma$). ``None`` keeps
            the plain Gaussian factor model. Prefer
            ``gauss_flows.RQSplineMarginal`` — closed-form in both
            directions and the exact identity at initialization, so a
            warped fit starts precisely at the unwarped fit. Conditional
            (input-dependent) warps are rejected.
        latent_noise: 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``.
        jitter: Numerical diagonal regularization for Cholesky stability.
    """

    kernels: tuple[Kernel, ...]
    X: Float[Array, "N D"]
    warp: AbstractBijection | None = None
    latent_noise: float = 1e-3
    jitter: float = 1e-6

    def __check_init__(self) -> None:
        if not self.kernels:
            raise ValueError(
                "kernels must contain at least one latent kernel; an empty "
                "tuple gives Q = 0 and fails inside latent_cholesky."
            )
        _validate_kernel_scopes_unique(self.kernels)
        if self.warp is not None and self.warp.cond_shape is not None:
            raise ValueError(
                "Conditional warps are not supported: the log-det Jacobian "
                "would depend on the inputs, and the per-channel marginal "
                "interpretation no longer holds."
            )

    @property
    def num_latents(self) -> int:
        """Number of latent scalar GPs ``Q``."""
        return len(self.kernels)

    def latent_priors(self) -> tuple[GPPrior, ...]:
        """Return one scalar `pyrox_gp.GPPrior` per latent process."""
        return tuple(
            GPPrior(kernel=k, X=self.X, jitter=self.jitter) for k in self.kernels
        )

    def latent_cholesky(self) -> Float[Array, "Q N N"]:
        """Batched Cholesky factors of the ``Q`` latent GP covariances."""
        n = self.X.shape[0]
        eye = jnp.eye(n, dtype=self.X.dtype)
        with call_contexts(self.kernels):
            covs = jnp.stack(
                [
                    k(self.X, self.X) + (self.latent_noise + self.jitter) * eye
                    for k in self.kernels
                ]
            )
        return jnp.linalg.cholesky(covs)

    def condition(
        self,
        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.

        !!! warning "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.
        """
        if Y.shape[0] != self.X.shape[0]:
            raise ValueError(
                f"Y must have {self.X.shape[0]} rows to match X; got {Y.shape[0]}."
            )
        if Z.shape != (self.X.shape[0], self.num_latents):
            raise ValueError(
                f"Z must have shape {(self.X.shape[0], self.num_latents)}; "
                f"got {Z.shape}."
            )
        if self.warp is None:
            mu_W, Sigma_W = decoder_posterior(Y, Z, noise_var)
        else:
            mu_W, Sigma_W = warped_decoder_posterior(Y, Z, noise_var, self.warp)
        # Condition each latent GP once, here, rather than on every predict
        # call: the training solve is O(N^3) per factor and does not depend
        # on the test inputs. Doing it here also captures the kernel
        # hyperparameters under whatever context the caller conditions in.
        with call_contexts(self.kernels):
            latents = tuple(
                prior.condition(Z[:, q], noise_var=jnp.asarray(self.latent_noise))
                for q, prior in enumerate(self.latent_priors())
            )
        return ConditionedLatentFactorGP(
            prior=self,
            Z=Z,
            mu_W=mu_W,
            Sigma_W=Sigma_W,
            noise_var=noise_var,
            latents=latents,
        )

num_latents: int property

Number of latent scalar GPs Q.

latent_priors() -> tuple[GPPrior, ...]

Return one scalar pyrox_gp.GPPrior per latent process.

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
def latent_priors(self) -> tuple[GPPrior, ...]:
    """Return one scalar `pyrox_gp.GPPrior` per latent process."""
    return tuple(
        GPPrior(kernel=k, X=self.X, jitter=self.jitter) for k in self.kernels
    )

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
def latent_cholesky(self) -> Float[Array, "Q N N"]:
    """Batched Cholesky factors of the ``Q`` latent GP covariances."""
    n = self.X.shape[0]
    eye = jnp.eye(n, dtype=self.X.dtype)
    with call_contexts(self.kernels):
        covs = jnp.stack(
            [
                k(self.X, self.X) + (self.latent_noise + self.jitter) * eye
                for k in self.kernels
            ]
        )
    return jnp.linalg.cholesky(covs)

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
def condition(
    self,
    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.

    !!! warning "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.
    """
    if Y.shape[0] != self.X.shape[0]:
        raise ValueError(
            f"Y must have {self.X.shape[0]} rows to match X; got {Y.shape[0]}."
        )
    if Z.shape != (self.X.shape[0], self.num_latents):
        raise ValueError(
            f"Z must have shape {(self.X.shape[0], self.num_latents)}; "
            f"got {Z.shape}."
        )
    if self.warp is None:
        mu_W, Sigma_W = decoder_posterior(Y, Z, noise_var)
    else:
        mu_W, Sigma_W = warped_decoder_posterior(Y, Z, noise_var, self.warp)
    # Condition each latent GP once, here, rather than on every predict
    # call: the training solve is O(N^3) per factor and does not depend
    # on the test inputs. Doing it here also captures the kernel
    # hyperparameters under whatever context the caller conditions in.
    with call_contexts(self.kernels):
        latents = tuple(
            prior.condition(Z[:, q], noise_var=jnp.asarray(self.latent_noise))
            for q, prior in enumerate(self.latent_priors())
        )
    return ConditionedLatentFactorGP(
        prior=self,
        Z=Z,
        mu_W=mu_W,
        Sigma_W=Sigma_W,
        noise_var=noise_var,
        latents=latents,
    )

ConditionedLatentFactorGP

Bases: Module

Latent-factor posterior — MAP latents plus the decoder posterior.

Attributes:

Name Type Description
prior LatentFactorGPPrior

The pyrox_gp.LatentFactorGPPrior this was conditioned from.

Z Float[Array, 'N Q']

MAP latent factor values at the training inputs, (N, Q).

mu_W Float[Array, 'Q P']

Decoder posterior mean, (Q, P).

Sigma_W Float[Array, 'Q Q']

Decoder posterior row covariance, (Q, Q).

noise_var Float[Array, '']

Scalar isotropic observation noise variance.

latents tuple[ConditionedGP, ...]

One conditioned scalar GP per latent process, built once by LatentFactorGPPrior.condition so the O(Q N^3) training solve is not repeated on every prediction.

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
class ConditionedLatentFactorGP(eqx.Module):
    """Latent-factor posterior — MAP latents plus the decoder posterior.

    Attributes:
        prior: The `pyrox_gp.LatentFactorGPPrior` this was conditioned from.
        Z: MAP latent factor values at the training inputs, ``(N, Q)``.
        mu_W: Decoder posterior mean, ``(Q, P)``.
        Sigma_W: Decoder posterior row covariance, ``(Q, Q)``.
        noise_var: Scalar isotropic observation noise variance.
        latents: One conditioned scalar GP per latent process, built once
            by `LatentFactorGPPrior.condition` so the ``O(Q N^3)``
            training solve is not repeated on every prediction.
    """

    prior: LatentFactorGPPrior
    Z: Float[Array, "N Q"]
    mu_W: Float[Array, "Q P"]
    Sigma_W: Float[Array, "Q Q"]
    noise_var: Float[Array, ""]
    latents: tuple[ConditionedGP, ...]

    def predict_latents(
        self, 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.
        """
        means, variances = [], []
        with call_contexts(self.prior.kernels):
            for cond in self.latents:
                m, v = cond.predict(X_new)
                means.append(m)
                variances.append(v)
        return jnp.stack(means, -1), jnp.stack(variances, -1)

    def predict(
        self,
        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`][pyrox_gp.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.

        !!! warning "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`][pyrox_gp.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.

        Args:
            X_new: Test inputs, shape ``(T, D)``.
            include_noise: Add the observation noise variance. With a
                warp, the noise lives in the warped space, so it is added
                before the pushforward.
            quad_order: Gauss-Hermite order for the warped pushforward, in
                ``[2, 256]``. Ignored when ``warp is None``. A moderate order
                is fine — the quadrature appears only here, never in training.

        Returns:
            Tuple ``(mean, var)`` of marginal moments, each ``(T, P)``.

        Raises:
            ValueError: If ``quad_order`` is outside ``[2, 256]`` with a warp.
        """
        z_mean, z_var = self.predict_latents(X_new)
        # lfr_model gives each latent factor the covariance K + nugget*I,
        # so a factor value at a *new* input carries an independent nugget
        # too. predict_latents returns the smooth GP conditional (there the
        # nugget acts as the noise the MAP factors are observed with), so
        # add it back or the decoder propagates an understated variance.
        z_var = z_var + self.prior.latent_noise
        mean, var = lfr_predictive_moments(
            z_mean,
            z_var,
            self.mu_W,
            self.Sigma_W,
            self.noise_var if include_noise else None,
        )
        warp = self.prior.warp
        if warp is None:
            return mean, var
        return _pushforward_moments(
            jax.vmap(warp.transform), mean, var, order=quad_order
        )

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
def predict_latents(
    self, 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.
    """
    means, variances = [], []
    with call_contexts(self.prior.kernels):
        for cond in self.latents:
            m, v = cond.predict(X_new)
            means.append(m)
            variances.append(v)
    return jnp.stack(means, -1), jnp.stack(variances, -1)

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 (T, D).

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 [2, 256]. Ignored when warp is None. A moderate order is fine — the quadrature appears only here, never in training.

32

Returns:

Type Description
tuple[Float[Array, 'T P'], Float[Array, 'T P']]

Tuple (mean, var) of marginal moments, each (T, P).

Raises:

Type Description
ValueError

If quad_order is outside [2, 256] with a warp.

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor_models.py
def predict(
    self,
    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`][pyrox_gp.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.

    !!! warning "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`][pyrox_gp.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.

    Args:
        X_new: Test inputs, shape ``(T, D)``.
        include_noise: Add the observation noise variance. With a
            warp, the noise lives in the warped space, so it is added
            before the pushforward.
        quad_order: Gauss-Hermite order for the warped pushforward, in
            ``[2, 256]``. Ignored when ``warp is None``. A moderate order
            is fine — the quadrature appears only here, never in training.

    Returns:
        Tuple ``(mean, var)`` of marginal moments, each ``(T, P)``.

    Raises:
        ValueError: If ``quad_order`` is outside ``[2, 256]`` with a warp.
    """
    z_mean, z_var = self.predict_latents(X_new)
    # lfr_model gives each latent factor the covariance K + nugget*I,
    # so a factor value at a *new* input carries an independent nugget
    # too. predict_latents returns the smooth GP conditional (there the
    # nugget acts as the noise the MAP factors are observed with), so
    # add it back or the decoder propagates an understated variance.
    z_var = z_var + self.prior.latent_noise
    mean, var = lfr_predictive_moments(
        z_mean,
        z_var,
        self.mu_W,
        self.Sigma_W,
        self.noise_var if include_noise else None,
    )
    warp = self.prior.warp
    if warp is None:
        return mean, var
    return _pushforward_moments(
        jax.vmap(warp.transform), mean, var, order=quad_order
    )

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, (N, D). Must match prior.X — the latent covariance is built from the prior, so X contributes only shape and dtype and a mismatch is rejected rather than fitted against the wrong locations.

required
Y Float[Array, 'N P']

Centered observations, (N, P).

required
prior LatentFactorGPPrior

The pyrox_gp.LatentFactorGPPrior to fit.

required
beta float | None

Inverse temperature forwarded to lfr_factor; None means Q / P.

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

    Args:
        X: Training inputs, ``(N, D)``. Must match ``prior.X`` — the latent
            covariance is built from the prior, so ``X`` contributes only
            shape and dtype and a mismatch is rejected rather than fitted
            against the wrong locations.
        Y: Centered observations, ``(N, P)``.
        prior: The `pyrox_gp.LatentFactorGPPrior` to fit.
        beta: Inverse temperature forwarded to
            [`lfr_factor`][pyrox_gp.lfr_factor]; ``None`` means ``Q / P``.
        noise_prior_scale: Scale of the half-normal prior on the noise
            standard deviation.

    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`.
    """
    if X.shape != prior.X.shape:
        raise ValueError(
            f"X must be the prior's training inputs, shape {prior.X.shape}; "
            f"got {X.shape}. The latent covariance is built from prior.X, so "
            "a different X would silently pair Y with the wrong locations."
        )
    n = X.shape[0]
    q = prior.num_latents
    Z_T = jnp.asarray(
        numpyro.sample(
            "Z_T",
            dist.MultivariateNormal(
                loc=jnp.zeros((q, n), dtype=X.dtype),
                scale_tril=prior.latent_cholesky(),
            ).to_event(1),
        )
    )
    noise = jnp.asarray(numpyro.sample("noise", dist.HalfNormal(noise_prior_scale)))
    if prior.warp is None:
        warp = None
    else:
        # Register the warp's array leaves as one pytree-valued numpyro.param
        # (the same mechanism numpyro.contrib.module uses for flax/haiku
        # params), so SVI fits the warp jointly with Z, noise, and the
        # kernel hyperparameters.
        params, static = eqx.partition(prior.warp, eqx.is_inexact_array)
        params = numpyro.param("warp_params", params)
        warp = cast(AbstractBijection, eqx.combine(params, static))
    _register_lfr("collapsed_lfr", Y, Z_T.T, noise**2, warp, beta)

lfr_factor(*args, **kwargs) -> None

lfr_factor(name: str, prior: LatentFactorGPPrior, Y: Float[Array, 'N P'], Z: Float[Array, 'N Q'], noise_var: Float[Array, ''], *, beta: float | None = None) -> None
lfr_factor(Y: Float[Array, 'N P'], Z: Float[Array, 'N Q'], noise_var: Float[Array, ''], *, warp: AbstractBijection | None = None, beta: float | None = None, name: str = 'collapsed_lfr') -> 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 LatentFactorGPPrior; its warp (if any) selects the warped likelihood. Its kernels are not evaluated.

required
Y

Observations, (N, P), with N the rows of prior.X.

required
Z

Latent factor values, (N, Q), with Q the prior's latents.

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. None selects Q / P, which keeps the likelihood and the latent GP prior balanced as the output dimension grows. Tune by held-out likelihood when it matters.

required

Raises:

Type Description
ValueError

If Y or Z does not match the prior's shapes.

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
def 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`.

    Args:
        name: NumPyro factor site name.
        prior: The `LatentFactorGPPrior`; its ``warp`` (if any) selects
            the warped likelihood. Its kernels are not evaluated.
        Y: Observations, ``(N, P)``, with ``N`` the rows of ``prior.X``.
        Z: Latent factor values, ``(N, Q)``, with ``Q`` the prior's latents.
        noise_var: Scalar isotropic observation noise variance (in the
            warped space when the prior has a warp).
        beta: Inverse temperature on the likelihood. ``None`` selects
            ``Q / P``, which keeps the likelihood and the latent GP prior
            balanced as the output dimension grows. Tune by held-out
            likelihood when it matters.

    Raises:
        ValueError: If ``Y`` or ``Z`` does not match the prior's shapes.

    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
    """
    if (args and isinstance(args[0], str)) or (not args and "prior" in kwargs):
        _lfr_factor(*args, **kwargs)
        return
    warnings.warn(
        "lfr_factor(Y, Z, noise_var, *, warp=None, beta=None, name=...) is "
        "deprecated; use lfr_factor(name, prior, Y, Z, noise_var, *, beta=None), "
        "which reads the warp from prior.warp.",
        DeprecationWarning,
        stacklevel=2,
    )
    _legacy_lfr_factor(*args, **kwargs)

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 (N, Q).

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
def 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]'``).

    Args:
        Z: MAP latent factor values, shape ``(N, Q)``.

    Returns:
        Scalar total correlation, zero for exactly independent factors.
    """
    from gauss_flows import gaussian_total_correlation

    # jnp.cov collapses to a scalar for a single factor; the total-
    # correlation routine needs a (Q, Q) matrix (and returns zero there).
    return gaussian_total_correlation(jnp.atleast_2d(jnp.cov(Z.T)))

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" (scores of the centred Y, no kernellib call), "kernel_pca" (kernellib.KernelPCA with kernel) or "laplacian_eigenmaps" (kernellib.LaplacianEigenmaps on a n_neighbors-nearest-neighbour graph).

'pca'
kernel AbstractKernel | None

The kernel for "kernel_pca".

None
n_neighbors int

Graph degree for "laplacian_eigenmaps".

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 "kernel_pca" without a kernel.

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

    Args:
        Y: Observations, one row per point.
        n_latent: Latent dimension $Q$.
        method: ``"pca"`` (scores of the centred ``Y``, no kernellib call),
            ``"kernel_pca"`` (`kernellib.KernelPCA` with ``kernel``) or
            ``"laplacian_eigenmaps"`` (`kernellib.LaplacianEigenmaps` on a
            ``n_neighbors``-nearest-neighbour graph).
        kernel: The kernel for ``"kernel_pca"``.
        n_neighbors: Graph degree for ``"laplacian_eigenmaps"``.
        standardize: Scale each column to unit variance, matching the GPLVM
            prior $X \\sim \\mathcal N(0, I_Q)$.

    Returns:
        The latents. Deterministic: each column's sign is fixed so that its
        largest-magnitude entry is positive.

    Raises:
        ValueError: For an unknown method, or ``"kernel_pca"`` without a
            kernel.

    Examples:
        Start a latent-factor model's latents ``Z_T`` (stored transposed,
        ``(Q, N)``) on the data manifold:

        ```python
        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}))
        ```
    """
    Y = jnp.asarray(Y)
    if method == "pca":
        centred = einx.subtract("n d, d -> n d", Y, jnp.mean(Y, axis=0))
        U, s, _ = jnp.linalg.svd(centred, full_matrices=False)
        Z = U[:, :n_latent] * s[:n_latent]
    elif method == "kernel_pca":
        if kernel is None:
            raise ValueError('method="kernel_pca" needs a kernel')
        Z = kl.KernelPCA(kernel, n_components=n_latent).fit(Y).embedding
    elif method == "laplacian_eigenmaps":
        Z = (
            kl.LaplacianEigenmaps(n_components=n_latent, n_neighbors=n_neighbors)
            .fit(Y)
            .embedding
        )
    else:
        raise ValueError(
            "method must be 'pca', 'kernel_pca' or 'laplacian_eigenmaps', "
            f"got {method!r}"
        )
    Z = jnp.asarray(Z)
    peak = jnp.take_along_axis(Z, jnp.argmax(jnp.abs(Z), axis=0)[None, :], axis=0)
    Z = Z * jnp.where(peak < 0, -1.0, 1.0)
    if standardize:
        centred = einx.subtract("n q, q -> n q", Z, jnp.mean(Z, axis=0))
        Z = einx.divide("n q, q -> n q", centred, jnp.std(Z, axis=0))
    return Z

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

\[ p(Y \mid Z, \sigma^2) = \prod_{j=1}^{P} \mathcal{N}(y_j \mid 0,\; ZZ^\top + \sigma^2 I_N) \]

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 (N, P). Assumed centered.

required
Z Float[Array, 'N Q']

Latent factor values at the training inputs, shape (N, Q).

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 noise_var before inversion.

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
def 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

    $$
    p(Y \\mid Z, \\sigma^2) = \\prod_{j=1}^{P}
        \\mathcal{N}(y_j \\mid 0,\\; ZZ^\\top + \\sigma^2 I_N)
    $$

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

    Args:
        Y: Observations of shape ``(N, P)``. Assumed centered.
        Z: Latent factor values at the training inputs, shape ``(N, Q)``.
        noise_var: Scalar isotropic observation noise variance. Per-output
            noise is not supported — it breaks the shared-covariance identity
            the derivation rests on.
        jitter: Added to ``noise_var`` before inversion.

    Returns:
        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
    """
    _check_rows_match(Y, Z)
    _check_scalar_noise(noise_var)
    N, P = Y.shape
    s2 = noise_var + jitter
    c, low = _psi_factor(Z, s2)
    logdet_psi = 2.0 * jnp.sum(jnp.log(jnp.diagonal(c)))
    ZTY = einx.dot("n q, n p -> q p", Z, Y)
    # Cancellation-free quadratic. The direct Woodbury form
    # ``||Y||^2 / s2 - ||Z^T Y||^2_{Psi^-1} / s2^2`` differences two terms of
    # order ``1 / s2`` whose true difference is order one whenever Y lies
    # close to the span of Z, losing most significant digits (and possibly
    # going negative) at small noise in float32. The equivalent penalized
    # residual form is a sum of non-negative terms:
    #   y^T C^-1 y = ||Y - Z W_map||_F^2 / s2 + ||W_map||_F^2,
    # with W_map the decoder posterior mean. Same O(NQP) cost.
    W_map = cho_solve((c, low), ZTY) / s2
    resid = Y - einx.dot("n q, q p -> n p", Z, W_map)
    quad = jnp.sum(resid * resid) / s2 + jnp.sum(W_map * W_map)
    return -0.5 * (
        N * P * jnp.log(2.0 * jnp.pi) + N * P * jnp.log(s2) + P * logdet_psi + quad
    )

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.

\[ p(W \mid Z, Y, \sigma) = \mathcal{MN}_{Q \times P} \big(\sigma^{-2}\Psi^{-1}Z^\top Y,\; \Psi^{-1},\; I_P\big) \]

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 (N, P).

required
Z Float[Array, 'N Q']

Latent factor values, shape (N, Q).

required
noise_var Float[Array, '']

Scalar isotropic observation noise variance.

required
jitter float

Added to noise_var before inversion.

1e-12

Returns:

Type Description
tuple[Float[Array, 'Q P'], Float[Array, 'Q Q']]

Tuple of (mean, row_cov) with shapes (Q, P) and (Q, Q).

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
def 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.

    $$
    p(W \\mid Z, Y, \\sigma) = \\mathcal{MN}_{Q \\times P}
        \\big(\\sigma^{-2}\\Psi^{-1}Z^\\top Y,\\; \\Psi^{-1},\\; I_P\\big)
    $$

    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.

    Args:
        Y: Observations of shape ``(N, P)``.
        Z: Latent factor values, shape ``(N, Q)``.
        noise_var: Scalar isotropic observation noise variance.
        jitter: Added to ``noise_var`` before inversion.

    Returns:
        Tuple of ``(mean, row_cov)`` with shapes ``(Q, P)`` and ``(Q, Q)``.
    """
    _check_rows_match(Y, Z)
    _check_scalar_noise(noise_var)
    s2 = noise_var + jitter
    c, low = _psi_factor(Z, s2)
    mean = cho_solve((c, low), einx.dot("n q, n p -> q p", Z, Y)) / s2
    row_cov = cho_solve((c, low), jnp.eye(Z.shape[1], dtype=Z.dtype))
    return mean, row_cov

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

\[ \mathrm{Var}[f_j] = m^\top \Sigma_W m + \sum_q v_q \mu_{W,qj}^2 + \sum_q v_q \Sigma_{W,qq} \]

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 (T, Q).

required
z_var Float[Array, 'T Q']

Latent predictive marginal variances, shape (T, Q).

required
mu_W Float[Array, 'Q P']

Decoder posterior mean, shape (Q, P).

required
Sigma_W Float[Array, 'Q Q']

Decoder posterior row covariance, shape (Q, Q).

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 (mean, variance), both shape (T, P).

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
def 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

    $$
    \\mathrm{Var}[f_j] = m^\\top \\Sigma_W m
        + \\sum_q v_q \\mu_{W,qj}^2
        + \\sum_q v_q \\Sigma_{W,qq}
    $$

    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.

    Args:
        z_mean: Latent predictive means, shape ``(T, Q)``.
        z_var: Latent predictive marginal variances, shape ``(T, Q)``.
        mu_W: Decoder posterior mean, shape ``(Q, P)``.
        Sigma_W: Decoder posterior row covariance, shape ``(Q, Q)``.
        noise_var: If given, added to the variance for the observation-noise
            predictive rather than the signal predictive.

    Returns:
        Tuple of ``(mean, variance)``, both shape ``(T, P)``.
    """
    mean = einx.dot("t q, q p -> t p", z_mean, mu_W)
    decoder = jnp.sum((z_mean @ Sigma_W) * z_mean, axis=-1, keepdims=True)
    latent = einx.dot("t q, q p -> t p", z_var, mu_W**2)
    cross = z_var @ jnp.diagonal(Sigma_W)[:, None]
    var = decoder + latent + cross
    return mean, var if noise_var is None else var + noise_var

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 (P,) — one marginal transform per output channel. flowjax convention: transform maps base to data, inverse maps data to base, so this uses inverse.

required
Y Float[Array, 'N P']

Observations of shape (N, P).

required

Returns:

Type Description
tuple[Float[Array, 'N P'], Float[Array, '']]

Tuple of (Y_tilde, total_log_det).

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
def 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.

    !!! warning "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.

    Args:
        warp: Elementwise bijection with event shape ``(P,)`` — one marginal
            transform per output channel. flowjax convention:
            ``transform`` maps base to data, ``inverse`` maps data to base,
            so this uses ``inverse``.
        Y: Observations of shape ``(N, P)``.

    Returns:
        Tuple of ``(Y_tilde, total_log_det)``.
    """
    if warp.cond_shape is not None:
        raise ValueError(
            "Conditional warps are not supported here: the log-det Jacobian "
            "would depend on the inputs, and the per-channel marginal "
            "interpretation no longer holds."
        )
    if warp.shape != (Y.shape[1],):
        raise ValueError(
            f"Warp event shape must be (P,) = {(Y.shape[1],)} -- one marginal "
            f"transform per output channel; got {warp.shape}."
        )
    Ytil, log_det = jax.vmap(warp.inverse_and_log_det)(Y)
    return Ytil, jnp.sum(log_det)

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

\[ \log p(Y) = \log p_{\mathrm{collapsed}}(G^{-1}(Y), Z, \sigma^2) + \sum_{n,j} \log \left| \partial G^{-1} / \partial y \right| \]

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 (N, P). Must lie inside the warp's support.

required
Z Float[Array, 'N Q']

Latent factor values at the training inputs, shape (N, Q).

required
noise_var Float[Array, '']

Scalar isotropic observation noise variance, in the warped space.

required
warp AbstractBijection

Bijection with event shape (P,).

required
jitter float

Added to noise_var before inversion.

1e-12

Returns:

Type Description
Float[Array, '']

Scalar log-likelihood.

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
def 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, ""]:
    r"""Collapsed latent-factor log-likelihood on warped observations.

    Models $G^{-1}(y_j) = Z w_j + \epsilon$, so

    $$
    \log p(Y) = \log p_{\mathrm{collapsed}}(G^{-1}(Y), Z, \sigma^2)
              + \sum_{n,j} \log \left| \partial G^{-1} / \partial y \right|
    $$

    The Jacobian term is free of $Z$, $W$ and $\sigma$, so the analytic
    decoder marginalization of
    [`collapsed_lfr_log_prob`][pyrox_gp.collapsed_lfr_log_prob] is
    unchanged and the cost stays linear in $P$.

    !!! warning "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.

    Args:
        Y: Observations of shape ``(N, P)``. Must lie inside the warp's
            support.
        Z: Latent factor values at the training inputs, shape ``(N, Q)``.
        noise_var: Scalar isotropic observation noise variance, in the
            warped space.
        warp: Bijection with event shape ``(P,)``.
        jitter: Added to ``noise_var`` before inversion.

    Returns:
        Scalar log-likelihood.
    """
    Ytil, log_det = warp_to_base(warp, Y)
    return collapsed_lfr_log_prob(Ytil, Z, noise_var, jitter=jitter) + log_det

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 (N, P).

required
Z Float[Array, 'N Q']

Latent factor values, shape (N, Q).

required
noise_var Float[Array, '']

Scalar isotropic observation noise variance, in the warped space.

required
warp AbstractBijection

Bijection with event shape (P,).

required
jitter float

Added to noise_var before inversion.

1e-12

Returns:

Type Description
tuple[Float[Array, 'Q P'], Float[Array, 'Q Q']]

Tuple of (mean, row_cov) with shapes (Q, P) and (Q, Q).

Source code in packages/pyrox-gp/src/pyrox_gp/_latent_factor.py
def 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`][pyrox_gp.decoder_posterior] applied
    to ``G^{-1}(Y)`` -- the warp does not change the conjugacy.

    Args:
        Y: Observations of shape ``(N, P)``.
        Z: Latent factor values, shape ``(N, Q)``.
        noise_var: Scalar isotropic observation noise variance, in the
            warped space.
        warp: Bijection with event shape ``(P,)``.
        jitter: Added to ``noise_var`` before inversion.

    Returns:
        Tuple of ``(mean, row_cov)`` with shapes ``(Q, P)`` and ``(Q, Q)``.
    """
    Ytil, _ = warp_to_base(warp, Y)
    return decoder_posterior(Ytil, Z, noise_var, jitter=jitter)

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
class PathwiseSampler(eqx.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)
    """

    conditioned_gp: ConditionedGP
    n_features: int = eqx.field(static=True, default=512)

    def sample_paths(self, 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.
        """
        rff_key, noise_key, _reserved = jax.random.split(key, 3)

        X = self.conditioned_gp.prior.X
        kernel = self.conditioned_gp.prior.kernel
        # Reuse the resolved (variance, lengthscale) captured by
        # GPPrior.condition under its kernel context. For Pattern B/C
        # kernels the cached operator was built with these exact
        # values; resampling here would put the RFF basis in a
        # different posterior than the cached training solve.
        cached = self.conditioned_gp.resolved_hyperparams
        cached_variance, cached_lengthscale = (
            cached if cached is not None else (None, None)
        )
        variance, lengthscale, omega, phase, feature_weights = draw_rff_cosine_basis(
            kernel,
            rff_key,
            n_paths=n_paths,
            n_features=self.n_features,
            in_features=X.shape[1],
            dtype=X.dtype,
            variance=cached_variance,
            lengthscale=cached_lengthscale,
        )
        prior_train = evaluate_rff_cosine_paths(
            X,
            variance=variance,
            lengthscale=lengthscale,
            omega=omega,
            phase=phase,
            weights=feature_weights,
        )
        mean_train = _broadcast_mean(self.conditioned_gp.prior.mean_fn, X)
        # Matheron requires Cov(eps_tilde) to match the diagonal added to
        # the cached operator. _noisy_operator uses (noise_var + jitter) I,
        # so eps_tilde must have the same variance — otherwise the
        # correction solve is inconsistent and paths are under-dispersed
        # (pronounced when jitter is bumped up for stability).
        noise_var = jnp.asarray(self.conditioned_gp.noise_var, dtype=X.dtype)
        jitter = jnp.asarray(self.conditioned_gp.prior.jitter, dtype=X.dtype)
        eps_var = noise_var + jitter
        noise = jnp.sqrt(eps_var) * jax.random.normal(
            noise_key, shape=(n_paths, X.shape[0]), dtype=X.dtype
        )
        residual = (
            self.conditioned_gp.y[None, :] - (mean_train[None, :] + prior_train) - noise
        )
        # Per-path Matheron correction weights alpha = (K + eps I)^{-1} r,
        # with the solver that produced the cache, so a matrix-free prior
        # never forms K (pyrox#558); None keeps gaussx's structural dispatch.
        # The preconditioner depends on the operator only, so under the vmap
        # over paths it is built once for the batch.
        prior = self.conditioned_gp.prior
        correction_weights = solve_rows(
            self.conditioned_gp.operator,
            residual,
            solver=None if prior.solver is None else prior.solver_strategy(),
        )
        return PathwiseFunction(
            kernel_fn=_frozen_kernel_fn(kernel, variance, lengthscale),
            correction_points=X,
            correction_weights=correction_weights,
            omega=omega,
            phase=phase,
            feature_weights=feature_weights,
            variance=variance,
            lengthscale=lengthscale,
            mean_fn=self.conditioned_gp.prior.mean_fn,
        )

    def __call__(
        self,
        key: Array,
        X_star: Float[Array, "N D"],
        n_paths: int = 1,
    ) -> Float[Array, "S N"]:
        """Convenience wrapper for ``sample_paths(key, n_paths)(X_star)``."""
        return self.sample_paths(key, n_paths=n_paths)(X_star)

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
def sample_paths(self, 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.
    """
    rff_key, noise_key, _reserved = jax.random.split(key, 3)

    X = self.conditioned_gp.prior.X
    kernel = self.conditioned_gp.prior.kernel
    # Reuse the resolved (variance, lengthscale) captured by
    # GPPrior.condition under its kernel context. For Pattern B/C
    # kernels the cached operator was built with these exact
    # values; resampling here would put the RFF basis in a
    # different posterior than the cached training solve.
    cached = self.conditioned_gp.resolved_hyperparams
    cached_variance, cached_lengthscale = (
        cached if cached is not None else (None, None)
    )
    variance, lengthscale, omega, phase, feature_weights = draw_rff_cosine_basis(
        kernel,
        rff_key,
        n_paths=n_paths,
        n_features=self.n_features,
        in_features=X.shape[1],
        dtype=X.dtype,
        variance=cached_variance,
        lengthscale=cached_lengthscale,
    )
    prior_train = evaluate_rff_cosine_paths(
        X,
        variance=variance,
        lengthscale=lengthscale,
        omega=omega,
        phase=phase,
        weights=feature_weights,
    )
    mean_train = _broadcast_mean(self.conditioned_gp.prior.mean_fn, X)
    # Matheron requires Cov(eps_tilde) to match the diagonal added to
    # the cached operator. _noisy_operator uses (noise_var + jitter) I,
    # so eps_tilde must have the same variance — otherwise the
    # correction solve is inconsistent and paths are under-dispersed
    # (pronounced when jitter is bumped up for stability).
    noise_var = jnp.asarray(self.conditioned_gp.noise_var, dtype=X.dtype)
    jitter = jnp.asarray(self.conditioned_gp.prior.jitter, dtype=X.dtype)
    eps_var = noise_var + jitter
    noise = jnp.sqrt(eps_var) * jax.random.normal(
        noise_key, shape=(n_paths, X.shape[0]), dtype=X.dtype
    )
    residual = (
        self.conditioned_gp.y[None, :] - (mean_train[None, :] + prior_train) - noise
    )
    # Per-path Matheron correction weights alpha = (K + eps I)^{-1} r,
    # with the solver that produced the cache, so a matrix-free prior
    # never forms K (pyrox#558); None keeps gaussx's structural dispatch.
    # The preconditioner depends on the operator only, so under the vmap
    # over paths it is built once for the batch.
    prior = self.conditioned_gp.prior
    correction_weights = solve_rows(
        self.conditioned_gp.operator,
        residual,
        solver=None if prior.solver is None else prior.solver_strategy(),
    )
    return PathwiseFunction(
        kernel_fn=_frozen_kernel_fn(kernel, variance, lengthscale),
        correction_points=X,
        correction_weights=correction_weights,
        omega=omega,
        phase=phase,
        feature_weights=feature_weights,
        variance=variance,
        lengthscale=lengthscale,
        mean_fn=self.conditioned_gp.prior.mean_fn,
    )

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
class DecoupledPathwiseSampler(eqx.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)
    """

    prior: SparseGPPrior
    guide: Guide
    n_features: int = eqx.field(static=True, default=512)

    def __check_init__(self) -> None:
        if self.prior.Z is None:
            raise ValueError(
                "DecoupledPathwiseSampler currently requires a point-inducing "
                "SparseGPPrior constructed with `Z=...`. Inducing-feature "
                "priors (FourierInducingFeatures, SphericalHarmonicInducingFeatures, "
                "LaplacianInducingFeatures) are not yet supported."
            )

    def sample_paths(self, 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.
        """
        rff_key, guide_key, jitter_key = jax.random.split(key, 3)

        Z = self.prior.Z
        assert Z is not None  # __check_init__ guarantees
        with call_context(self.prior.kernel):
            basis = draw_rff_cosine_basis(
                self.prior.kernel,
                rff_key,
                n_paths=n_paths,
                n_features=self.n_features,
                in_features=Z.shape[1],
                dtype=Z.dtype,
            )
            variance, lengthscale, omega, phase, feature_weights = basis
            prior_inducing = evaluate_rff_cosine_paths(
                Z,
                variance=variance,
                lengthscale=lengthscale,
                omega=omega,
                phase=phase,
                weights=feature_weights,
            )
            inducing_op = self.prior.inducing_operator()

        # See docstring: u_tilde must have covariance K_zz + jitter I.
        jitter = jnp.asarray(self.prior.jitter, dtype=Z.dtype)
        prior_inducing = prior_inducing + jnp.sqrt(jitter) * jax.random.normal(
            jitter_key, shape=prior_inducing.shape, dtype=Z.dtype
        )

        guide_keys = jax.random.split(guide_key, n_paths)
        guide_samples = jax.vmap(self.guide.sample)(guide_keys)
        if isinstance(self.guide, WhitenedGuide):
            inducing_chol = cholesky(inducing_op)
            inducing_samples = jax.vmap(lambda sample: unwhiten(sample, inducing_chol))(
                guide_samples
            )
        else:
            inducing_samples = guide_samples

        # Per-path Matheron correction weights, with the prior's solver and
        # preconditioner (None keeps gaussx's structural dispatch).
        correction_weights = solve_rows(
            inducing_op,
            inducing_samples - prior_inducing,
            solver=None if self.prior.solver is None else self.prior.solver_strategy(),
        )
        return PathwiseFunction(
            kernel_fn=_frozen_kernel_fn(self.prior.kernel, variance, lengthscale),
            correction_points=Z,
            correction_weights=correction_weights,
            omega=omega,
            phase=phase,
            feature_weights=feature_weights,
            variance=variance,
            lengthscale=lengthscale,
            mean_fn=self.prior.mean_fn,
        )

    def __call__(
        self,
        key: Array,
        X_star: Float[Array, "N D"],
        n_paths: int = 1,
    ) -> Float[Array, "S N"]:
        """Convenience wrapper for ``sample_paths(key, n_paths)(X_star)``."""
        return self.sample_paths(key, n_paths=n_paths)(X_star)

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
def sample_paths(self, 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.
    """
    rff_key, guide_key, jitter_key = jax.random.split(key, 3)

    Z = self.prior.Z
    assert Z is not None  # __check_init__ guarantees
    with call_context(self.prior.kernel):
        basis = draw_rff_cosine_basis(
            self.prior.kernel,
            rff_key,
            n_paths=n_paths,
            n_features=self.n_features,
            in_features=Z.shape[1],
            dtype=Z.dtype,
        )
        variance, lengthscale, omega, phase, feature_weights = basis
        prior_inducing = evaluate_rff_cosine_paths(
            Z,
            variance=variance,
            lengthscale=lengthscale,
            omega=omega,
            phase=phase,
            weights=feature_weights,
        )
        inducing_op = self.prior.inducing_operator()

    # See docstring: u_tilde must have covariance K_zz + jitter I.
    jitter = jnp.asarray(self.prior.jitter, dtype=Z.dtype)
    prior_inducing = prior_inducing + jnp.sqrt(jitter) * jax.random.normal(
        jitter_key, shape=prior_inducing.shape, dtype=Z.dtype
    )

    guide_keys = jax.random.split(guide_key, n_paths)
    guide_samples = jax.vmap(self.guide.sample)(guide_keys)
    if isinstance(self.guide, WhitenedGuide):
        inducing_chol = cholesky(inducing_op)
        inducing_samples = jax.vmap(lambda sample: unwhiten(sample, inducing_chol))(
            guide_samples
        )
    else:
        inducing_samples = guide_samples

    # Per-path Matheron correction weights, with the prior's solver and
    # preconditioner (None keeps gaussx's structural dispatch).
    correction_weights = solve_rows(
        inducing_op,
        inducing_samples - prior_inducing,
        solver=None if self.prior.solver is None else self.prior.solver_strategy(),
    )
    return PathwiseFunction(
        kernel_fn=_frozen_kernel_fn(self.prior.kernel, variance, lengthscale),
        correction_points=Z,
        correction_weights=correction_weights,
        omega=omega,
        phase=phase,
        feature_weights=feature_weights,
        variance=variance,
        lengthscale=lengthscale,
        mean_fn=self.prior.mean_fn,
    )

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

\[ f_{\text{post}}(x_*) = \tilde{f}(x_*) + K(x_*,\, X_{\mathrm{corr}})\,\alpha + \mu(x_*), \]

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
class PathwiseFunction(eqx.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

    $$
    f_{\\text{post}}(x_*) =
        \\tilde{f}(x_*)
        + K(x_*,\\, X_{\\mathrm{corr}})\\,\\alpha
        + \\mu(x_*),
    $$

    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)
    """

    kernel_fn: Callable[
        [Float[Array, "N1 D"], Float[Array, "N2 D"]], Float[Array, "N1 N2"]
    ]
    correction_points: Float[Array, "R D"]
    correction_weights: Float[Array, "S R"]
    omega: Float[Array, "S D F"]
    phase: Float[Array, "S F"]
    feature_weights: Float[Array, "S F"]
    variance: Float[Array, ""]
    lengthscale: Float[Array, ""]
    mean_fn: Callable[[Float[Array, "N D"]], Float[Array, " N"]] | None = None

    def __call__(self, X_star: Float[Array, "N D"]) -> Float[Array, "S N"]:
        """Evaluate the sampled function(s) at arbitrary inputs ``X_star``."""
        prior = evaluate_rff_cosine_paths(
            X_star,
            variance=self.variance,
            lengthscale=self.lengthscale,
            omega=self.omega,
            phase=self.phase,
            weights=self.feature_weights,
        )
        K_cross = self.kernel_fn(X_star, self.correction_points)
        # Matheron correction: contract the correction-point axis r,
        # broadcasting over sample paths s → (S, N).
        update = einx.dot("n r, s r -> s n", K_cross, self.correction_weights)
        mean = _broadcast_mean(self.mean_fn, X_star)
        return prior + update + mean[None, :]

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 from q(f); log_prob(self, f) evaluates log q(f). Neither touches the NumPyro trace.
  • register(name, prior) (optional) — the NumPyro-integration hook invoked by pyrox_gp.gp_sample when a guide is supplied. Use it to register a sample / param site (or compose one out of guide state) under name and return the latent function value. Concrete guides that participate in gp_sample should 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
class Guide(eqx.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 from ``q(f)``;
      ``log_prob(self, f)`` evaluates ``log q(f)``. Neither touches the
      NumPyro trace.
    * ``register(name, prior)`` (optional) — the NumPyro-integration hook
      invoked by `pyrox_gp.gp_sample` when a guide is supplied. Use
      it to register a sample / param site (or compose one out of guide
      state) under ``name`` and return the latent function value. Concrete
      guides that participate in `gp_sample` should 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,)
    """

    @abstractmethod
    def sample(self, key: Any) -> Float[Array, " ..."]:
        raise NotImplementedError

    @abstractmethod
    def log_prob(self, f: Float[Array, " ..."]) -> Float[Array, ""]:
        raise NotImplementedError

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
class Likelihood(eqx.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...
    """

    @abstractmethod
    def log_prob(
        self,
        f: Float[Array, " ..."],
        y: Float[Array, " ..."],
        X: Float[Array, " ..."] | None = None,
    ) -> Float[Array, ""]:
        """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.
        """
        raise NotImplementedError

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
@abstractmethod
def log_prob(
    self,
    f: Float[Array, " ..."],
    y: Float[Array, " ..."],
    X: Float[Array, " ..."] | None = None,
) -> Float[Array, ""]:
    """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.
    """
    raise NotImplementedError

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.