# Priors

> **TIP:**
>
> The contract below is a protocol. Subclass it, as in `class MyClass(lk.core.Prior):`, and your editor marks a missing method in red. [Protocols in one page](../plugins/protocols.llms.md) shows how.

A prior is any `Prior`. It has a log density and a location, and it can add its precision to a curvature operator. The built-in priors put one precision on everything (`Isotropic`), one per entry (`Diagonal`), or one per layer (`Layerwise`). We write a prior with two precisions, one for the weights and one for the biases, and let `lk.laplace` tune both.

``` python
Op = TypeVar("Op", bound=Operator)


class Prior(Protocol):
    def log_prob(self, params: Params, /) -> Tensor: ...

    def location(self, like: Params, /) -> Params: ...

    def add_precision_to(self, op: Op, /) -> Op: ...


class PriorWithCovariance(Prior, Protocol):
    def cov_mv(self, v: Params, /) -> Params: ...


class TunablePrior(Prior, Protocol):
    def tunable(self) -> Tensor | Mapping[str, Tensor]: ...


class HasExpand(Protocol):
    def expand(self, params: Params, /) -> Self: ...
```

`cov_mv` lets the predictives push the prior forward. `tunable` tells the hyper tuners which hyperparameters to tune. `expand` builds the prior for the parameters that get the posterior. `subset` picks them, so a prior with one precision per parameter only knows its size once `lk.laplace` calls `expand`.

``` python
from collections.abc import Mapping
from typing import Self, TypeVar

import torch
from sklearn.datasets import make_blobs
from torch import Tensor, nn

import laplacekit as lk
from laplacekit.core import Operator, Params

Op = TypeVar("Op", bound=Operator)


@lk.core.pytree
class WeightBias:
    """Zero-mean Gaussian prior, one precision for weights, one for biases."""

    prior_precision: Mapping[str, Tensor]  # {"weight": ..., "bias": ...}
    # 1.0 at each bias entry, 0.0 elsewhere, flat over the parameters;
    # `expand` sets it
    is_bias: Tensor | None = None

    def __repr__(self) -> str:
        lam = self.prior_precision
        return f"WeightBias(weight={lam['weight']:.3g}, bias={lam['bias']:.3g})"

    def expand(self, params: Params, /) -> Self:
        parts = [
            torch.full((p.numel(),), float(p.ndim == 1), dtype=p.dtype)
            for p in params.values()
        ]

        return lk.replace(self, is_bias=torch.cat(parts))

    def _diagonal(self) -> lk.priors.Diagonal:
        if self.is_bias is None:
            raise lk.StructureError("WeightBias needs expand(params) first")

        w, b = self.prior_precision["weight"], self.prior_precision["bias"]

        return lk.priors.Diagonal(w * (1 - self.is_bias) + b * self.is_bias)

    def log_prob(self, params: Params, /) -> Tensor:
        return self._diagonal().log_prob(params)

    def location(self, like: Params, /) -> Params:
        return self._diagonal().location(like)

    def add_precision_to(self, op: Op, /) -> Op:
        return self._diagonal().add_precision_to(op)

    def cov_mv(self, v: Params, /) -> Params:
        return self._diagonal().cov_mv(v)

    def tunable(self) -> Mapping[str, Tensor]:
        return self.prior_precision


def weight_bias(weight: float = 1.0, bias: float = 1.0) -> WeightBias:
    """A `WeightBias` prior; the 1-d tensors are the biases."""

    return WeightBias(
        {"weight": torch.tensor(weight), "bias": torch.tensor(bias)}
    )
```

The prior is a [`@lk.core.pytree`](../plugins/pytrees.llms.md), so a tuner can find its tensors. Every method hands the work to a built-in `Diagonal` with the right entries. Which entries are biases depends on the parameters, and `weight_bias` doesn’t see them. `lk.laplace` calls `expand` with the parameters it fits, and `expand` marks the biases among them. We fit an MLP on four blobs and put the posterior on all its parameters, once with our prior and once with the default `Isotropic`. There is no scikit-learn in the template, so add it first with `uv add --dev scikit-learn`.

