Skip to main content

Reference

Everyday

What a fit needs, from the model to the predictive.

Fit and predict

laplace Fit a Laplace approximation in weight space, then tune its hyperparameters.
predict Predictive distribution over targets, observation noise included.
predict_outputs Linearized pushforward of a posterior, \(\mathcal{N}(f(x; \mu), J \Sigma J^\top)\).
sample_outputs n_samples draws of the model’s outputs at inputs, stacked along a new leading axis.
save Write a posterior (or any @pytree object) to a file, without its model.
load Read a file written by save, attaching model.
replace A copy of obj with some fields changed, as copy.replace in Python 3.13.

Likelihoods

Categorical Softmax likelihood over a class axis of \(f\).
Bernoulli Sigmoid likelihood: each entry of \(f\) is the logit of an independent 0/1 target.
Gaussian Independent Gaussian noise over the last event_dims dims of \(f\).

Priors

priors.Isotropic Isotropic Gaussian prior \(\mathcal{N}(\mu, \lambda^{-1} I)\) over all parameters.
priors.Diagonal Diagonal Gaussian prior \(\mathcal{N}(\mu, \operatorname{diag}(\lambda)^{-1})\).
priors.Layerwise Gaussian prior with one precision per block, \(\prod_b \mathcal{N}(\mu_b, \lambda_b^{-1} I)\).
priors.KronSum A chain of KFAC posteriors as the prior of a KFAC fit, by summing Kronecker factors.
priors.LowRankSum A chain of LowRankGGN posteriors as the prior of a LowRankGGN fit, cut to a fixed rank.

Subsets

subsets.all Every parameter of the module.
subsets.trainable Parameters with requires_grad=True, e.g. LoRA adapters.
subsets.last_layer Own parameters of the last parameterized module that ran in the probe.
subsets.named Parameters whose name matches any of the glob patterns.
subsets.from_mask The entries where each bool mask is True.

Subnetworks

The laplacekit-subnet plugin, reached as lk.subnet.

laplacekit_subnet Subnetwork Laplace (Daxberger et al. 2021): the approximation over n chosen weight entries.

Heteroscedastic regression

The laplacekit-heteroscedastic plugin, reached as lk.heteroscedastic.

laplacekit_heteroscedastic Heteroscedastic regression, with Gaussian likelihoods whose variance depends on the input.

Reward models

The laplacekit-reward plugin, reached as lk.reward.

laplacekit_reward Laplace on reward models trained on preference pairs with Bradley–Terry.

Curvature

DiagGGN Diagonal of the GGN, \(C_n = \operatorname{diag}(J_n^\top H_n J_n)\).
DenseGGN Dense GGN, \(C_n = J_n^\top H_n J_n\), with \(J_n\) from jacrev.
DenseHessian Exact Hessian of the negative log-likelihood at the batch’s targets.
LowRankGGN Low-rank GGN over all fitted blocks jointly, from a Nyström sketch.
KFAC Kronecker-factored GGN per Linear / Conv2d layer, computed by Curvlinops.
per_block A method per block; the first rule matching a block wins.
curvature.default A method per block, from the probe.

Predictive

Linearized Linearize the model at the mean, push the weight-space posterior to outputs, apply a link.
predictive.Exact Gaussian outputs plus observation noise: \(\mathcal{N}(\bar f_i, V_{ii} + \sigma^2)\).
WeightSamples Sample weights from the posterior and average the predictive over the samples.
MC Average over Gaussian draws of the outputs.
Probit Moderated softmax, or moderated sigmoid, by the probit approximation.
Bridge The Laplace bridge: a Dirichlet over the class probabilities, matched to the logits.

Tuning

tune Tune a fitted posterior’s hyperparameters, without refitting.
MarginalLikelihood Maximize the Laplace marginal likelihood of the fit data. The default tuner.
Minimize Minimize an objective over every hyperparameter, with L-BFGS on their logs.
GridSearch Set the prior precision to the value from a grid that minimizes an objective.
tuning.HyperTuner Tunes the hyperparameters of a posterior: its prior precision, a learned sigma.
objectives.neg_log_marglik Laplace negative log marginal likelihood of the fit data, -post.log_marglik().
objectives.predictive_nll Mean negative log predictive density of the batches’ targets, per example.
objectives.brier Brier score: the squared error between predictive probabilities and targets, per example.
objectives.ece Expected calibration error with equal-width bins, positions pooled.

Function space

Function-space (GP) Laplace, as laplacekit.function_space.

