Skip to content

Full-Rank BLR

The exact end of the spectrum: a dense precision matrix \(\Lambda \in \mathbb{R}^{d \times d}\) over flat parameter vectors. With an exact-Hessian callable the fixed point is the exact Gaussian posterior of a conjugate model, which makes this variant the reference implementation the cheaper families are tested against. Solves go through gaussx.solve (requires the optional gaussx extra).

Transforms

blr_full_rank_for_loss(learning_rate: float = 0.01, prior_precision: float = 0.0001, prior_mean: jnp.ndarray | None = None, hessian_estimator: str | Callable = 'ggn', damping: float = 1e-06, solver: Solver | None = None) -> optax.GradientTransformation

Full-rank BLR accepting standard loss gradients.

Wraps blr_full_rank: negates incoming gradients (\(g_{\text{loglik}} = -g_{\text{loss}}\)) and, for callable Hessian estimators, negates the returned matrix so the inner BLR transform receives log-likelihood Hessians.

Parameters:

Name Type Description Default
learning_rate float

Step size rho in (0, 1].

0.01
prior_precision float

Scalar multiplied by I to form Lambda_0.

0.0001
prior_mean ndarray | None

Prior mean vector (d,), or None for zeros.

None
hessian_estimator str | Callable

"ggn", "identity", or a callable fn(mean, grads) -> (d, d) returning the loss Hessian.

'ggn'
damping float

Additive damping epsilon * I.

1e-06
solver Solver | None

Optional lineax solver or gaussx solver strategy.

None

Returns:

Type Description
GradientTransformation

An optax.GradientTransformation.

Source code in src/optax_bayes/_src/wrappers.py
def blr_full_rank_for_loss(
    learning_rate: float = 1e-2,
    prior_precision: float = 1e-4,
    prior_mean: jnp.ndarray | None = None,
    hessian_estimator: str | Callable = "ggn",
    damping: float = 1e-6,
    solver: Solver | None = None,
) -> optax.GradientTransformation:
    r"""Full-rank BLR accepting standard loss gradients.

    Wraps [`blr_full_rank`][optax_bayes.blr_full_rank]: negates incoming
    gradients ($g_{\text{loglik}} = -g_{\text{loss}}$) and, for callable
    Hessian estimators, negates the returned matrix so the inner BLR
    transform receives log-likelihood Hessians.

    Args:
        learning_rate: Step size rho in (0, 1].
        prior_precision: Scalar multiplied by I to form Lambda_0.
        prior_mean: Prior mean vector (d,), or None for zeros.
        hessian_estimator: ``"ggn"``, ``"identity"``, or a callable
            ``fn(mean, grads) -> (d, d)`` returning the **loss** Hessian.
        damping: Additive damping epsilon * I.
        solver: Optional ``lineax`` solver or ``gaussx`` solver strategy.

    Returns:
        An ``optax.GradientTransformation``.
    """
    return _wrap_for_loss(
        blr_full_rank(
            learning_rate=learning_rate,
            prior_precision=prior_precision,
            prior_mean=prior_mean,
            hessian_estimator=_negate_hessian_for_loss(hessian_estimator),
            damping=damping,
            solver=solver,
        )
    )

blr_full_rank(learning_rate: float = 0.01, prior_precision: float = 0.0001, prior_mean: jnp.ndarray | None = None, hessian_estimator: str | Callable = 'ggn', damping: float = 1e-06, solver: Solver | None = None) -> optax.GradientTransformation

Full-rank Gaussian BLR as an optax transform.

Implements the Bayesian Learning Rule (Khan & Rue, 2023) with a full-rank Gaussian variational family \(q(\theta) = \mathcal{N}(m, \Lambda^{-1})\) over flat parameter vectors \(\theta \in \mathbb{R}^d\). Optimizer state stores the precision matrix \(\Lambda\) ((d, d)) and the natural mean \(\eta = \Lambda m\) ((d,)), updated as

\[ \begin{aligned} \Lambda_{t+1} &= (1 - \rho)\, \Lambda_t + \rho\, (\Lambda_0 - H_t) \\ \eta_{t+1} &= (1 - \rho)\, \eta_t + \rho\, (\eta_0 + g_t - H_t m_t) \end{aligned} \]

with \(g_t\) the log-likelihood gradient and \(H_t \preceq 0\) the Hessian estimate. With the exact Hessian, the fixed point is the exact Gaussian posterior of a conjugate model. The state initialises its mean at the params passed to init; prior_mean and prior_precision anchor every update.

