Skip to main content

Using a plugin

A plugin is a separate package that adds methods to laplacekit. We install laplacekit-subnet, which picks a subnetwork of weights for the Laplace approximation.

pip install "laplacekit[subnet]"

A plugin’s method goes wherever a built-in one goes. Here, the subnetwork goes in as subset=: the 100 weights with the largest magnitude.

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

import laplacekit as lk

x_np, y_np = make_blobs(
    n_samples=500, centers=4, cluster_std=1.2, random_state=37
)
x, y = torch.tensor(x_np, dtype=torch.float32), torch.tensor(y_np)

torch.manual_seed(0)
model = nn.Sequential(
    nn.Linear(2, 20), nn.ReLU(), nn.Linear(20, 20), nn.ReLU(), nn.Linear(20, 4)
)
opt = torch.optim.Adam(model.parameters(), lr=1e-2, weight_decay=5e-4)

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

model.eval()
post = lk.laplace(
    model,
    [(x, y)],
    likelihood=lk.Categorical(),
    subset=lk.subnet.largest_magnitude(100),
)
print(post)
LaplacePosterior(
  subset         = largest_magnitude {"0.weight[idx]": (23,), "0.bias[idx]": (12,), "2.weight[idx]": (35,), "2.bias[idx]": (5,), "4.weight[idx]": (25,)}
  hessian_approx = PerBlockCurvature({'*': DenseGGN()})
  curvature      = BlockDiag[Dense] (3 blocks, 100 parameters)
  prior          = Isotropic(prior_precision=0.594)
  likelihood     = Categorical()
  hyper_tuner    = MarginalLikelihood()
  n_data         = 500
)

Installing a plugin changes no defaults. Without subset=, lk.laplace still takes the last layer. The plugin is reached as lk.subnet, which imports it on first use.

What is installed

lk.plugins() lists the installed plugins and what each one provides.

print(lk.plugins())
laplacekit-diffusers 1.0.1  Hugging Face diffusers presets for laplacekit: last-layer Laplace on denoisers with DDPM-family schedulers
  denoiser: Wrap a `diffusers` denoiser as a `ModelFn` that returns the output's `.sample`.
  laplace: Fit a Laplace approximation to a denoiser trained with a DDPM-family scheduler.

laplacekit-example 1.0.0  The docs' example plugin: the last n layers as a subset
  last_layers: Select the parameters of the last `n` modules with parameters that ran in the probe.

laplacekit-gp 1.0.1  GP methods for laplacekit: function-space Laplace with Nystrom features, inducing points and GP priors
  MAX_BASIS_ENTRIES
  MAX_CONTEXT_JACOBIAN_ENTRIES
  MAX_KMEANS_ENTRIES
  RBF: The RBF kernel $k(x, y) = \sigma^2 \exp(-\tfrac{1}{2} \lVert (x - y) / \ell \rVert^2)$.
  Drawn: Points that need no data.
  FSPPosterior: FSP-Laplace's posterior over the weights, $\mathcal{N}(\theta_*, S S^\top)$.
  FunctionPrior: A GP prior over the outputs, $f \sim \mathcal{GP}(\mu, k)$, shared by every output entry.
  Kernel: A covariance function $k$, evaluated between two batches of inputs.
  Matern: The Matérn kernel with smoothness $\nu$, on $s = \lVert (x - y) / \ell \rVert$.
  ELLA: ELLA (Deng et al. 2022), the linearized Laplace GP on a Nyström basis of rank `rank`.
  NystromGP: The linearized Laplace posterior on a Nyström basis, as a GP over the outputs.
  Periodic: The periodic kernel, a product over the flattened input entries $d$.
  Picked: The points a method uses, with what it needs to place outputs on them.
  Points: Where a method evaluates its kernel.
  Product: The product kernel $a(x, y) \, b(x, y)$, entrywise, also written `a * b`.
  RangePrecision: The precision of an `FSPPosterior`, $V \operatorname{diag}(d) V^\top$.
  Sum: The sum kernel $a(x, y) + b(x, y)$, also written `a + b`.
  VaLLA: VaLLA (Ortega et al. 2024), the linearized Laplace GP with variational inducing outputs.
  VariationalGP: The linearized Laplace prior conditioned on $M$ inducing outputs, as a GP over the outputs.
  fit_variational: Fit VaLLA's variational posterior with `n_steps` Adam steps on `variational_loss`.
  fixed: Use the given inputs as the points. The fit reads no data for them.
  from_data: Pick $m$ training inputs uniformly without replacement, in one pass over the data.
  fsp_laplace: FSP-Laplace (Cinquin et al. 2024, Algorithm 2): Laplace under a GP prior on the outputs.
  grid: Place points on the product grid of `torch.linspace(low[d], high[d], n[d])`.
  kmeans: Pick points by k-means on the training inputs.
  rkhs_norm: The estimate of $\lVert f - \mu \rVert^2_{\mathcal{H}}$ in Eq. 3.7 of Cinquin et al. (2024).
  uniform: Draw $m$ points uniformly from the box $[\text{low}, \text{high}]$, as `[m, D]`.
  variational_loss: VaLLA's objective on one batch (Ortega et al. 2024).

