# laplacekit_reward

`laplacekit_reward`

Laplace on reward models trained on preference pairs with Bradley–Terry.

A reward model maps an item to one number, its reward $r$. A preference pair holds two items, and its label is the index of the preferred one, 0 for the first. Bradley–Terry gives

$$p(\text{first} \succ \text{second}) = \sigma(r_1 - r_2),$$

which is the softmax over the two rewards.

A fit on pairs of tensors looks like this:

``` python
fn = lk.reward.pairwise(reward_model)
data = lk.data.from_loader(loader, prepare=lk.reward.prepare_pairs)
post = lk.laplace(fn, data, likelihood=lk.reward.bradley_terry())
out = lk.predict_outputs(post, x)  # one reward per item, with its variance
probs = lk.predict(post, lk.reward.pair(a, b))  # the preference probabilities
```

`pairwise` wraps a reward model so that it scores a `Pair` as `[N, 2]` and single items as `[N, 1]`. A `Pair` holds the two sides of a batch of pairs, and `pair` builds one. `bradley_terry` is the likelihood, `lk.Categorical()` over the two rewards. `prepare_pairs` turns `(first, second, label)` rows into a `Batch`.

## Language-model reward models

Laplace-LoRA (Yang et al., 2024, https://arxiv.org/abs/2308.13111) also works on a language-model reward model. The model is a sequence classifier with `num_labels=1`, wrapped by peft, and the Laplace approximation covers its LoRA adapters, plus the `score` head when it is in `modules_to_save`. This needs `lk.transformers` (`pip install "laplacekit[transformers]"`) and `peft`. `prepare_preferences` turns the tokenizer outputs `{"chosen": ..., "rejected": ...}` into a `Batch` of pairs, with the chosen side first.

``` python
fn = lk.reward.pairwise(lk.transformers.sequence_classification(peft_model))
post = lk.laplace(
    fn,
    lk.data.from_loader(loader, prepare=lk.reward.prepare_preferences),
    likelihood=lk.reward.bradley_terry(),
    subset=lk.subsets.trainable,
    hessian_approx=lk.KFAC(),
)
out = lk.predict_outputs(post, tokenizer(texts, padding=True, return_tensors="pt"))
```

Laplace-LoRA uses KFAC, and `lk.DiagGGN()` also works. `out.mean` is the reward, `[N, 1]`, and `out.cov.per_input()` its variance. Tokenize the chosen and rejected texts in one padded call, so that both sides have the same length, and then split the result.

Code reaches this package as `lk.reward`, which imports it on first use.

## Classes

| Name | Description |
|----|----|
| [Pair](#laplacekit_reward.Pair) | A batch of preference pairs, where `first[i]` and `second[i]` are the items of pair `i`. |

### Pair

``` python
Pair()
```

A batch of preference pairs, where `first[i]` and `second[i]` are the items of pair `i`.

Each side is an input of the reward model: a tensor `[N, ...]`, or a mapping of tensors such as a tokenizer’s output. A named tuple is a torch pytree, so `vmap` and the probe see the tensors of both sides. `pairwise` recognizes a `Pair` by its class, so a plain tuple does not count as one.

#### Parameters

| Name   | Type | Description                   | Default    |
|--------|------|-------------------------------|------------|
| first  |      | The first item of each pair.  | *required* |
| second |      | The second item of each pair. | *required* |

## Functions

| Name | Description |
|----|----|
| [bradley_terry](#laplacekit_reward.bradley_terry) | The Bradley–Terry likelihood over a pair’s rewards `[N, 2]`, which is `lk.Categorical()`. |
| [pair](#laplacekit_reward.pair) | Build `Pair(first, second)`. |
| [pairwise](#laplacekit_reward.pairwise) | Wrap a reward model as a `ModelFn` that scores pairs and single items. |
| [prepare_pairs](#laplacekit_reward.prepare_pairs) | Turn a `(first, second, label)` row, as a `TensorDataset` of pairs gives it, into a `Batch`. |
| [prepare_preferences](#laplacekit_reward.prepare_preferences) | Turn tokenized preferences `{"chosen": ..., "rejected": ...}` into a `Batch` of pairs. |

### bradley_terry

``` python
bradley_terry()
```

The Bradley–Terry likelihood over a pair’s rewards `[N, 2]`, which is `lk.Categorical()`.

Let $r = (r_1, r_2)$, where $r_1$ is the first item’s reward at index 0 of the class axis. Then

$$p(\text{first} \succ \text{second}) = \sigma(r_1 - r_2) = \operatorname{softmax}(r)_1,
\qquad H = \sigma(r_1 - r_2) \, \sigma(r_2 - r_1)
\begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix},$$

where $H$ is the output Hessian. It is the $\operatorname{diag}(q) - q q^\top$ of `Categorical` for two classes, with $q = \operatorname{softmax}(r)$. As in laplace-torch, the target is the index of the preferred item, 0 for the first.

`lk.predict_outputs(post, x)` on single items gives each reward with its variance. `lk.predict(post, pair)` on a `Pair` uses the binary probit on $r_1 - r_2$ instead of the bridge. `lk.predict` on single items raises `CapabilityError`, since a single reward makes only one class.

#### Returns

| Name | Type           | Description         |
|------|----------------|---------------------|
|      | lk.Categorical | `lk.Categorical()`. |

### pair

``` python
pair(first, second, /)
```

Build `Pair(first, second)`.

#### Parameters

| Name   | Type   | Description                   | Default    |
|--------|--------|-------------------------------|------------|
| first  | Inputs | The first item of each pair.  | *required* |
| second | Inputs | The second item of each pair. | *required* |

#### Returns

| Name | Type | Description |
|------|------|-------------|
|      | Pair | The `Pair`. |

### pairwise

``` python
pairwise(model, /)
```

Wrap a reward model as a `ModelFn` that scores pairs and single items.

On a `Pair`, the two sides are concatenated along dim 0 and the inner model runs once on `[2N, ...]`, so module hooks see one call per layer. The result is `[N, 2]`, the rewards of the first and the second items.

Any other input is one item per row and gets its reward, `[N, 1]`. That includes a plain dict with the keys `"first"` and `"second"`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| model | nn.Module \| lk.core.ModelFn | The reward model, as a module or a `ModelFn`, with one output per item. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.core.ModelFn | The `ModelFn`. Its module is the inner one, so the parameter names stay the same. A call raises `StructureError` when the inner output has more than one value per item, or when the two sides of a `Pair` are not both tensors or both mappings of tensors, or differ in shape. Mapping sides need the same keys and the same shape for each key, and the error names the key that differs. |

### prepare_pairs

``` python
prepare_pairs(raw, generator, /)
```

Turn a `(first, second, label)` row, as a `TensorDataset` of pairs gives it, into a `Batch`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| raw | Sequence\[Any\] | The row `(first, second, label)`. `label` is a tensor, the index of the preferred item. | *required* |
| generator | torch.Generator | Unused: nothing is drawn. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.Batch | A `Batch` with inputs `pair(first, second)` and targets `label.long()`. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `raw` does not have 3 entries, or `label` is not a tensor. |

### prepare_preferences

``` python
prepare_preferences(raw, generator, /)
```

Turn tokenized preferences `{"chosen": ..., "rejected": ...}` into a `Batch` of pairs.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| raw | Mapping\[str, Mapping\[str, Tensor\]\] | The batch. `raw["chosen"]` and `raw["rejected"]` are tokenizer outputs, `[N, T]`. Tokenize both sides in one padded call so that they have the same length. Other keys are dropped. | *required* |
| generator | torch.Generator | Unused: nothing is drawn. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.Batch | A `Batch` with inputs `pair(chosen, rejected)` and targets `zeros(N)`, because the chosen side comes first and is the preferred one. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | A side is missing, or is not a non-empty mapping of tensors. |
