# KFAC

``` python
KFAC(fisher='exact', mc_samples=None)
```

Kronecker-factored GGN per Linear / Conv2d layer, computed by Curvlinops.

Per layer, the per-example average curvature is approximated by $G \otimes A$, on the weight and bias folded into one matrix (row-major, as in `KronEigenbasis`):

$$A = \frac{1}{N} \sum_n \frac{1}{T} \sum_t x_{n,t} x_{n,t}^\top, \qquad
G = \frac{1}{N} \sum_n \sum_t \sum_c d_{n,t,c} \, d_{n,t,c}^\top.$$

Here $x_{n,t}$ is the layer’s input at position $t$ of example $n$ (with a 1 appended when the layer has a bias), over $T$ positions (spatial, or along a sequence), and the $d_{n,t,c}$ are vectors backpropagated to the layer’s output at that position. With `"exact"` they come from the columns $c$ of a square root of the output Hessian. With `"mc"` and `"empirical"` there is one per position, from the score $\nabla_f \log p(y \mid f)$ at a target $y$ drawn from the model or at the batch’s own target.

The empirical Fisher needs targets and can’t apply a late $\sigma$, so it takes a fixed $\sigma$ such as `Gaussian(sigma=0.1)`, but not `Gaussian()`, which learns it. On sequence outputs `[N, T, C]` it sums the per-position $d d^\top$ (KFAC-expand), so it does not factor the same matrix as `DenseGGN(fisher="empirical")`, whose gradient is per sequence.

Per-example weights are not supported. Masked likelihoods (`Categorical(mask_fn=...)`) are refused: Curvlinops builds the input factor from every position’s layer input and can’t leave padding out. Tied tensors are refused, since the hooks see only the layer’s own use.

## Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| fisher | Fisher | `"exact"` uses the exact output Hessian, `"mc"` sampled targets, seeded from the batch’s generator, and `"empirical"` the batch’s own targets. | `'exact'` |
| mc_samples | int \| None | Sampled targets per example for `fisher="mc"`, at least 1 (1 when `None`). Refused with another `fisher`. | `None` |

## Raises

| Name | Type | Description |
|----|----|----|
|  | ValueError | `fisher` is not `"exact"`, `"mc"` or `"empirical"`, or `mc_samples` comes without `fisher="mc"` or is below 1. |

## Attributes

| Name | Description |
|----|----|
| [requires](#laplacekit.KFAC.requires) | Needs hooks on `nn.Linear` and `nn.Conv2d`, and no per-example weights. |

## Methods

| Name | Description |
|----|----|
| [finalize](#laplacekit.KFAC.finalize) | $G \otimes A$ per block, as a `KronEigenbasis`. |
| [init](#laplacekit.KFAC.init) | Zero factor sums per block, `[in (+1), in (+1)]` and `[out, out]`. |
| [supports](#laplacekit.KFAC.supports) | Whether KFAC can fit `likelihood` on the parameters `names`. |
| [template](#laplacekit.KFAC.template) | Identity eigenbases with zero eigenvalues and zero Kronecker factors. |
| [update](#laplacekit.KFAC.update) | Add the batch’s factor sums, computed by Curvlinops at the module’s parameters. |

### finalize

``` python
KFAC.finalize(stat, /)
```

$G \otimes A$ per block, as a `KronEigenbasis`.

It holds the eigenvectors of $A$ and $G$ and the eigenvalues $\lambda_G \lambda_A^\top$, with each factor’s negative eigenvalues (round-off) clamped to zero. The Kronecker factors are kept in `factors`, with count 1.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| stat | KronStat | The statistic over all the data, after `all_reduce`. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | BlockDiag\[KronEigenbasis\] | The per-example average $\bar{C} = \sum_n w_n C_n / \sum_n w_n$. The posterior multiplies it by `scale`. |

### init

``` python
KFAC.init(params, ctx, /)
```

Zero factor sums per block, `[in (+1), in (+1)]` and `[out, out]`.

#### Parameters

| Name   | Type       | Description                           | Default    |
|--------|------------|---------------------------------------|------------|
| params | Params     | The params the curvature is taken at. | *required* |
| ctx    | FitContext | The fit’s context.                    | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | KronStat | A statistic $e$ with $e + s = s$ for every statistic $s$ of this fit. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | CapabilityError | The likelihood is not one KFAC takes (see `supports`), the model was not built from an `nn.Module`, the capabilities miss `requires` (`Capabilities.check`, which also refuses blocks not reached by hooks or of another type, and parameters that were `selected`, since hooks see whole tensors), the likelihood has a late hyperparameter with `"empirical"`, a parameter is a tied tensor, there are no parameters, or a block has no weight in the subset. |

### supports

``` python
KFAC.supports(likelihood, /, caps=None, names=())
```

Whether KFAC can fit `likelihood` on the parameters `names`.

`init` raises for everything refused here.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| likelihood | Likelihood \| None | The likelihood, or None to skip its check. KFAC takes `Gaussian`, `Bernoulli`, and `Categorical` with `class_dim=-1` and no `mask_fn`. | *required* |
| caps | Capabilities \| None | The probe’s capabilities, read for the tied tensors `caps.tied`. None skips the tie check. | `None` |
| names | Iterable\[str\] | Parameter names. A name of a tied tensor is refused: the hooks see only one of its uses. | `()` |

#### Returns

| Name | Type | Description                                                 |
|------|------|-------------------------------------------------------------|
|      | bool | True unless the likelihood or a tied tensor rules KFAC out. |

### template

``` python
KFAC.template(params, ctx, /)
```

Identity eigenbases with zero eigenvalues and zero Kronecker factors.

#### Parameters

| Name   | Type       | Description                           | Default    |
|--------|------------|---------------------------------------|------------|
| params | Params     | The params the curvature is taken at. | *required* |
| ctx    | FitContext | The fit’s context.                    | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | BlockDiag\[KronEigenbasis\] | A zero operator with the operator types, blocks, static fields, leaf shapes and dtypes that `finalize` returns. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | CapabilityError | There are no parameters, or a block has no weight in the subset. |

### update

``` python
KFAC.update(stat, params, batch, generator, ctx, /)
```

Add the batch’s factor sums, computed by Curvlinops at the module’s parameters.

Curvlinops differentiates the module’s live parameters, so `params` must hold their values.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| stat | KronStat | The statistic so far. | *required* |
| params | Params | The params the curvature is taken at. | *required* |
| batch | Batch | The batch to add. | *required* |
| generator | torch.Generator | The batch’s generator. With `fisher="mc"`, Curvlinops draws the targets from a seed drawn from it (`lk.core.spawn_generator`). | *required* |
| ctx | FitContext | The fit’s context. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | KronStat | `stat` with the batch added. Updating with batches $a$, then $b$, equals adding the statistics of $a$ and of $b$. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | CapabilityError | The batch has per-example weights, it has no targets with `"empirical"`, or `params` differ from the module’s live parameters. |
|  | ValueError | A `Bernoulli` target lies outside $[0, 1]$ with `"empirical"`. |
|  | StructureError | A per-output $\sigma$ doesn’t fit the outputs’ event shape. |