``` python
x_np, y_np = make_blobs(
    n_samples=400, centers=4, cluster_std=1.2, random_state=0
)
x, y = torch.tensor(x_np, dtype=torch.float32), torch.tensor(y_np)

torch.manual_seed(0)
model = nn.Sequential(
    nn.Linear(2, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 4)
)
opt = torch.optim.Adam(model.parameters(), lr=1e-2)

for _ in range(300):
    opt.zero_grad()
    nn.functional.cross_entropy(model(x), y).backward()
    opt.step()

for prior in (weight_bias(), lk.priors.Isotropic(1.0)):
    post = lk.laplace(
        model,
        [(x, y)],
        likelihood=lk.Categorical(),
        subset=lk.subsets.all,
        hessian_approx=lk.DiagGGN(),
        prior=prior,
    )
    print(post)
    print(f"log marginal likelihood: {post.log_marglik():.1f}\n")
```

    LaplacePosterior(
      subset         = all {"0.weight": (64, 2), "0.bias": (64,), "2.weight": (64, 64), "2.bias": (64,), "4.weight": (4, 64), "4.bias": (4,)}
      hessian_approx = DiagGGN()
      curvature      = BlockDiag[Diag] (3 blocks, 4612 parameters)
      prior          = WeightBias(weight=2.68, bias=1.65)
      likelihood     = Categorical()
      hyper_tuner    = MarginalLikelihood()
      n_data         = 400
    )
    log marginal likelihood: -1120.8

    LaplacePosterior(
      subset         = all {"0.weight": (64, 2), "0.bias": (64,), "2.weight": (64, 64), "2.bias": (64,), "4.weight": (4, 64), "4.bias": (4,)}
      hessian_approx = DiagGGN()
      curvature      = BlockDiag[Diag] (3 blocks, 4612 parameters)
      prior          = Isotropic(prior_precision=2.6)
      likelihood     = Categorical()
      hyper_tuner    = MarginalLikelihood()
      n_data         = 400
    )
    log marginal likelihood: -1125.3

For both posteriors, `lk.MarginalLikelihood()` maximized the marginal likelihood over the prior’s precisions. With our prior, it tuned both precisions, because `WeightBias` is a `TunablePrior`. A prior without `tunable` has nothing to tune, so the tuner leaves it as it is.

The weights end up with about the precision `Isotropic` picks, and the biases get a looser prior. The marginal likelihood goes up by a few nats. Since `Isotropic` is the special case of equal precisions, the best `WeightBias` can’t do worse. Here, the second precision buys only a little.

Since `lk.laplace` expands the prior, the same `weight_bias()` works on any subset of whole tensors. A subset of single entries (`lk.subsets.from_mask`, say) turns each selection into a 1-d tensor, and `WeightBias` would take them all for biases. On the last layer alone:

``` python
post = lk.laplace(
    model,
    [(x, y)],
    likelihood=lk.Categorical(),
    subset=lk.subsets.last_layer,
    hessian_approx=lk.DiagGGN(),
    prior=weight_bias(),
)
print(post.prior)
```

    WeightBias(weight=6.64, bias=34.9)

A prior built for all the parameters would have the wrong size here, and `lk.laplace` would raise `StructureError` before the fit.

We used `lk.DiagGGN()` on purpose. A vector precision has to be added to the curvature entry by entry, and a Kronecker-factored curvature such as KFAC has no room for that. It refuses any vector precision, even a constant one, with `StructureError`. It only takes one scalar per block, as `Isotropic` gives it, or a `Layerwise` with a scalar per block.

## The math

With $b_i = 1$ when entry $i$ of $\theta$ is a bias, the prior is

$$p(\theta) = \mathcal{N}\big(0, \Lambda_0^{-1}\big) , \qquad \Lambda_0 = \mathrm{diag}\big(\lambda_w (1 - b) + \lambda_b \, b\big) ,$$

and the Laplace precision is $\Lambda_0 + N G$, with $G$ the curvature. The default hyper tuner maximizes the Laplace marginal likelihood over $\log \lambda_w$ and $\log \lambda_b$ without refitting $G$. That is why `tunable` must return the prior’s own positive leaves: the tuner finds them in the posterior by identity, replaces them, and optimizes their logs. `lk.laplace` checks this before it reads any data, so a `tunable` that returns a copy raises `StructureError` right away instead of after the fit.

## The test

`lk.testing.check_prior` checks the contract in float64. There is no `lk.laplace` here to expand the prior, so we call `expand` ourselves. The `log_prob` must be finite, `add_precision_to` must keep each operator’s type, and `cov_mv` must be the inverse of the precision. Since our prior is a `TunablePrior`, `tunable` must also return its own positive leaves. On top of that, we compare the density and the precision against a reference built from `torch.distributions`.

``` python
def test_weight_bias():
    p64 = {k: v.detach().double() for k, v in model.named_parameters()}
    prior = weight_bias(weight=2.0, bias=0.5).expand(p64)

    lk.testing.check_prior(prior, p64)

    assert isinstance(prior, lk.core.TunablePrior)
    assert isinstance(prior, lk.core.HasExpand)

    std = {k: (0.5 if p.ndim == 1 else 2.0) ** -0.5 for k, p in p64.items()}
    want = sum(
        torch.distributions.Normal(0.0, std[k]).log_prob(p).sum()
        for k, p in p64.items()
    )

    torch.testing.assert_close(prior.log_prob(p64), want)

    flat = torch.cat([p.reshape(-1) for p in p64.values()])
    zero = lk.core.Diag(torch.zeros_like(flat))
    is_bias = torch.cat(
        [torch.full((p.numel(),), p.ndim == 1) for p in p64.values()]
    )

    torch.testing.assert_close(
        prior.add_precision_to(zero).diagonal(),
        torch.where(is_bias, 0.5, 2.0).double(),
    )


test_weight_bias()
```
