hk.kfac and hk.diagonal make every choice for us (see Basics). 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.
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). 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:
Results add, so going over a dataset in batches is just a sum. hk.Result() is the zero result:
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:
tau =1.0variance = { name: (d.weight+ tau).reciprocal() for name, d in total.diagonal.items()}print(variance["2"][0])
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
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:
import timetorch.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() - startparams = {k: v.detach() for k, v in mlp.named_parameters()}defoutput(p, xi):return torch.func.functional_call(mlp, p, (xi.unsqueeze(0),))[0]defper_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 inrange(0, len(X), 32): # 32 examples at a time, to bound the memoryfor k, d in torch.func.vmap(per_example)(X[i : i +32]).items(): slow[k] += d.sum(0)t_func = time.perf_counter() - starterr = (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}")
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.