KFAC approximates the GGN block of each layer by a Kronecker product \(G \otimes A\): \(A\) from the layer’s inputs and \(G\) from the gradients at its output. We ask for it with kfac=, on a token model that maps [N, T, D] to logits [N, T, C].
Each layer gets a LayerKron. a is [D_in + 1, D_in + 1]: the bias is folded in as an input that is always 1, in the last row and column. g is [D_out, D_out]. Like the diagonal, both are sums over the batch, and total_weight is the number of examples that went in. Divided by total_weight, they are the two Kronecker factors of the per-example average GGN block.
grouping="columns" puts one class of every token in one factor, so there are 5 factors, one per class, instead of 60. That is what Curvlinops does for KFAC, and with it the factors here equal Curvlinops 3.0.1’s. The conventions page has the formulas and the exact correspondence.
Expand or reduce
With several positions per example (tokens, pixels), there are two ways to form a and g. Expand treats every position as an example of its own. Reduce first sums the output gradients over the positions and averages the inputs over them, then forms one outer product per example.
reduced = hk.compute(model, None, x, factors, layers=["0", "2"], kfac="reduce")for name in ["0", "2"]: e, r = result.kron[name], reduced.kron[name] g_ratio = (r.g.trace() / e.g.trace()).item() a_ratio = (r.a.trace() / e.a.trace()).item()print(f"layer {name}: G reduce/expand {g_ratio:.1f}, A {a_ratio:.2f}")
layer 0: G reduce/expand 11.0, A 0.19
layer 2: G reduce/expand 11.9, A 0.36
Reduce’s g is about 12 times expand’s, one for each token, since the gradients of the tokens add up before the outer product. Its a is smaller, since the average of the inputs is shorter than the inputs. With one position per example, the two are the same.
NoteThe math
For a layer with input \(x_{n,t}\) (a 1 appended for the bias) and output gradient \(d_{n,t,e}\) at position \(t\) of example \(n\) along output factor \(e\), expand gives
\[
A = \sum_n \frac{1}{T} \sum_t x_{n,t} x_{n,t}^\top , \qquad
G = \sum_n \sum_t \sum_e d_{n,t,e}\, d_{n,t,e}^\top ,
\]
and reduce gives, with \(\bar x_n = \frac{1}{T} \sum_t x_{n,t}\),
\[
A = \sum_n \bar x_n \bar x_n^\top , \qquad
G = \sum_n \sum_e \Big(\sum_t d_{n,t,e}\Big) \Big(\sum_t d_{n,t,e}\Big)^\top .
\]
With \(N\) examples, the GGN block of the loss summed over the batch is approximated by \(N\, (G/N) \otimes (A/N)\).
Over a dataset
Results add, as with the diagonal. Here with the empirical Fisher, whose factors need the labels of each batch:
compute calls empirical before it returns, so it sees the current yb either way. The default argument yb=yb pins it anyway, in case the function is kept and called later.
A Kronecker Laplace posterior
The posterior precision of a layer is the Kronecker product of the two averaged factors, times the number of data points, plus the prior precision. Eigendecomposing each factor diagonalizes it, so we never form the full matrix (see the math below). We take the last layer, with the weight and bias side by side as one [D_out, D_in + 1] matrix:
tau =1.0kron = total.kron["2"]n_data = kron.total_weightlam_a, q_a = torch.linalg.eigh(kron.a/ kron.total_weight)lam_g, q_g = torch.linalg.eigh(kron.g/ kron.total_weight)precision = n_data * torch.outer(lam_g, lam_a) + tau # [D_out, D_in + 1]# Posterior variance of each entry of [W, b]: the diagonal of the inverse.variance = (q_g**2) @ precision.reciprocal() @ (q_a**2).Tprint(variance.shape)
torch.Size([5, 17])
A small check against the dense matrix, which is cheap for this layer:
Samples come the same way: draw a standard normal of shape [D_out, D_in + 1], divide it by the square root of the eigenvalues, and rotate it back with both eigenbases.
layer = model[2]mean = torch.cat([layer.weight, layer.bias[:, None]], 1).detach()z = torch.randn(4, *precision.shape, dtype=torch.float64)samples = mean + q_g @ (z / precision.sqrt()) @ q_a.Tprint(samples.shape) # 4 samples of [W, b]
torch.Size([4, 5, 17])
NoteThe math
With \(N\) data points, total weight \(W\) and a prior \(\mathcal{N}(0, \tau^{-1} I)\), the posterior precision of a layer is
\[
N \Big(\frac{G}{W}\Big) \otimes \Big(\frac{A}{W}\Big) + \tau I .
\]
The eigendecompositions \(A/W = Q_A \Lambda_A Q_A^\top\) and \(G/W = Q_G \Lambda_G Q_G^\top\) diagonalize it: its eigenvalues are \(N \lambda^G_i \lambda^A_j + \tau\), with eigenvectors \(q^G_i \otimes q^A_j\). The variance of entry \((i, j)\) of \([W, b]\) is \(\sum_{k,l} (Q_G)_{ik}^2 (Q_A)_{jl}^2 / (N \lambda^G_k \lambda^A_l + \tau)\), which is the line (q_g**2) @ precision.reciprocal() @ (q_a**2).T. A sample is \(\theta_\text{MAP} + Q_G (Z \oslash \sqrt{P}) Q_A^\top\), with \(Z\) standard normal and \(P\) the matrix of eigenvalues.