# Function-space priors

The default prior is over the weights: an isotropic Gaussian. It says little about the functions the network draws—with Tanh, they’re smooth, whatever the objective is. Sometimes, though, we know more: the objective repeats over a cycle, or it’s rough. FSP-Laplace ([Cinquin et al. 2024](https://arxiv.org/abs/2407.13711)) puts the prior on the function instead, as a GP with a kernel of our choosing. Here, `FSPLaplace` is its trainer.

As an example, let’s take a draw from a GP whose kernel is periodic, with a cycle of length 0.2, plus a slow trend. A network can’t easily reproduce it from a few points.

``` python
import matplotlib.pyplot as plt
import numpy as np
import torch
from botorch.models.transforms.input import Normalize
from botorch.models.transforms.outcome import Standardize
from gpytorch.kernels import PeriodicKernel, RBFKernel, ScaleKernel
from gpytorch.priors import GammaPrior
from torch import nn

import laplacekit as lk
from laplacekit_bayesopt import FSPLaplace, LaplaceBoTorchSurrogate

torch.set_default_dtype(torch.float64)

grid = torch.linspace(0, 1, 1000).unsqueeze(-1)
true_kernel = lk.gp.Periodic(torch.tensor(0.2), torch.tensor(1.5)) + lk.gp.RBF(
    torch.tensor(0.3), torch.tensor(0.5)
)
chol = torch.linalg.cholesky(true_kernel(grid, grid) + 1e-8 * torch.eye(1000))
f = chol @ torch.randn(1000, generator=torch.Generator().manual_seed(1))


def objective(x):
    values = np.interp(x.numpy().ravel(), grid.numpy().ravel(), f.numpy())
    return torch.from_numpy(values).unsqueeze(-1)


bounds = torch.tensor([[0.0], [1.0]])
```

`FSPLaplace` takes a GPyTorch kernel, as `SingleTaskGP(covar_module=...)` does. In each round, it tunes the kernel’s hyperparameters on the marginal likelihood of a GP, as BoTorch does with its GPs, and then trains the network under it. We know roughly how long a cycle is, so the period gets a prior around 0.2 (the mean of `GammaPrior(12, 60)`).

``` python
def make_kernel():
    periodic = PeriodicKernel(period_length_prior=GammaPrior(12.0, 60.0))
    return ScaleKernel(periodic) + ScaleKernel(RBFKernel())


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


trainers = {
    "Weight-space prior (default)": None,
    "Function-space prior": FSPLaplace(kernel=make_kernel()),
}


def surrogate(trainer, train_X, train_Y):
    extra = {} if trainer is None else {"trainer": trainer}

    return LaplaceBoTorchSurrogate(
        make_net(),
        train_X,
        train_Y,
        input_transform=Normalize(d=1, bounds=bounds),
        outcome_transform=Standardize(m=1),
        **extra,
    )
```

First, the fits on 20 points:

``` python
torch.manual_seed(4)
train_X = torch.rand(20, 1)
train_Y = objective(train_X)

fig, axes = plt.subplots(1, 2, figsize=(10, 3.5), sharey=True)
t = grid.squeeze()

for ax, (name, trainer) in zip(axes, trainers.items(), strict=True):
    torch.manual_seed(0)
    model = surrogate(trainer, train_X, train_Y)

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

    mean, std = post.mean.squeeze(), post.variance.sqrt().squeeze()
    ax.plot(t, f, "--", color="0.5", label="objective")
    ax.plot(t, mean, label="mean")
    ax.fill_between(t, mean - 2 * std, mean + 2 * std, alpha=0.3)
    ax.scatter(train_X.squeeze(), train_Y.squeeze(), color="k", zorder=3)
    ax.set_ylim(-3, 4)
    ax.set_title(name)

axes[0].legend()
plt.show()
```

![](fsp_files/figure-html/cell-4-output-1.png)

The weight-space prior gives a smooth curve through the points, and it’s sure of it everywhere, even where it’s wrong (around 0.3 and 0.5, say). The function-space prior is unsure between the points, as the GP prior is, so the acquisition function keeps exploring there.

## A loop

Now let’s maximize the objective, starting from 5 random points. Except for the trainer, the loop is the one from [Basics](../quickstart/basics.llms.md).

``` python
from botorch.acquisition import LogExpectedImprovement
from botorch.optim import optimize_acqf

best = {}

for name, trainer in trainers.items():
    torch.manual_seed(1)
    train_X = torch.rand(5, 1)
    train_Y = objective(train_X)

    for _ in range(15):
        model = surrogate(trainer, train_X, train_Y)
        acq = LogExpectedImprovement(model, best_f=train_Y.max())
        x, _ = optimize_acqf(
            acq, bounds=bounds, q=1, num_restarts=10, raw_samples=64
        )
        train_X = torch.cat([train_X, x])
        train_Y = torch.cat([train_Y, objective(x)])

    best[name] = train_Y.max().item()

print(f"maximum of the objective:     {f.max().item():.3f}")

for name, value in best.items():
    print(f"{name + ':':29s} {value:.3f}")
```

    maximum of the objective:     1.922
    Weight-space prior (default): 1.061
    Function-space prior:         1.822

We only do 15 rounds here so that the page runs quickly. In practice, BO runs for hundreds or thousands of rounds.

A few things to know:

- The context points, where the prior is enforced, are drawn from the unit box, which `Normalize` with the problem’s `bounds` maps the inputs into. For other inputs, set `context_bounds`.
- `FSPLaplace` keeps the noise fixed, as the other trainers do by default, and supports one outcome.
- The kernel can be an `RBFKernel`, `MaternKernel` or `PeriodicKernel`, or a `ScaleKernel`, sum or product of them. A `MaternKernel(nu=0.5)` says the objective is rough. Without a kernel, `FSPLaplace()` takes a Matérn-5/2, as the paper does.
- Each fit takes a few seconds, most of it in the posterior: as in the paper, it’s constrained at 10,000 Sobol points, so that its variance stays below the prior’s almost everywhere in the box.

For more on FSP-Laplace itself, see [laplacekit’s page](https://laplacekit.org/examples/fsp.html).
