Likelihoods API¶
The pyrox.likelihoods module holds the protocols that every observation model and variational guide in the pyrox packages subclasses, so a package built on the core can take a pyrox likelihood without depending on pyrox-gp. It carries no numerics: expectations and per-site derivatives of a likelihood are computed by gaussx in the packages that need them. pyrox_gp re-exports the protocols, so pyrox_gp.Likelihood is pyrox.likelihoods.Likelihood.
Protocols¶
Likelihood
¶
Bases: Module
Abstract base for observation models.
Implements the conditional p(y | f), summed over points. The advanced
inference strategies in pyrox-gp integrate log p(y | f) against a
Gaussian cavity via any gaussx.AbstractIntegrator. Concrete
scalar-latent likelihoods (GaussianLikelihood here;
BernoulliLikelihood, PoissonLikelihood, StudentTLikelihood in
pyrox-gp) and multi-latent ones (SoftmaxLikelihood,
HeteroscedasticGaussianLikelihood) subclass it.
Multi-latent likelihoods declare latent_dim: int as a static
field (e.g. latent_dim = num_classes for softmax). Scalar
likelihoods may omit the field; consumers should read
getattr(lik, "latent_dim", 1).
Examples:
A Laplace observation model with unit scale:
>>> import jax.numpy as jnp
>>> from pyrox.likelihoods import Likelihood
>>> class LaplaceLikelihood(Likelihood):
... def log_prob(self, f, y, X=None):
... return jnp.sum(-jnp.abs(y - f) - jnp.log(2.0))
>>> float(LaplaceLikelihood().log_prob(jnp.zeros(2), jnp.zeros(2)))
-1.386...
Source code in packages/pyrox/src/pyrox/likelihoods.py
log_prob(f: Float[Array, ' ...'], y: Float[Array, ' ...'], X: Float[Array, ' ...'] | None = None) -> Float[Array, '']
abstractmethod
¶
Conditional p(y | f), optionally conditioned on inputs.
X is consumed only by likelihoods whose parameters are
functions of the input (see pyrox_gp.WarpedGaussianLikelihood
with a conditional warp). Scalar observation models ignore it.
Source code in packages/pyrox/src/pyrox/likelihoods.py
Guide
¶
Bases: Module
Abstract base for variational posterior families.
Concrete guides (DeltaGuide, MeanFieldGuide, LowRankGuide,
FullRankGuide, etc.) live in pyrox-gp. The whitening principle keeps
optimization geometry well-conditioned — sample from a unit-scale latent
and unwhiten with the prior Cholesky.
Two distinct entry points:
sample/log_prob— pure variational draws and densities.sample(self, key)returns a draw fromq(f);log_prob(self, f)evaluateslog q(f). Neither touches the NumPyro trace.register(name, prior)(optional) — the NumPyro-integration hook invoked bypyrox_gp.gp_samplewhen a guide is supplied. Use it to register a sample / param site (or compose one out of guide state) undernameand return the latent function value. Concrete guides that participate ingp_sampleshould implement this; the protocol leaves it unspecified so guides usable purely outside NumPyro stay valid.
Examples:
A point-mass guide at a fixed vector:
>>> import jax.numpy as jnp
>>> from pyrox.likelihoods import Guide
>>> class PointGuide(Guide):
... loc: jnp.ndarray
... def sample(self, key):
... return self.loc
... def log_prob(self, f):
... return jnp.asarray(0.0)
>>> PointGuide(jnp.zeros(3)).sample(None).shape
(3,)
Source code in packages/pyrox/src/pyrox/likelihoods.py
Observation models¶
AbstractObservation is the base of an observation model that declares its own hyperparameters and builds a gaussx likelihood holding the data; latent_dim (1 by default) is the number of latents per site. pyrox_lgm re-exports it, so pyrox_lgm.AbstractObservation is pyrox.likelihoods.AbstractObservation.
pyrox-gp's likelihoods are observation models too: each one's build(y, theta, data) returns the gaussx likelihood below, with the inputs in data["X"], and log_prob(f, y, X) evaluates it. pyrox_gp.GaussianLikelihood subclasses pyrox.likelihoods.GaussianLikelihood, so the closed-form paths that dispatch on the core class take it.
| pyrox name | gaussx likelihood it builds |
|---|---|
pyrox_gp.GaussianLikelihood |
gaussx.GaussianLikelihood |
pyrox_gp.BernoulliLikelihood |
gaussx.BernoulliLikelihood |
pyrox_gp.PoissonLikelihood |
gaussx.PoissonLikelihood |
pyrox_gp.StudentTLikelihood |
gaussx.StudentTLikelihood |
pyrox_gp.SoftmaxLikelihood |
gaussx.SoftmaxLikelihood |
pyrox_gp.HeteroscedasticGaussianLikelihood |
gaussx.HeteroscedasticGaussianLikelihood |
AbstractObservation
¶
Bases: Module
Observation model \(p(y \mid \eta, \theta)\) with its own hyperparameters.
An observation model declares its hyperparameters \(\theta\) (theta_spec)
and builds, for data y at a given \(\theta\), the gaussx likelihood
that inference runs on (build). Per-site data other than y
(offsets, trial counts, inputs) passes through data. The per-site
methods (site_distribution, site_log_prob, site_cdf) evaluate
\(p(y_i \mid \eta_i, \theta)\) directly, for diagnostics. pyrox-lgm's
observation models (pyrox_lgm.Gaussian, pyrox_lgm.Poisson, …)
subclass it, and pyrox_lgm.AbstractObservation is this class.
The linear predictor eta has shape (N,) when latent_dim is 1
(the default) and (N, latent_dim) otherwise: one row of latents per
site, as for a softmax over \(K\) classes (latent_dim = K) or a
heteroscedastic Gaussian (latent_dim = 2). A subclass changes it by
overriding the property, or with a static field that has a default
(latent_dim: int = eqx.field(static=True, default=2)).
The class registers no NumPyro sites, and the core imports no gaussx:
build is annotated Any, and a subclass returns a
gaussx.AbstractLikelihood. The one exception is the core's own
DistLikelihood, whose build returns the two arguments of
gaussx.CallableLikelihood for the gaussx-backed packages to wrap.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
AbstractVar[str]
|
Prefix of the hyperparameter names, which join \(\theta\) as
|
Examples:
A heteroscedastic Gaussian with two latents per site, the mean and
the noise scale before a softplus (gaussx's likelihood takes the two
latent columns concatenated, eta.T.reshape(-1)):
>>> import equinox as eqx
>>> import jax
>>> import jax.numpy as jnp
>>> import numpyro.distributions as dist
>>> from pyrox.likelihoods import AbstractObservation
>>> class Heteroscedastic(AbstractObservation):
... name: str = eqx.field(static=True, default="lik")
... @property
... def latent_dim(self):
... return 2
... def build(self, y, theta, data):
... import gaussx as gx
... return gx.HeteroscedasticGaussianLikelihood(y)
... def site_distribution(self, eta, theta, data):
... return dist.Normal(eta[:, 0], jax.nn.softplus(eta[:, 1]))
>>> obs = Heteroscedastic()
>>> eta = jnp.zeros((3, obs.latent_dim))
>>> obs.site_log_prob(jnp.zeros(3), eta, {}, {}).shape
(3,)
Source code in packages/pyrox/src/pyrox/likelihoods.py
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 | |
latent_dim: int
property
¶
Latents per site: the trailing size of eta; 1 by default.
theta_spec() -> dict[str, tuple[nd.Distribution, Transform]]
¶
Hyperparameters of the likelihood; none by default.
Returns:
| Type | Description |
|---|---|
dict[str, tuple[Distribution, Transform]]
|
|
dict[str, tuple[Distribution, Transform]]
|
unconstrained value to the prior's support. |
Source code in packages/pyrox/src/pyrox/likelihoods.py
build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> Any
abstractmethod
¶
The gaussx likelihood holding y at hyperparameters theta.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Array
|
Observations, |
required |
theta
|
dict[str, Array]
|
Hyperparameters, keyed as in |
required |
data
|
Mapping[str, ArrayLike]
|
Per-site data other than |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A |
Any
|
|
Any
|
|
Any
|
|
Source code in packages/pyrox/src/pyrox/likelihoods.py
site_distribution(eta: Float[Array, ' N'] | Float[Array, 'N L'], theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> nd.Distribution
¶
p(y_i | eta_i) per site as a NumPyro distribution (batched in eta).
eta is (N,) for one latent per site and (N, latent_dim)
otherwise. Diagnostics may evaluate it on quadrature nodes, so for
one latent eta may carry trailing axes after the sites'
(broadcast per-site data against them). Only diagnostics need it
(pyrox_lgm.diagnostics), so an observation model that does not
define it still fits.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Unless a subclass defines it. |
Source code in packages/pyrox/src/pyrox/likelihoods.py
site_log_prob(y: Array, eta: Float[Array, ' N'] | Float[Array, 'N L'], theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> Array
¶
log p(y_i | eta_i) per site, from site_distribution.
Source code in packages/pyrox/src/pyrox/likelihoods.py
site_cdf(y: Array, eta: Float[Array, ' N'] | Float[Array, 'N L'], theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> Array
¶
P(Y_i <= y_i | eta_i) per site, from site_distribution.
Source code in packages/pyrox/src/pyrox/likelihoods.py
Bring your own likelihood¶
DistLikelihood turns a NumPyro distribution into an observation model, for a likelihood gaussx has no class for (a zero-inflated Poisson, a Beta, a censored Gaussian). Pass make_dist(eta_i, theta, data_i), which returns site \(i\)'s distribution of \(y_i\), and the hyperparameters it reads as theta:
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},
)
Its log density is the distribution's log_prob, site by site. The core imports no gaussx, so build(y, theta, data) does not return a gaussx likelihood as the other observation models do: it returns the per-site log density and data that gaussx.CallableLikelihood takes. pyrox-gp's inference (Laplace, Gauss-Newton, posterior linearisation, EP, the SVGP expected log likelihood, CVI) and pyrox-ssm's Markov strategies wrap that pair as gaussx.CallableLikelihood(*zip_lik.build(y, {}, data)), so they take its site derivatives and expectations from gaussx. The inputs reach make_dist as data_i["X"].
theta holds arrays that are leaves of the module, so they receive gradients and can be NumPyro sample values: inside a model, DistLikelihood(make_dist, theta={"pi": numpyro.sample("pi", dist.Beta(2.0, 4.0))}) passed to pyrox_ssm.markov_laplace_factor puts the gate under NUTS. make_dist itself is a static field, so a parameter it closes over never trains. make_dist must return one site's distribution for one site's inputs, and log_prob(f, y, X) calls it on every site at once, so it should broadcast over a leading site axis as NumPyro distributions do.
pyrox_gp.DistLikelihood is this class. The old one-argument link, DistLikelihood(lambda f: dist.Bernoulli(logits=f)), still works and ignores theta and the inputs; DistLikelihood(dist_fn=...) warns and points to make_dist.
DistLikelihood
¶
Bases: AbstractObservation, Likelihood
Observation model over any NumPyro distribution, \(p(y_i \mid \eta_i, \theta)\).
The user's make_dist(eta_i, theta, data_i) returns site \(i\)'s
distribution, and its log_prob is the per-site log density
so a likelihood gaussx has no class for (zero-inflated Poisson, Beta, a censored Gaussian) gets Laplace, EP and the Markov strategies.
The core imports no gaussx, so build does not return a gaussx
likelihood, unlike other observation models: it returns the pair
(log_density, data) that gaussx.CallableLikelihood takes, where
log_density(eta_i, d_i) is \(\ell\) and data is
{"y": y, "data": data}, every leaf with a leading site axis of
length \(N\). pyrox-gp's inference and pyrox-ssm's strategies recognise a
DistLikelihood and wrap the pair as
gaussx.CallableLikelihood(*lik.build(y, theta, data)), which gives
the per-site derivatives and expectations. log_prob(f, y, X) and the
per-site diagnostics (site_distribution) call make_dist on every
site at once, so make_dist must broadcast over a leading site axis,
as NumPyro distributions do; index inputs from the end
(data_i["X"][..., 0]).
The hyperparameters \(\theta\) that make_dist reads are the theta
field, updated key by key by the theta passed to build (pyrox-gp
and pyrox-ssm pass none). They are array leaves of the module, so they
receive gradients and may be NumPyro sample values. pyrox-gp and
pyrox-ssm pass the inputs as data_i = {"X": x_i}. pyrox_lgm.inla
does not take a DistLikelihood yet: it uses what build returns as a
gaussx likelihood. The class registers no NumPyro sites.
The old one-argument link DistLikelihood(lambda f: dist.Bernoulli(logits=f))
still works: a callable with exactly one required positional argument is
wrapped to ignore theta and data_i, keeping the defaults of any
optional ones (lambda f, df=3.0: ...), so a make_dist must take
theta and data_i without defaults. DistLikelihood(dist_fn=...)
warns and always does the same.
The callable cannot carry trainable parameters
make_dist is a static field, so anything it closes over is
invisible to eqx.filter_grad and silently never trains. Put
scalar hyperparameters in theta; for a parameterized link (a
warp, a network), write a Likelihood subclass holding it as a
child module.
Attributes:
| Name | Type | Description |
|---|---|---|
make_dist |
Callable[..., Distribution]
|
|
theta |
dict[str, Array]
|
Hyperparameter values |
name |
str
|
Prefix of the hyperparameter names ( |
Examples:
A zero-inflated Poisson with gate \(\pi\), and the gaussx likelihood a gaussx-backed package wraps it into:
>>> import gaussx as gx
>>> import jax.numpy as jnp
>>> import numpyro.distributions as dist
>>> from pyrox.likelihoods import DistLikelihood
>>> zip_lik = DistLikelihood(
... lambda eta, th, d: dist.ZeroInflatedPoisson(
... gate=th["pi"], rate=jnp.exp(eta)
... ),
... theta={"pi": 0.2},
... )
>>> y = jnp.array([0.0, 2.0, 1.0])
>>> site_lik = gx.CallableLikelihood(*zip_lik.build(y, {}, {}))
>>> g, h = site_lik.site_derivatives(jnp.zeros(3))
>>> g.shape, h.shape
((3,), (3,))
The old one-argument link:
>>> lik = DistLikelihood(lambda f: dist.Bernoulli(logits=f))
>>> float(lik.log_prob(jnp.zeros(2), jnp.array([1.0, 0.0])))
-1.386...
Source code in packages/pyrox/src/pyrox/likelihoods.py
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 | |
dist_fn: Callable[[Array], nd.Distribution]
property
¶
Deprecated: the one-argument link f -> Distribution; use make_dist.
The old one-argument callable when one was passed, else make_dist
at the theta field with empty data.
build(y: Array, theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> tuple[Callable[[Float[Array, ''], PyTree], Float[Array, '']], PyTree]
¶
The per-site log density and data that gaussx.CallableLikelihood takes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Array
|
Observations, |
required |
theta
|
dict[str, Array]
|
Hyperparameters, overriding the |
required |
data
|
Mapping[str, ArrayLike]
|
Per-site data other than |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Float[Array, ''], PyTree], Float[Array, '']]
|
|
PyTree
|
\(\log p(y_i \mid \eta_i, \theta, \mathrm{data}_i)\) for a scalar |
tuple[Callable[[Float[Array, ''], PyTree], Float[Array, '']], PyTree]
|
|
tuple[Callable[[Float[Array, ''], PyTree], Float[Array, '']], PyTree]
|
|
Source code in packages/pyrox/src/pyrox/likelihoods.py
site_distribution(eta: Float[Array, ' N'], theta: dict[str, Array], data: Mapping[str, ArrayLike]) -> nd.Distribution
¶
make_dist on every site at once (batched in eta).
Source code in packages/pyrox/src/pyrox/likelihoods.py
log_prob(f: Float[Array, ' ...'], y: Float[Array, ' ...'], X: Float[Array, ' ...'] | None = None) -> Float[Array, '']
¶
\(\sum_i \log p(y_i \mid f_i)\), with the inputs in data["X"].
Source code in packages/pyrox/src/pyrox/likelihoods.py
Gaussian observations¶
GaussianLikelihood
¶
Bases: Likelihood
Gaussian observation model \(p(y \mid f) = N(y \mid f, \sigma^2)\).
The only likelihood with a closed-form expected log-likelihood,
enabling the analytical Titsias ELBO via
gaussx.variational_elbo_gaussian.
Attributes:
| Name | Type | Description |
|---|---|---|
noise_var |
float | Float[Array, '']
|
Observation noise variance \(\sigma^2\). |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox.likelihoods import GaussianLikelihood
>>> lik = GaussianLikelihood(noise_var=1.0)
>>> float(lik.log_prob(jnp.zeros(1), jnp.zeros(1)))
-0.918...
Source code in packages/pyrox/src/pyrox/likelihoods.py
log_prob(f: Float[Array, ' ...'], y: Float[Array, ' ...'], X: Float[Array, ' ...'] | None = None) -> Float[Array, '']
¶
Sum of per-point Gaussian log-densities.
Source code in packages/pyrox/src/pyrox/likelihoods.py
Helpers¶
likelihood_accepts_inputs(lik: Likelihood) -> bool
¶
Whether lik.log_prob takes the optional trailing X.
The protocol widened in gh-204 to carry the inputs an
input-dependent observation model conditions on. Third-party
Likelihood subclasses written against the original
log_prob(self, f, y) are still concrete and valid, and handing
one a third positional argument raises TypeError at the first
quadrature evaluation -- so probe rather than assume.
Static Python on the unbound signature, evaluated once per trace, so
it costs nothing under jit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lik
|
Likelihood
|
The likelihood to probe. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Examples:
>>> from pyrox.likelihoods import GaussianLikelihood, likelihood_accepts_inputs
>>> likelihood_accepts_inputs(GaussianLikelihood(noise_var=1.0))
True