# Library integrations

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

A library integration gives another library’s models a front door. It uses the same protocols as the other guides, plus a `ModelFn` that tells the core how to call the model. As an example, we go through `laplacekit-diffusers`, which fits a Laplace approximation to the denoiser of a diffusion model:

``` python
post = lk.diffusers.laplace(unet, scheduler, loader)
```

It has four parts: a `ModelFn` wrapper, a `prepare` function that turns raw batches into inputs and targets, the checks that run before any data, and the plugin record. The excerpts below are the package’s own source, with the docstrings left out.

## The model

``` python
def denoiser(unet: nn.Module, /) -> lk.core.ModelFn:
    def forward(params: Params, inputs: Inputs) -> Outputs:
        if not isinstance(inputs, Mapping):
            raise lk.StructureError(
                f"lk.diffusers.model needs inputs {{'sample', 'timestep', ...}}, got "
                f"{type(inputs).__name__}"
            )

        missing = [k for k in _POSITIONAL if k not in inputs]

        if missing:
            raise lk.StructureError(f"lk.diffusers.model needs {', '.join(missing)} in the inputs")

        # As in `ModelFn.from_module`: a tensor passed under one name reaches its other names
        # through functional_call's tying, so none of its names goes into `fixed`.
        passed = {id(p) for k, p in unet.named_parameters(remove_duplicate=False) if k in params}
        fixed = {k: v.detach() for k, v in unet.named_parameters() if id(v) not in passed}
        rest = {k: v for k, v in inputs.items() if k not in _POSITIONAL}

        out = functional_call(
            unet, {**fixed, **params}, (inputs["sample"], inputs["timestep"]), rest
        )

        if not isinstance(out, BaseOutput) or "sample" not in out:
            raise lk.StructureError(
                f"lk.diffusers.model needs a model that returns a diffusers BaseOutput with a "
                f"`sample`, got {type(out).__name__}"
            )

        return out["sample"]

    return lk.core.ModelFn(forward, unet)
```

The core calls every model as `forward(params, inputs)`, a function of the parameters it fits. `lk.core.ModelFn.from_module` covers `module(x)` for a tensor and `module(**x)` for a mapping, and returns whatever the module returns. But a `diffusers` denoiser takes the noisy sample and the timestep positionally, plus conditioning such as class labels by name, and returns a `BaseOutput`. So the wrapper takes a mapping of inputs, calls the network with `torch.func.functional_call`, and returns the output’s `.sample`. Parameters that are not fitted are passed detached, so no gradient flows into them. Passing the module as the second argument of `lk.core.ModelFn` lets the probe find its layers, which subsets such as `last_layer` then read.

## The data

A diffusion model is trained on clean samples $x_0$, but its loss is a regression. At a random timestep $t$, it predicts the noise $\epsilon$ in $x_t = \sqrt{\bar\alpha_t} \, x_0 + \sqrt{1 - \bar\alpha_t} \, \epsilon$. The Laplace approximation needs that regression’s inputs and targets, so `prepare` builds them from each raw batch:

``` python
def _prepare(
    scheduler: _NoiseScheduler, prediction: _Prediction, steps: int, velocity: _Velocity | None
) -> Callable[[Any, torch.Generator], lk.Batch]:
    def prepare(raw: Any, generator: torch.Generator, /) -> lk.Batch:
        x0, cond = _split(raw)

        g = generator
        t = torch.randint(0, steps, (len(x0),), generator=g, device=g.device).to(x0.device)
        eps = torch.randn(x0.shape, generator=g, dtype=x0.dtype, device=g.device).to(x0.device)
        x_t = scheduler.add_noise(x0, eps, t)

        match prediction:
            case "epsilon":
                target = eps
            case "v_prediction":
                # `_check_scheduler` gives a velocity for every "v_prediction" scheduler.
                assert velocity is not None
                target = velocity(x0, eps, t)
            case "sample":
                target = x0

        return lk.Batch({"sample": x_t, "timestep": t, **cond}, target)

    return prepare
```

`lk.data.from_loader(data, prepare=...)` calls `prepare(raw, generator)` on every batch. The generator is the batch’s own, seeded from the pass and the examples before the batch. So $t$ and $\epsilon$ are the same each time the fit sees the batch, and the curvature’s statistic stays a [monoid](../plugins/statistics.llms.md). `prediction` is the scheduler’s `prediction_type`, a value from a third-party config. `_check_scheduler` has already checked it against an allow-list, so the `match` covers every case.

## The front door

`laplace` puts the parts together and hands the rest to `lk.laplace`:

