compute
compute
compute: one forward, one backward pass per output factor, and the reductions.
Attributes
| Name | Description |
|---|---|
KFACType |
How KFAC treats several positions per example: expand them as examples, or sum them. |
Masks |
masks, output_mask and event_axes, as compute takes them. |
Functions
| Name | Description |
|---|---|
| compute | The exact GGN diagonal and the KFAC factors of the requested layers, summed over a batch. |
| run | compute, with the masks built from the output and each layer’s positions T. |
compute
compute.compute(
module,
params,
inputs,
factors,
*,
layers,
call=None,
diagonal=False,
kfac=None,
weights=None,
masks=None,
output_mask=None,
event_axes=None,
dtype=None,
rules=DEFAULT_RULES,
check_reuse=True,
create_graph=False,
chunk_bytes=2 ** 28,
)The exact GGN diagonal and the KFAC factors of the requested layers, summed over a batch.
The model runs once, with forward hooks on the requested layers. Each output factor is then backpropagated, and each layer’s rule turns its input and output gradient into the canonical form the reductions use: inputs x_nt and output gradients d_nte at positions t. With output factors v_ne and signs s_ne, the diagonal of a layer’s parameter is sum_n w_n sum_e s_ne (J_n^T v_ne)^2, J_n the Jacobian of example n’s output in that parameter. The KFAC factors are, with T_n the unmasked positions of example n and xbar_n the mean of its unmasked inputs,
- expand:
A = sum_n w_n / T_n sum_t m_nt x_nt x_nt^T,G = sum_n w_n sum_t m_nt sum_e d_nte d_nte^T; - reduce:
A = sum_n w_n xbar_n xbar_n^T,G = sum_n w_n sum_e (sum_t m_nt d_nte)(sum_t m_nt d_nte)^T.
Results are sums; divide by total_weight for the per-example average. Masks and weights follow two rules: a weight k is the example repeated k times, and a masked position contributes nothing, to the sums, to T_n or to total_weight (an example with no unmasked position does not count). Works under torch.no_grad() too, also with create_graph.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| module | nn.Module | The model. It is never changed, buffers included, and needs no requires_grad. |
required |
| params | Mapping[str, Tensor] | None | Parameters by full dotted name (as named_parameters(remove_duplicate=False) gives them), overriding the module’s own. None uses the module’s. |
required |
| inputs | Any | What the model takes. | required |
| factors | Callable[[Tensor], OutputFactors] | Called with the outputs [N, *output_shape], detached unless create_graph; returns their output factors [E, N, *output_shape]. |
required |
| layers | Sequence[str] | Module paths of the layers to compute for, as named_modules gives them. |
required |
| call | Callable[[Mapping[str, Tensor], Any], Tensor] | None | Runs the model as call(params, inputs), params holding every parameter and buffer name of the module. The buffers are clones, so the module’s own never change, as long as call runs the model with the dict it gets: a call that uses the module’s own buffers can update them (a BatchNorm in train mode). It must return one Tensor with the batch on dim 0. The default is torch.func.functional_call(module, params, (inputs,)). |
None |
| diagonal | bool | Compute the exact GGN diagonal. | False |
| kfac | KFACType | None | Compute the KFAC factors, "expand" or "reduce". Takes positive signs only. |
None |
| weights | Tensor | None | Example weights [N], not negative. None weighs every example 1. |
None |
| masks | Mapping[str, Tensor] | None | Position masks by layer path, [N, T] of bool or 0 and 1 at the layer’s positions (1 keeps). A layer without an entry is unmasked, unless output_mask is given. |
None |
| output_mask | Tensor | None | Boolean mask over the output’s positions, with one axis per output axis: the output’s size on the batch and position axes and 1 on every event axis ([N, 1, H, W] for logits [N, C, H, W], [N, T, 1] for [N, T, C], [N, 1] for [N, C]). Its positions, P of them, are the axes after N in row-major order. It zeroes the output factors at masked positions. For a layer with no entry in masks it is also the position mask when the layer has as many positions as the output (T = P), its positions taken to be the output’s in the same row-major order, and it drops the examples with no unmasked position when the layer has one. With a position axis of size 1 shapes can’t tell it from an event axis, so the mask must be 1 on every event axis. |
None |
| event_axes | tuple[int, …] | None | The output’s event axes, non-negative, as a likelihood’s event_axes gives them. Given, output_mask must be size 1 exactly on these axes and of the output’s size on the others, which are its positions; () makes every entry a position (hk.Bernoulli). None takes any mask of the form above. |
None |
| dtype | torch.dtype | None | The dtype the sums accumulate in. Defaults to the output’s. | None |
| rules | Mapping[type[nn.Module], LayerRule] | Layer rules by module type, looked up by the exact type. | DEFAULT_RULES |
| check_reuse | bool | Check, for each layer on the first output factor that reaches it, that its autograd gradient equals the one rebuilt from its input and output gradient. This catches a parameter used outside its layer’s call, and a rule that lays out a layer’s input or output gradient in another order than its weight. | True |
| create_graph | bool | Make the results differentiable in the parameters: in params, or in the module’s own when params is None, for every parameter that requires grad. factors then gets the outputs with their graph, so the output Hessian’s dependence on the parameters is differentiated too when the factors keep that graph (the built-in helpers do). weights, masks and output_mask are constants. Without it, the results carry no graph. |
False |
| chunk_bytes | int | Upper bound on the bytes of per-example gradients held at once, for the diagonal of layers with several positions per example. | 2 ** 28 |
Returns
| Name | Type | Description |
|---|---|---|
| Result | A Result with a LayerDiagonal (if diagonal) and a LayerKron (if kfac) for each requested layer. |
Raises
| Name | Type | Description |
|---|---|---|
| UnsupportedLayerError | A path names no module, a layer has no rule, or its rule refuses its input. | |
| CaptureError | A layer runs other than once, shares a parameter with another requested layer, or is not reached by the output; a layer’s input has a different batch size than the output; or the model returns something other than a Tensor. | |
| FunctionalReuseError | A layer’s parameter is also used outside its call. | |
| FactorError | The batch is empty; the factors don’t fit the output; KFAC got a negative sign; the weights are not [N] or are negative; a mask has the wrong shape or values, or names a layer not requested; or output_mask is given and a layer with neither T = P nor T = 1 has no entry in masks. All before any backward pass. |
|
| ValueError | Nothing is requested, a layer is listed twice, params has a name the module doesn’t have, or chunk_bytes is below 1. |
run
compute.run(
module,
params,
inputs,
factors,
*,
layers,
call,
diagonal,
kfac,
weights,
masks_for,
dtype,
rules,
check_reuse,
create_graph,
chunk_bytes,
)compute, with the masks built from the output and each layer’s positions T.
masks_for(f, positions) gets the output, detached, and T by layer path, and returns what compute takes as masks, output_mask and event_axes. The front door uses it to build masks that depend on the output’s shape.