# laplacekit_marglik

`laplacekit_marglik`

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

`train` trains a network as usual. Every few epochs, it also fits the prior precision and the likelihood’s noise by maximizing the Laplace approximation of the log marginal likelihood:

``` python
trained = lk.marglik.train(
    model, loader, lk.Gaussian(), n_data=len(dataset),
    optimizer=torch.optim.Adam(model.parameters(), lr=1e-2),  # no weight decay
    epochs=300, marglik_frequency=5,
)
post = trained.posterior  # the Laplace fit of the kept epoch, at the learned prior and noise
```

`prior=` sets how the weights share the prior precision: `lk.priors.Isotropic` gives one precision for all weights, `lk.priors.Layerwise` (the default) one per parameter block, and `lk.priors.Diagonal` one per weight.

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

## Classes

| Name | Description |
|----|----|
| [Trained](#laplacekit_marglik.Trained) | The result of `train`: the kept fit and the training history. |

### Trained

``` python
Trained(posterior, margliks, losses, best_epoch)
```

The result of `train`: the kept fit and the training history.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| posterior | LaplacePosterior\[Any, Any, \_L_co\] | The Laplace fit of the kept epoch. Its type carries the likelihood that `train` was given. | *required* |
| margliks | tuple\[float, …\] | The negative log marginal likelihood at every hyperparameter step. | *required* |
| losses | tuple\[float, …\] | The mean training loss per example of every epoch. | *required* |
| best_epoch | int \| None | The kept epoch, or `None` when no estimation ran. | *required* |

## Functions

| Name | Description |
|----|----|
| [train](#laplacekit_marglik.train) | Train `model` and its hyperparameters together (Immer et al. 2021, Alg. 1). |

### train

``` python
train(
    model,
    data,
    likelihood,
    *,
    optimizer,
    epochs,
    n_data=None,
    hessian_approx=None,
    prior=lk.priors.Layerwise,
    lr_hyper=0.1,
    n_hypersteps=10,
    marglik_frequency=1,
    n_epochs_burnin=0,
    sigma_init=None,
    scheduler=None,
    generator=None,
)
```

Train `model` and its hyperparameters together (Immer et al. 2021, Alg. 1).

Each epoch takes one pass over the data. Each batch takes one `optimizer` step on the negative log joint per example,

$$-\frac{\sum_i w_i \log p(y_i \mid f_i)}{\sum_i w_i}
+ \frac{1}{2N} \sum_b \lambda_b \lVert \theta_b \rVert^2,$$

at the current prior precision $\lambda$ and noise $\sigma$, followed by one `scheduler` step if there is a scheduler. Here $w_i$ are the batch’s weights (1 when there are none), $N$ is the number of training examples, and $b$ runs over the groups of weights that share a $\lambda_b$.

After epoch $e$, when `e % marglik_frequency == 0` and `e >= n_epochs_burnin`, `lk.laplace` fits the trainable parameters with `hessian_approx` and without tuning. `n_hypersteps` Adam steps at `lr_hyper` then minimize the fit’s negative log marginal likelihood $-\log p(\mathcal{D} \mid \lambda, \sigma)$ in $\log \lambda$, and also in $\log \sigma$ for a learned `lk.Gaussian()`. One Adam optimizer, in float64, runs through the whole training. These are laplace-torch’s `marglik_training` arguments.

A per-output $\sigma$, `lk.Gaussian()` with `sigma_init=torch.ones(k)`, is fixed during a fit, so Adam cannot move it. MacKay’s closed-form update sets it after the Adam steps of each estimation:

$$\sigma_k^2 = \frac{\sum_n w_n \big[(y_{nk} - f_{nk})^2
+ \operatorname{Var} f_{nk}\big]}{\sum_n w_n}.$$

This is the weighted mean, over the data, of the squared residual plus the variance of $f_k$ from `lk.predict_outputs` without noise, at the $\lambda$ of the estimation’s last marginal likelihood. It takes one more pass over the data per estimation. Later epochs and estimations use the new $\sigma$.

`train` keeps the estimation with the lowest final negative log marginal likelihood, as laplace-torch’s `marglik_training` does. At the end, the model gets the state dict of that epoch back, and `posterior` is a new fit at the $\lambda$ and $\sigma$ of that value. A per-output $\sigma$ is the one that estimation was fitted with, before its update. When no estimation ran, `posterior` is fitted at the initial $\lambda$ and $\sigma$. A 0-dim $\lambda$ stays in float64, as in the Adam steps, and a vector $\lambda$ takes the model’s dtype.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| model | nn.Module | The network. Its trainable parameters are trained in place, and its train or eval mode is left unchanged. | *required* |
| data | lk.data.Data \| Iterable\[Any\] | Training data with targets, as an `lk.data.Data` or a re-iterable loader that `lk.data.from_loader` wraps. | *required* |
| likelihood | L | The likelihood. `lk.Gaussian()` learns $\sigma$ from 1, and `lk.Gaussian(sigma=0.1)` keeps it fixed. | *required* |
| optimizer | torch.optim.Optimizer | The optimizer over the model’s parameters. Its param groups need `weight_decay=0`, since $\lambda$ sets the weight decay. | *required* |
| epochs | int | The number of epochs, at least 1. | *required* |
| n_data | int \| None | The number of training examples $N$ for a plain loader. An `lk.data.Data` gives it as `data.n_data`. | `None` |
| hessian_approx | HessianApprox\[Any\] \| None | The curvature method of each fit. `None` means `lk.laplace`’s default. | `None` |
| prior | type\[lk.priors.Isotropic \| lk.priors.Layerwise \| lk.priors.Diagonal\] \| lk.priors.Isotropic \| lk.priors.Layerwise \| lk.priors.Diagonal | How $\lambda$ is shared, as a prior class or an instance with one shared precision: `lk.priors.Isotropic` (laplace-torch’s `"scalar"`), `lk.priors.Layerwise` (one $\lambda$ per `Layout.by_module` block) or `lk.priors.Diagonal` (one per weight). An instance’s precision is the starting value of every $\lambda$; a class starts at 1. | `lk.priors.Layerwise` |
| lr_hyper | float | The Adam learning rate of the hypersteps. | `0.1` |
| n_hypersteps | int | The number of Adam steps per estimation, at least 1. | `10` |
| marglik_frequency | int | The number of epochs between estimations, at least 1. | `1` |
| n_epochs_burnin | int | The first epoch that may run an estimation. | `0` |
| sigma_init | float \| Tensor \| None | The start of a learned $\sigma$ (`lk.Gaussian()`), a float or one value per output, as laplace-torch’s `sigma_noise_init`. `None` starts at 1. Only for a learned $\sigma$: with a fixed one it raises. | `None` |
| scheduler | torch.optim.lr_scheduler.LRScheduler \| None | A learning-rate scheduler for `optimizer`, stepped after every optimizer step. | `None` |
| generator | torch.Generator \| None | Seeds the data passes and the fits. One seed is drawn from it, or from torch’s global RNG when `None`, so `torch.manual_seed` makes training repeatable. The passes and fits draw, in turn, from one CPU generator seeded from it. | `None` |

#### Returns

| Name | Type         | Description           |
|------|--------------|-----------------------|
|      | Trained\[L\] | The `Trained` result. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | TypeError | `prior` is not one of the three built-in priors, or `data` is its own iterator (a generator, for example), or an item is neither a `Batch` nor an `(inputs, targets)` pair. |
|  | ValueError | Before the first optimizer step, when `epochs`, `n_hypersteps` or `marglik_frequency` is below 1, `sigma_init` is given without a learned $\sigma$ or is not positive and finite, the prior has several precisions or a mean, an optimizer param group has a nonzero `weight_decay`, the module has no trainable parameter, `n_data` differs from `data.n_data`, neither gives the number of examples, the data has no batches, or the first batch has no targets. Only the first batch is checked for targets. A later batch without targets raises when training reaches it, after the earlier batches have changed the parameters. A fit can also raise it, as in `lk.laplace`. |
|  | StructureError | Before the first optimizer step, a dry run of `lk.laplace` on the first batch raises it when the curvature or the prior refuses the structure (for example KFAC with `"diagonal"`), or when the log marginal likelihood refuses the fit (as in `LaplacePosterior.log_marglik`). Later fits and estimations can raise it the same way. |
|  | CapabilityError | The dry run raises it when the curvature or the prior refuses the model’s capabilities. Otherwise as in `lk.laplace`. |
