Skip to main content

Masks and weights

Segmentation labels have void pixels, and batches of sequences have padding; neither should count in the sums. We start with a segmentation head: a 3x3 convolution and a 1x1 head, mapping images [N, 3, H, W] to logits [N, C, H, W], with label 255 for void.

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

import hessiankit as hk

torch.manual_seed(0)
seg = nn.Sequential(
    nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(), nn.Conv2d(8, 4, 1)
).double()
x = torch.randn(6, 3, 8, 8, dtype=torch.float64)
y = torch.randint(0, 4, (6, 8, 8))
y[:, :2] = 255  # the top two rows are void
y[5] = 255  # and image 5 is void everywhere

keep = (y != 255).unsqueeze(1)  # [N, 1, H, W]: the class axis as a singleton


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


result = hk.compute(
    seg, None, x, factors, layers=["0", "2"], kfac="expand", output_mask=keep
)
print(result.kron["2"].total_weight)
tensor(5., dtype=torch.float64)

output_mask is a boolean mask over the output’s positions, here the pixels. It has one axis per axis of the logits, with size 1 on the class axis: [N, 1, H, W] here, and [N, T, 1] for logits [N, T, C]. Shapes alone can’t tell which axis holds the classes when two axes have the same size, so compute refuses a mask without that singleton.

The mask zeroes the output factors at void pixels, so nothing is backpropagated from them. Both layers here have one position per output pixel, so it is also their position mask: a void pixel adds nothing to \(A\) and doesn’t count as a position of its image. Image 5 has no pixel left, so it drops out, and total_weight is 5.

For the 1x1 head this is the same as running a linear layer on the kept pixels alone:

head = nn.Linear(8, 4).double()
head.weight.data = seg[2].weight.data.reshape(4, 8)
head.bias.data = seg[2].bias.data

with torch.no_grad():
    features = seg[1](seg[0](x)).flatten(2).transpose(1, 2)  # [N, H * W, 8]


def token_factors(f):
    return hk.categorical(f, kind="exact", grouping="columns")


alone = hk.Result()
for n in range(5):
    pixels = features[n, keep[n].flatten()][None]  # [1, kept pixels, 8]
    alone = alone + hk.compute(
        nn.Sequential(head),
        None,
        pixels,
        token_factors,
        layers=["0"],
        kfac="expand",
    )

print(torch.allclose(alone.kron["0"].a, result.kron["2"].a))
print(torch.allclose(alone.kron["0"].g, result.kron["2"].g))
True
True

Padded sequences

A batch of sequences of different lengths is padded to the longest. The mask marks the real tokens, and it is again an output_mask with one position per token:

torch.manual_seed(0)
lm = nn.Sequential(nn.Linear(8, 16), nn.Tanh(), nn.Linear(16, 5)).double()
lengths = torch.tensor([12, 3, 7, 12, 1])
tokens = torch.randn(5, 12, 8, dtype=torch.float64)  # [N, T, D], padded
real = torch.arange(12) < lengths[:, None]  # [N, T]
real = real[..., None]  # [N, T, 1], like logits [N, T, C]


def lm_factors(f):
    return hk.categorical(f, kind="exact", grouping="columns")


padded = hk.compute(
    lm,
    None,
    tokens,
    lm_factors,
    layers=["0", "2"],
    kfac="reduce",
    output_mask=real,
)

A masked position contributes nothing to \(A\), to \(G\), to the number of positions \(T_n\) that expand divides by and reduce averages over, or to total_weight. So the padded batch gives the same sums as the sequences one by one, with no padding at all:

unpadded = hk.Result()
for n in range(5):
    seq = tokens[n : n + 1, : lengths[n]]
    unpadded = unpadded + hk.compute(
        lm, None, seq, lm_factors, layers=["0", "2"], kfac="reduce"
    )

for name in ["0", "2"]:
    p, u = padded.kron[name], unpadded.kron[name]
    print(name, torch.allclose(p.a, u.a), torch.allclose(p.g, u.g))
0 True True
2 True True

This holds for the token model because its tokens don’t interact. For a model where they do, such as attention, the masked tokens still change the others through the forward pass; the mask only keeps them out of the sums.

Weights

weights gives each example a weight, a tensor [N] that is not negative. A weight \(k\) counts as the example repeated \(k\) times:

w = torch.tensor([2.0, 0.0, 1.0, 3.0, 1.0], dtype=torch.float64)
weighted = hk.compute(
    lm, None, tokens, lm_factors, layers=["2"], kfac="expand", weights=w
)

repeated = torch.repeat_interleave(
    torch.arange(5), w.long()
)  # [0, 0, 2, 3, 3, 3, 4]
copies = hk.compute(
    lm, None, tokens[repeated], lm_factors, layers=["2"], kfac="expand"
)

print(torch.allclose(weighted.kron["2"].g, copies.kron["2"].g))
print(weighted.kron["2"].total_weight, copies.kron["2"].total_weight)
True
tensor(7., dtype=torch.float64) tensor(7., dtype=torch.float64)

total_weight is the sum of the weights of the examples that counted, so dividing by it still gives the per-example average. Weights and masks go together, also with the diagonal (diagonal=True).

With mask \(m_{n,t} \in \{0, 1\}\), weight \(w_n\) and \(T_n = \sum_t m_{n,t}\), expand is

\[ A = \sum_n \frac{w_n}{T_n} \sum_t m_{n,t}\, x_{n,t} x_{n,t}^\top , \qquad G = \sum_n w_n \sum_t m_{n,t} \sum_e d_{n,t,e}\, d_{n,t,e}^\top , \]

reduce averages \(x_{n,t}\) over the unmasked positions into \(\bar x_n\) and sums \(m_{n,t} d_{n,t,e}\) over \(t\) before the outer product, and the diagonal is \(\sum_n w_n \sum_e s_{n,e} \big(\sum_t m_{n,t}\, d_{n,t,e} x_{n,t}^\top\big)^2\). An example with \(T_n = 0\) gets \(w_n = 0\), and \(W = \sum_n w_n\). The conventions page has all of them in one place.

Layers with other positions

A layer that downsamples has fewer positions than the output. The output mask can’t say which of them to keep, so compute refuses:

class UNetish(nn.Module):
    def __init__(self):
        super().__init__()
        self.down = nn.Conv2d(3, 8, 3, stride=2, padding=1)
        self.head = nn.Conv2d(8, 4, 1)

    def forward(self, x):
        h = F.interpolate(torch.relu(self.down(x)), scale_factor=2.0)

        return self.head(h)


unet = UNetish().double()

try:
    hk.compute(
        unet,
        None,
        x,
        factors,
        layers=["down", "head"],
        kfac="expand",
        output_mask=keep,
    )
except hk.FactorError as error:
    print(error)
down: it has 16 positions per example and the output has 64, so output_mask can't say which of its positions to keep; pass masks={'down': ...} of shape [N, 16]

masks gives a layer its own mask, [N, T] at its positions, and it wins over the output mask. Which of the 4x4 positions of down to keep is our call. Here we keep a position when any pixel of its 2x2 block is kept:

down_keep = F.max_pool2d(keep.double(), 2).flatten(1).bool()  # [N, 16]

result = hk.compute(
    unet,
    None,
    x,
    factors,
    layers=["down", "head"],
    kfac="expand",
    output_mask=keep,
    masks={"down": down_keep},
)
print(result.kron["down"].total_weight, result.kron["head"].total_weight)
tensor(5., dtype=torch.float64) tensor(5., dtype=torch.float64)