Uses gaussx.solve for the precision solve at each step (requires the optional gaussx extra).

This API expects log-likelihood gradients. For standard loss minimisation, use blr_full_rank_for_loss instead.

Parameters:

Name Type Description Default
learning_rate float

Step size rho in (0, 1].

0.01
prior_precision float

Scalar multiplied by I to form Lambda_0.

0.0001
prior_mean ndarray | None

Prior mean vector (d,), or None for zeros.

None
hessian_estimator str | Callable

"ggn" (outer product -g g^T), "identity" (zero), or a callable fn(mean, grads) -> (d, d).

'ggn'
damping float

Additive damping epsilon * I after each precision update.

1e-06
solver Solver | None

A lineax solver (e.g. lx.Cholesky()) or a gaussx solver strategy (e.g. gaussx.DenseSolver(), gaussx.CGSolver()). None uses gaussx.solve's structural dispatch.

None

Returns:

Type Description
GradientTransformation

An optax.GradientTransformation.

Raises:

Type Description
ImportError

If the optional gaussx dependency is not installed.

Source code in src/optax_bayes/_src/full_rank.py
def blr_full_rank(
    learning_rate: float = 1e-2,
    prior_precision: float = 1e-4,
    prior_mean: jnp.ndarray | None = None,
    hessian_estimator: str | Callable = "ggn",
    damping: float = 1e-6,
    solver: Solver | None = None,
) -> optax.GradientTransformation:
    r"""Full-rank Gaussian BLR as an optax transform.

    Implements the Bayesian Learning Rule (Khan & Rue, 2023) with a
    full-rank Gaussian variational family
    $q(\theta) = \mathcal{N}(m, \Lambda^{-1})$ over flat parameter
    vectors $\theta \in \mathbb{R}^d$. Optimizer state stores the
    precision matrix $\Lambda$ (``(d, d)``) and the natural mean
    $\eta = \Lambda m$ (``(d,)``), updated as

    $$
    \begin{aligned}
    \Lambda_{t+1} &= (1 - \rho)\, \Lambda_t + \rho\, (\Lambda_0 - H_t) \\
    \eta_{t+1}    &= (1 - \rho)\, \eta_t    + \rho\, (\eta_0 + g_t - H_t m_t)
    \end{aligned}
    $$

    with $g_t$ the log-likelihood gradient and $H_t \preceq 0$ the
    Hessian estimate. With the exact Hessian, the fixed point is the
    exact Gaussian posterior of a conjugate model. The state initialises
    its mean at the params passed to ``init``; ``prior_mean`` and
    ``prior_precision`` anchor every update.

    Uses ``gaussx.solve`` for the precision solve at each step (requires
    the optional ``gaussx`` extra).

    **This API expects log-likelihood gradients.**  For standard loss
    minimisation, use
    [`blr_full_rank_for_loss`][optax_bayes.blr_full_rank_for_loss] instead.

    Args:
        learning_rate: Step size rho in (0, 1].
        prior_precision: Scalar multiplied by I to form Lambda_0.
        prior_mean: Prior mean vector (d,), or None for zeros.
        hessian_estimator: ``"ggn"`` (outer product ``-g g^T``),
            ``"identity"`` (zero), or a callable
            ``fn(mean, grads) -> (d, d)``.
        damping: Additive damping epsilon * I after each precision
            update.
        solver: A ``lineax`` solver (e.g. ``lx.Cholesky()``) or a
            ``gaussx`` solver strategy (e.g. ``gaussx.DenseSolver()``,
            ``gaussx.CGSolver()``). ``None`` uses ``gaussx.solve``'s
            structural dispatch.

    Returns:
        An ``optax.GradientTransformation``.

    Raises:
        ImportError: If the optional ``gaussx`` dependency is not
            installed.
    """
    return _blr_full_rank(
        learning_rate=learning_rate,
        prior_precision=prior_precision,
        prior_mean=prior_mean,
        hessian_estimator=hessian_estimator,
        damping=damping,
        solver=solver,
        psd=True,
    )

Newton's method

Classic damped Newton falls out of full-rank BLR at \(\rho = 1\) with a near-flat prior and an exact Hessian.

newton_for_loss(loss_hessian_fn: Callable, damping: float = 1e-06, solver: Solver | None = None) -> optax.GradientTransformation

Newton's method for loss minimisation.

