import torch
import hessiankit as hk
torch.manual_seed(0)
f = torch.randn(4, 3, dtype=torch.float64) # logits [N, C]
fac = hk.categorical(f, kind="exact")
print(fac.num, tuple(fac.vectors.shape))3 (3, 4, 3)
hessiankit never sees the loss. It takes output factors instead: vectors at the model’s output whose outer products sum to the Hessian of the loss in the output. Later, each factor is pushed backward through the model, and that gives the GGN.
Let’s take a 3-class classifier with four examples.
3 (3, 4, 3)
That’s three factors for each example, one per class, stacked in front of the logits’ shape. Their outer products sum to the Hessian of the cross-entropy in the logits, and dense() gives that sum, [N, K, K] with \(K\) the size of one output. We can check it against torch.func.hessian:
True
Write the negative log-likelihood of one example as \(L(f)\), with \(f\) the model’s output, and \(H = \nabla_f^2 L\). Output factors are vectors \(v_1, \dots, v_E\) with
\[ H = \sum_{e=1}^{E} v_e v_e^\top . \]
For the softmax with probabilities \(p\), \(H = \operatorname{diag}(p) - p p^\top\), and the factors are \(v_c = \sqrt{p_c}\,(e_c - p)\). The GGN of a parameter block \(\theta\) is \(J^\top H J\) with \(J = \partial f / \partial \theta\), so
\[ J^\top H J = \sum_e (J^\top v_e)(J^\top v_e)^\top , \]
and each \(J^\top v_e\) is one backward pass. The MC Fisher replaces \(H\) by \((e_{\tilde y} - p)(e_{\tilde y} - p)^\top\) with \(\tilde y \sim p\), whose mean is \(H\). The empirical Fisher uses the observed \(y\) instead, which gives the outer product of the gradient.
kind="exact" gives the Hessian. kind="mc" draws labels from the model and gives the MC Fisher, one factor per draw. kind="empirical" uses the targets and gives the empirical Fisher, one factor per example.
10000 1
tensor(0.0080, dtype=torch.float64)
The MC estimate is unbiased, so with more samples it gets closer to the exact Hessian. Pass a generator to get the same draws every time. hk.bernoulli and hk.gaussian take the same arguments. hk.gaussian also takes sigma, a number or a tensor with one value per output:
A sequence model gives logits [N, C, T], a class per token. class_dim says where the classes are. With grouping="full" (the default) every token and class gets its own factor, so there are \(T \times C\) of them, each nonzero at one token only. grouping="columns" sums each class’s factor over the tokens, which leaves \(C\) factors. That is cheaper, and it is what Curvlinops does for KFAC, but it is exact only when the tokens don’t interact in the model. The reductions handle padding tokens and void pixels; Masks and weights shows how.
For any other likelihood, compute its Hessian in the output and pass it to hk.from_dense. Here is the Student-t with \(\nu = 3\) degrees of freedom. Its Hessian is negative for large residuals, so some factors carry the sign \(-1\):
nu = 3.0
def student_t(fi, yi):
return 0.5 * (nu + 1) * torch.log1p((yi - fi) ** 2 / nu).sum()
mean = torch.randn(4, 2, dtype=torch.float64) # [N, K]
target = mean + torch.tensor([[0.1, 3.0]], dtype=torch.float64)
H_t = torch.func.vmap(torch.func.hessian(student_t))(mean, target) # [N, K, K]
own = hk.from_dense(H_t, (2,))
print(own.signs)
print(torch.allclose(own.dense(), H_t))tensor([[-1., -1., -1., -1.],
[ 1., 1., 1., 1.]], dtype=torch.float64)
True
dense() takes the signs into account.
The helpers above take the output and the targets as they are. A segmentation target, though, often marks void pixels with the label 255, and a language model’s targets mark padding with -100. hk.Categorical, hk.Bernoulli, hk.Gaussian and hk.FromHessian wrap the helpers and know which axes of the output form one event. Give Categorical the void label as ignore_index, and it builds the output mask that compute takes and zeroes the factors at void pixels:
logits = torch.randn(2, 5, 4, 4, dtype=torch.float64) # [N, C, H, W]
labels = torch.randint(0, 5, (2, 4, 4))
labels[0, :2] = 255 # two void rows
seg = hk.Categorical(class_dim=1, ignore_index=255)
print(seg.event_axes(logits))
print(tuple(seg.output_mask(logits, labels).shape))
emp = seg.factors(logits, labels, fisher="empirical")
print(bool((emp.vectors[:, 0, :, :2] == 0).all()))(1,)
(2, 1, 4, 4)
True
The factors are zero on the void rows. The label 255 never reaches the helper, so fisher="empirical" doesn’t raise on a label out of range. For a likelihood of your own, hk.FromHessian takes a function that returns its Hessian, as we passed to hk.from_dense above, and gives the exact factors.