# LaplacePosterior

``` python
LaplacePosterior(
    mean,
    curvature,
    prior,
    n_data,
    model=static(),
    likelihood,
    layout=static(),
    caps=Capabilities(),
    versions=dict[str, int](),
    provenance=(),
    data_fit=(),
    index=dict[str, Tensor](),
)
```

The result of a Laplace update: the prior precision plus the scaled curvature.

The posterior is $\mathcal{N}(\mu, \Lambda^{-1})$ with the precision

$$\Lambda = \Lambda_0 + c N \bar C,$$

where $\Lambda_0$ is the prior’s precision, $N$ the `n_data`, $\bar C$ the `curvature`, and $c$ the likelihood’s `curvature_scale()` for a `LateLikelihood` (a Gaussian with `sigma`), else 1. For a `LateLikelihood`, `curvature` is the unit one, so replacing `likelihood` (or tuning its leaves) never refits. The posterior is itself a `Prior`, so it can be the prior of the next update.

The third type parameter is the likelihood’s type, so `post.likelihood` keeps it (`lk.Gaussian` for a posterior fitted with one). `LaplacePosterior[Op, Pr]` means any likelihood, and a posterior with a narrower one is assignable to it.

A per-block curvature (`HasBlocks`: `BlockDiag`, `Joint`) takes vectors keyed by block. Any other curvature needs a layout with exactly one block: otherwise the methods that turn parameters into vectors raise `StructureError`.

## Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| mean | Params | The mean $\mu$, a parameter mapping. | *required* |
| curvature | \_Op | The curvature $\bar C$, a per-example average. | *required* |
| prior | \_Pr | The prior posterior, which adds $\Lambda_0$. | *required* |
| n_data | Tensor | The effective data size $N$. | *required* |
| model | ModelFn | The model. | `static()` |
| likelihood | \_L_co | The likelihood. Its tensors (such as `sigma`) are leaves, so they can be tuned. | *required* |
| layout | Layout | The block layout of `mean`. | `static()` |
| caps | Capabilities | The model’s capabilities. The default has nothing probed. | `Capabilities()` |
| versions | Mapping\[str, int\] | Version counters at fit time: of each `mean` tensor (a view of the module’s parameter shares its counter; a copy has its own) and of the module’s other, fixed parameters. `check_versions` compares them with the current ones. | `dict[str, int]()` |
| provenance | tuple\[tuple\[str, str\], …\] | Resolved front-door choices, shown before the curvature in the repr. Display only, never dispatch. | `()` |
| data_fit | tuple\[Tensor, …\] | The data-fit term of the fit data at the mean (`FitStat.data_fit`), as a one-element tuple, or empty when unknown (a tuple keeps None out of the leaves). | `()` |
| index | Mapping\[str, Tensor\] | For a `Selection`, each selected name (`"fc.weight[idx]"`) mapped to its flat indices (`Selection.selected_index`); empty for whole tensors. `lk.laplace` sets it. By hand: `replace(post, index=sel.selected_index)`. It identifies the entries only; nothing computes with it. | `dict[str, Tensor]()` |

## Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `layout` is not `Layout.by_module(mean)`. Custom layouts are not supported. |

## Attributes

