Skip to main content

kfac, diagonal, plan

KFAC, the GGN diagonal, and what they would do, with defaults.

kfac

kfac(
    model,
    batches,
    likelihood,
    *,
    layers=None,
    fisher='auto',
    mc_samples=None,
    form='auto',
    forward=None,
    position_mask=None,
    dtype=torch.float64,
    generator=None,
    create_graph=False,
    rules=DEFAULT_RULES,
)

KFAC factors of the model’s layers, summed over the batches, with defaults.

The choices come from the first batch (see plan, which prints them): the layers, exact factors when they take at most EXACT_MAX_PASSES backward passes per batch (one per entry of an event, factors grouped by "columns") else Monte Carlo with MC_SAMPLES["kfac"] samples, and the form "expand" when the output has several positions per example else "reduce". Every batch then goes through compute with them, and the results are added. The model is never changed.

Parameters

Name Type Description Default
model nn.Module The model. required
batches Iterable[Batch] An iterable of (inputs, targets) or (inputs, targets, weights), a DataLoader say. targets may be None unless fisher="empirical" or the likelihood needs them for void labels. required
likelihood Likelihood hk.Categorical, hk.Bernoulli, hk.Gaussian, hk.FromHessian, or any Likelihood. required
layers Sequence[str] | None Module paths to compute for. None picks every module whose type has a rule, whose own parameters all require grad, which ran once on the first batch and shares no parameter. Given, the list goes to compute as it is. None
fisher FisherOption "auto", or "exact", "mc" or "empirical". 'auto'
mc_samples int | None Samples per example for "mc"; None takes MC_SAMPLES["kfac"]. None
form FormOption "auto", or "expand" or "reduce". 'auto'
forward Forward | None forward(model, inputs) returns the output tensor, the batch first. The default is model(inputs); for a Hugging Face model, lambda m, x: m(**x).logits. None
position_mask Callable[[Any], Tensor] | None position_mask(inputs) returns a mask [N, T] (the attention mask), 1 at positions to keep. It masks every layer with T positions, and the output too when that has T positions, together with the likelihood’s output mask. A layer whose positions match neither the output’s, nor 1, nor this mask’s (a downsampled convolution under void pixels) keeps all its positions of every example with an unmasked output: its G and diagonal stay exact, since void outputs have zero factors, and its A counts those positions. plan shows the mask of each layer. For a finer mask, call compute with masks={...}. None
dtype torch.dtype The dtype the sums accumulate in. torch.float64
generator torch.Generator | None Random generator for "mc". None uses a new one seeded 0 on every call, so results are reproducible. None
create_graph bool Make the results differentiable in the model’s parameters. False
rules Mapping[type[nn.Module], LayerRule] Layer rules by module type. DEFAULT_RULES

Returns

Name Type Description
Result A Result with a LayerKron per layer and uncovered, the trainable parameters no layer covers with the reason.

Raises

Name Type Description
FactorError The likelihood can’t give the chosen Fisher; "empirical" without targets; no layer to compute for; or a mask doesn’t fit.
ValueError batches is empty, or a batch is not a tuple of 2 or 3.
HessiankitError Whatever compute raises, such as for an explicit layer it refuses.

Examples

>>> import torch, hessiankit as hk
>>> from torch import nn
>>> model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 3))
>>> batches = [(torch.randn(16, 4), torch.randint(0, 3, (16,))) for _ in range(2)]
>>> result = hk.kfac(model, batches, hk.Categorical())
>>> kron = result.kron["2"]
>>> kron.a.shape, kron.g.shape, kron.total_weight.item()
(torch.Size([9, 9]), torch.Size([3, 3]), 32.0)

diagonal

diagonal(
    model,
    batches,
    likelihood,
    *,
    layers=None,
    fisher='auto',
    mc_samples=None,
    forward=None,
    position_mask=None,
    dtype=torch.float64,
    generator=None,
    create_graph=False,
    rules=DEFAULT_RULES,
)

