laplacekit puts a Laplace approximation on a diffusion model’s denoiser and carries a variance for every pixel through the sampling loop. The denoiser predicts the noise in a noisy image, with a squared-error loss, so its likelihood is a Gaussian over the channels of every pixel.
import torchimport torch.nn.functionalas Ffrom torch import nnimport hessiankit as hktorch.manual_seed(0)classDenoiser(nn.Module):"""Predicts the noise in x_t [N, 1, 16, 16] at time t [N]."""def__init__(self, width=16):super().__init__()self.time= nn.Linear(1, width)self.inp= nn.Conv2d(1, width, 3, padding=1)self.mid= nn.Conv2d(width, width, 3, padding=1)self.out= nn.Conv2d(width, 1, 3, padding=1)defforward(self, x, t): h = F.silu(self.inp(x) +self.time(t[:, None])[:, :, None, None])returnself.out(F.silu(self.mid(h)))model =Denoiser().eval()alpha_bar = torch.linspace(0.999, 0.01, 1000)defbatch(n=16):"""Noisy images at random times, and the noise to predict.""" x0 = torch.rand(n, 1, 16, 16) t = torch.randint(0, 1000, (n,)) a = alpha_bar[t][:, None, None, None] noise = torch.randn_like(x0) x_t = a.sqrt() * x0 + (1- a).sqrt() * noisereturn {"x": x_t, "t": t /1000}, noisebatches = [batch() for _ inrange(4)]likelihood = hk.Gaussian(sigma=1.0, event_dim=1)forward =lambdam, x: m(x["x"], x["t"]) # noqa: E731print(hk.plan(model, batches[0], likelihood, forward=forward))
hk.plan: kfac on output [16, 1, 16, 16], event axes (1,), 256 positions per example
layer type T params A G mask
time Linear 1 32 2 16 none
inp Conv2d 256 160 10 16 none
mid Conv2d 256 2320 145 16 none
out Conv2d 256 145 145 1 none
fisher: mc, 4 samples (exact would take 256 backward passes per batch, more than EXACT_MAX_PASSES = 64)
form: expand (reduce is opt-in: it cancels to zero when positions enter with opposite signs)
backward passes per batch: 4
memory: 335.3 KiB in float64
event_dim=1 says the channels of a pixel form one event, so the output has 256 positions per image and KFAC takes its expand form. Exact factors would take one backward pass per pixel and channel, 256 per batch, so the Fisher is Monte Carlo: four sampled noises per pixel, four backward passes per batch. The time embedding sees one position per image while the convolutions see 256; each layer gets the positions it has.
Two checks, on the middle convolution. First, the Monte Carlo noise: we compare the default with the exact KFAC, fisher="exact", which takes 256 backward passes per batch, through the diagonal of \((G \otimes A) / W\). Second, KFAC’s approximation: we compare the exact KFAC’s diagonal with the exact GGN diagonal.
MC vs exact KFAC: 1.000
exact KFAC vs exact diagonal: 0.729
With four samples per pixel, the default matches the exact KFAC on this layer (a correlation of 1.000 to three digits). The exact KFAC and the exact diagonal correlate at 0.73, and that gap is KFAC’s own approximation: when only the diagonal is needed, hk.diagonal gives it exactly.
NoteThe math
With the loss \(\frac{1}{2 \sigma^2} \lVert \epsilon - \hat\epsilon_\theta(x_t, t) \rVert^2\) per image, the Hessian in the output is \(I / \sigma^2\), so the GGN is \(\sigma^{-2} \sum_n J_n^\top J_n\). The usual DDPM loss \(\lVert \epsilon - \hat\epsilon \rVert^2\) is that with \(\sigma^2 = 1/2\).
When to override
A different \(\sigma\) or a loss weight per time step: sigma= takes a tensor that broadcasts against the output, and a batch can carry per-example weights as its third entry.
A Hugging Face diffusers UNet returns an object: forward=lambda m, x: m(x["x"], x["t"]).sample. Its convolutions and nn.Linear layers have rules; its norms don’t, and plan lists them under uncovered.
Last-layer Laplace, as in laplacekit’s diffusion page: layers=["out"].