# laplacekit_gp

`laplacekit_gp`

GP methods for function-space Laplace: ELLA, VaLLA and FSP-Laplace.

The methods are ELLA (Deng et al. 2022), VaLLA (Ortega et al. 2024) and FSP-Laplace (Cinquin et al. 2024). ELLA approximates the linearized network’s kernel with Nyström features. VaLLA fits variational inducing points. FSP-Laplace places a GP prior on the network’s outputs.

Code reaches this package as `lk.gp`, which imports it on first use.

## Attributes

| Name | Description |
|----|----|
| [MAX_BASIS_ENTRIES](#laplacekit_gp.MAX_BASIS_ENTRIES) | The largest array `ELLA` builds, in entries: $2^{28}$, which is 1 GiB in float32. |
| [MAX_CONTEXT_JACOBIAN_ENTRIES](#laplacekit_gp.MAX_CONTEXT_JACOBIAN_ENTRIES) | The most entries $n_C E P$ of the Jacobian at the context points: $2^{28}$, which is 2 GiB in |
| [MAX_KMEANS_ENTRIES](#laplacekit_gp.MAX_KMEANS_ENTRIES) | The most input entries (rows times entries per row) that the `kmeans` pass may hold. |

## Classes

| Name | Description |
|----|----|
| [Drawn](#laplacekit_gp.Drawn) | Points that need no data. |
| [ELLA](#laplacekit_gp.ELLA) | ELLA (Deng et al. 2022), the linearized Laplace GP on a Nyström basis of rank `rank`. |
| [FSPPosterior](#laplacekit_gp.FSPPosterior) | FSP-Laplace’s posterior over the weights, $\mathcal{N}(\theta_*, S S^\top)$. |
| [FunctionPrior](#laplacekit_gp.FunctionPrior) | A GP prior over the outputs, $f \sim \mathcal{GP}(\mu, k)$, shared by every output entry. |
| [Matern](#laplacekit_gp.Matern) | The Matérn kernel with smoothness $\nu$, on $s = \lVert (x - y) / \ell \rVert$. |
| [NystromGP](#laplacekit_gp.NystromGP) | The linearized Laplace posterior on a Nyström basis, as a GP over the outputs. |
| [Periodic](#laplacekit_gp.Periodic) | The periodic kernel, a product over the flattened input entries $d$. |
| [Picked](#laplacekit_gp.Picked) | The points a method uses, with what it needs to place outputs on them. |
| [Points](#laplacekit_gp.Points) | Where a method evaluates its kernel. |
| [Product](#laplacekit_gp.Product) | The product kernel $a(x, y) \, b(x, y)$, entrywise, also written `a * b`. |
| [RBF](#laplacekit_gp.RBF) | The RBF kernel $k(x, y) = \sigma^2 \exp(-\tfrac{1}{2} \lVert (x - y) / \ell \rVert^2)$. |
| [RangePrecision](#laplacekit_gp.RangePrecision) | The precision of an `FSPPosterior`, $V \operatorname{diag}(d) V^\top$. |
| [Sum](#laplacekit_gp.Sum) | The sum kernel $a(x, y) + b(x, y)$, also written `a + b`. |
| [VaLLA](#laplacekit_gp.VaLLA) | VaLLA (Ortega et al. 2024), the linearized Laplace GP with variational inducing outputs. |
| [VariationalGP](#laplacekit_gp.VariationalGP) | The linearized Laplace prior conditioned on $M$ inducing outputs, as a GP over the outputs. |

### Drawn

``` python
Drawn()
```

Points that need no data.

#### Methods

| Name                              | Description      |
|-----------------------------------|------------------|
| [draw](#laplacekit_gp.Drawn.draw) | Draw the points. |

##### draw

``` python
Drawn.draw(generator=None)
```

Draw the points.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| generator | torch.Generator \| None | The generator to draw with. `None` means torch’s global RNG. Points that are not random ignore it. | `None` |

###### Returns

| Name | Type   | Description                                           |
|------|--------|-------------------------------------------------------|
|      | Inputs | The points, with the examples along the leading axis. |

### ELLA

``` python
ELLA(points, rank=static(), *, outputs='random', strategy=None)
```

ELLA (Deng et al. 2022), the linearized Laplace GP on a Nyström basis of rank `rank`.

`points` selects $m$ inputs. At each one, `outputs` decides which $k$ Jacobian rows to take, and the rows stack into $R$, `[m k, P]`. The top `rank` eigenpairs $(U, \Lambda)$ of the kernel $K = R R^\top$, computed in float64, give the basis

$$V = R^\top U \Lambda^{-1/2}.$$

A second pass sums the GGN projected onto $V$, and `fs.laplace` returns a `NystromGP`.

The prior must be an `Isotropic` with one precision, because `NystromGP` applies it after the fit, as it does the likelihood’s `curvature_scale`. `plan` refuses any other prior before it reads data.

The kernel needs `rank` eigenvalues above ELLA’s tolerance, $\epsilon \max(m k, P) \max_i |\lambda_i|$, where $\lambda_i$ are the eigenvalues of $K$ and $\epsilon$ is the float64 machine epsilon. With fewer, the fit raises `ValueError` and names the usable rank. Every built-in `Points` knows $m$ in advance, so $m k < \text{rank}$ is caught before any data. Duplicate points and a Jacobian of lower rank show up once the points are picked, before the second pass. k-means can snap two centres to the same data row, and such duplicates lower the usable rank.

An output coordinate outside $[0, E)$ raises `StructureError`. Given coordinates are checked before any data, and picked ones as soon as the points are picked.

`MAX_BASIS_ENTRIES` caps the basis ($P \cdot \text{rank}$ entries), the picked rows ($m k P$) and, in reverse mode, the Jacobian of one input ($E P$). Going over raises `StructureError` with the sizes. Each cap is checked before any data, except $m k P$ for points picked from the data, which is checked once they are picked. A model whose outputs are not one tensor is refused before any data when the likelihood is a mapping, and before the second pass otherwise.

The model must support vjp and vmap to form the rows, and jvp as well with `strategy="forward-mode"`. The likelihood needs an output Hessian, or sampling for the Monte Carlo Fisher. Points picked from the data refuse weighted batches. With `fixed` points, the second pass uses the weights.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| points | Points | Selects the $m$ inputs, for example `fixed`, `from_data` or `kmeans`. | *required* |
| rank | int | The rank $r$ of the basis. | `static()` |
| outputs | \_Outputs | Which Jacobian rows each point gives. `"random"` gives one row ($k = 1$), at the coordinate the point carries (`fixed(..., coords)`) or at $\lfloor u E \rfloor$ for its `Picked.u`. `"all"` gives all $k = E$ rows. | `'random'` |
| strategy | Strategy \| None | How the second pass and `NystromGP.at` form $\Phi$. `None` uses forward mode when the probe found jvp and reverse mode otherwise, as laplace-torch does. `"forward-mode"` or `"reverse-mode"` sets the mode, and `fs.laplace` refuses before any data when the probe did not find it. | `None` |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `rank` is below 1, `outputs` is neither `"random"` nor `"all"`, or `strategy` is not `"forward-mode"`, `"reverse-mode"` or `None`. |

#### Attributes

| Name | Description |
|----|----|
| [requires](#laplacekit_gp.ELLA.requires) | What the passes need: vjp, vmap, an output Hessian, and jvp in forward mode. |

#### Methods

| Name | Description |
|----|----|
| [plan](#laplacekit_gp.ELLA.plan) | Plan the passes: pick the points, build the basis, then sum the projected GGN. |

##### plan

``` python
ELLA.plan(params, ctx, prior, /)
```

Plan the passes: pick the points, build the basis, then sum the projected GGN.

`Drawn` points need no data, so `plan` builds the basis right away and raises its errors itself. Points picked from the data build the basis after the pass that picks them.

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Pass\[NystromGP\] | The first pass. Running it raises `ValueError` when the data has no examples, the total weight is zero, a weight is negative or the kernel has fewer than `rank` usable directions, and `StructureError` when the model’s outputs are not one tensor, a picked coordinate lies outside $[0, E)$ or $m k P$ exceeds `MAX_BASIS_ENTRIES`. |

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| params | Params | The parameters to fit, as the fit’s subset gives them. | *required* |
| ctx | FitContext | The fit’s context: the model, the likelihood, the capabilities the probe found, and the layout of the parameters. | *required* |
| prior | PriorWithCovariance | The prior over the parameters. | *required* |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | The prior is not an `Isotropic` with one precision, the likelihood is a mapping, a budget known before data fails, a given coordinate lies outside $[0, E)$, or the MC Fisher (a likelihood without `HasOutputHessian`) would form dense blocks above `MAX_DENSE_EVENT`. With `Drawn` points, also when the model’s outputs are not one tensor, a picked coordinate lies outside $[0, E)$ or $m k P$ exceeds `MAX_BASIS_ENTRIES`. |
|  | ValueError | The points give fewer than `rank` Jacobian rows, or, with `Drawn` points, the kernel has fewer than `rank` usable directions. |
|  | TypeError | `points.pick` returns `Done` instead of handing its points on. |

### FSPPosterior

``` python
FSPPosterior(
    model=static(),
    likelihood,
    mean,
    caps=static(),
    layout=static(),
    basis,
    prior_evals,
    gram,
    n_data,
    context_jac,
    prior_var,
    kernel=static(),
    strategy=static(),
    versions=dict[str, int](),
)
```

FSP-Laplace’s posterior over the weights, $\mathcal{N}(\theta_*, S S^\top)$.

$\theta_*$ is `mean`, and $S$ has rank $r' \le r$. Let $c$ be the likelihood’s curvature scale (1 if it has none). Every use rebuilds $S$ (steps 5 to 9 of Algorithm 2), so it reads the current $\sigma$ from `likelihood`:

- Diagonalize $A = \operatorname{diag}(D_M^2) + s c G = U_A D_A U_A^\top$, with the eigenvalues in ascending order.
- Drop the eigenvalues at most $\epsilon r \max_i (D_A)_{ii}$, where $\epsilon$ is the machine epsilon of the dtype of `gram`. This takes the pseudo-inverse of $A$, since rounding gives $A$ eigenvalues at or below zero when $D_M^2$ spans many decades.
- Set $S = U_M U_A D_A^{-1/2}$ on the remaining eigenvalues.
- Drop the first $k$ columns, which carry the most variance. $k$ is the smallest number for which the variance at every context point, $\operatorname{diag}\big(J(C) S S^\top J(C)^\top\big)$, is at most $v_C (1 + 100 \epsilon)$. Without data near a context point, the variance there equals the prior’s in exact arithmetic, and the slack keeps rounding from dropping the column with the most variance.

`lk.core.mean_outputs`, `lk.predict_outputs` and `lk.sample_outputs` call `check_versions` first (`HasVersions`).

Predict with `Linearized`, the default of `lk.predict(post, x)`. `WeightSamples` and `sample_outputs(kind="network")` also run, but the covariance is large along the directions that the context points barely constrain, so draws of the network can be far from the linearized predictive.

The posterior is degenerate, with rank $r' < P$. `log_prob` and `add_precision_to` raise `StructureError`, and `precision()` returns a `RangePrecision`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| model | ModelFn | The model as a function of the parameters. | `static()` |
| likelihood | \_L_co | The likelihood of the fit. Its `sigma` is read on every use. | *required* |
| mean | Params | The fitted parameters $\theta_*$. | *required* |
| caps | Capabilities | The model’s capabilities. | `static()` |
| layout | Layout | The block layout of the parameters. | `static()` |
| basis | Tensor | $U_M$, `[P, r]`. | *required* |
| prior_evals | Tensor | $D_M^2$, `[r]`. | *required* |
| gram | Tensor | $G = U_M^\top \bar{G} U_M$, `[r, r]`, where $\bar{G}$ is the per-example average of the GGN without the likelihood’s curvature scale. | *required* |
| n_data | Tensor | $s$, the total weight of the data. | *required* |
| context_jac | Tensor | $J(C) U_M$, `[n_C E, r]`, where $J(C)$ is the Jacobian at the context points $C$. | *required* |
| prior_var | Tensor | $v_C$, the jittered diagonal of the prior covariance at $C$, repeated over the $E$ outputs, `[n_C E]`. | *required* |
| kernel | str | The name of the prior’s kernel, for display only. The kernel itself was used at fit time. | `static()` |
| strategy | Strategy | How the fit formed $J(x) U_M$ for the Gram matrix. | `static()` |
| versions | Mapping\[str, int\] | The version counters of the module’s fixed parameters at fit time (see `check_versions`). | `dict[str, int]()` |

#### Attributes

| Name | Description |
|----|----|
| [variance](#laplacekit_gp.FSPPosterior.variance) | $\operatorname{diag}(S S^\top)$. |

#### Methods

| Name | Description |
|----|----|
| [add_precision_to](#laplacekit_gp.FSPPosterior.add_precision_to) | Not available, because the posterior cannot be the prior of a Laplace update. |
| [check_versions](#laplacekit_gp.FSPPosterior.check_versions) | Raise `RuntimeError` if a fixed parameter of the module changed in place since the fit. |
| [cov_mv](#laplacekit_gp.FSPPosterior.cov_mv) | $S S^\top v$. |
| [cov_sqrt_mv](#laplacekit_gp.FSPPosterior.cov_sqrt_mv) | $L v$ with the square root $L = [S, 0]$, so $L L^\top = S S^\top$. |
| [location](#laplacekit_gp.FSPPosterior.location) | The mean, after checking that it has the names, shapes, dtypes and devices of `like`. |
| [log_prob](#laplacekit_gp.FSPPosterior.log_prob) | Not available, because the posterior has no density over the weights. |
| [precision](#laplacekit_gp.FSPPosterior.precision) | The pseudo-inverse of $S S^\top$, which is $V D_A V^\top$ with $V = U_M U_A$. |
| [sample](#laplacekit_gp.FSPPosterior.sample) | `n` draws from $\mathcal{N}(\theta_*, S S^\top)$. |
| [sample_centered](#laplacekit_gp.FSPPosterior.sample_centered) | `n` draws $S z$ with $z \sim \mathcal{N}(0, I)$, in the basis’s dtype. |

##### add_precision_to

``` python
FSPPosterior.add_precision_to(op, /)
```

Not available, because the posterior cannot be the prior of a Laplace update.

###### Parameters

| Name | Type | Description                                    | Default    |
|------|------|------------------------------------------------|------------|
| op   | Op   | The operator that would receive the precision. | *required* |

###### Returns

| Name | Type | Description                                                  |
|------|------|--------------------------------------------------------------|
|      | Op   | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

##### check_versions

``` python
FSPPosterior.check_versions()
```

Raise `RuntimeError` if a fixed parameter of the module changed in place since the fit.

The basis, the context Jacobian and the Gram matrix were computed with the old value, so the posterior no longer describes the model. `cov_mv`, `cov_sqrt_mv`, `sample_centered`, `sample`, `lk.core.mean_outputs`, `lk.predict_outputs` and `lk.sample_outputs` call this first.

##### cov_mv

``` python
FSPPosterior.cov_mv(v, /)
```

$S S^\top v$.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| v | Params | A parameter mapping, with the names and shapes of the mean. | *required* |

###### Returns

| Name | Type   | Description                                    |
|------|--------|------------------------------------------------|
|      | Params | $S S^\top v$, as a parameter mapping like `v`. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |

##### cov_sqrt_mv

``` python
FSPPosterior.cov_sqrt_mv(v, /)
```

$L v$ with the square root $L = [S, 0]$, so $L L^\top = S S^\top$.

Only the first $r'$ entries of $v$ matter.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| v | Params | A parameter mapping, with the names and shapes of the mean. | *required* |

###### Returns

| Name | Type   | Description                             |
|------|--------|-----------------------------------------|
|      | Params | $L v$, as a parameter mapping like `v`. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |

##### location

``` python
FSPPosterior.location(like, /)
```

The mean, after checking that it has the names, shapes, dtypes and devices of `like`.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| like | Params | A parameter mapping whose names, shapes, dtypes and devices the mean must match. | *required* |

###### Returns

| Name | Type   | Description           |
|------|--------|-----------------------|
|      | Params | The mean, $\theta_*$. |

##### log_prob

``` python
FSPPosterior.log_prob(params, /)
```

Not available, because the posterior has no density over the weights.

###### Parameters

| Name   | Type   | Description                                      | Default    |
|--------|--------|--------------------------------------------------|------------|
| params | Params | The parameters at which to evaluate the density. | *required* |

###### Returns

| Name | Type   | Description                                                  |
|------|--------|--------------------------------------------------------------|
|      | Tensor | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

##### precision

``` python
FSPPosterior.precision()
```

The pseudo-inverse of $S S^\top$, which is $V D_A V^\top$ with $V = U_M U_A$.

Both use only the kept columns.

###### Returns

| Name | Type           | Description                                          |
|------|----------------|------------------------------------------------------|
|      | RangePrecision | The pseudo-inverse precision, as a `RangePrecision`. |

##### sample

``` python
FSPPosterior.sample(n, /, *, generator=None)
```

`n` draws from $\mathcal{N}(\theta_*, S S^\top)$.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| n | int | The number of draws. | *required* |
| generator | torch.Generator \| None | The generator to draw with, on any device: the draws move to the basis’s. `None` means torch’s global RNG. | `None` |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Params | A parameter mapping whose tensors have a leading axis of `n` draws. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |

##### sample_centered

``` python
FSPPosterior.sample_centered(n, /, *, generator=None)
```

`n` draws $S z$ with $z \sim \mathcal{N}(0, I)$, in the basis’s dtype.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| n | int | The number of draws. | *required* |
| generator | torch.Generator \| None | The generator to draw with, on any device: the draws move to the basis’s. `None` means torch’s global RNG. | `None` |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Params | A parameter mapping whose tensors have a leading axis of `n` draws. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |

### FunctionPrior

``` python
FunctionPrior(kernel, mean=None, jitter=1e-06)
```

A GP prior over the outputs, $f \sim \mathcal{GP}(\mu, k)$, shared by every output entry.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| kernel | Kernel | The kernel $k$. | *required* |
| mean | Callable\[\[Tensor\], Tensor\] \| None | The mean $\mu$, a function from inputs `[n, ...]` to outputs shaped like the network’s. `None` means zero. | `None` |
| jitter | float | The relative jitter $\delta \ge 0$ that `cov` adds. | `1e-06` |

#### Raises

| Name | Type       | Description           |
|------|------------|-----------------------|
|      | ValueError | `jitter` is negative. |

#### Methods

| Name | Description |
|----|----|
| [cov](#laplacekit_gp.FunctionPrior.cov) | The prior covariance at `x`, $K + \delta \, \overline{\operatorname{diag} K} \, I$. |

##### cov

``` python
FunctionPrior.cov(x, /)
```

The prior covariance at `x`, $K + \delta \, \overline{\operatorname{diag} K} \, I$.

Here $K = k(x, x)$, and $\overline{\operatorname{diag} K}$ is the mean of its diagonal.

###### Parameters

| Name | Type   | Description        | Default    |
|------|--------|--------------------|------------|
| x    | Tensor | Inputs `[n, ...]`. | *required* |

###### Returns

| Name | Type   | Description               |
|------|--------|---------------------------|
|      | Tensor | The covariance, `[n, n]`. |

###### Raises

| Name | Type           | Description             |
|------|----------------|-------------------------|
|      | StructureError | The kernel refuses `x`. |

### Matern

``` python
Matern(nu=static(), lengthscale, variance=_one())
```

The Matérn kernel with smoothness $\nu$, on $s = \lVert (x - y) / \ell \rVert$.

$$k(x, y) = \sigma^2 \begin{cases}
e^{-s} & \nu = 1/2 \text{ (the exponential kernel)}, \\
(1 + \sqrt{3} s) \, e^{-\sqrt{3} s} & \nu = 3/2, \\
(1 + \sqrt{5} s + 5 s^2 / 3) \, e^{-\sqrt{5} s} & \nu = 5/2.
\end{cases}$$

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| nu | Literal\['1/2', '3/2', '5/2'\] | The smoothness $\nu$, one of `"1/2"`, `"3/2"` and `"5/2"`. It is a string because a `Literal` cannot hold floats. | `static()` |
| lengthscale | Tensor | The lengthscale $\ell$, as in `RBF`. | *required* |
| variance | Tensor | The variance $\sigma^2$, as in `RBF`. | `_one()` |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `nu` is another value, or an entry of `lengthscale` or `variance` is not positive. |
|  | StructureError | `lengthscale` or `variance` has a shape `RBF` refuses. |

### NystromGP

``` python
NystromGP(
    model=static(),
    likelihood,
    mean,
    prior,
    caps=static(),
    basis,
    gram,
    n_data,
    strategy=static(),
    versions=dict[str, int](),
)
```

The linearized Laplace posterior on a Nyström basis, as a GP over the outputs.

At inputs $x$, let $\Phi = J(x) V$, `[N, E, r]`, where $J(x)$ is the Jacobian at the mean parameters and $V$ is the basis. The covariance of each input’s outputs is

$$\Phi \, (s c G + \lambda I)^{-1} \, \Phi^\top,$$

where $c$ is the likelihood’s `curvature_scale` (1 if it has none) and $\lambda$ is the prior’s precision. The mean is $f(x)$ at the mean parameters. `at` reads the prior and the likelihood on every call, so tuning $\lambda$ or `sigma` needs no refit.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| model | ModelFn | The model as a function of the parameters. | `static()` |
| likelihood | \_L_co | The likelihood of the fit. Its tensors, such as `sigma`, are leaves that tuning can change. | *required* |
| mean | Params | The fitted parameters. | *required* |
| prior | lk.priors.Isotropic | The prior, an `Isotropic` with one precision $\lambda$. | *required* |
| caps | Capabilities | The model’s capabilities. | `static()` |
| basis | Tensor | The Nyström basis $V$, `[P, r]`. | *required* |
| gram | Tensor | $G$, the per-example average of $\Phi_n^\top H_n \Phi_n$ over the data, `[r, r]`. $H_n$ is the output Hessian without the likelihood’s `curvature_scale`. | *required* |
| n_data | Tensor | $s$, the total weight of the data. | *required* |
| strategy | Strategy | Whether `at` forms $\Phi$ in forward mode (`"forward-mode"`) or reverse mode (`"reverse-mode"`). | `static()` |
| versions | Mapping\[str, int\] | The version counters of the module’s fixed parameters at fit time. `at` raises `RuntimeError` when one has changed in place since then (see `check_versions`). | `dict[str, int]()` |

#### Attributes

| Name | Description |
|----|----|
| [requires](#laplacekit_gp.NystromGP.requires) | What `at` needs to form $\Phi$ at new inputs: vmap, and jvp or vjp by `strategy`. |

#### Methods

| Name | Description |
|----|----|
| [at](#laplacekit_gp.NystromGP.at) | The Gaussian over the outputs at `inputs`, with one $E \times E$ block per input. |
| [check_versions](#laplacekit_gp.NystromGP.check_versions) | Raise `RuntimeError` if a fixed parameter of the module changed in place since the fit. |

##### at

``` python
NystromGP.at(inputs, /)
```

The Gaussian over the outputs at `inputs`, with one $E \times E$ block per input.

The solve uses a Cholesky factor of $s c G + \lambda I$, in the dtype of `gram`.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| inputs | Inputs | The inputs, with the examples along the leading axis. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | OutputGaussian | An `OutputGaussian` whose mean is the network’s outputs at `inputs` and whose covariance holds one $E \times E$ block per input. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | CapabilityError | The model does not support vmap or the mode that `strategy` names. |
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |
|  | StructureError | The model’s outputs are not one tensor, the likelihood’s `curvature_scale` has more than one element, or the prior is no longer an `Isotropic` with one precision. |

##### check_versions

``` python
NystromGP.check_versions()
```

Raise `RuntimeError` if a fixed parameter of the module changed in place since the fit.

The basis and $G$ were computed with the old value. `at` calls this first.

### Periodic

``` python
Periodic(period, lengthscale, variance=_one())
```

The periodic kernel, a product over the flattened input entries $d$.

$$k(x, y) = \sigma^2 \prod_d \exp\!\Big(-\frac{2}{\ell^2}
\sin^2\!\big(\pi \, |x_d - y_d| / p\big)\Big).$$

With one entry per example, this is the 1-D kernel of Rasmussen and Williams (2006), Eq. 4.31. With more entries, it multiplies unit-variance 1-D kernels over the entries and then $\sigma^2$ once, which keeps it positive semidefinite.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| period | Tensor | The period $p$, a positive 0-dim tensor. | *required* |
| lengthscale | Tensor | The lengthscale $\ell$, a positive 0-dim tensor. | *required* |
| variance | Tensor | The variance $\sigma^2$, a positive 0-dim tensor. | `_one()` |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `period`, `lengthscale` or `variance` is not a 0-dim tensor. |
|  | ValueError | One of them is not positive. |

### Picked

``` python
Picked(inputs, u, coords, seen)
```

The points a method uses, with what it needs to place outputs on them.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| inputs | Inputs | The $m$ points, along the leading axis. | *required* |
| u | Tensor | Uniform draws in $[0, 1)$, `[m]` float64. Methods that draw an output coordinate per point use them. | *required* |
| coords | Tensor \| None | Output coordinates, `[m]` int64, used in place of `u`. Only `fixed` sets them. | *required* |
| seen | Tensor | The number of examples the pass read, or 0 when there was no pass. | *required* |

### Points

``` python
Points()
```

Where a method evaluates its kernel.

#### Methods

| Name | Description |
|----|----|
| [pick](#laplacekit_gp.Points.pick) | Pick the points and hand them to `then`. |

##### pick

``` python
Points.pick(params, ctx, then, /)
```

Pick the points and hand them to `then`.

Points that need no data call `then` directly. The others `chain` a pass over the data first.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| params | Params | The fitted params. Points move to their device. | *required* |
| ctx | FitContext | The fit’s context. | *required* |
| then | Callable\[\[Picked\], Pass\[R\] \| Done\[R\]\] | The method’s next step, which takes the `Picked` points. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Pass\[R\] \| Done\[R\] | What `then` returns, or a pass over the data chained before `then`. |

### Product

``` python
Product(a, b)
```

The product kernel $a(x, y) \, b(x, y)$, entrywise, also written `a * b`.

#### Parameters

| Name | Type   | Description        | Default    |
|------|--------|--------------------|------------|
| a    | Kernel | The first kernel.  | *required* |
| b    | Kernel | The second kernel. | *required* |

### RBF

``` python
RBF(lengthscale, variance=_one())
```

The RBF kernel $k(x, y) = \sigma^2 \exp(-\tfrac{1}{2} \lVert (x - y) / \ell \rVert^2)$.

A lengthscale $\ell$ with one entry per flattened input entry divides entrywise.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| lengthscale | Tensor | The lengthscale $\ell$, a positive 0-dim tensor, or a 1-dim one with one entry per flattened input entry. | *required* |
| variance | Tensor | The variance $\sigma^2$, a positive 0-dim tensor. | `_one()` |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `lengthscale` or `variance` is not a tensor of the allowed shape. |
|  | ValueError | An entry of `lengthscale` or `variance` is not positive. |

### RangePrecision

``` python
RangePrecision(vecs, evals)
```

The precision of an `FSPPosterior`, $V \operatorname{diag}(d) V^\top$.

The orthonormal columns of $V$ span the range of the covariance. Vectors are flat, in the order of the posterior’s mean. The matrix has rank $r' < P$. `mv`, `diagonal` and `scaled` work, while `solve`, `inverse_diagonal`, `logdet`, `cov_sqrt_mv` and the `add_*` methods raise `StructureError`.

#### Parameters

| Name  | Type   | Description     | Default    |
|-------|--------|-----------------|------------|
| vecs  | Tensor | $V$, `[P, r']`. | *required* |
| evals | Tensor | $d$, `[r']`.    | *required* |

#### Methods

| Name | Description |
|----|----|
| [add_diagonal](#laplacekit_gp.RangePrecision.add_diagonal) | Not available, because FSP-Laplace’s posterior has no full-rank precision. |
| [add_isotropic](#laplacekit_gp.RangePrecision.add_isotropic) | Not available, because FSP-Laplace’s posterior has no full-rank precision. |
| [add_same](#laplacekit_gp.RangePrecision.add_same) | Not available, because FSP-Laplace’s posterior has no full-rank precision. |
| [cov_sqrt_mv](#laplacekit_gp.RangePrecision.cov_sqrt_mv) | Not available, because the precision is singular. Use `FSPPosterior.cov_sqrt_mv`. |
| [diagonal](#laplacekit_gp.RangePrecision.diagonal) | The diagonal, `[P]`. |
| [inverse_diagonal](#laplacekit_gp.RangePrecision.inverse_diagonal) | Not available, because the precision is singular. |
| [logdet](#laplacekit_gp.RangePrecision.logdet) | Not available, because the precision is singular. |
| [mv](#laplacekit_gp.RangePrecision.mv) | $V \operatorname{diag}(d) V^\top v$. |
| [scaled](#laplacekit_gp.RangePrecision.scaled) | The precision with $d$ multiplied by `s`. |
| [solve](#laplacekit_gp.RangePrecision.solve) | Not available, because the precision is singular. |

##### add_diagonal

``` python
RangePrecision.add_diagonal(d, /)
```

Not available, because FSP-Laplace’s posterior has no full-rank precision.

###### Parameters

| Name | Type   | Description          | Default    |
|------|--------|----------------------|------------|
| d    | Tensor | The diagonal to add. | *required* |

###### Returns

| Name | Type | Description                                                  |
|------|------|--------------------------------------------------------------|
|      | Self | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

##### add_isotropic

``` python
RangePrecision.add_isotropic(precision, /)
```

Not available, because FSP-Laplace’s posterior has no full-rank precision.

###### Parameters

| Name      | Type   | Description           | Default    |
|-----------|--------|-----------------------|------------|
| precision | Tensor | The precision to add. | *required* |

###### Returns

| Name | Type | Description                                                  |
|------|------|--------------------------------------------------------------|
|      | Self | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

##### add_same

``` python
RangePrecision.add_same(other, /)
```

Not available, because FSP-Laplace’s posterior has no full-rank precision.

###### Parameters

| Name  | Type               | Description          | Default    |
|-------|--------------------|----------------------|------------|
| other | Operator\[Tensor\] | The operator to add. | *required* |

###### Returns

| Name | Type | Description                                                  |
|------|------|--------------------------------------------------------------|
|      | Self | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

##### cov_sqrt_mv

``` python
RangePrecision.cov_sqrt_mv(v, /)
```

Not available, because the precision is singular. Use `FSPPosterior.cov_sqrt_mv`.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| v | Tensor | A flat vector `[P]`, in the order of the posterior’s mean. | *required* |

###### Returns

| Name | Type   | Description                                                  |
|------|--------|--------------------------------------------------------------|
|      | Tensor | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

##### diagonal

``` python
RangePrecision.diagonal()
```

The diagonal, `[P]`.

###### Returns

| Name | Type   | Description          |
|------|--------|----------------------|
|      | Tensor | The diagonal, `[P]`. |

##### inverse_diagonal

``` python
RangePrecision.inverse_diagonal()
```

Not available, because the precision is singular.

###### Returns

| Name | Type   | Description                                                  |
|------|--------|--------------------------------------------------------------|
|      | Tensor | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

##### logdet

``` python
RangePrecision.logdet()
```

Not available, because the precision is singular.

###### Returns

| Name | Type   | Description                                                  |
|------|--------|--------------------------------------------------------------|
|      | Tensor | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

##### mv

``` python
RangePrecision.mv(v, /)
```

$V \operatorname{diag}(d) V^\top v$.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| v | Tensor | A flat vector `[P]`, in the order of the posterior’s mean. | *required* |

###### Returns

| Name | Type   | Description                                 |
|------|--------|---------------------------------------------|
|      | Tensor | $V \operatorname{diag}(d) V^\top v$, `[P]`. |

##### scaled

``` python
RangePrecision.scaled(s, /)
```

The precision with $d$ multiplied by `s`.

###### Parameters

| Name | Type   | Description                 | Default    |
|------|--------|-----------------------------|------------|
| s    | Tensor | The factor, a 0-dim tensor. | *required* |

###### Returns

| Name | Type | Description                                     |
|------|------|-------------------------------------------------|
|      | Self | A `RangePrecision` with the same $V$ and $s d$. |

##### solve

``` python
RangePrecision.solve(v, /)
```

Not available, because the precision is singular.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| v | Tensor | A flat vector `[P]`, in the order of the posterior’s mean. | *required* |

###### Returns

| Name | Type   | Description                                                  |
|------|--------|--------------------------------------------------------------|
|      | Tensor | It never returns, because it always raises `StructureError`. |

###### Raises

| Name | Type           | Description |
|------|----------------|-------------|
|      | StructureError | Always.     |

### Sum

``` python
Sum(a, b)
```

The sum kernel $a(x, y) + b(x, y)$, also written `a + b`.

#### Parameters

| Name | Type   | Description        | Default    |
|------|--------|--------------------|------------|
| a    | Kernel | The first kernel.  | *required* |
| b    | Kernel | The second kernel. | *required* |

### VaLLA

``` python
VaLLA(points, *, coords='predicted')
```

VaLLA (Ortega et al. 2024), the linearized Laplace GP with variational inducing outputs.

`points` picks the $M$ inducing inputs, and each gets one output coordinate. A second pass sums the weights of the data without running the model. `fs.laplace` then returns a `VariationalGP` with factor $I$ and that total as its `scale`.

laplace-torch uses the training labels of points picked from the data as their coordinates, where `"predicted"` uses the argmax of the outputs. `fixed(x, coords=y)` gives the label coordinates. In regression with $E > 1$, the argmax depends on the scales of the outputs, and laplace-torch takes output 0.

Any pushable prior works. The model must support vjp and vmap. Points picked from the data refuse weighted batches, and with `fixed` points the count uses the weights. A model whose outputs are not one tensor is refused before any data when the likelihood is a mapping, and otherwise when the coordinates are set, after the points are picked.

Some checks run before any data and raise `StructureError`: coordinates must lie in $[0, E)$, and both $M P$ (the inducing Jacobian rows) and $E P$ (the Jacobian of one input, the smallest block of `at`) must stay within `MAX_BASIS_ENTRIES`. Every built-in `Points` knows $M$ before the data. For other points, $M$ and the coordinates they set are checked when the points are handed over.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| points | Points | Selects the inducing inputs, for example `fixed`, `from_data` or `kmeans`. | *required* |
| coords | \_Coords | How a point gets its output coordinate when `fixed(..., coords)` gives none. `"predicted"` takes the argmax of the outputs at the point, and `"random"` takes $\lfloor u E \rfloor$ for its `Picked.u`. | `'predicted'` |

#### Raises

| Name | Type       | Description                                       |
|------|------------|---------------------------------------------------|
|      | ValueError | `coords` is neither `"predicted"` nor `"random"`. |

#### Attributes

| Name | Description |
|----|----|
| [requires](#laplacekit_gp.VaLLA.requires) | What the passes need: vjp and vmap. Points picked from the data refuse weights. |

#### Methods

| Name | Description |
|----|----|
| [plan](#laplacekit_gp.VaLLA.plan) | Plan the passes: pick the points, then count the data. |

##### plan

``` python
VaLLA.plan(params, ctx, prior, /)
```

Plan the passes: pick the points, then count the data.

`Drawn` points need no data, so `plan` sets their coordinates right away and raises those errors itself. Points picked from the data get their coordinates after the pass that picks them.

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Pass\[VariationalGP\] | The first pass. Running it raises `ValueError` when the data has no examples, a weight is negative or the total weight is not positive, and `StructureError` when the model’s outputs are not one tensor, a picked coordinate lies outside $[0, E)$, or $M P$ exceeds `MAX_BASIS_ENTRIES`. |

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| params | Params | The parameters to fit, as the fit’s subset gives them. | *required* |
| ctx | FitContext | The fit’s context: the model, the likelihood, the capabilities the probe found, and the layout of the parameters. | *required* |
| prior | PriorWithCovariance | The prior over the parameters. | *required* |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | The likelihood is a mapping, $M P$ or $E P$ exceeds `MAX_BASIS_ENTRIES` for sizes known before data, or a given coordinate lies outside $[0, E)$. With `Drawn` points, also when the model’s outputs are not one tensor, a picked coordinate lies outside $[0, E)$, or $M P$ or $E P$ exceeds `MAX_BASIS_ENTRIES`. |
|  | TypeError | `points.pick` returns `Done` instead of handing its points on. |

### VariationalGP

``` python
VariationalGP(
    model=static(),
    likelihood,
    mean,
    prior,
    caps=static(),
    inducing,
    coords,
    factor,
    n_data,
    versions=dict[str, int](),
)
```

The linearized Laplace prior conditioned on $M$ inducing outputs, as a GP over the outputs.

Let $J_a$ be the Jacobian at the mean for inputs $a$, $\Sigma_0$ the prior’s covariance (applied through `cov_mv`), and $K_{ab} = J_a \Sigma_0 J_b^\top$. For the inducing inputs $z$, $J_z$ holds one row per point, at the output that `coords` names. With $L = \operatorname{tril}(\text{factor})$, the covariance at an input $x$ is

$$K_{xx} - (L^\top K_{zx})^\top \, (I + L^\top K_{zz} L)^{-1} \, (L^\top K_{zx}).$$

This is the prior conditioned on pseudo-observations of $f_z$ with noise covariance $(L L^\top)^{-1}$. The mean is $f(x)$ at the mean parameters.

`at` and `kl` read the prior on every call. Both are differentiable in `factor`, in the prior’s tensors and in the inducing inputs. They compute in float64 and return results in the `stat_dtype` of the outputs.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| model | ModelFn | The model as a function of the parameters. | `static()` |
| likelihood | \_L_co | The likelihood of the fit. Its tensors, such as `sigma`, are leaves that tuning can change. | *required* |
| mean | Params | The fitted parameters. | *required* |
| prior | PriorWithCovariance | The prior, whose covariance is $\Sigma_0$. | *required* |
| caps | Capabilities | The model’s capabilities. | `static()` |
| inducing | Inputs | The $M$ inducing inputs $z$, along the leading axis. | *required* |
| coords | Tensor | The flattened output coordinate of each inducing point, `[M]` int64. | *required* |
| factor | Tensor | The variational factor, `[M, M]`. Only its lower triangle $L$ is used. | *required* |
| n_data | Tensor | The total weight of the data, $N$ in `variational_loss`. | *required* |
| versions | Mapping\[str, int\] | The version counters of the module’s fixed parameters at fit time. `at` and `kl` raise `RuntimeError` when one has changed in place since then (see `check_versions`). | `dict[str, int]()` |

#### Attributes

| Name | Description |
|----|----|
| [requires](#laplacekit_gp.VariationalGP.requires) | What the Jacobian rows need: vjp and vmap. |

#### Methods

| Name | Description |
|----|----|
| [at](#laplacekit_gp.VariationalGP.at) | The Gaussian over the outputs at `inputs`, with one $E \times E$ block per input. |
| [check_versions](#laplacekit_gp.VariationalGP.check_versions) | Raise `RuntimeError` if a fixed parameter of the module changed in place since the fit. |
| [kl](#laplacekit_gp.VariationalGP.kl) | The KL divergence $\mathrm{KL}(q(f_z) \,\Vert\, p(f_z))$ at the inducing outputs. |

##### at

``` python
VariationalGP.at(inputs, /)
```

The Gaussian over the outputs at `inputs`, with one $E \times E$ block per input.

The Jacobian at `inputs` is formed a few inputs at a time, in blocks of at most $2^{24}$ entries (inputs times $E$ times $P$) or of one input.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| inputs | Inputs | The inputs, with the examples along the leading axis. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | OutputGaussian | An `OutputGaussian` whose mean is the network’s outputs at `inputs` and whose covariance holds one $E \times E$ block per input. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | CapabilityError | The model does not support vjp or vmap. |
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |
|  | StructureError | The model’s outputs are not one tensor, or `prior.cov_mv` refuses the parameters. |

##### check_versions

``` python
VariationalGP.check_versions()
```

Raise `RuntimeError` if a fixed parameter of the module changed in place since the fit.

The GP linearizes the model at the old value. `at` and `kl` call this first.

##### kl

``` python
VariationalGP.kl()
```

The KL divergence $\mathrm{KL}(q(f_z) \,\Vert\, p(f_z))$ at the inducing outputs.

$$\mathrm{KL} = \tfrac{1}{2} \big(\log\det(I + A) - \operatorname{tr}((I + A)^{-1} A)\big),
\qquad A = L^\top K_{zz} L.$$

Both Gaussians have mean zero. The covariance of $q$ is $(K_{zz}^{-1} + L L^\top)^{-1}$, and that of the prior is $K_{zz}$.

###### Returns

| Name | Type   | Description                                  |
|------|--------|----------------------------------------------|
|      | Tensor | A 0-dim tensor, in `stat_dtype` of the mean. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | CapabilityError | The model does not support vjp or vmap. |
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |
|  | StructureError | `prior.cov_mv` refuses the parameters. |

## Functions

| Name | Description |
|----|----|
| [fit_variational](#laplacekit_gp.fit_variational) | Fit VaLLA’s variational posterior with `n_steps` Adam steps on `variational_loss`. |
| [fixed](#laplacekit_gp.fixed) | Use the given inputs as the points. The fit reads no data for them. |
| [from_data](#laplacekit_gp.from_data) | Pick $m$ training inputs uniformly without replacement, in one pass over the data. |
| [fsp_laplace](#laplacekit_gp.fsp_laplace) | FSP-Laplace (Cinquin et al. 2024, Algorithm 2): Laplace under a GP prior on the outputs. |
| [grid](#laplacekit_gp.grid) | Place points on the product grid of `torch.linspace(low[d], high[d], n[d])`. |
| [kmeans](#laplacekit_gp.kmeans) | Pick points by k-means on the training inputs. |
| [rkhs_norm](#laplacekit_gp.rkhs_norm) | The estimate of $\lVert f - \mu \rVert^2_{\mathcal{H}}$ in Eq. 3.7 of Cinquin et al. (2024). |
| [uniform](#laplacekit_gp.uniform) | Draw $m$ points uniformly from the box $[\text{low}, \text{high}]$, as `[m, D]`. |
| [variational_loss](#laplacekit_gp.variational_loss) | VaLLA’s objective on one batch (Ortega et al. 2024). |

### fit_variational

``` python
fit_variational(
    gp,
    data,
    /,
    *,
    n_steps,
    lr=0.001,
    alpha=1.0,
    n_samples=None,
    learn_inducing=True,
    learn_prior=True,
    learn_noise=True,
    generator=None,
)
```

Fit VaLLA’s variational posterior with `n_steps` Adam steps on `variational_loss`.

As in laplace-torch, Adam trains the factor (of which only the lower triangle is used), the log of each of the prior’s `tunable()` leaves, $\log \sigma^2$ for an `lk.Gaussian` with a one-element $\sigma$, and the inducing inputs when they are a floating-point tensor and `learn_inducing` is true. It leaves alone a prior without `tunable`, a per-output $\sigma$ and inducing inputs given as a mapping. `learn_prior=False` fixes the prior’s leaves and `learn_noise=False` fixes $\sigma$, for example at the values from a marginal-likelihood fit. With the mean fixed, the ELBO ($\alpha = 0$) has no minimum in the prior’s precision $\lambda$ (Ortega et al. 2024, §3.4). The model’s parameters never change: the mean is detached, gradients flow to the trained leaves only, and grad is enabled only inside the loop.

Each step takes the next batch, and the batches cycle through the data, one pass per epoch. One seed is drawn from `generator`, or from torch’s global RNG when it is `None`, and seeds a CPU generator. Each pass and each step’s Monte Carlo draws take their turn on it. $N$ in the objective is `gp.n_data`, the total weight that the `fs.laplace` pass of `VaLLA` counted. `Data.size` is never read, so passing data of another length here changes nothing.

`n_steps`, `lr`, `alpha`, `n_samples`, the likelihood, the model’s capabilities, the versions and the prior’s leaves are all checked before any data is read. Each batch’s targets are checked at its step.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| gp | VariationalGP\[L\] | The fitted posterior. It is left unchanged. | *required* |
| data | lk.data.Data \| Iterable\[Any\] | A `Data` source, or a re-iterable of `Batch`es or `(inputs, targets)` pairs, which `lk.data.from_loader` wraps. | *required* |
| n_steps | int | The number of Adam steps, at least 1. | *required* |
| lr | float | Adam’s learning rate, positive and finite. | `0.001` |
| alpha | float | $\alpha$ of `variational_loss`. | `1.0` |
| n_samples | int \| None | The number of Monte Carlo draws, as in `variational_loss`. `None` uses the closed form. | `None` |
| learn_inducing | bool | Whether to train the inducing inputs. | `True` |
| learn_prior | bool | Whether to train the prior’s `tunable()` leaves. | `True` |
| learn_noise | bool | Whether to train $\sigma$. | `True` |
| generator | torch.Generator \| None | Seeds the batches and the draws, as above. `torch.manual_seed` makes the fit repeatable when it is `None`. | `None` |

#### Returns

| Name | Type               | Description                                       |
|------|--------------------|---------------------------------------------------|
|      | VariationalGP\[L\] | A new posterior with the trained leaves detached. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `n_steps` is not an int of at least 1, `lr` is not positive and finite, `alpha` or `n_samples` is refused as in `variational_loss`, a trained leaf of the prior has non-positive entries, the data has no batches, or a batch fails `variational_loss` (no targets, a bad target value). |
|  | CapabilityError | `variational_loss` has no closed form for the likelihood, or the model does not support vjp or vmap. |
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |
|  | StructureError | A batch fails `variational_loss` (see there). |
|  | TypeError | `data` is a one-shot iterator, or an item is neither a `Batch` nor an `(inputs, targets)` pair. |

### fixed

``` python
fixed(inputs, /, coords=None, *, generator=None)
```

Use the given inputs as the points. The fit reads no data for them.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| inputs | Inputs | The $m$ points along the leading axis. A mapping of tensors also works. | *required* |
| coords | Tensor \| None | One output coordinate per point, `[m]` int64. Methods that would draw a coordinate use these instead. | `None` |
| generator | torch.Generator \| None | Seeds `Picked.u`. `fixed` draws one seed from it when it is called, or from torch’s global RNG when `None`, so `torch.manual_seed` makes the draw repeatable. Every fit with these points gets the same `u`, and the `generator=` of the fit does not change it. | `None` |

#### Returns

| Name | Type  | Description |
|------|-------|-------------|
|      | Fixed | The points. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `inputs` has no per-example leaf, or `coords` is not int64 of shape `[m]`. |

### from_data

``` python
from_data(n_points, /)
```

Pick $m$ training inputs uniformly without replacement, in one pass over the data.

Every example gets a uniform priority, and the $m$ smallest are kept. Each batch’s generator draws the priorities and then `Picked.u`. The fit seeds that generator from its own seed, the pass’s position in the method’s chain, the number of examples before the batch and, under `torch.distributed`, the rank. The pick is therefore fixed by the fit’s seed, the data order and batching, the pass position and the rank. When both run as the first pass over the same batches with the same seed, it is the subset that `fs.SubsetOfData(m)` picks.

The pass runs no forward pass, and mapping inputs work. Weighted batches raise `CapabilityError` during the fit.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| n_points | int | The number of points $m$. When there are fewer training inputs, all of them become points. | *required* |

#### Returns

| Name | Type     | Description |
|------|----------|-------------|
|      | FromData | The points. |

#### Raises

| Name | Type       | Description            |
|------|------------|------------------------|
|      | ValueError | `n_points` is below 1. |

### fsp_laplace

``` python
fsp_laplace(
    model,
    data,
    likelihood,
    *,
    prior,
    context,
    rank,
    subset=lk.subsets.last_layer,
    strategy=None,
    generator=None,
)
```

FSP-Laplace (Cinquin et al. 2024, Algorithm 2): Laplace under a GP prior on the outputs.

Fit it at a MAP trained with `rkhs_norm` in the loss. The probe and the parameter subset work as in `lk.function_space.laplace`. `context.pick` gives the $n_C$ context points $C$. The fit forms the dense Jacobian $J(C)$, `[n_C E, P]`, and builds the basis $U_M$ of the prior precision

$$J(C)^\top \Sigma(C, C)^{-1} J(C), \qquad \Sigma(C, C) = K_{CC} \otimes I_E,$$

where $K_{CC}$ is `prior.cov(C)`. It then sums the GGN projected onto $U_M$ in one pass over the data, or two when the context points are picked from the data.

To build the basis, Lanczos runs on $K_{CC}$ rather than on $K_{CC} \otimes I_E$, whose eigenvalues each have multiplicity $E$. It gives $L_C$ with $L_C L_C^\top \approx K_{CC}^{-1}$, and the thin SVD

$$J(C)^\top (L_C \otimes I_E) = U_M D_M V_M^\top$$

gives $U_M$ and $D_M^2$. The SVD drops singular values at most $\epsilon$ times the larger side of that matrix times the largest singular value. All of this runs in float64, and $\epsilon$ is its machine epsilon.

Predict with `Linearized`, the default of `lk.predict(post, x)`. `WeightSamples` also runs, but the covariance is large along the directions that the context points barely constrain, so draws of the network can be far from the linearized predictive.

`rank`, the model’s capabilities and the budget are checked before any data beyond the probe’s batch. With `Drawn` context points (`grid`, `uniform`, `fixed`), the checks that the points and the model’s outputs are each one tensor run early as well, and so do the kernel’s checks of the points.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| model | nn.Module \| ModelFn | The model. A module is wrapped with `ModelFn.from_module`. | *required* |
| data | lk.data.Data \| Iterable\[Any\] | A `Data` source, or a re-iterable of `Batch`es or `(inputs, targets)` pairs, which `lk.data.from_loader` wraps. | *required* |
| likelihood | L | The likelihood. The posterior reads its `sigma` on every use, so tuning can still change it. | *required* |
| prior | FunctionPrior | The function prior. The fit uses its kernel once, and the posterior keeps only the kernel’s name, so `lk.tune` cannot change a kernel hyperparameter. Fit again to use another kernel. | *required* |
| context | Points | Picks the context points $C$ as one tensor that the kernel accepts: `grid`, `uniform`, `fixed`, `from_data` or `kmeans`. | *required* |
| rank | int | The number of Lanczos steps on the $n_C \times n_C$ kernel matrix. At most $n_C$ of them run. The basis has up to $\text{rank} \cdot E$ columns. | *required* |
| subset | Subset \| Params \| Selection | The parameters to fit, as for `lk.function_space.laplace`: a subset function, a parameter mapping or a `Selection`. | `lk.subsets.last_layer` |
| strategy | Strategy \| None | How the pass over the data forms $J(x) U_M$. `None` uses forward mode when the probe found it and vjp otherwise. A mode given here must be one the probe found. | `None` |
| generator | torch.Generator \| None | Seeds the data passes and the fit’s draws. One seed is drawn from it, or from torch’s global RNG when `None`, so `torch.manual_seed` makes the fit repeatable. | `None` |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | FSPPosterior\[L\] | The posterior. It holds a copy of the fitted parameters and the likelihood. Changing another parameter of the module in place afterwards makes `cov_mv` raise. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `rank` is below 1, `strategy` is not `"forward-mode"`, `"reverse-mode"` or `None`, the data has no batches or no examples, a weight is negative, the total weight is zero, the Lanczos start vector (the row sums of $J(C)$ added over the $E$ outputs) is zero, or the likelihood finds a bad target value. |
|  | CapabilityError | The model does not support vjp, vmap, or jvp with `strategy="forward-mode"`. The likelihood has neither an output Hessian nor sampling for the Monte Carlo Fisher. A batch carries weights while the context points are picked from the data, or `last_layer` finds no module with parameters. |
|  | StructureError | $n_C E P$ exceeds `MAX_CONTEXT_JACOBIAN_ENTRIES` (the built-in points know $n_C$ before the data), the context points are not one tensor, the model’s outputs are not one tensor, the likelihood is a mapping, the MC Fisher (a likelihood without `HasOutputHessian`) would form dense blocks above `MAX_DENSE_EVENT`, the kernel refuses the context points, `kmeans` holds too many entries, the subset refuses the model, or the probe or a pass finds badly shaped outputs or targets. |
|  | TypeError | `data` is a one-shot iterator, an item is neither a `Batch` nor an `(inputs, targets)` pair, or `context.pick` returns `Done` instead of handing its points on. |

### grid

``` python
grid(low, high, n)
```

Place points on the product grid of `torch.linspace(low[d], high[d], n[d])`.

The points are `[prod(n), D]`, and the last axis varies fastest. Their dtype is the promoted dtype of the floating-point tensors given, or the default dtype if there are none. `draw` ignores its generator. `pick` moves the points to the parameters’ device and draws `Picked.u` from a CPU generator seeded with 0. The fit reads no data for a grid, so data weights play no part.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| low | Tensor \| float | The lower corner. $D$ is 1 for a float or a 0-dim tensor, else its length. | *required* |
| high | Tensor \| float | The upper corner, as a float, a one-entry tensor, or one value per axis. | *required* |
| n | int \| Sequence\[int\] | The number of points per axis. An int applies to every axis. | *required* |

#### Returns

| Name | Type | Description |
|------|------|-------------|
|      | Grid | The grid.   |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `low` has more than 1 dim, `high` has more than 1 dim or neither 1 nor $D$ entries, or `n` does not give one count per axis. |
|  | ValueError | A count is below 1, or `high` is not at least `low` on every axis. |

### kmeans

``` python
kmeans(n_points, /, n_iters=20)
```

Pick points by k-means on the training inputs.

One pass collects every row, each with a priority drawn as in `from_data`. Lloyd’s algorithm starts from the $m$ rows of smallest priority and runs `n_iters` iterations, and an empty cluster keeps its centre. Each centre then moves to its nearest row, as in laplace-torch, which runs `scipy`’s `kmeans2` with other random draws. As with `from_data`, the fit’s seed, the data order and batching, the pass position and the rank fix the result. On CUDA the centre sums use atomic adds, so two runs can differ slightly.

The inputs must be one floating-point tensor. Distances use the rows flattened after the first axis. Other inputs raise `StructureError` during the fit, and so does a pass that holds more than `MAX_KMEANS_ENTRIES` input entries. Weighted batches raise `CapabilityError`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| n_points | int | The number of points $m$. When there are $m$ rows or fewer, every row becomes a point. | *required* |
| n_iters | int | The number of Lloyd iterations. | `20` |

#### Returns

| Name | Type   | Description |
|------|--------|-------------|
|      | KMeans | The points. |

#### Raises

| Name | Type       | Description                                     |
|------|------------|-------------------------------------------------|
|      | ValueError | `n_points` is below 1 or `n_iters` is negative. |

### rkhs_norm

``` python
rkhs_norm(prior, inputs, f, /)
```

The estimate of $\lVert f - \mu \rVert^2_{\mathcal{H}}$ in Eq. 3.7 of Cinquin et al. (2024).

$$\sum_e (f_e - \mu_e)^\top \, C^{-1} \, (f_e - \mu_e),$$

where $C$ is `prior.cov(inputs)`, and $f_e$ and $\mu_e$ are output entry $e$ of $f$ and of the prior’s mean at the $n$ inputs. Output entries are flattened after the first axis. The estimate is the norm of the smallest interpolant of $f$ at `inputs`, so it underestimates $\lVert f - \mu \rVert^2_{\mathcal{H}}$. It is differentiable in `f` and in the kernel’s leaves.

In the MAP loss of Algorithm 1, a minibatch holds $b$ of the $N$ examples, and each step draws new context points:

``` python
context = lk.gp.uniform(low, high, m)
for x, y in loader:
    c = context.draw()  # new points from torch's global RNG
    loss = -(N / b) * lik.log_prob(model(x), y).sum() + 0.5 * lk.gp.rkhs_norm(
        prior, c, model(c)
    )
```

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| prior | FunctionPrior | The prior, with the kernel and the mean $\mu$. | *required* |
| inputs | Tensor | The $n$ points, one tensor `[n, ...]`. | *required* |
| f | Tensor | The network’s outputs at `inputs`, `[n, ...]`. | *required* |

#### Returns

| Name | Type   | Description     |
|------|--------|-----------------|
|      | Tensor | A 0-dim tensor. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `inputs` or `f` is not a tensor with a leading example axis, the leading axis of `f` is not $n$, the prior’s mean has a shape other than that of `f`, or the kernel refuses `inputs`. |
|  | ValueError | `prior.cov(inputs)` is not positive definite. |

### uniform

``` python
uniform(low, high, n_points, *, generator=None)
```

Draw $m$ points uniformly from the box $[\text{low}, \text{high}]$, as `[m, D]`.

`draw(generator=g)` draws uniforms $r$, `[m, D]`, and returns $\text{low} + (\text{high} - \text{low}) \, r$. Each call gives new points, the way FSP-Laplace draws new context points at every training step. `pick` draws the points and then `Picked.u` from a CPU generator seeded once, when `uniform` is called, so every fit with these points gets the same ones. It moves the points to the parameters’ device. The fit reads no data for these points, so data weights play no part. The dtype follows the rule of `grid`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| low | Tensor \| float | The lower corner, as for `grid`. | *required* |
| high | Tensor \| float | The upper corner, as for `grid`. | *required* |
| n_points | int | The number of points $m$. | *required* |
| generator | torch.Generator \| None | Seeds the points `pick` uses. `uniform` draws one seed from it when it is called, or from torch’s global RNG when `None`, so `torch.manual_seed` makes them repeatable. The `generator=` of the fit does not change them. | `None` |

#### Returns

| Name | Type    | Description |
|------|---------|-------------|
|      | Uniform | The points. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `n_points` is below 1, or `high` is not at least `low` on every axis. |
|  | StructureError | `low` or `high` has a shape `grid` refuses. |

### variational_loss

``` python
variational_loss(gp, batch, /, *, alpha=1.0, n_samples=None, generator=None)
```

VaLLA’s objective on one batch (Ortega et al. 2024).

$$\mathcal{L} = -\frac{N}{B} D + \mathrm{KL}\big(q(f_z) \,\|\, p(f_z)\big), \qquad
D = \sum_n w_n \frac{1}{\alpha} \log \mathbb{E}_q\big[p(y_n \mid f_n)^\alpha\big],$$

where $N$ is `gp.n_data`, $B$ is the batch’s total weight (its size when it has no weights), $w_n$ are the weights (1 when there are none), and $D$ is the batch’s alpha-divergence data term. $\alpha = 0$ gives the ELBO, $D = \sum_n w_n \mathbb{E}_q[\log p(y_n \mid f_n)]$. Let $\mu$ and $v$ be the mean and variance of an output entry under $q$. The data term follows laplace-torch:

- With `n_samples=None` and `lk.Gaussian`, it has a closed form, exact for $\alpha \in [0, 1]$, with $\sigma$ from the likelihood (1 when `sigma` is `None`). Per output entry it is $-\tfrac{1}{2} \big[(y - \mu)^2 / (\sigma^2 + \alpha v)
  + \tfrac{1}{\alpha} \log(1 + \alpha v / \sigma^2) + \log 2 \pi \sigma^2\big]$, and $-\tfrac{1}{2} \big[((y - \mu)^2 + v) / \sigma^2 + \log 2 \pi \sigma^2\big]$ at $\alpha = 0$.
- With `n_samples=None` and `lk.Categorical` or `lk.Bernoulli`, it is the probit approximation $\log p\big(y \mid \mu / \sqrt{1 + \pi v / 8}\big)$. That does not depend on $\alpha$, so $\alpha \ne 1$ raises `ValueError`.
- With `n_samples=S`, it is the Monte Carlo estimate $\frac{1}{\alpha} \log \frac{1}{S} \sum_s p(y_n \mid f_s)^\alpha$, or the mean of $\log p(y_n \mid f_s)$ at $\alpha = 0$. Each input gets $S$ draws from its $E \times E$ Gaussian, scored with `log_prob`. The draws use a Cholesky factor of each block, jittered by $j \epsilon \max \operatorname{diag}$ of the block, where $\epsilon$ is the machine epsilon and $j$ is the smallest of $(1, 10, 100)$ for which the factorization succeeds.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| gp | VariationalGP | The variational GP. | *required* |
| batch | Batch | One batch, with targets. | *required* |
| alpha | float | $\alpha \in [0, 1]$. | `1.0` |
| n_samples | int \| None | $S$, the number of Monte Carlo draws per input, at least 2. `None` uses the closed form. | `None` |
| generator | torch.Generator \| None | The generator of the Monte Carlo draws, on any device. `None` means torch’s global RNG. | `None` |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Tensor | $\mathcal{L}$, a 0-dim tensor. It is differentiable in `factor`, in the tensors of the prior and the likelihood, and in the inducing inputs. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `alpha` lies outside $[0, 1]$, `n_samples` is neither an int nor `None` or is below 2, $\alpha \ne 1$ with the closed form for `lk.Categorical` or `lk.Bernoulli`, the batch has no targets, or the likelihood finds a bad target value. |
|  | CapabilityError | `n_samples=None` with a likelihood other than `lk.Gaussian`, `lk.Categorical` and `lk.Bernoulli`, or the model does not support vjp or vmap. |
|  | RuntimeError | A fixed parameter of the module changed in place since the fit. |
|  | StructureError | The model’s outputs are not one tensor, the targets are not shaped like the outputs in the Gaussian closed form, `prior.cov_mv` refuses the parameters, a covariance block’s Cholesky fails at every jitter, or the likelihood refuses the outputs or targets. |
