# Classifiers

The first use case of laplace**kit** is a trained classifier: a Laplace approximation turns it into a Bayesian one, which is less overconfident away from its data. All it needs from us is a Hessian approximation at the MAP, here for a small CNN.

``` python
import torch
from torch import nn

import hessiankit as hk

torch.manual_seed(0)
model = nn.Sequential(
    nn.Conv2d(3, 8, 3, padding=1),
    nn.BatchNorm2d(8),
    nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Conv2d(8, 16, 3, padding=1),
    nn.ReLU(),
    nn.AdaptiveAvgPool2d(1),
    nn.Flatten(),
    nn.Linear(16, 10),
).eval()

batches = [
    (torch.randn(32, 3, 16, 16), torch.randint(0, 10, (32,))) for _ in range(4)
]
likelihood = hk.Categorical()

print(hk.plan(model, batches[0], likelihood))
```

    hk.plan: kfac on output [32, 10], event axes (1,), 1 position per example
    layer  type    T    params  A   G   mask
    0      Conv2d  256  224     28  8   none
    4      Conv2d  64   1168    73  16  none
    8      Linear  1    170     17  10  none
    uncovered (trainable, not computed):
      1.weight  no rule for BatchNorm2d
      1.bias    no rule for BatchNorm2d
    fisher: exact (10 backward passes per batch, at most EXACT_MAX_PASSES = 64)
    form: expand (reduce is opt-in: it cancels to zero when positions enter with opposite signs)
    backward passes per batch: 10
    memory: 53.3 KiB in float64

The two convolutions and the linear head are in. A convolution has one position per output pixel ($T = 256$ and $64$), and KFAC takes its expand form, which treats each pixel as an example. Ten classes take ten backward passes per batch, so the Fisher is exact. The `BatchNorm2d` has no rule, so `plan` lists its parameters as uncovered.

The default call is one line, and `hk.diagonal` takes the same arguments:

``` python
kron = hk.kfac(model, batches, likelihood)
diag = hk.diagonal(model, batches, likelihood)

print(kron.kron["8"].a.shape, kron.kron["8"].g.shape, kron.uncovered)
```

    torch.Size([17, 17]) torch.Size([10, 10]) {'1.weight': 'no rule for BatchNorm2d', '1.bias': 'no rule for BatchNorm2d'}

A check against a closed form. The head is linear in the features $\phi_n$ it gets, so its GGN diagonal is $\sum_n \lambda_{n,c}\, \phi_{n,d}^2$ for weight $W_{cd}$ and $\sum_n \lambda_{n,c}$ for bias $b_c$, with $\lambda_{n,c} = p_{n,c} (1 - p_{n,c})$ the diagonal of the softmax Hessian. We compute that from the features and the logits directly, and compare:

``` python
x = torch.cat([b[0] for b in batches])

with torch.no_grad():
    phi = model[:-1](x).double()
    p = model(x).double().softmax(-1)

lam = p * (1 - p)
weight, bias = lam.T @ phi**2, lam.sum(0)

head = diag.diagonal["8"]
print(torch.allclose(head.weight, weight), torch.allclose(head.bias, bias))
```

    True True

## When to override

- Only the last layer, as in last-layer Laplace: `layers=["8"]`.
- More than 64 classes switch the Fisher to Monte Carlo with four samples per example; pass `mc_samples=` for more, or `fisher="exact"` to pay for every class.
- Frozen layers are left out by default. To leave out trainable ones, list the layers you want.
- `form="reduce"` averages each convolution’s pixels before the outer product, which is cheaper. It is opt-in, since it can cancel to zero when positions enter the output with opposite signs ([Reward models](../use_cases/reward.llms.md)).
