Skip to main content

Segmentation

laplacekit puts a Laplace approximation on the decode head of a segmentation model and reads off an uncertainty for every pixel. We take a tiny random SegFormer, built from a config, with the encoder frozen and label 255 for void pixels.

import torch
import torch.nn.functional as F
import transformers
from transformers import SegformerConfig, SegformerForSemanticSegmentation

import hessiankit as hk

transformers.logging.set_verbosity_error()
torch.manual_seed(0)

config = SegformerConfig(
    num_encoder_blocks=2,
    depths=[1, 1],
    sr_ratios=[2, 1],
    hidden_sizes=[8, 16],
    num_attention_heads=[1, 2],
    patch_sizes=[7, 3],
    strides=[4, 2],
    decoder_hidden_size=16,
    num_labels=4,
)
model = SegformerForSemanticSegmentation(config).eval()

for name, p in model.named_parameters():
    p.requires_grad_(name.startswith("decode_head"))


def batch(n=4):
    """Images [N, 3, 32, 32] and labels [N, 32, 32]; the top quarter is void."""

    y = torch.randint(0, 4, (n, 32, 32))
    y[:, :8] = 255
    return torch.randn(n, 3, 32, 32), y


def upsampled(m, x):
    """SegFormer's logits are at 1/4 of the image; we upsample them."""

    logits = m(pixel_values=x).logits
    return F.interpolate(logits, size=x.shape[-2:], mode="bilinear")


batches = [batch() for _ in range(4)]
likelihood = hk.Categorical(class_dim=1, ignore_index=255)

print(hk.plan(model, batches[0], likelihood, forward=upsampled))
hk.plan: kfac on output [4, 4, 32, 32], event axes (1,), 1024 positions per example
layer                                  type    T   params  A   G   mask
decode_head.linear_projections.0.proj  Linear  64  144     9   16  examples with a kept output
decode_head.linear_projections.1.proj  Linear  16  272     17  16  examples with a kept output
decode_head.linear_fuse                Conv2d  64  512     32  16  examples with a kept output
decode_head.classifier                 Conv2d  64  68      17  4   examples with a kept output
uncovered (trainable, not computed):
  decode_head.batch_norm.weight  no rule for BatchNorm2d
  decode_head.batch_norm.bias    no rule for BatchNorm2d
fisher: mc, 4 samples (exact would take 4096 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: 19.3 KiB in float64

class_dim=1 says the classes are on axis 1 of [N, 4, 32, 32], so the output has 1024 positions per image. Exact factors would take one backward pass per pixel and class, 4096 per batch, so the Fisher is Monte Carlo: four sampled labels per pixel, four backward passes per batch. ignore_index=255 masks the void pixels in the output: their output factors are zero, so they add nothing to any \(G\) or to the diagonal.

The head’s layers work at \(8 \times 8\), not at the \(32 \times 32\) of the output, so a void pixel doesn’t map to one of their positions. The mask they get is examples with a kept output: all their positions, in every image with at least one labelled pixel. That leaves \(G\) and the diagonal unaffected by the void pixels; only KFAC’s \(A\) also counts positions that feed void pixels alone. The BatchNorm2d of the head has no rule and is listed as uncovered.

result = hk.kfac(model, batches, likelihood, forward=upsampled)

print(result.kron["decode_head.classifier"].total_weight)
tensor(16., dtype=torch.float64)

A check: an image whose pixels are all void should drop out. We void the first image of every batch, and the total weight goes from 16 images to 12:

void = [
    (x, y.clone().index_fill_(0, torch.tensor([0]), 255)) for x, y in batches
]
result = hk.kfac(model, void, likelihood, forward=upsampled)

print(result.kron["decode_head.classifier"].total_weight)
tensor(12., dtype=torch.float64)

When to override

  • To keep the positions that feed only void pixels out of \(A\) too, give each layer its own mask; see the next section.
  • Labels at the logits’ resolution (\(8 \times 8\), nearest) instead: drop the upsampling from forward, and the layers at \(8 \times 8\) get the void mask exactly (output in the plan). The likelihood is then over the coarse labels.
  • hk.kfac and hk.diagonal take one backward pass per pixel and class when exact, 4096 per batch here, so both pick Monte Carlo, with 4 and 32 samples per pixel. Pass fisher="exact" if you can afford it.

A finer mask

hk.compute takes a mask per layer with masks=. A position of the \(8 \times 8\) grid should count when it feeds a labelled pixel through the upsampling, and the transpose of the upsampling tells us which ones do. compute takes the model as a function of its parameters, so call goes through torch.func.functional_call. We compare with the front door’s exact KFAC, whose factors are grouped "full":

head = ["decode_head.linear_fuse", "decode_head.classifier"]
x, y = batches[0]
keep = (y != 255)[:, None].float()  # [N, 1, 32, 32]


def up(z):
    return F.interpolate(z, size=(32, 32), mode="bilinear")


_, transpose = torch.func.vjp(up, torch.zeros(len(x), 1, 8, 8))
coarse = (transpose(keep)[0] > 0).flatten(1)  # [N, 64]


def call(params, x):
    out = torch.func.functional_call(model, params, (), {"pixel_values": x})
    return F.interpolate(out.logits, size=x.shape[-2:], mode="bilinear")


def factors(f):
    return hk.categorical(f, kind="exact", class_dim=1, grouping="full")


by_hand = hk.compute(
    model,
    None,
    x,
    factors,
    layers=head,
    call=call,
    kfac="expand",
    masks={name: coarse for name in head},
    output_mask=keep.bool(),  # [N, 1, 32, 32]: a singleton for the classes
    dtype=torch.float64,  # as the front door
)
exact = hk.kfac(
    model, [batches[0]], likelihood, forward=upsampled, fisher="exact"
)

for name in head:
    ours, theirs = by_hand.kron[name], exact.kron[name]
    print(torch.allclose(ours.g, theirs.g), torch.allclose(ours.a, theirs.a))
True False
True False

\(G\) is the same as the front door’s; only \(A\) changed, and only a little, since just the top row of the \(8 \times 8\) grid feeds void pixels alone.

With the factors grouped "columns", compute gives Curvlinops’ exact KFAC instead: one factor per class, summed over the pixels. With bilinear upsampling, neighbouring pixels share positions of the \(8 \times 8\) grid, so that \(G\) keeps cross terms between pixels and differs from the front door’s, which is the expectation of its Monte Carlo estimate.