The By hand page had one output per example. Here we take a model with several positions per example, a likelihood with an indefinite Hessian, and a model that doesn’t return a plain tensor.
Several positions
A token model maps [N, T, D] to logits [N, T, C]. Every token gets its own class, so categorical with grouping="full" gives \(T \times C\) factors per example.
With several positions, a weight’s gradient for one example is a sum over its positions, and that sum has to be squared as a whole. So compute forms the per-example gradients of one layer at a time, a chunk of examples at a time. chunk_bytes caps the size of a chunk (256 MiB by default). It bounds the memory and leaves the numbers as they are:
The exact diagonal takes one backward pass per factor, and exact factors number as many as the outputs of an example: \(T \times C\) here. Its cost grows with the output size. For long sequences or many classes, MC factors (kind="mc") keep the number of passes at mc_samples.
NoteThe math
For a linear layer with input \(x_{n,t}\) and output gradient \(d_{n,t,e}\) at position \(t\), the gradient of example \(n\) along factor \(e\) is
\[
g_{n,e} = \sum_t d_{n,t,e}\, x_{n,t}^\top ,
\]
and the diagonal is \(\sum_n \sum_e s_{n,e}\, g_{n,e}^2\). The square of a sum is not the sum of the squares, so \(g_{n,e}\) is formed before squaring. With one position this is \(d_{n,e}^2 (x_n^2)^\top\) and nothing per example needs to be stored.
Signed factors
Factors from hk.from_dense can carry the sign \(-1\) when the output Hessian is indefinite (the Student-t of the Output factors page). compute takes them as they are, so the result is the diagonal of \(\sum_n J_n^\top H_n J_n\), which can be negative: