Skip to content

Low-Rank BLR

The scalable middle ground: precision parameterised as \(\Lambda = \operatorname{diag}(D) + UU^\top\) with \(U \in \mathbb{R}^{d \times r}\), giving \(O(dr)\) storage and \(O(dr^2 + r^3)\) solves through the Woodbury identity. Structured solves are dispatched via gaussx LowRankUpdate operators (requires the optional gaussx extra).

Transforms

blr_low_rank_for_loss(learning_rate: float = 0.01, rank: int = 10, 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

Low-rank BLR accepting standard loss gradients.

Wraps blr_low_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
rank int

Target rank r of the low-rank factor U.

10
prior_precision float

Scalar diagonal prior precision.

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 on the diagonal.

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_low_rank_for_loss(
    learning_rate: float = 1e-2,
    rank: int = 10,
    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"""Low-rank BLR accepting standard loss gradients.

    Wraps [`blr_low_rank`][optax_bayes.blr_low_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].
        rank: Target rank r of the low-rank factor U.
        prior_precision: Scalar diagonal prior precision.
        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 on the diagonal.
        solver: Optional ``lineax`` solver or ``gaussx`` solver strategy.

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

blr_low_rank(learning_rate: float = 0.01, rank: int = 10, 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

Low-rank Gaussian BLR as an optax transform.

Parameterises the precision as \(\Lambda = \operatorname{diag}(D) + U U^\top\) with \(D \in \mathbb{R}^d\) and \(U \in \mathbb{R}^{d \times r}\), giving \(O(dr)\) storage and \(O(dr^2 + r^3)\) solves via the Woodbury identity through gaussx structured operators (requires the optional gaussx extra).

The update is SLANG's (Mishkin et al., 2018). With the curvature in factor form \(-H_t = G_t G_t^\top\) (\(G_t = g_t\) for "ggn"), the target precision \((1-\rho)\Lambda_t + \rho(\Lambda_0 - H_t)\) is \(\operatorname{diag}((1-\rho) D_t + \rho D_0) + \tilde U \tilde U^\top\) with \(\tilde U = [\sqrt{1-\rho}\, U_t,\ \sqrt{\rho}\, G_t]\). A thin SVD keeps the top \(r\) directions of \(\tilde U\), and the diagonal of the discarded part is added to \(D\):

\[ \begin{aligned} U_{t+1} &= \operatorname{top}_r(\tilde U) \\ D_{t+1} &= (1-\rho) D_t + \rho D_0 + \operatorname{diag}(\tilde U \tilde U^\top - U_{t+1} U_{t+1}^\top) + \epsilon \end{aligned} \]

so the diagonal of the precision is updated exactly, and the whole precision is exact when \(r \ge d\). A step costs \(O(d (r + k)^2)\) for a rank-\(k\) factor: \(O(d r^2)\) for "ggn". The mean takes the mean-form Gaussian BLR step

\[ m_{t+1} = m_t + \rho\, \Lambda_{t+1}^{-1} \big(g_t - D_0 (m_t - m_0)\big), \]

which matches the natural-mean recursion of blr_full_rank whenever the precision is exact and stays stable when it is truncated. The state initialises its mean at the params passed to init; prior_mean and prior_precision anchor every update.

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

Parameters:

Name Type Description Default
learning_rate float

Step size rho in (0, 1].

0.01
rank int

Target rank r of the low-rank factor U.

10
prior_precision float

Scalar diagonal prior precision D_0 = s0 * I.

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). A callable's dense Hessian is factored by eigendecomposition, \(O(d^3)\) per step, keeping only its negative-definite part.

'ggn'
damping float

Additive damping epsilon on the diagonal after each update, as in blr_full_rank.

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/low_rank.py
def blr_low_rank(
    learning_rate: float = 1e-2,
    rank: int = 10,
    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"""Low-rank Gaussian BLR as an optax transform.

    Parameterises the precision as
    $\Lambda = \operatorname{diag}(D) + U U^\top$ with $D \in
    \mathbb{R}^d$ and $U \in \mathbb{R}^{d \times r}$, giving
    $O(dr)$ storage and $O(dr^2 + r^3)$ solves via the Woodbury
    identity through ``gaussx`` structured operators (requires the
    optional ``gaussx`` extra).

    The update is SLANG's (Mishkin et al., 2018). With the curvature in
    factor form $-H_t = G_t G_t^\top$ ($G_t = g_t$ for ``"ggn"``), the
    target precision $(1-\rho)\Lambda_t + \rho(\Lambda_0 - H_t)$ is
    $\operatorname{diag}((1-\rho) D_t + \rho D_0) + \tilde U \tilde U^\top$
    with $\tilde U = [\sqrt{1-\rho}\, U_t,\ \sqrt{\rho}\, G_t]$. A thin
    SVD keeps the top $r$ directions of $\tilde U$, and the diagonal of
    the discarded part is added to $D$:

    $$
    \begin{aligned}
    U_{t+1} &= \operatorname{top}_r(\tilde U) \\
    D_{t+1} &= (1-\rho) D_t + \rho D_0
        + \operatorname{diag}(\tilde U \tilde U^\top - U_{t+1} U_{t+1}^\top)
        + \epsilon
    \end{aligned}
    $$

    so the diagonal of the precision is updated exactly, and the whole
    precision is exact when $r \ge d$. A step costs $O(d (r + k)^2)$ for
    a rank-$k$ factor: $O(d r^2)$ for ``"ggn"``. The mean takes the
    mean-form Gaussian BLR step

    $$
    m_{t+1} = m_t + \rho\, \Lambda_{t+1}^{-1} \big(g_t - D_0 (m_t - m_0)\big),
    $$

    which matches the natural-mean recursion of ``blr_full_rank`` whenever
    the precision is exact and stays stable when it is truncated. The
    state initialises its mean at the params passed to ``init``;
    ``prior_mean`` and ``prior_precision`` anchor every update.

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

    Args:
        learning_rate: Step size rho in (0, 1].
        rank: Target rank r of the low-rank factor U.
        prior_precision: Scalar diagonal prior precision D_0 = s0 * I.
        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)``. A callable's dense Hessian is
            factored by eigendecomposition, $O(d^3)$ per step, keeping
            only its negative-definite part.
        damping: Additive damping epsilon on the diagonal after each
            update, as in ``blr_full_rank``.
        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.
    """
    require_gaussx("blr_low_rank")
    _factor_fn = resolve_hessian_factor_low_rank(hessian_estimator)

    def init_fn(params: jnp.ndarray) -> BLRLowRankState:
        d = params.shape[0]
        # Clamp rank to d: SVD of a (d, k) matrix returns at most d singular
        # vectors, so a rank > d request would be silently truncated later
        # and produce a shape mismatch.
        effective_rank = min(rank, d)
        d0 = jnp.full(d, prior_precision, params.dtype)
        u0 = jnp.zeros((d, effective_rank), params.dtype)
        # The variational mean starts at the user's params (standard optax
        # drop-in semantics).  The prior mean still anchors every update
        # through eta_0 inside update_fn.
        eta_0 = d0 * params
        return BLRLowRankState(
            diag_precision=d0,
            low_rank_factor=u0,
            nat_mean=eta_0,
            count=jnp.zeros([], jnp.int32),
        )

    def update_fn(
        grads: jnp.ndarray,
        state: BLRLowRankState,
        params: jnp.ndarray | None = None,
    ) -> tuple[jnp.ndarray, BLRLowRankState]:
        rho = learning_rate
        # The state's dtype (set from the params at init) is the working
        # dtype: inputs are cast to it so nothing promotes the state.
        dtype = state.nat_mean.dtype
        grads = jnp.asarray(grads, dtype)
        d = grads.shape[0]
        d0 = jnp.full(d, prior_precision, dtype)
        m0 = (
            jnp.zeros(d, dtype)
            if prior_mean is None
            else jnp.asarray(prior_mean, dtype)
        )

        # Current mean via gaussx structured solve
        m_t = solve(
            low_rank_precision_operator(state.diag_precision, state.low_rank_factor),
            state.nat_mean,
            solver,
        )

        # Curvature in factor form, -H = G G^T, with G of shape (d, k).
        g_factor = jnp.asarray(_factor_fn(m_t, grads), dtype)

        # SLANG precision update: stack the decayed factor with the new
        # curvature, keep the top-r directions, and fold the diagonal of
        # what was discarded into D.
        u_aug = jnp.concatenate(
            [
                jnp.sqrt(jnp.maximum(1 - rho, 0.0)) * state.low_rank_factor,
                jnp.sqrt(rho) * g_factor,
            ],
            axis=1,
        )
        new_u, residual_diag = _truncate_to_rank(u_aug, min(rank, d))
        new_diag = (1 - rho) * state.diag_precision + rho * d0 + residual_diag + damping

        # Mean update in mean form, m += rho * Lambda^{-1} (g - D_0 (m - m_0)).
        # It equals the natural-mean recursion when the precision is exact,
        # but stays a well-defined preconditioned step after truncation;
        # the recursion would instead amplify the truncation error by
        # Lambda^{-1} along weakly curved directions.
        new_op = low_rank_precision_operator(new_diag, new_u)
        updates = solve(new_op, rho * (grads - d0 * (m_t - m0)), solver)
        new_mean = m_t + updates
        new_nat_mean = new_op.mv(new_mean)

        new_state = BLRLowRankState(
            diag_precision=new_diag,
            low_rank_factor=new_u,
            nat_mean=new_nat_mean,
            count=state.count + 1,
        )
        return updates, new_state

    return optax.GradientTransformation(init_fn, update_fn)  # ty: ignore[invalid-argument-type]

Posterior extraction & sampling

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

Extract the approximate posterior from low-rank BLR state.

Returns the mean and covariance of \(q(\theta) = \mathcal{N}(\Lambda^{-1}\eta,\ \Lambda^{-1})\) with \(\Lambda = \operatorname{diag}(D) + U U^\top\), using gaussx structured operators for the mean solve and gaussx.inv for the covariance (Woodbury-dispatched; requires the optional gaussx extra).

Parameters:

Name Type Description Default
state BLRLowRankState

A BLRLowRankState from blr_low_rank or blr_low_rank_for_loss.

required
solver Solver | None

Optional lineax solver or gaussx solver strategy.

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_low_rank(
    state: BLRLowRankState,
    solver: Solver | None = None,
) -> tuple[jnp.ndarray, jnp.ndarray]:
    r"""Extract the approximate posterior from low-rank BLR state.

    Returns the mean and covariance of
    $q(\theta) = \mathcal{N}(\Lambda^{-1}\eta,\ \Lambda^{-1})$ with
    $\Lambda = \operatorname{diag}(D) + U U^\top$, using ``gaussx``
    structured operators for the mean solve and ``gaussx.inv`` for the
    covariance (Woodbury-dispatched; requires the optional ``gaussx``
    extra).

    Args:
        state: A ``BLRLowRankState`` from ``blr_low_rank`` or
            ``blr_low_rank_for_loss``.
        solver: Optional ``lineax`` solver or ``gaussx`` solver strategy.

    Returns:
        Tuple ``(mean, covariance)`` where mean is (d,) and
        covariance is (d, d).
    """
    require_gaussx("get_posterior_low_rank")
    op = low_rank_precision_operator(state.diag_precision, state.low_rank_factor)
    return solve(op, state.nat_mean, solver), inverse_matrix(op, solver)

sample_posterior_low_rank(state: BLRLowRankState, key: jax.Array) -> jnp.ndarray

Draw one reparameterised sample from the low-rank posterior.

Samples \(\theta \sim \mathcal{N}(m, \Lambda^{-1})\) where \(\Lambda = \operatorname{diag}(D) + U U^\top\), using a two-step Gaussian trick that never forms the dense covariance:

  1. Draw \(z \sim \mathcal{N}(0, \Lambda)\) cheaply via \(z = \sqrt{D} \odot \epsilon_1 + U \epsilon_2\).
  2. Solve \(\Lambda y = z\) via Woodbury; then \(y \sim \mathcal{N}(0, \Lambda^{-1})\).

Cost: \(O(dr + r^3)\) memory, \(O(dr^2 + r^3)\) time.

Parameters:

Name Type Description Default
state BLRLowRankState

A BLRLowRankState.

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_low_rank(
    state: BLRLowRankState,
    key: jax.Array,
) -> jnp.ndarray:
    r"""Draw one reparameterised sample from the low-rank posterior.

    Samples $\theta \sim \mathcal{N}(m, \Lambda^{-1})$ where
    $\Lambda = \operatorname{diag}(D) + U U^\top$, using a two-step
    Gaussian trick that never forms the dense covariance:

    1. Draw $z \sim \mathcal{N}(0, \Lambda)$ cheaply via
       $z = \sqrt{D} \odot \epsilon_1 + U \epsilon_2$.
    2. Solve $\Lambda y = z$ via Woodbury; then
       $y \sim \mathcal{N}(0, \Lambda^{-1})$.

    Cost: $O(dr + r^3)$ memory, $O(dr^2 + r^3)$ time.

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

    Returns:
        Sampled parameter vector, shape (d,).
    """
    require_gaussx("sample_posterior_low_rank")
    op = low_rank_precision_operator(state.diag_precision, state.low_rank_factor)
    mean = solve(op, state.nat_mean)

    d = state.diag_precision.shape[0]
    r = state.low_rank_factor.shape[1]

    k1, k2 = jax.random.split(key)
    eps_d = jax.random.normal(k1, (d,), mean.dtype)
    eps_r = jax.random.normal(k2, (r,), mean.dtype)

    # z ~ N(0, Lambda) via the factorisation
    z = jnp.sqrt(state.diag_precision) * eps_d + state.low_rank_factor @ eps_r

    # y = Lambda^{-1} z ~ N(0, Lambda^{-1}) via Woodbury (gaussx)
    y = solve(op, z)

    return mean + y

State

BLRLowRankState

Bases: NamedTuple

Low-rank natural-parameter state: \(\Lambda = \operatorname{diag}(D) + U U^\top\).

Attributes:

Name Type Description
diag_precision Array

Diagonal precision \(D\), shape (d,).

low_rank_factor Array

Low-rank factor \(U\), shape (d, r).

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 BLRLowRankState(NamedTuple):
    r"""Low-rank natural-parameter state:
    $\Lambda = \operatorname{diag}(D) + U U^\top$.

    Attributes:
        diag_precision: Diagonal precision $D$, shape ``(d,)``.
        low_rank_factor: Low-rank factor $U$, shape ``(d, r)``.
        nat_mean: Natural mean $\eta = \Lambda m$, shape ``(d,)``.
        count: Scalar step counter.
    """

    diag_precision: jax.Array  # (d,)
    low_rank_factor: jax.Array  # (d, r)
    nat_mean: jax.Array  # (d,)
    count: jax.Array