# Your first plugin

The smallest contract in laplace**kit** is a subset. It is a function that gets the model and what [the probe](../plugins/requirements.llms.md) found, and returns the parameters that get a posterior. We write one, `last_layers(n)`, which picks the last $n$ layers, and ship it as a package with a test and an entry point. The package lives in its own repository, [`laplacekit-plugin-example`](https://github.com/laplacekit/laplacekit-plugin-example). It doubles as a template: GitHub’s **Use this template** button starts a new plugin from it.

## The code

A plugin is an import package, here `laplacekit_example`. All of it fits in its `__init__.py`:

``` python
"""The example plugin from the docs, a parameter subset of the last `n` layers."""

import laplacekit as lk
from laplacekit.core import (
    ROOT_BLOCK,
    Capabilities,
    CapabilityError,
    ModelFn,
    Params,
    StructureError,
    Subset,
)

__all__ = ["last_layers"]


def last_layers(n: int) -> Subset:
    """Select the parameters of the last `n` modules with parameters that ran in the probe.

    Args:
        n: The number of modules, at least 1.

    Returns:
        A `Subset`. Called with the model and the probe's capabilities, it returns the
        parameters that those modules hold themselves, by their full names. A call
        raises `StructureError` when the model has no module, and `CapabilityError` when
        the probe found fewer than `n` modules with parameters.

    Raises:
        ValueError: `n` is below 1.
    """

    if n < 1:
        raise ValueError(f"last_layers needs n >= 1, got {n}")

    def subset(model: ModelFn, caps: Capabilities, /) -> Params:
        if model.module is None:
            raise StructureError("last_layers needs a module, but ModelFn.module is None")

        found = caps.module_order

        if len(found) < n:
            raise CapabilityError(
                f"last_layers({n}): the probe found {len(found)} parameterized modules"
            )

        params = {}

        for name in found[-n:]:
            module = model.module if name == ROOT_BLOCK else model.module.get_submodule(name)
            prefix = "" if name == ROOT_BLOCK else f"{name}."

            for own, p in module.named_parameters(recurse=False):
                params[prefix + own] = p

        return params

    return subset


plugin = lk.Plugin(supports=">=1.0,<2")
"""The record behind the `laplacekit.plugins` entry point."""
```

A subset is called after the probe has run the model on the first batch, and before any data goes into the fit. `caps.module_order` lists the modules that own parameters, in the order their forward finished, so the last $n$ entries are the last $n$ layers. The root module comes first as `ROOT_BLOCK` when it owns parameters itself. If we ask for more layers than the model has, it raises `CapabilityError` with the count instead of returning fewer layers.

The subset returns the module’s own parameter tensors under their names. It must not copy them: a copy fails `check_subset`.

## Using it

The function goes wherever a built-in subset goes. We fit a small classifier on four blobs and put a posterior on its last two layers. There is no scikit-learn in the template, so add it first with `uv add --dev scikit-learn`.

``` python
import torch
from laplacekit_example import last_layers
from sklearn.datasets import make_blobs
from torch import nn

import laplacekit as lk

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, 16), nn.Tanh(), nn.Linear(16, 16), nn.Tanh(), nn.Linear(16, 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()

post = lk.laplace(
    model, [(x, y)], likelihood=lk.Categorical(), subset=last_layers(2)
)
print(post)
```

    LaplacePosterior(
      subset         = last_layers {"2.weight": (16, 16), "2.bias": (16,), "4.weight": (4, 16), "4.bias": (4,)}
      hessian_approx = PerBlockCurvature({'*': DenseGGN()})
      curvature      = BlockDiag[Dense] (2 blocks, 340 parameters)
      prior          = Isotropic(prior_precision=0.611)
      likelihood     = Categorical()
      hyper_tuner    = MarginalLikelihood()
      n_data         = 400
    )

The posterior covers layers `2` and `4`, the last two `Linear` layers. Layer `0` stays a point estimate.

## The test

`lk.testing.check_subset` checks what every subset must do: return a non-empty mapping of the module’s own parameters, by their names, and the same selection on a second call. On top of that, we compare the result against names we write out by hand:

``` python
import laplacekit as lk
import pytest
import torch
from torch import nn

from laplacekit_example import last_layers


def mlp() -> nn.Sequential:
    torch.manual_seed(0)

    return nn.Sequential(nn.Linear(2, 8), nn.Tanh(), nn.Linear(8, 8), nn.Tanh(), nn.Linear(8, 3))


def probed(model: nn.Module) -> lk.core.Capabilities:
    batch = lk.Batch(torch.randn(4, 2), torch.zeros(4, dtype=torch.long))

    return lk.core.probe(lk.core.ModelFn.from_module(model), lk.Categorical(), batch, params={})


def select(subset: lk.core.Subset, model: nn.Module) -> lk.core.Params:
    chosen = subset(lk.core.ModelFn.from_module(model), probed(model))
    assert not isinstance(chosen, lk.core.Selection)

    return chosen


def test_passes_the_subset_checks():
    model = mlp()

    for n in (1, 2, 3):
        lk.testing.check_subset(last_layers(n), model, probed(model))


def test_selects_the_last_two_layers():
    model = mlp()
    params = select(last_layers(2), model)

    assert list(params) == ["2.weight", "2.bias", "4.weight", "4.bias"]
    assert params["4.weight"] is model[4].weight
```

The full file also checks the forward order (a layer defined first but run last is the last layer), the root module’s own parameters, each error, and that `lk.plugins()` finds the package. From a clone of the repository, run it with:

``` bash
uv sync
uv run pytest
```

[Testing](../plugins/testing.llms.md) lists the checkers for the other kinds of plugin.

## The package

The package is a `pyproject.toml` next to `src/` and `tests/`. Its first part:

``` toml
[project]
name = "laplacekit-example"
version = "1.0.0"
description = "The docs' example plugin: the last n layers as a subset"
authors = [{ name = "Agustinus Kristiadi", email = "agustinus@kristia.de" }]
license = "MIT"
requires-python = ">=3.11"
dependencies = ["laplacekit>=1.0,<2"]

[project.entry-points."laplacekit.plugins"]
laplacekit_example = "laplacekit_example:plugin"

[build-system]
requires = ["uv_build>=0.13.0,<0.14"]
build-backend = "uv_build"

[dependency-groups]
dev = [
  "pytest>=8",
  "ruff>=0.14",
  "ty>=0.0.104",
  "import-linter>=2.1",
]
```

The rest of the file configures `ruff`, `import-linter` (see [Testing](../plugins/testing.llms.md#imports)) and `pytest`.

The convention is `laplacekit-<name>` for the distribution and `laplacekit_<name>` for the import package. The entry point in the group `laplacekit.plugins` names the import package and points at its `plugin`, the `lk.Plugin` record at the bottom of `__init__.py`. Its `supports` says which laplace**kit** versions the plugin works with. The `dev` group is for working on the plugin only, so a project that installs the plugin keeps its own `laplacekit`.

Running `uv sync` in a clone makes an editable install, so Python sees the package and its entry point.

## Listing it

`lk.plugins()` reads the entry points of everything installed. Each plugin’s summary is the `description` from its `pyproject.toml`, and under it come the names in its `__all__`, each with the first line of its docstring.

``` python
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 this page’s own package, installed with the docs and never published.

Next, [Plugin record and health](../plugins/record.llms.md) adds checks to `lk.health()`, and [Publishing](../plugins/publishing.llms.md) puts the package on PyPI.