The GGN diagonal of the model’s layers, summed over the batches, with defaults.

As kfac, without form: exact factors when they take at most EXACT_MAX_PASSES backward passes per batch (one per position and entry of an event, factors grouped "full"), else Monte Carlo with MC_SAMPLES["diagonal"] samples. With exact factors the diagonal is exact.

Parameters

Name Type Description Default
model nn.Module The model. required
batches Iterable[Batch] An iterable of (inputs, targets) or (inputs, targets, weights). required
likelihood Likelihood The likelihood. required
layers Sequence[str] | None Module paths, or None for the default (see kfac). None
fisher FisherOption "auto", or "exact", "mc" or "empirical". 'auto'
mc_samples int | None Samples per example for "mc"; None takes MC_SAMPLES["diagonal"]. None
forward Forward | None forward(model, inputs) returns the output tensor. None
position_mask Callable[[Any], Tensor] | None position_mask(inputs) returns a mask [N, T]. See kfac, also for a layer whose positions don’t match the output’s: it keeps all its positions of every example with an unmasked output, which leaves the diagonal exact. None
dtype torch.dtype The dtype the sums accumulate in. torch.float64
generator torch.Generator | None Random generator for "mc"; None seeds a new one with 0. None
create_graph bool Make the results differentiable in the model’s parameters. False
rules Mapping[type[nn.Module], LayerRule] Layer rules by module type. DEFAULT_RULES

Returns

Name Type Description
Result A Result with a LayerDiagonal per layer and uncovered.

Raises

Name Type Description
FactorError As for kfac.
ValueError As for kfac.

Examples

>>> import torch, hessiankit as hk
>>> from torch import nn
>>> model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 3))
>>> batches = [(torch.randn(16, 4), torch.randint(0, 3, (16,))) for _ in range(2)]
>>> result = hk.diagonal(model, batches, hk.Categorical())
>>> {k: tuple(v.shape) for k, v in result.by_parameter().items()}
{'0.weight': (8, 4), '0.bias': (8,), '2.weight': (3, 8), '2.bias': (3,)}

plan

plan(
    model,
    batch,
    likelihood,
    *,
    method='kfac',
    layers=None,
    fisher='auto',
    mc_samples=None,
    form='auto',
    forward=None,
    position_mask=None,
    dtype=torch.float64,
    generator=None,
    create_graph=False,
    rules=DEFAULT_RULES,
)

What kfac or diagonal would do on this batch, and why, without computing it.

The model runs forward once under no_grad, with its buffers cloned, to find the layers and the output’s shape; no Hessian or output factor is computed. The options are those of kfac (form only with method="kfac"); generator and create_graph don’t change the plan and are taken so the same keywords work for both.

Returns

Name Type Description
Plan A Plan; print it for a table of the layers, the uncovered parameters and the choices with their reasons.

Raises

Name Type Description
FactorError As for kfac.
UnsupportedLayerError layers names a module the model doesn’t have, or one compute would refuse.

Examples

>>> import torch, hessiankit as hk
>>> from torch import nn
>>> model = nn.Sequential(nn.Linear(4, 8), nn.LayerNorm(8), nn.Linear(8, 3))
>>> batch = (torch.randn(16, 4), torch.randint(0, 3, (16,)))
>>> print(hk.plan(model, batch, hk.Categorical()))
hk.plan: kfac on output [16, 3], event axes (1,), 1 position per example
layer  type    T  params  A  G  mask
0      Linear  1  40      5  8  none
2      Linear  1  27      9  3  none
uncovered (trainable, not computed):
  1.weight  no rule for LayerNorm
  1.bias    no rule for LayerNorm
fisher: exact (3 backward passes per batch, at most EXACT_MAX_PASSES = 64)
form: reduce (the output has one position per example)
backward passes per batch: 3
memory: 1.4 KiB in float64