Wraps newton: accepts standard loss gradients and a loss Hessian function, negating both internally to match the BLR log-likelihood convention.

Parameters:

Name Type Description Default
loss_hessian_fn Callable

Callable fn(mean) -> (d, d) returning the Hessian of the loss (not log-likelihood).

required
damping float

Additive damping epsilon * I for numerical safety.

1e-06
solver Solver | None

Optional lineax solver or gaussx solver strategy.

None

Returns:

Type Description
GradientTransformation

An optax.GradientTransformation.

Source code in src/optax_bayes/_src/presets.py
def newton_for_loss(
    loss_hessian_fn: Callable,
    damping: float = 1e-6,
    solver: Solver | None = None,
) -> optax.GradientTransformation:
    """Newton's method for loss minimisation.

    Wraps [`newton`][optax_bayes.newton]: accepts standard loss
    gradients and a loss Hessian function, negating both internally to
    match the BLR log-likelihood convention.

    Args:
        loss_hessian_fn: Callable ``fn(mean) -> (d, d)`` returning
            the Hessian of the **loss** (not log-likelihood).
        damping: Additive damping epsilon * I for numerical safety.
        solver: Optional ``lineax`` solver or ``gaussx`` solver strategy.

    Returns:
        An ``optax.GradientTransformation``.
    """

    def _neg_loss_hessian(mean, grads):
        return -loss_hessian_fn(mean)

    inner = newton(
        hessian_fn=_neg_loss_hessian,
        damping=damping,
        solver=solver,
    )
    return _wrap_for_loss(inner)

newton(hessian_fn: Callable, damping: float = 1e-06, solver: Solver | None = None) -> optax.GradientTransformation

Newton's method as full-rank BLR.

Equivalent to BLR with \(\rho = 1\), a near-flat prior, and an exact Hessian, recovering the classic update

\[ m_{t+1} = m_t - H^{-1} g. \]

Expects log-likelihood gradients. For standard loss minimisation, use newton_for_loss instead.

Parameters:

Name Type Description Default
hessian_fn Callable

Callable fn(mean, grads) -> (d, d) returning the Hessian of the log-likelihood.

required
damping float

Additive damping epsilon * I for numerical safety.

1e-06
solver Solver | None

Optional lineax solver or gaussx solver strategy.

None

Returns:

Type Description
GradientTransformation

An optax.GradientTransformation.

Source code in src/optax_bayes/_src/presets.py
def newton(
    hessian_fn: Callable,
    damping: float = 1e-6,
    solver: Solver | None = None,
) -> optax.GradientTransformation:
    r"""Newton's method as full-rank BLR.

    Equivalent to BLR with $\rho = 1$, a near-flat prior, and an exact
    Hessian, recovering the classic update

    $$
    m_{t+1} = m_t - H^{-1} g.
    $$

    **Expects log-likelihood gradients.** For standard loss
    minimisation, use [`newton_for_loss`][optax_bayes.newton_for_loss]
    instead.

    Args:
        hessian_fn: Callable ``fn(mean, grads) -> (d, d)`` returning
            the Hessian of the log-likelihood.
        damping: Additive damping epsilon * I for numerical safety.
        solver: Optional ``lineax`` solver or ``gaussx`` solver strategy.

    Returns:
        An ``optax.GradientTransformation``.
    """
    # Damped Newton: a weak damping * I prior ensures the initial state is
    # invertible and acts as spectral regularisation on the Hessian.  We
    # zero the BLR's per-step damping so damping is applied only once
    # (via the prior), not twice.  With rho=1 this produces the update
    #   m_{t+1} = (damping * I - H_t)^{-1} (g_t - H_t m_t)
    # which converges to classical Newton as damping -> 0.
    return _blr_full_rank(
        learning_rate=1.0,
        prior_precision=damping,
        prior_mean=None,
        hessian_estimator=hessian_fn,
        damping=0.0,
        solver=solver,
        psd=False,
    )

Posterior extraction & sampling

get_posterior_full_rank(state: BLRFullRankState, solver: Solver | None = None) -> tuple[jnp.ndarray, jnp.ndarray]

Extract the approximate posterior from full-rank BLR state.

Returns the mean and covariance of \(q(\theta) = \mathcal{N}(\Lambda^{-1}\eta,\ \Lambda^{-1})\), using gaussx.solve for the mean and gaussx.inv for the covariance (requires the optional gaussx extra).

Parameters:

Name Type Description Default
state BLRFullRankState

