# Your own layers

hessiankit knows `nn.Linear` and `nn.Conv2d`. Any other layer whose own parameters are a weight and an optional bias takes a rule, and we write one here for `nn.Conv1d`.

A rule has three methods. `check` refuses what the rule can’t handle, `inputs` gives the layer’s input as `[N, T, G, D_in]`, and `grads` gives the gradient at its output as `[N, T, D_out]`. `T` counts the positions of an example, and `G` the groups of output channels. The weight gradient of one position is then the outer product of the two, so the weight must flatten to `[D_out, D_in]` in the same order as the input. For a convolution, `D_in` is a patch of the input: `C_in / G` channels times `k` taps, channel-major, which is how `weight.flatten(1)` lays out a `[C_out, C_in / G, k]` kernel.

``` python
from dataclasses import dataclass

import torch
import torch.nn.functional as F
from torch import nn

import hessiankit as hk


@dataclass(frozen=True)
class Conv1dRule:
    def check(self, module, x, name):
        if not isinstance(module, nn.Conv1d) or x.ndim != 3:
            raise hk.UnsupportedLayerError(
                f"{name}: needs an nn.Conv1d on [N, C, L]"
            )

        if isinstance(module.padding, str) or module.padding_mode != "zeros":
            raise hk.UnsupportedLayerError(f"{name}: only integer zero padding")

    def inputs(self, module, x):
        # [N, C, L] as an image of height 1, so F.unfold cuts the patches.
        patches = F.unfold(
            x.unsqueeze(2),
            (1, module.kernel_size[0]),
            dilation=(1, module.dilation[0]),
            padding=(0, module.padding[0]),
            stride=(1, module.stride[0]),
        )  # [N, C * k, L_out], channel-major
        n, _, t = patches.shape

        return patches.reshape(n, module.groups, -1, t).permute(0, 3, 1, 2)

    def grads(self, module, g):
        return g.transpose(1, 2)  # [N, C_out, L_out] -> [N, L_out, C_out]
```

Rules are looked up by the exact type of the layer, in the mapping passed as `rules`. We add ours to the built-in ones:

``` python
torch.manual_seed(0)
model = nn.Sequential(
    nn.Conv1d(2, 4, 3, padding=1, stride=2, groups=2),
    nn.Tanh(),
    nn.Flatten(),
    nn.Linear(4 * 5, 3),
).double()
x = torch.randn(16, 2, 10, dtype=torch.float64)  # [N, C, L]

rules = {**hk.DEFAULT_RULES, nn.Conv1d: Conv1dRule()}


def factors(f):
    return hk.categorical(f, kind="exact")


result = hk.compute(
    model, None, x, factors, layers=["0", "3"], diagonal=True, rules=rules
)
print(result.diagonal["0"].weight.shape)
```

    torch.Size([4, 1, 3])

Without the rule, `compute` refuses the layer and says how to pass one:

``` python
try:
    hk.compute(model, None, x, factors, layers=["0"], diagonal=True)
except hk.UnsupportedLayerError as error:
    print(error)
```

    0: no rule for Conv1d; pass one through rules={**hk.DEFAULT_RULES, Conv1d: ...}

Before trusting a new rule, we compare it with the dense GGN from `torch.func`, which needs nothing from hessiankit:

``` python
params = {k: v.detach() for k, v in model.named_parameters()}


def output(p, xi):
    return torch.func.functional_call(model, p, (xi.unsqueeze(0),))[0]


def ggn_diagonal(xi):
    jac = torch.func.jacrev(output)(params, xi)  # each [C, *param.shape]
    p = output(params, xi).softmax(-1)
    H = torch.diag(p) - torch.outer(p, p)

    return {
        k: torch.einsum("k...,kl,l...->...", j, H, j) for k, j in jac.items()
    }


dense = {k: v.sum(0) for k, v in torch.func.vmap(ggn_diagonal)(x).items()}

print(torch.allclose(result.diagonal["0"].weight, dense["0.weight"]))
print(torch.allclose(result.diagonal["0"].bias, dense["0.bias"]))
```

    True
    True

`compute` also checks a rule as it goes. On the first output factor that reaches the layer, it rebuilds the weight gradient from `inputs` and `grads` and compares it with the one autograd computes. A rule that gets the order of the positions wrong fails that check:

``` python
class Flipped(Conv1dRule):
    def grads(self, module, g):
        return g.transpose(1, 2).flip(1)  # the positions reversed


try:
    hk.compute(
        model,
        None,
        x,
        factors,
        layers=["0"],
        diagonal=True,
        rules={**hk.DEFAULT_RULES, nn.Conv1d: Flipped()},
    )
except hk.FunctionalReuseError as error:
    print(error)
```

    0.weight: autograd's gradient differs from the one built from the layer's input and output gradient; is it used outside 0's call (functional reuse or a tied weight), or does the layer's rule lay out its inputs or grads in another order than the weight?

`check_reuse=False` turns the check off. It can’t catch everything: a rule that permutes the positions of `inputs` and `grads` the same way passes it, and gives the right diagonal anyway.
