# Differentiating

The Laplace approximation gives a marginal likelihood, and we tune hyperparameters with its gradient: the prior precision, the noise, or hyperparameters inside the network. The marginal likelihood has the log-determinant of the GGN in it. With `create_graph=True`, the results of `compute` are differentiable in the parameters, so autograd can go through that term too.

We fit a small regression net first.

``` python
import math

import torch
from torch import nn

import hessiankit as hk

torch.manual_seed(0)
x = torch.linspace(-3, 3, 64, dtype=torch.float64).unsqueeze(1)  # [N, 1]
y = torch.sin(x) + 0.1 * torch.randn_like(x)
model = nn.Sequential(nn.Linear(1, 32), nn.Tanh(), nn.Linear(32, 1)).double()
sigma = 0.1

opt = torch.optim.Adam(model.parameters(), lr=1e-2)

for _ in range(1000):
    opt.zero_grad()
    loss = 0.5 * ((model(x) - y) ** 2).sum() / sigma**2 + 0.5 * sum(
        (p**2).sum() for p in model.parameters()
    )
    loss.backward()
    opt.step()
```

The log marginal likelihood of a diagonal Laplace posterior, with a Gaussian likelihood and the prior $\mathcal{N}(0, \delta^{-1} I)$. We write the GGN diagonal and the rest apart, so the diagonal can be computed once and reused:

``` python
def factors(f):
    return hk.gaussian(f, kind="exact", sigma=sigma)


def ggn_diagonal(params, create_graph=True):
    result = hk.compute(
        model,
        params,
        x,
        factors,
        layers=["0", "2"],
        diagonal=True,
        create_graph=create_graph,
    )

    return torch.cat(
        [
            t.flatten()
            for d in result.diagonal.values()
            for t in (d.weight, d.bias)
        ]
    )


def log_marglik(params, log_delta, ggn):
    theta = torch.cat([p.flatten() for p in params.values()])
    delta = log_delta.exp()

    f = torch.func.functional_call(model, params, (x,))
    log_lik = -0.5 * ((y - f) ** 2).sum() / sigma**2 - y.numel() * math.log(
        sigma * math.sqrt(2 * math.pi)
    )
    log_prior = (
        -0.5 * delta * (theta**2).sum() + 0.5 * theta.numel() * log_delta
    )

    return log_lik + log_prior - 0.5 * torch.log(ggn + delta).sum()


params = dict(model.named_parameters())
log_delta = torch.zeros((), dtype=torch.float64, requires_grad=True)

lml = log_marglik(params, log_delta, ggn_diagonal(params))
grads = torch.autograd.grad(lml, [log_delta, *params.values()])
print(f"log marglik {lml.item():.1f}, d/d log_delta {grads[0].item():.2f}")
```

    log marglik -249.7, d/d log_delta 40.14

`params` are the model’s own parameters, and they require grad, so the GGN diagonal depends on them. Without `create_graph`, the diagonal comes back as a constant, and the gradient in the parameters misses the log-determinant term:

``` python
plain = log_marglik(params, log_delta, ggn_diagonal(params, create_graph=False))
plain_grads = torch.autograd.grad(plain, list(params.values()))

for (name, _), g, p in zip(params.items(), grads[1:], plain_grads, strict=True):
    print(
        f"{name:9s} gradient norm {g.norm():8.2f}, without the graph {p.norm():8.2f}"
    )
```

    0.weight  gradient norm    16.68, without the graph     6.76
    0.bias    gradient norm    12.46, without the graph    13.38
    2.weight  gradient norm    96.15, without the graph    21.47
    2.bias    gradient norm    11.65, without the graph    11.65

The last bias gets the same gradient either way, since the GGN doesn’t depend on it.

The gradient in `log_delta` is the same with or without the graph, because the prior precision only enters after `compute`. So to tune the prior precision, we compute the diagonal once, without a graph, and step on `log_delta` alone:

``` python
fixed = {k: v.detach() for k, v in params.items()}
ggn = ggn_diagonal(fixed, create_graph=False)
opt = torch.optim.Adam([log_delta], lr=1e-1)

for _ in range(200):
    opt.zero_grad()
    (-log_marglik(fixed, log_delta, ggn)).backward()
    opt.step()

print(f"delta {log_delta.exp().item():.3f}")
```

    delta 5.858

In marginal-likelihood training (Immer et al., 2021), the parameters step on the usual MAP loss and the hyperparameters on the marginal likelihood, so for the prior precision alone the diagonal needs no graph. The graph matters when the GGN depends on the hyperparameters through the network, as with learned invariances, where they sit inside the model, or for objectives that differentiate the GGN in the parameters themselves. There, `create_graph=True` gives that gradient.

> **NOTE:**
>
> With `create_graph=True`, `compute` calls `factors` on the outputs with their graph. The Gaussian factors here don’t depend on the outputs, but categorical and Bernoulli factors do, and the gradient goes through them too, so the output Hessian $H_n(f)$ is differentiated along with the Jacobians. A `sigma` that requires grad gets a gradient as well. `weights`, `masks` and `output_mask` are constants.

> **NOTE:**
>
> With MAP estimate $\theta$ of $P$ parameters, the Laplace approximation of the log marginal likelihood is
>
> $$\log p(y \mid x) \approx \log p(y \mid x, \theta) + \log p(\theta) + \frac{P}{2} \log 2\pi - \frac{1}{2} \log \det (\mathrm{GGN}(\theta) + \delta I) .$$
>
> With the prior $\mathcal{N}(0, \delta^{-1} I)$, $\log p(\theta) = -\frac{\delta}{2} \lVert\theta\rVert^2 + \frac{P}{2}\log\delta - \frac{P}{2}\log 2\pi$, and the $2\pi$ terms cancel. The diagonal approximation replaces the log-determinant by $\sum_i \log(h_i + \delta)$, with $h$ the GGN diagonal that `compute` returns. The GGN is $\sum_n J_n^\top H_n J_n$. The Jacobians $J_n$ depend on $\theta$, and for a categorical or Bernoulli likelihood so does $H_n$; `create_graph=True` keeps both.