A BLRFullRankState from blr_full_rank or blr_full_rank_for_loss.

required
solver Solver | None

Optional lineax solver (e.g. lx.Cholesky()) or gaussx solver strategy (e.g. gaussx.DenseSolver()).

None

Returns:

Type Description
ndarray

Tuple (mean, covariance) where mean is (d,) and

ndarray

covariance is (d, d).

Source code in src/optax_bayes/_src/posterior.py
def get_posterior_full_rank(
    state: BLRFullRankState,
    solver: Solver | None = None,
) -> tuple[jnp.ndarray, jnp.ndarray]:
    r"""Extract the approximate posterior from full-rank BLR state.

    Returns the mean and covariance of
    $q(\theta) = \mathcal{N}(\Lambda^{-1}\eta,\ \Lambda^{-1})$,
    using ``gaussx.solve`` for the mean and ``gaussx.inv`` for the
    covariance (requires the optional ``gaussx`` extra).

    Args:
        state: A ``BLRFullRankState`` from ``blr_full_rank`` or
            ``blr_full_rank_for_loss``.
        solver: Optional ``lineax`` solver (e.g. ``lx.Cholesky()``) or
            ``gaussx`` solver strategy (e.g. ``gaussx.DenseSolver()``).

    Returns:
        Tuple ``(mean, covariance)`` where mean is (d,) and
        covariance is (d, d).
    """
    require_gaussx("get_posterior_full_rank")
    op = precision_operator(state.precision)
    return solve(op, state.nat_mean, solver), inverse_matrix(op, solver)

sample_posterior_full_rank(state: BLRFullRankState, key: jax.Array) -> jnp.ndarray

Draw one reparameterised sample from the full-rank posterior.

Samples \(\theta \sim \mathcal{N}(m, \Lambda^{-1})\) via the Cholesky factor \(L L^\top = \Lambda\) of the precision:

\[ \theta = m + L^{-\top} \epsilon, \qquad \epsilon \sim \mathcal{N}(0, I). \]

Parameters:

Name Type Description Default
state BLRFullRankState

A BLRFullRankState.

required
key Array

PRNG key.

required

Returns:

Type Description
ndarray

Sampled parameter vector, shape (d,).

Source code in src/optax_bayes/_src/sampling.py
def sample_posterior_full_rank(
    state: BLRFullRankState,
    key: jax.Array,
) -> jnp.ndarray:
    r"""Draw one reparameterised sample from the full-rank posterior.

    Samples $\theta \sim \mathcal{N}(m, \Lambda^{-1})$ via the
    Cholesky factor $L L^\top = \Lambda$ of the precision:

    $$
    \theta = m + L^{-\top} \epsilon, \qquad
    \epsilon \sim \mathcal{N}(0, I).
    $$

    Args:
        state: A ``BLRFullRankState``.
        key: PRNG key.

    Returns:
        Sampled parameter vector, shape (d,).
    """
    require_gaussx("sample_posterior_full_rank")
    mean = solve(precision_operator(state.precision), state.nat_mean)

    # Cholesky of precision: Lambda = L L^T
    chol = jnp.linalg.cholesky(state.precision)

    d = mean.shape[0]
    eps = jax.random.normal(key, (d,), mean.dtype)

    # Sample: theta = m + L^{-T} eps
    # L^{-T} eps = solve(L^T, eps)
    sample = mean + jax.scipy.linalg.solve_triangular(chol.T, eps, lower=False)
    return sample

State

BLRFullRankState

Bases: NamedTuple

Natural-parameter state for \(q(\theta) = \mathcal{N}(m, \Lambda^{-1})\), \(\theta \in \mathbb{R}^d\).

Attributes:

Name Type Description
precision Array

Precision matrix \(\Lambda\), shape (d, d).

nat_mean Array

Natural mean \(\eta = \Lambda m\), shape (d,).

count Array

Scalar step counter.

Source code in src/optax_bayes/_src/types.py
class BLRFullRankState(NamedTuple):
    r"""Natural-parameter state for
    $q(\theta) = \mathcal{N}(m, \Lambda^{-1})$, $\theta \in \mathbb{R}^d$.

    Attributes:
        precision: Precision matrix $\Lambda$, shape ``(d, d)``.
        nat_mean: Natural mean $\eta = \Lambda m$, shape ``(d,)``.
        count: Scalar step counter.
    """

    precision: jax.Array  # (d, d)
    nat_mean: jax.Array  # (d,)
    count: jax.Array