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 torchimport torch.nn.functionalas Ffrom torch import nnimport hessiankit as hktorch.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 voidy[5] =255# and image 5 is void everywherekeep = (y !=255).unsqueeze(1) # [N, 1, H, W]: the class axis as a singletondeffactors(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:
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:
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 inrange(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:
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).
NoteThe math
With mask \(m_{n,t} \in \{0, 1\}\), weight \(w_n\) and \(T_n = \sum_t m_{n,t}\), expand is
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:
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: