# Why hessiankit

There are already good libraries for Hessian approximations in PyTorch. We wrote another one because the Laplace approximation asks for things they weren’t built for, and laplace**kit** kept working around them.

## Laplace first

When there is more than one way to do something, hessiankit picks the one that serves the Laplace approximation. Laplace here doesn’t mean laplace**kit**: the library never imports it, and it should make sense to anyone fitting a Laplace approximation in PyTorch. Here is what that means, next to what optimization and geometry libraries do.

| Laplace needs | Optimization libraries do | Geometry libraries do |
|----|----|----|
| The Hessian once, at a fixed point (the MAP), over the whole dataset | Every step, on one batch | Spectra, traces |
| Exact sums over the data, deterministic, in float64 when asked | Running averages, damping, float32 | Matrix-free products |
| Positive semidefinite approximations (GGN, Fisher) by default | Whatever preconditions well | The Hessian |
| The raw statistic, which the posterior inverts and scales | Inverse updates inside the library | Eigenvalues only |
| Masks, per-example weights, sequence outputs, many outputs (vocabularies, pixels) | The mean loss over a batch | Small models |
| Differentiable when asked (marginal-likelihood training) | Everything detached |  |

So `compute` returns sums with the total weight of the examples that counted, never averages, and never inverts or damps anything. It never runs a data loop either: we give it one batch at a time and add the results.

## What we kept and what we avoided

| Library | Kept | Avoided |
|----|----|----|
| [BackPACK](https://backpack.pt) | Layer structure makes exact diagonals cheap: for a linear layer, the weight diagonal is $\sum_n \sum_c (g_{nc} \odot g_{nc})(a_n \odot a_n)^\top$, never a per-example gradient. | Pushing the square root of the output Hessian through every module, so every module type needs hand-written Jacobian code. `extend(model)` changes the model. Autograd internals. |
| [ASDL](https://github.com/kazukiosawa/asdl) | Capture once: hooks save the inputs and output gradients of the layers with parameters, and the diagonal and the Kronecker factors both come from those. Exact, MC and empirical Fisher differ only in what is backpropagated. | Built around an optimizer: global state, context managers, running statistics. |
| [Curvlinops](https://github.com/f-dangel/curvlinops) | Careful, tested numerics; KFAC expand and reduce; conventions written down. | The operator owns the data loop, and the loss is an `nn.Module`. No masks, no weights, and the class axis has to be dim 1. |
| [nngeometry](https://github.com/tfjgeorge/nngeometry) | The representation (diagonal, KFAC, low rank) is apart from the code that computes it. | Per-example Jacobians: memory grows with examples times parameters times outputs. |
| [laplace-torch](https://github.com/aleximmer/Laplace) | A front door with presets. | Several backends with different normalizations (a factor 2, sums against means). |
| [PyHessian](https://github.com/amirgholami/PyHessian) | Matrix-free tools work on any architecture. | Hessian summaries only (spectra, traces), no structured blocks. |
| [KFAC-JAX](https://github.com/google-deepmind/kfac-jax) | Finds the layers by tracing the graph, so functional layers are reached too. | Tracing, in the first release: hooks on modules work on any eager PyTorch model, so we use hooks. A functional layer, such as `F.linear` inside attention, has no module to hook and isn’t reached. |

That gives hessiankit’s design:

1.  Autograd carries the gradients between layers, and hooks capture them at the layers with parameters. Only those layers need code of their own (a [rule](quickstart/layers.llms.md)).
2.  One capture, many reductions: the diagonal and the KFAC factors come from the same inputs and output gradients.
3.  Output factors go in, not losses (see [Output factors](quickstart/factors.llms.md)). Masks and weights are arguments, not loss reductions.
4.  Per-batch sums, and no data loop.
5.  Public torch API only, a short list of supported layers, and an error for everything else.

## How fast

On a 784-256-128-10 MLP with 5,000 MNIST images, in batches of 500 on a CPU with 4 threads, the exact GGN diagonal takes about 0.09 s and KFAC about 0.07 s. BackPACK’s `DiagGGNExact` takes about 0.03 s for the same diagonal. The benchmark is `bench/diag_mnist.py` in the repository.
