Skip to main content

Exact diagonal

The By hand page had one output per example. Here we take a model with several positions per example, a likelihood with an indefinite Hessian, and a model that doesn’t return a plain tensor.

Several positions

A token model maps [N, T, D] to logits [N, T, C]. Every token gets its own class, so categorical with grouping="full" gives \(T \times C\) factors per example.

import torch
from torch import nn

import hessiankit as hk

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(8, 16), nn.Tanh(), nn.Linear(16, 5)).double()
x = torch.randn(64, 12, 8, dtype=torch.float64)  # [N, T, D]


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


print(factors(model(x)).num)  # T * C = 12 * 5

result = hk.compute(model, None, x, factors, layers=["0", "2"], diagonal=True)
print(result.diagonal["0"].weight.shape)
60
torch.Size([16, 8])

With several positions, a weight’s gradient for one example is a sum over its positions, and that sum has to be squared as a whole. So compute forms the per-example gradients of one layer at a time, a chunk of examples at a time. chunk_bytes caps the size of a chunk (256 MiB by default). It bounds the memory and leaves the numbers as they are:

small = hk.compute(
    model, None, x, factors, layers=["0", "2"], diagonal=True, chunk_bytes=2**12
)

print(torch.allclose(small.diagonal["0"].weight, result.diagonal["0"].weight))
True
Note

The exact diagonal takes one backward pass per factor, and exact factors number as many as the outputs of an example: \(T \times C\) here. Its cost grows with the output size. For long sequences or many classes, MC factors (kind="mc") keep the number of passes at mc_samples.

For a linear layer with input \(x_{n,t}\) and output gradient \(d_{n,t,e}\) at position \(t\), the gradient of example \(n\) along factor \(e\) is

\[ g_{n,e} = \sum_t d_{n,t,e}\, x_{n,t}^\top , \]

and the diagonal is \(\sum_n \sum_e s_{n,e}\, g_{n,e}^2\). The square of a sum is not the sum of the squares, so \(g_{n,e}\) is formed before squaring. With one position this is \(d_{n,e}^2 (x_n^2)^\top\) and nothing per example needs to be stored.

Signed factors

Factors from hk.from_dense can carry the sign \(-1\) when the output Hessian is indefinite (the Student-t of the Output factors page). compute takes them as they are, so the result is the diagonal of \(\sum_n J_n^\top H_n J_n\), which can be negative:

nu = 3.0
reg = nn.Sequential(nn.Linear(4, 16), nn.Tanh(), nn.Linear(16, 2)).double()
xr = torch.randn(64, 4, dtype=torch.float64)
yr = 3 * torch.randn(64, 2, dtype=torch.float64)


def student_t(fi, yi):
    return 0.5 * (nu + 1) * torch.log1p((yi - fi) ** 2 / nu).sum()


def t_factors(f):
    H = torch.func.vmap(torch.func.hessian(student_t))(f, yr)  # [N, K, K]

    return hk.from_dense(H, (2,))


signed = hk.compute(reg, None, xr, t_factors, layers=["0", "2"], diagonal=True)
print((signed.diagonal["2"].weight < 0).sum().item(), "negative entries")
2 negative entries

For a Laplace posterior, use the GGN or a Fisher instead: they are positive semidefinite.

Models that return more than a tensor

compute needs one tensor with the batch on dim 0. A model that returns a dict or a tuple is refused:

class Classifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.body = nn.Linear(6, 3)

    def forward(self, x):
        return {"logits": self.body(x)}


clf = Classifier().double()
xc = torch.randn(16, 6, dtype=torch.float64)

try:
    hk.compute(clf, None, xc, factors, layers=["body"], diagonal=True)
except hk.CaptureError as error:
    print(error)
the model returned dict; it must return one Tensor with the batch on dim 0 (pass `call` to pick it out)

call picks the tensor out. It gets every parameter and buffer of the model by name, and the inputs, and runs the model with them:

def call(params, inputs):
    return torch.func.functional_call(clf, params, (inputs,))["logits"]


picked = hk.compute(
    clf, None, xc, factors, layers=["body"], diagonal=True, call=call
)
print(picked.diagonal["body"].weight.shape)
torch.Size([3, 6])