# Diffusion models

laplace**kit** 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.

``` python
import torch
import torch.nn.functional as F
from torch import nn

import hessiankit as hk

torch.manual_seed(0)


class Denoiser(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)

    def forward(self, x, t):
        h = F.silu(self.inp(x) + self.time(t[:, None])[:, :, None, None])
        return self.out(F.silu(self.mid(h)))


model = Denoiser().eval()
alpha_bar = torch.linspace(0.999, 0.01, 1000)


def batch(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() * noise
    return {"x": x_t, "t": t / 1000}, noise


batches = [batch() for _ in range(4)]
likelihood = hk.Gaussian(sigma=1.0, event_dim=1)
forward = lambda m, x: m(x["x"], x["t"])  # noqa: E731

print(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.

``` python
kron = hk.kfac(model, batches, likelihood, forward=forward)

print(kron.kron["out"].a.shape, kron.kron["out"].g.shape)
```

    torch.Size([145, 145]) torch.Size([1, 1])

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.

``` python
options = dict(forward=forward, fisher="exact")
full = hk.kfac(model, batches, likelihood, **options)
diag = hk.diagonal(model, batches, likelihood, **options)


def kfac_diagonal(k):
    g, a = k.g.diagonal(), k.a.diagonal()
    return (torch.outer(g, a) / k.total_weight).flatten()


def corr(a, b):
    return torch.corrcoef(torch.stack([a, b]))[0, 1].item()


mc = kfac_diagonal(kron.kron["mid"])
exact = kfac_diagonal(full.kron["mid"])
d = diag.diagonal["mid"]
ggn = torch.cat([d.weight.flatten(1), d.bias[:, None]], dim=1).flatten()

print(f"MC vs exact KFAC: {corr(mc, exact):.3f}")
print(f"exact KFAC vs exact diagonal: {corr(exact, ggn):.3f}")
```

    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.

> **NOTE:**
>
> 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 laplace**kit**’s diffusion page: `layers=["out"]`.