laplacekit-heteroscedastic 1.0.1  Heteroscedastic regression for laplacekit: a Gaussian likelihood in natural parameters
  MeanVarianceGaussian: A Gaussian over targets `[..., K]` from outputs $f = [m, v]$, `[..., 2K]`.
  Moments: The predictive mean and its epistemic and aleatoric variances, each `[N, ..., K]`.
  NaturalGaussian: A Gaussian over targets `[..., K]` in its natural parameters $f = [\eta_1, \eta_2]$.
  NaturalHead: A last layer that maps $[h_1, h_2]$ to the natural parameters $[\eta_1, \eta_2]$.
  NoisyMean: The default predictive of `NaturalGaussian` and `MeanVarianceGaussian`.
  moments: Split the predictive into its mean, epistemic variance and aleatoric variance.

laplacekit-marglik 1.0.1  Marginal-likelihood training for laplacekit: fit the network and its prior and noise together
  Trained: The result of `train`: the kept fit and the training history.
  train: Train `model` and its hyperparameters together (Immer et al. 2021, Alg. 1).

laplacekit-reward 1.0.1  Reward models for laplacekit: Bradley-Terry over preference pairs
  Pair: A batch of preference pairs, where `first[i]` and `second[i]` are the items of pair `i`.
  bradley_terry: The Bradley–Terry likelihood over a pair's rewards `[N, 2]`, which is `lk.Categorical()`.
  pair: Build `Pair(first, second)`.
  pairwise: Wrap a reward model as a `ModelFn` that scores pairs and single items.
  prepare_pairs: Turn a `(first, second, label)` row, as a `TensorDataset` of pairs gives it, into a `Batch`.
  prepare_preferences: Turn tokenized preferences `{"chosen": ..., "rejected": ...}` into a `Batch` of pairs.

laplacekit-subnet 1.0.1  Subnetwork selection for laplacekit: random, largest magnitude, largest marginal variance
  largest_magnitude: Pick the `n` entries of the parameters of `of` with the largest $|\theta|$.
  largest_variance: Pick the `n` entries with the largest marginal variance.
  random: Pick `n` entries of the parameters of `of`, uniformly without replacement.
  rescaled_prior: An isotropic prior over a subnetwork of $S$ entries, with precision $\lambda S / D$.
  swag_variance: Diagonal SWAG variances of `model`'s parameters (Maddox et al. 2019).

laplacekit-transformers 1.0.1  Hugging Face transformers presets for laplacekit: Laplace-LoRA on causal language models and sequence classifiers
  CausalLM: The task of `laplace_lora` for a causal LM (`AutoModelForCausalLM`).
  SequenceClassification: The task of `laplace_lora` for a sequence classifier (`AutoModelForSequenceClassification`).
  Tokenizer: A tokenizer for `answer_logits`, which only needs its `encode` method.
  answer_logits: Build a `select` for `lk.predict` that keeps the logits of `answers` at the last real token.
  causal_lm: Wrap a Hugging Face causal LM as a `ModelFn` that returns the logits.
  laplace_lora: Fit a Laplace approximation over the trainable parameters of a Hugging Face model.
  last_token: The logits at each sequence's last real token, with left or right padding.
  padding_mask: Mark the positions that count in a causal LM's loss, as a `mask_fn` for `lk.Categorical`.
  prepare_causal_lm: Turn a tokenizer batch into a `Batch` for next-token prediction.
  prepare_sequence_classification: Turn a tokenizer batch with `"labels"` into a `Batch` for sequence classification.
  sequence_classification: Wrap a Hugging Face sequence classifier as a `ModelFn` that returns the logits.

laplacekit-example is the docs’ own example from Your first plugin, installed with the docs and never published.

lk.health() checks the install: the core first, then each plugin with its own checks.

print(lk.health())
laplacekit
- OK torch: 2.15.0+cpu (>= 2.15)
- OK curvlinops-for-pytorch: 3.0.1
- OK autograd: vjp, jvp, vmap, vjp_twice work on a 2-layer CPU MLP
- OK float64: tensors and a Cholesky factor in float64 work

laplacekit_diffusers
- OK supports: laplacekit 1.0.1 is in >=1.0,<2
- OK diffusers: 0.43.0

laplacekit_example
- OK supports: laplacekit 1.0.1 is in >=1.0,<2

laplacekit_gp
- OK supports: laplacekit 1.0.1 is in >=1.0,<2

laplacekit_heteroscedastic
- OK supports: laplacekit 1.0.1 is in >=1.0,<2

laplacekit_marglik
- OK supports: laplacekit 1.0.1 is in >=1.0,<2

laplacekit_reward
- OK supports: laplacekit 1.0.1 is in >=1.0,<2

laplacekit_subnet
- OK supports: laplacekit 1.0.1 is in >=1.0,<2

laplacekit_transformers
- OK supports: laplacekit 1.0.1 is in >=1.0,<2
- OK transformers: 5.23.0
- OK peft: 0.21.3

Subnetwork Laplace (Daxberger et al., 2021) keeps a Gaussian over \(S\) chosen weights \(\theta_S\) and fixes the others at their trained values,

\[ p(\theta_S \mid \mathcal{D}) \approx \mathcal{N}\big(\hat\theta_S, (\lambda I + G_S)^{-1}\big) , \]

where \(G_S\) is the GGN restricted to those weights. With \(S\) small, \(G_S\) fits as a dense matrix.

The full tutorial: Subnetworks