| Name | Description |
|----|----|
| [prior_precision](#laplacekit.LaplacePosterior.prior_precision) | The prior’s precision hyperparameter, `prior.tunable()`. |
| [variance](#laplacekit.LaplacePosterior.variance) | $\operatorname{diag}(\Lambda^{-1})$ by `inverse_diagonal`, in the mean’s dtypes. |

## Methods

| Name | Description |
|----|----|
| [add_precision_to](#laplacekit.LaplacePosterior.add_precision_to) | `op` plus $\Lambda$ by `op.add_same`, so `op` must have the curvature’s type. |
| [check_versions](#laplacekit.LaplacePosterior.check_versions) | Raise `RuntimeError` if a parameter changed in place since the fit. |
| [cov_many](#laplacekit.LaplacePosterior.cov_many) | `cov_mv` of `n` vectors at once (a leading axis on every leaf); see `HasCovMany`. |
| [cov_mv](#laplacekit.LaplacePosterior.cov_mv) | $\Lambda^{-1} v$ by the operator’s `solve`, in the mean’s dtypes. |
| [cov_sqrt_many](#laplacekit.LaplacePosterior.cov_sqrt_many) | `cov_sqrt_mv` of `n` vectors at once (a leading axis on every leaf). |
| [cov_sqrt_mv](#laplacekit.LaplacePosterior.cov_sqrt_mv) | $L v$ with $L L^\top = \Lambda^{-1}$, the root the operator uses for sampling. |
| [location](#laplacekit.LaplacePosterior.location) | The mean, after `check_location`: a posterior over other parameters can’t be a prior. |
| [log_det_ratio](#laplacekit.LaplacePosterior.log_det_ratio) | The Occam term of `log_marglik`, $\log \det \Lambda - \log \det \Lambda_0$. |
| [log_marglik](#laplacekit.LaplacePosterior.log_marglik) | Laplace log marginal likelihood of the fit data. |
| [log_prob](#laplacekit.LaplacePosterior.log_prob) | $\log \mathcal{N}(\theta; \mu, \Lambda^{-1})$ by the operator’s `mv` and `logdet`. |
| [precision](#laplacekit.LaplacePosterior.precision) | $\Lambda = \Lambda_0 + c N \bar C$: the prior’s precision added to the scaled curvature. |
| [prior_scatter](#laplacekit.LaplacePosterior.prior_scatter) | The prior scatter $(\mu - \mu_0)^\top \Lambda_0 (\mu - \mu_0)$. |
| [sample](#laplacekit.LaplacePosterior.sample) | `n_samples` draws from $\mathcal{N}(\mu, \Lambda^{-1})$. |
| [sample_centered](#laplacekit.LaplacePosterior.sample_centered) | `n_samples` draws from $\mathcal{N}(0, \Lambda^{-1})$, in at least float32. |
| [snapshot](#laplacekit.LaplacePosterior.snapshot) | The same posterior with its own copy of the mean. |

### add_precision_to

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

`op` plus $\Lambda$ by `op.add_same`, so `op` must have the curvature’s type.

#### Parameters

| Name | Type | Description           | Default    |
|------|------|-----------------------|------------|
| op   | Op   | A precision operator. | *required* |

#### Returns

| Name | Type | Description                                            |
|------|------|--------------------------------------------------------|
|      | Op   | An operator of the same type, $\text{op} + \Lambda_0$. |

### check_versions

``` python
LaplacePosterior.check_versions()
```

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

A fixed parameter: the curvature was computed with its old value. A posterior parameter: only a mean that shares memory with the module (a by-hand posterior over views) or a mean edited in place moves; `lk.laplace` keeps a copy. Either way the posterior no longer describes the model. Predictives and `outputs` call this first.

A posterior parameter whose counter went down is another tensor than the recorded one (counters only go up): its mean was replaced by a copy, as `lk.load` does into a template whose mean views the module.

#### Raises

| Name | Type | Description |
|----|----|----|
|  | RuntimeError | A counter in `versions` differs from the current one, or a fixed parameter is gone from the module. When a posterior parameter’s counter went down, the message points to `snapshot()`. |

### cov_many

``` python
LaplacePosterior.cov_many(v, /)
```

`cov_mv` of `n` vectors at once (a leading axis on every leaf); see `HasCovMany`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| v | Params | Parameter mapping whose leaves have a leading axis of `n` vectors. | *required* |

#### Returns

| Name | Type   | Description                                                |
|------|--------|------------------------------------------------------------|
|      | Params | A parameter mapping shaped like `v`, in the mean’s dtypes. |

### cov_mv

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

$\Lambda^{-1} v$ by the operator’s `solve`, in the mean’s dtypes.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| v | Params | Parameter mapping with the posterior’s keys and shapes. | *required* |

#### Returns

| Name | Type   | Description                      |
|------|--------|----------------------------------|
|      | Params | $\Sigma v$, a parameter mapping. |

### cov_sqrt_many

``` python
LaplacePosterior.cov_sqrt_many(v, /)
```

`cov_sqrt_mv` of `n` vectors at once (a leading axis on every leaf).

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| v | Params | Parameter mapping whose leaves have a leading axis of `n` vectors. | *required* |

#### Returns

| Name | Type   | Description                                                |
|------|--------|------------------------------------------------------------|
|      | Params | A parameter mapping shaped like `v`, in the mean’s dtypes. |

### cov_sqrt_mv

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

$L v$ with $L L^\top = \Lambda^{-1}$, the root the operator uses for sampling.

#### Parameters

| Name | Type   | Description                                        | Default    |
|------|--------|----------------------------------------------------|------------|
| v    | Params | Parameter mapping with the mean’s keys and shapes. | *required* |

#### Returns

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

### location

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

The mean, after `check_location`: a posterior over other parameters can’t be a prior.

#### Parameters

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

#### Returns

| Name | Type   | Description                    |
|------|--------|--------------------------------|
|      | Params | The mean, a parameter mapping. |

### log_det_ratio

``` python
LaplacePosterior.log_det_ratio()
```

The Occam term of `log_marglik`, $\log \det \Lambda - \log \det \Lambda_0$.

The prior precision $\Lambda_0$ is the prior added to the curvature scaled by zero, so it has the curvature’s operator structure.

#### Returns

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

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | The prior can’t add its precision to the curvature’s operator, or the operator finds a precision that is not positive definite (as `Dense` does). |

### log_marglik

``` python
LaplacePosterior.log_marglik()
```

Laplace log marginal likelihood of the fit data.

$$\log p(\mathcal{D}) \approx \log p(\mathcal{D} \mid \mu)
    - \tfrac{1}{2} \left( \log \det \Lambda - \log \det \Lambda_0 \right)
    - \tfrac{1}{2} (\mu - \mu_0)^\top \Lambda_0 (\mu - \mu_0),$$

the data fit minus half of `log_det_ratio` and `prior_scatter`. The log-likelihood $\log p(\mathcal{D} \mid \mu)$ is read from `data_fit` with the current `likelihood`. `lk.laplace` keeps `data_fit` when the data had targets.

#### Returns

| Name | Type   | Description                         |
|------|--------|-------------------------------------|
|      | Tensor | A 0-dim tensor for a 0-dim `scale`. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `data_fit` is empty (a fit without targets). |
|  | StructureError | The prior can’t add its precision to the curvature’s operator, the operator finds a precision that is not positive definite (as `Dense` does), the prior’s location doesn’t match `mean`, or the curvature is not `HasBlocks` and the layout has more than one block. |

### log_prob

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

$\log \mathcal{N}(\theta; \mu, \Lambda^{-1})$ by the operator’s `mv` and `logdet`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| params | Params | Parameter mapping with the posterior’s keys and shapes. | *required* |

#### Returns

| Name | Type   | Description                       |
|------|--------|-----------------------------------|
|      | Tensor | A 0-dim tensor, $\log q(\theta)$. |

### precision

``` python
LaplacePosterior.precision()
```

$\Lambda = \Lambda_0 + c N \bar C$: the prior’s precision added to the scaled curvature.

#### Returns

| Name | Type | Description           |
|------|------|-----------------------|
|      | \_Op | A precision operator. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | The prior can’t add its precision to the curvature’s operator. |

### prior_scatter

``` python
LaplacePosterior.prior_scatter()
```

The prior scatter $(\mu - \mu_0)^\top \Lambda_0 (\mu - \mu_0)$.

$\mu_0$ is the prior’s location and $\Lambda_0$ its precision, formed as in `log_det_ratio`.

#### Returns

| Name | Type   | Description                         |
|------|--------|-------------------------------------|
|      | Tensor | A 0-dim tensor for a 0-dim `scale`. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | The prior’s location doesn’t match `mean`, the prior can’t add its precision to the curvature’s operator, or the curvature is not `HasBlocks` and the layout has more than one block. |

### sample

``` python
LaplacePosterior.sample(n_samples, /, *, generator=None)
```

`n_samples` draws from $\mathcal{N}(\mu, \Lambda^{-1})$.

Each is the mean plus a draw of `sample_centered`, cast to the mean’s dtypes.

#### Parameters

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

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Params | A parameter mapping with a leading axis of `n_samples` on every leaf. |

### sample_centered

``` python
LaplacePosterior.sample_centered(n_samples, /, *, generator=None)
```

`n_samples` draws from $\mathcal{N}(0, \Lambda^{-1})$, in at least float32.

Each is $L \varepsilon$ with $\varepsilon \sim \mathcal{N}(0, I)$ and $L$ the root of `cov_sqrt_mv`. They are the draws in `sample` minus the mean, without rounding at the mean’s precision.

#### Parameters

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

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Params | A parameter mapping with a leading axis of `n_samples` on every leaf, in at least float32. |

### snapshot

``` python
LaplacePosterior.snapshot()
```

The same posterior with its own copy of the mean.

Training the module afterwards then moves neither the mean nor a later fit’s prior. The copy is a `clone`, so it stays differentiable with respect to the old mean. The fixed parameters keep their fit-time counters, so the guard still fires when they move later.

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Self | A `LaplacePosterior` with the cloned mean, and with `versions` updated to the clones’ counters. |

#### Raises

| Name | Type         | Description                                    |
|------|--------------|------------------------------------------------|
|      | RuntimeError | The posterior is stale (see `check_versions`). |