``` python
def laplace(
    unet: nn.Module,
    scheduler: object,
    data: Iterable[Tensor | Mapping[str, Tensor]],
    *,
    n_data: int | None = None,
    subset: Subset | Params | Selection = lk.subsets.last_layer,
    hessian_approx: lk.core.HessianApprox[Any] | None = None,
    prior: lk.core.Prior = lk.priors.Isotropic(),  # noqa: B008  # immutable
    hyper_tuner: lk.core.HyperTuner | None = lk.MarginalLikelihood(),  # noqa: B008  # immutable
    generator: torch.Generator | None = None,
) -> lk.LaplacePosterior[Any, Any]:
    sched, prediction, steps, velocity = _check_scheduler(scheduler)
    fn = denoiser(unet)

    src = lk.data.from_loader(
        data, prepare=_prepare(sched, prediction, steps, velocity), n_data=n_data
    )
    # Only the shapes of this batch matter, so a fixed generator draws it.
    first = next(iter(src(torch.Generator())), None)

    if first is None:
        raise ValueError("lk.diffusers.laplace: the data yielded no batches")

    with torch.no_grad():
        out = fn({}, first.inputs)

    target = first.targets

    if not isinstance(out, Tensor) or not isinstance(target, Tensor):
        raise lk.StructureError("lk.diffusers.laplace needs tensor outputs and targets")

    if out.shape != target.shape:
        raise lk.StructureError(
            f"lk.diffusers.laplace: the model's output {tuple(out.shape)} does not match the "
            f"target {tuple(target.shape)}; models with learned variance "
            f"(`out_channels == 2 * in_channels`) are not supported"
        )

    return lk.laplace(
        fn,
        src,
        lk.Gaussian(sigma=1.0, event_dims=target.ndim - 1),
        subset=subset,
        hessian_approx=hessian_approx,
        prior=prior,
        hyper_tuner=hyper_tuner,
        generator=generator,
    )
```

The checks come first. `_check_scheduler` runs on the scheduler alone, before any data. It checks the scheduler against runtime-checkable protocols, one per member it needs. It also checks `prediction_type` against the allow-list, and checks on three timesteps that the noise is variance-preserving. Then, before the fit starts, one batch goes through the network to check that the output has the target’s shape. Each check raises `StructureError` naming what is wrong. Here, `EulerDiscreteScheduler`, whose noise is not variance-preserving, is refused before the data is touched:

``` python
from diffusers import EulerDiscreteScheduler, UNet2DModel

import laplacekit as lk


def untouched():
    raise AssertionError("the data was read")
    yield


unet = UNet2DModel(
    sample_size=8,
    in_channels=1,
    out_channels=1,
    layers_per_block=1,
    block_out_channels=(8, 16),
    norm_num_groups=4,
    down_block_types=("DownBlock2D", "DownBlock2D"),
    up_block_types=("UpBlock2D", "UpBlock2D"),
    add_attention=False,
)

try:
    lk.diffusers.laplace(unet, EulerDiscreteScheduler(), untouched())
except lk.StructureError as e:
    print(e)
```

    lk.diffusers.laplace needs a variance-preserving (DDPM-family) scheduler, where add_noise gives sqrt(abar_t) x0 + sqrt(1 - abar_t) eps; EulerDiscreteScheduler is not

## The record

The package ends with its health check and the record its entry point names, as in [Plugin record and health](../plugins/record.llms.md):

``` python
def health() -> tuple[lk.HealthCheck, ...]:
    try:
        return (lk.HealthCheck("diffusers", "ok", metadata.version("diffusers")),)
    except metadata.PackageNotFoundError:
        return (lk.HealthCheck("diffusers", "error", "not installed (required)"),)
```

``` python
plugin = lk.Plugin(supports=">=1.0,<2", health=health)
```

`laplacekit-diffusers` is first-party, so `laplacekit` also has a `diffusers` extra and the `lk.diffusers` alias, which imports the package on first use. A third-party integration is the same package without those two, and users import it by name. The [Overview](../plugins/overview.llms.md) has the comparison.

## The test

There is no checker for a whole integration, so its tests compare against a reference written by hand. The `diffusers` tests fit the same tiny `UNet2DModel` twice: once with `lk.diffusers.laplace`, and once with `lk.laplace` on a hand-written model function and a `prepare` that builds $x_t$ from the scheduler’s $\bar\alpha_t$ directly. The two posteriors must agree in the mean, the prior, the data fit and the covariance, for each `prediction_type`. Other tests check each refusal before data, as above, and that conditioning entries such as `class_labels` reach the network.
