# By hand

`hk.kfac` and `hk.diagonal` make every choice for us (see [Basics](../quickstart/basics.llms.md)). Underneath them is `hk.compute`, which makes none: we name the layers, build the output factors ourselves, and loop over the batches. Here we take a small classifier and a batch, and ask it for the exact diagonal of the GGN of its layers.

``` python
import torch
from torch import nn

import hessiankit as hk

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(6, 16), nn.ReLU(), nn.Linear(16, 3)).double()
x = torch.randn(32, 6, dtype=torch.float64)


def factors(f):
    return hk.categorical(f, kind="exact")


result = hk.compute(model, None, x, factors, layers=["0", "2"], diagonal=True)

diag = result.diagonal["2"]
print(diag.weight.shape, diag.bias.shape, diag.total_weight)
```

    torch.Size([3, 16]) torch.Size([3]) tensor(32., dtype=torch.float64)

`compute` runs the model once, with hooks on the layers we name (their paths in `model.named_modules()`). `factors` gets the model’s outputs and returns their output factors (see [Output factors](../quickstart/factors.llms.md)). Passing `None` for the parameters uses the model’s own; a dict of tensors overrides them. The model is never changed, and its parameters don’t need `requires_grad`.

Each layer gets a `LayerDiagonal`: one entry per parameter, shaped like the weight and the bias. They are sums over the batch. `total_weight` is the number of examples that went in, and dividing by it gives the diagonal of the average GGN:

``` python
mean_ggn = diag.weight / diag.total_weight
print(mean_ggn[0])
```

    tensor([0.0629, 0.0268, 0.0079, 0.0189, 0.1362, 0.1093, 0.0155, 0.0125, 0.0099,
            0.0440, 0.0033, 0.0084, 0.0482, 0.0207, 0.0075, 0.0805],
           dtype=torch.float64)

Results add, so going over a dataset in batches is just a sum. `hk.Result()` is the zero result:

``` python
batches = torch.randn(4, 32, 6, dtype=torch.float64)

total = hk.Result()
for xb in batches:
    total = total + hk.compute(
        model, None, xb, factors, layers=["0", "2"], diagonal=True
    )

print(total.diagonal["2"].total_weight)
```

    tensor(128., dtype=torch.float64)

## A diagonal Laplace posterior

The GGN of the summed loss is the sum we got, so with a Gaussian prior of precision $\tau$ the diagonal posterior precision is that sum plus $\tau$. The posterior variance is one over it:

``` python
tau = 1.0

variance = {
    name: (d.weight + tau).reciprocal() for name, d in total.diagonal.items()
}
print(variance["2"][0])
```

    tensor([0.1024, 0.2790, 0.3656, 0.3111, 0.1051, 0.0756, 0.3343, 0.1506, 0.6454,
            0.1968, 0.6130, 0.3828, 0.1445, 0.1005, 0.5763, 0.1222],
           dtype=torch.float64)

> **NOTE:**
>
> For example $n$ with output $f_n$, let $J_n = \partial f_n / \partial \theta$ and let $v_{n,1}, \dots, v_{n,E}$ be the output factors, so that $\sum_e s_{n,e} v_{n,e} v_{n,e}^\top = H_n$ is the Hessian of the loss in $f_n$. The GGN of the loss summed over the batch is
>
> $$G = \sum_n J_n^\top H_n J_n = \sum_n \sum_e s_{n,e}\, (J_n^\top v_{n,e})(J_n^\top v_{n,e})^\top ,$$
>
> and its diagonal is $\sum_n \sum_e s_{n,e}\, (J_n^\top v_{n,e})^2$, squared entry by entry. Each $J_n^\top v_{n,e}$ is a per-example gradient. For a linear layer with input $x_n$ and output gradient $d_{n,e}$, that gradient is $d_{n,e} x_n^\top$, so its square is $d_{n,e}^2 (x_n^2)^\top$. One backward pass per factor gives every $d_{n,e}$ of the batch at once, and the hooks give $x_n$.
>
> With a prior $\mathcal{N}(0, \tau^{-1} I)$, the Laplace posterior is $\mathcal{N}(\theta_\text{MAP}, (G + \tau I)^{-1})$. Keeping only the diagonal of $G$ makes the inverse entry-wise.

## How fast

The plain way to get this diagonal is a per-example Jacobian from `torch.func`. Here is an MLP for MNIST-sized inputs (784-256-128-10) with 256 random examples:

``` python
import time

torch.manual_seed(0)
mlp = nn.Sequential(
    nn.Linear(784, 256),
    nn.ReLU(),
    nn.Linear(256, 128),
    nn.ReLU(),
    nn.Linear(128, 10),
)
X = torch.randn(256, 784)
layers = ["0", "2", "4"]

start = time.perf_counter()
fast = hk.compute(mlp, None, X, factors, layers=layers, diagonal=True)
t_hk = time.perf_counter() - start

params = {k: v.detach() for k, v in mlp.named_parameters()}


def output(p, xi):
    return torch.func.functional_call(mlp, p, (xi.unsqueeze(0),))[0]


def per_example(xi):
    jac = torch.func.jacrev(output)(params, xi)
    p = output(params, xi).softmax(-1)
    H = torch.diag(p) - torch.outer(p, p)

    return {
        k: torch.einsum("k...,kl,l...->...", j, H, j) for k, j in jac.items()
    }


start = time.perf_counter()
slow = {k: torch.zeros_like(v) for k, v in params.items()}

for i in range(0, len(X), 32):  # 32 examples at a time, to bound the memory
    for k, d in torch.func.vmap(per_example)(X[i : i + 32]).items():
        slow[k] += d.sum(0)

t_func = time.perf_counter() - start

err = (fast.diagonal["0"].weight - slow["0.weight"]).norm() / slow[
    "0.weight"
].norm()
print(
    f"hessiankit {t_hk:.2f} s, torch.func {t_func:.2f} s, relative difference {err:.1e}"
)
```

    hessiankit 0.01 s, torch.func 0.71 s, relative difference 1.2e-07

The two agree up to float32 rounding, and hessiankit takes a fraction of the time. The Jacobian route builds a full `[10, P]` Jacobian for every example. hessiankit runs one backward pass per factor for the whole batch, then one einsum per layer.