function_space.laplace Function-space Laplace: probe, pick a subset of parameters, run the method’s passes.
function_space.SubsetOfData A subset-of-data GP: condition on \(m\) training inputs drawn uniformly without replacement.
function_space.SubsetGP A GP over the outputs, conditioned on the outputs at a subset of \(m\) training inputs.
function_space.FunctionSpaceMethod A function-space method: passes over the data that end in the posterior itself.
function_space.rows_of The examples index of inputs.
function_space.is_shared Whether an inputs leaf is shared by every example: a non-tensor or a 0-dim tensor.
function_space.jacobian The Jacobian of the flattened outputs with respect to params.
function_space.cov_rows \(\Sigma_0 r\) for each row \(r\) of rows, through prior.cov_mv under vmap.

GP methods

The laplacekit-gp plugin, reached as lk.gp.

laplacekit_gp GP methods for function-space Laplace: ELLA, VaLLA and FSP-Laplace.
laplacekit_gp.Kernel A covariance function \(k\), evaluated between two batches of inputs.

Marglik training

The laplacekit-marglik plugin, reached as lk.marglik.

laplacekit_marglik Marginal-likelihood training (Immer et al. 2021).

Library integrations

Plugin packages, reached as lk.transformers and lk.diffusers.

laplacekit_transformers Laplace-LoRA on Hugging Face transformers models: causal LMs and sequence classifiers.
laplacekit_diffusers Laplace on denoisers from Hugging Face diffusers.

Plugins and health

plugins List the plugins registered under laplacekit.plugins, by distribution name.
health Check the install: the core, then each plugin registered under laplacekit.plugins.

Building blocks

The contracts and machinery that plugins and by-hand fits use.

Fitting by hand

core.fit_curvature Bind a model, likelihood, params and curvature method for fitting.
core.run Run every pass of fit over data, under no_grad.
core.chain A type-safe pass.
core.CurvatureFit A model, likelihood, params and single-pass method bound for fitting.
core.Staged A weight-space method needing several passes.
core.StagedCurvatureFit A model, likelihood, params and multi-pass method bound for fitting.
core.Pass Run curvature over the data, then call then with its result.
core.Running One pass of a fit in progress.
core.Done The last step of a Staged plan.
core.Finished A completed fit.
core.FitContext What every pass knows about the fit, fixed for its duration.
core.FitStat The curvature statistic plus what objectives need from the same pass.

Data and models

Params is the type alias Mapping[str, Tensor]: parameters by name.

data.from_loader Wrap an iterable of raw items, one batch each.
data.as_data The Data source for any data form lk.laplace accepts.
data.Data A data source: data(generator) returns the batches of one pass.
Batch What prepare produces and update consumes.
core.spawn_generator Draw one seed and return a fresh generator seeded with it.
core.generator_for_batch Give the batch that starts at example count of a pass its own generator.
core.ModelFn forward(params, inputs) -> outputs, plus the module when there is one.
core.Selection Some entries of some parameters, each turned into its own 1-D parameter.
core.select The model and parameters to fit.
core.Subset Chooses which parameters get a posterior.
distributed.all_reduce Combine a statistic across the ranks of group.

Posteriors

Posterior is the type alias WeightPosterior | FunctionPosterior.

core.Prior Anything that can be the prior of a Laplace update.
core.PriorWithCovariance A prior that the predictives can push forward, because it multiplies by its covariance.
core.WeightPosterior A fitted weight-space Gaussian \(\mathcal{N}(\mu, \Sigma)\) over the parameters in mean.
core.HasCovMany A weight-space posterior whose covariance products take many vectors in one call.
core.HasVersions A posterior that can tell when it no longer describes the model.
LaplacePosterior The result of a Laplace update: the prior precision plus the scaled curvature.
core.FunctionPosterior A posterior over the model’s outputs, evaluated at inputs.
core.OutputGaussian Gaussian over model outputs (not targets: no observation noise).
core.Layout Parameter names grouped into blocks, and each parameter’s shape.
core.TunablePrior A prior whose precision the hyper tuners tune (lk.MarginalLikelihood, say).
core.HasExpand A prior with one shared precision that can expand to one per block or per weight.

Covariances

core.OutputCov Covariance of model outputs for a batch of inputs, never formed as an \(NE \times NE\) matrix.
core.SampleCov Zero-mean draws \(J z_s\), \(z_s \sim \mathcal{N}(0, \Sigma)\). For large output events.
core.FactorCov Low-rank covariance \(F F^\top\) per input.
core.PerInputCov Dense [N, E, E] blocks, one per input. Fine for classifiers with small C.

Curvature contracts

HessianApprox[Op] is the type alias Curvature[Any, Op] | Staged[Op]: what hessian_approx= takes.

