# Reward models

A reward model gives one number per answer and learns from pairs: two answers and which one a person preferred. laplace**kit** gives each reward an error bar with a Laplace approximation. Pairs are also why KFAC’s default form is expand.

``` python
import torch
from torch import nn

import hessiankit as hk

torch.manual_seed(0)
scorer = nn.Sequential(nn.Linear(6, 32), nn.Tanh(), nn.Linear(32, 1))


def difference(m, x):
    """r(a) - r(b) for pairs x [N, 2, 6]: both answers in one call."""

    r = m(x)  # [N, 2, 1]
    return r[:, 0] - r[:, 1]


batches = [
    (torch.randn(32, 2, 6), torch.randint(0, 2, (32, 1)).float())
    for _ in range(4)
]
# Bradley-Terry: p(a preferred) = sigmoid(r(a) - r(b))
likelihood = hk.Bernoulli()

print(hk.plan(scorer, batches[0], likelihood, forward=difference))
```

    hk.plan: kfac on output [32, 1], event axes (), 1 position per example
    layer  type    T  params  A   G   mask
    0      Linear  2  224     7   32  none
    2      Linear  2  33      33  1   none
    fisher: exact (1 backward pass per batch, at most EXACT_MAX_PASSES = 64)
    form: expand (reduce is opt-in: it cancels to zero when positions enter with opposite signs)
    backward passes per batch: 1
    memory: 16.9 KiB in float64

The two answers of a pair are two positions of each layer ($T = 2$), and the output, the difference of their rewards, has one position. KFAC takes its expand form, which treats the two answers as separate examples:

``` python
result = hk.kfac(scorer, batches, likelihood, forward=difference)

print(result.kron["2"].g)
```

    tensor([[63.5570]], dtype=torch.float64)

The reduce form, `form="reduce"`, sums each layer’s output gradients over its positions first. Here that sum cancels: the two answers enter the output with opposite signs, so the head’s gradients at them are equal and opposite, and its $G$ is zero.

``` python
reduce = hk.kfac(scorer, batches, likelihood, forward=difference, form="reduce")

print(reduce.kron["2"].g)
```

    tensor([[0.]], dtype=torch.float64)

A zero $G$ would leave the head’s posterior at the prior, as if the data said nothing about it. The rule can’t see signs, only shapes, so reduce is never the default.

The exact diagonal is right with no choice to make, and it gives a check. The head’s bias adds the same number to both rewards, so it cancels in the difference, and the data say nothing about it: its diagonal is zero, while its weights’ is not.

``` python
diag = hk.diagonal(scorer, batches, likelihood, forward=difference)

print(diag.diagonal["2"].bias, diag.diagonal["2"].weight.abs().max())
```

    tensor([0.], dtype=torch.float64) tensor(21.8354, dtype=torch.float64)

> **NOTE:**
>
> For the head with weight $w$, the output of pair $n$ is $w^\top (h_{n,a} - h_{n,b})$, with $h$ the features of each answer; the bias cancels. Its exact GGN block is $\sum_n \lambda_n (h_{n,a} - h_{n,b})(h_{n,a} - h_{n,b})^\top$, with $\lambda_n = p_n (1 - p_n)$. The reduce form multiplies the mean of the inputs, $(h_{n,a} + h_{n,b}) / 2$, with the sum of the output gradients, $g_n - g_n = 0$. The expand form uses $\frac12 (h_{n,a} h_{n,a}^\top + h_{n,b} h_{n,b}^\top)$ and $2 g_n g_n^\top$. That isn’t exact either, since it drops the cross terms $-(h_{n,a} h_{n,b}^\top + h_{n,b} h_{n,a}^\top)$, but it is positive semidefinite and doesn’t vanish.

## When to override

- Don’t pass `form="reduce"` when the two answers of a pair are positions of the same call: the head’s $G$ comes out zero. For the diagonal without KFAC’s approximation, use `hk.diagonal`, which is exact.
- Score both answers in one call, as positions `[N, 2, ...]`. A `forward` that calls the model once per answer runs every layer twice, and the defaults then leave every layer out (`ran 2 times` in `plan`).
