# Training

Since the surrogate is a neural network, it needs to be trained. A `Trainer` does this for us: it trains the network, then fits the Laplace approximation. There are two (see [Kristiadi et al. 2023](https://openreview.net/forum?id=gDcaUj4Myhn)):

| Trainer | What it does |
|----|----|
| `PosthocMarglik()` (default) | Adam on the mean squared error, then tunes the prior precision on the marginal likelihood. Cheaper, but theoretically less correct. |
| `OnlineMarglik()` | Tunes the prior precision during training ([Immer et al. 2021](https://arxiv.org/abs/2104.04975)). More expensive, but theoretically better. |

Both take the number of epochs, the learning rate, the prior, the curvature, and so on—see the [reference](../reference/PosthocMarglik.llms.md). Let’s compare them on Hartmann6 with 30 points.

``` python
import time

import torch
from botorch.models.transforms.outcome import Standardize
from botorch.test_functions import Hartmann
from torch import nn

from laplacekit_bayesopt import (
    LaplaceBoTorchSurrogate,
    OnlineMarglik,
    PosthocMarglik,
)

torch.set_default_dtype(torch.float64)
torch.manual_seed(0)

problem = Hartmann(dim=6, negate=True)
train_X = torch.rand(30, 6)
train_Y = problem(train_X).unsqueeze(-1)
test_X = torch.rand(1000, 6)
test_Y = problem(test_X)


def make_net():
    return nn.Sequential(
        nn.Linear(6, 50),
        nn.Tanh(),
        nn.Linear(50, 50),
        nn.Tanh(),
        nn.Linear(50, 1),
    )


trainers = {
    "PosthocMarglik()": PosthocMarglik(),
    "PosthocMarglik(lr=0.01)": PosthocMarglik(epochs=500, lr=0.01),
    "PosthocMarglik(noise=None)": PosthocMarglik(noise=None),
    "OnlineMarglik()": OnlineMarglik(),
}

for name, trainer in trainers.items():
    start = time.perf_counter()
    model = LaplaceBoTorchSurrogate(
        make_net(),
        train_X,
        train_Y,
        outcome_transform=Standardize(m=1),
        trainer=trainer,
    )
    seconds = time.perf_counter() - start

    with torch.no_grad():
        post = model.posterior(test_X.unsqueeze(-2))

    mean, std = post.mean.squeeze(), post.variance.sqrt().squeeze()
    rmse = (mean - test_Y).pow(2).mean().sqrt()
    z = ((test_Y - mean) / std).std()  # about 1 if the std is right

    print(
        f"{name:27s} {seconds:4.1f} s, RMSE {rmse:.3f}, std of z-scores {z:.2f}"
    )
```

    PosthocMarglik()             1.6 s, RMSE 0.455, std of z-scores 15.69
    PosthocMarglik(lr=0.01)      0.5 s, RMSE 0.471, std of z-scores 11.17
    PosthocMarglik(noise=None)   1.0 s, RMSE 0.455, std of z-scores 0.54
    OnlineMarglik()              2.8 s, RMSE 0.359, std of z-scores 195.79

A z-score above one means the surrogate is overconfident, and below one, too cautious. Thirty points are too few for the network to fit Hartmann6 well, and with the default small fixed noise (see below), the surrogates are overconfident. `OnlineMarglik` fits the function best, but it’s also the most overconfident. With `noise=None`, the marginal likelihood explains part of the misfit as noise, so the surrogate is too cautious instead.

## Noise

By default, the noise is fixed and small: its variance is `1e-3` times the variance of the outcomes the network is trained on (with `Standardize`, just `1e-3`). So, the marginal likelihood only tunes the prior. As in `SingleTaskGP`, `train_Yvar` fixes the noise at a value of our own:

``` python
model = LaplaceBoTorchSurrogate(
    make_net(),
    train_X,
    train_Y,
    train_Yvar=0.01,
)
```

And `noise=None` tunes it on the marginal likelihood, along with the prior:

``` python
trainer = PosthocMarglik(noise=None)
```

Why fixed? With a tuned noise, the marginal likelihood tends to explain part of the outcomes as noise at small $n$. Then, `PosthocMarglik`’s surrogate is too cautious, and `OnlineMarglik` often ends with a network that predicts a constant (9 of 12 fits on Hartmann6 and Branin with 8 or 25 points, against none with the fixed noise).

> **WARNING:**
>
> The flip side: if the network fits the function poorly, a small fixed noise makes the surrogate overconfident. On Hartmann6 with 15 to 30 points, the default gave posterior standard deviations 8 to 16 times smaller than the test error, and `PosthocMarglik(noise=1e-2)` gave 3 to 6 times. `PosthocMarglik(subset=lk.subsets.last_layer, noise=None)` is worse still: its tuned noise comes out hundreds of times smaller, with standard deviations 12 to 55 times too small.

## Warm starts

The network is trained in place. So a network reused across rounds starts from its trained weights:

``` python
net = make_net()

for _ in range(rounds):
    model = LaplaceBoTorchSurrogate(net, train_X, train_Y)
    ...
```

A fresh network in each round, as on the other pages, starts over.

## A constant network

Sometimes, training ends with a network that predicts the same value everywhere. Often, the learning rate was too large for its inputs (so its units saturated), or a tuned noise (`noise=None`) let the marginal likelihood push it there at small $n$. The acquisition function then gets no signal from the mean, so the surrogate warns. A smaller learning rate, such as `PosthocMarglik(epochs=500, lr=0.01)`, usually avoids it.