core.Curvature One pass over the data, a fold of batches into a statistic S.
core.Stat A statistic that merges under +, a monoid with the curvature’s init as identity.
core.HasTemplate A Curvature or Staged method that knows its result’s structure before any data.
core.Operator A precision operator on vectors V: products, solves, its diagonal and log-determinant.
core.Diag A diagonal precision \(P = \operatorname{diag}(d)\), stored as its diagonal.
core.Dense A full precision matrix \(P\), for small blocks such as a last layer.
core.with_eigen op with each Dense in it carrying its eigendecomposition (Dense.with_eigen).
core.KronEigenbasis A Kronecker-factored matrix held in its eigenbasis, for one layer’s block.
core.BlockDiag One operator per block, keyed by block name (see layout).
core.Joint One operator across all blocks, on vectors keyed by block name.
core.LowRankPlusDiag A diagonal plus a low-rank term, \(P = D + U \operatorname{diag}(s) U^\top\).
core.HasBlocks An operator on mappings keyed by block name, such as BlockDiag or Joint.

Likelihood contracts

core.Likelihood A likelihood \(p(y \mid f)\) over targets given model outputs.
core.HasDistribution The distribution over targets. default_log_prob and default_sample derive from it.
core.HasSample Sampling of targets, used by the sampled and MC Fishers.
core.HasOutputHessian Closed-form output Hessian. Without it, output_hessian uses the MC Fisher.
core.OutputHessian Hessian \(H = -\nabla_f^2 \log p(y \mid f)\) with respect to \(f\), per example.
core.HasDefaultLink The link a likelihood uses when Linearized has link=None.
core.HasSampleAverage The predictive from output draws.
core.HasMask Which output positions count, e.g. non-padding tokens.
core.HasOutputCheck Checks the model’s outputs before any data is fitted.
core.HasTargetCheck Checks a batch’s targets before the fit uses them, e.g. values outside the support.
core.LateLikelihood A likelihood whose hyperparameters are applied after the fit.
likelihoods.from_log_prob Wrap a per-example log-likelihood fn(f, y) (contrastive, ranking, a custom energy).

Predictive contracts

core.Predictive Turns a posterior B and inputs into a distribution over targets.
core.LinkApprox Turns Gaussian outputs into a distribution over targets.
core.mean_outputs The model’s outputs at the posterior’s mean.

Requirements and errors

core.Requirements What a method needs from the model beyond one backward pass, and from the likelihood.
core.Capabilities What the probe found. Each capability is independent of the others.
core.probe Capability probe: run the model once and record what works.
CapabilityError A requested method needs something the model or likelihood doesn’t support.
StructureError Shapes or structures don’t fit together, such as a prior and a curvature.
core.exact_fits Whether n_samples=None gives the exact output covariance by strategy.
core.resolve_strategy The pushforward mode strategy=None picks, for \(E\) output entries and \(P\) parameters.
core.check_outputs_args Refuse what predict_outputs refuses before any forward.
core.is_transformed Whether t is wrapped by a torch.func transform (a vmap, grad or jvp level).

Pytrees

core.pytree Make cls a frozen dataclass registered as a torch pytree node.
core.static Mark a field as static: part of the structure, not a pytree leaf.
core.as_pytree Turn each mapping that torch’s pytree would treat as a leaf into a plain dict.
core.hyperparameters Every hyperparameter of a posterior a tuner may change.
core.HasPrior A posterior that keeps its prior, so a tuner can reach the prior precision.
core.HasLikelihood A posterior that keeps its likelihood, so a tuner can reach its hyperparameters.
core.TunableLikelihood A likelihood with hyperparameters a tuner may change, such as a learned sigma.
core.detach_leaves Detach every tensor leaf of a pytree.
core.replace_leaves Swap leaves of a pytree by identity.

Plugin records

Plugin A plugin’s record, the target of its laplacekit.plugins entry point.
PluginInfo One registered plugin: its package metadata, its supports range, what it provides.
Plugins The registered plugins. print lists them.
HealthCheck One result of lk.health().
HealthReport What lk.health() found, per package. print lists the checks.

Testing plugins

Conformance checks for plugin authors.

testing.check_curvature Check a curvature (Curvature or Staged) against the core contracts.
testing.check_prior Check a prior against the core contracts.
testing.check_likelihood Check a likelihood’s laws at outputs f and targets y (one batch).
testing.check_link Check a link approximation against the core contracts.
testing.check_subset Check a subset against the core contracts.
testing.check_objective Check a tuning objective against the core contracts.
testing.check_predictive Check a predictive against the core contracts.