# laplacekit_transformers

`laplacekit_transformers`

Laplace-LoRA on Hugging Face `transformers` models: causal LMs and sequence classifiers.

`laplace_lora` fits a Laplace approximation over the LoRA adapters of a peft model:

``` python
task = lk.transformers.SequenceClassification()
post = lk.transformers.laplace_lora(model, batches, task=task, n_data=len(train))
probs = lk.predict(post, inputs).probs  # linearized over the K class logits
```

For a causal LM, a batch is a tokenizer’s output, `{"input_ids", "attention_mask"}`, each `[N, T]`. The model predicts token `t + 1` from the tokens up to `t`, so position `t` counts when both tokens are real (`padding_mask`). Right padding then changes neither the curvature nor the data-fit term. Masked positions still enter the Jacobian, and a non-finite activation there leaks through, since `0 * NaN` is NaN. Left padding with eager attention in float64 gives such NaNs, so pad on the right for the fit.

`transformers` loads models with SDPA attention by default, and the fit works with it. The linearized predictive, the default of `lk.predict`, differentiates the model’s backward pass, which SDPA does not support, so it raises `CapabilityError`. Load the model with `attn_implementation="eager"`, or predict with `lk.WeightSamples()`.

A causal LM’s logits span the vocabulary. To predict among a few answers, such as $P(\text{True})$ or a multiple-choice letter, `answer_logits` selects their logits at the last real token. A sequence classifier (`SequenceClassification()`) has $K$ logits per sequence to begin with.

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

## Classes

| Name | Description |
|----|----|
| [CausalLM](#laplacekit_transformers.CausalLM) | The task of `laplace_lora` for a causal LM (`AutoModelForCausalLM`). |
| [SequenceClassification](#laplacekit_transformers.SequenceClassification) | The task of `laplace_lora` for a sequence classifier (`AutoModelForSequenceClassification`). |
| [Tokenizer](#laplacekit_transformers.Tokenizer) | A tokenizer for `answer_logits`, which only needs its `encode` method. |

### CausalLM

``` python
CausalLM()
```

The task of `laplace_lora` for a causal LM (`AutoModelForCausalLM`).

The model predicts each next token, with logits `[N, T, V]` over the vocabulary. `laplace_lora` then uses `causal_lm`, `prepare_causal_lm` and `padding_mask`.

### SequenceClassification

``` python
SequenceClassification()
```

The task of `laplace_lora` for a sequence classifier (`AutoModelForSequenceClassification`).

The model predicts one of $K$ labels per sequence, with logits `[N, K]`. The batches carry `"labels"`, and `laplace_lora` uses `sequence_classification` and `prepare_sequence_classification`.

### Tokenizer

``` python
Tokenizer()
```

A tokenizer for `answer_logits`, which only needs its `encode` method.

Every Hugging Face tokenizer has it, and so can any other object.

#### Methods

| Name | Description |
|----|----|
| [encode](#laplacekit_transformers.Tokenizer.encode) | Encode `text` as token ids. |

##### encode

``` python
Tokenizer.encode(text, /, *, add_special_tokens=True)
```

Encode `text` as token ids.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| text | str | The text. | *required* |
| add_special_tokens | bool | Whether to add the tokenizer’s special tokens. `answer_logits` passes `False`. | `True` |

###### Returns

| Name | Type        | Description              |
|------|-------------|--------------------------|
|      | list\[int\] | The token ids of `text`. |

## Functions

| Name | Description |
|----|----|
| [answer_logits](#laplacekit_transformers.answer_logits) | Build a `select` for `lk.predict` that keeps the logits of `answers` at the last real token. |
| [causal_lm](#laplacekit_transformers.causal_lm) | Wrap a Hugging Face causal LM as a `ModelFn` that returns the logits. |
| [health](#laplacekit_transformers.health) | Check for `lk.health()` that `transformers` is installed, and `peft` if possible. |
| [laplace_lora](#laplacekit_transformers.laplace_lora) | Fit a Laplace approximation over the trainable parameters of a Hugging Face model. |
| [last_token](#laplacekit_transformers.last_token) | The logits at each sequence’s last real token, with left or right padding. |
| [padding_mask](#laplacekit_transformers.padding_mask) | Mark the positions that count in a causal LM’s loss, as a `mask_fn` for `lk.Categorical`. |
| [prepare_causal_lm](#laplacekit_transformers.prepare_causal_lm) | Turn a tokenizer batch into a `Batch` for next-token prediction. |
| [prepare_sequence_classification](#laplacekit_transformers.prepare_sequence_classification) | Turn a tokenizer batch with `"labels"` into a `Batch` for sequence classification. |
| [sequence_classification](#laplacekit_transformers.sequence_classification) | Wrap a Hugging Face sequence classifier as a `ModelFn` that returns the logits. |

### answer_logits

``` python
answer_logits(tokenizer, answers, /)
```

Build a `select` for `lk.predict` that keeps the logits of `answers` at the last real token.

With it, the linearized predictive covers only those logits instead of the whole vocabulary:

``` python
select = lk.transformers.answer_logits(tokenizer, [" True", " False"])
probs = lk.predict(post, inputs, select=select).probs  # [N, 2]
```

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| tokenizer | Tokenizer | A `Tokenizer`. | *required* |
| answers | Sequence\[str\] | The answers, as a sequence of strings. Each is encoded as given, without special tokens, and must be exactly one token. A leading space is part of the answer, as in `" True"` for most BPE tokenizers. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Callable\[\[Outputs, Inputs\], Outputs\] | A function that maps causal LM logits `[N, T, V]` to `[N, len(answers)]`, in the order of `answers`, through `last_token`. Errors from `last_token` pass through. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `tokenizer` has no `encode` method, `answers` is a single string or empty, an answer encodes to zero or several tokens, or two answers encode to the same token. The messages of the last two name the tokens. All of these checks run before any call of the model. |

### causal_lm

``` python
causal_lm(model, /)
```

Wrap a Hugging Face causal LM as a `ModelFn` that returns the logits.

#### Parameters

| Name  | Type      | Description                           | Default    |
|-------|-----------|---------------------------------------|------------|
| model | nn.Module | The causal LM, plain or peft-wrapped. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.core.ModelFn | A `ModelFn` whose `forward(params, inputs)` calls `model(**inputs, use_cache=False)` and returns its `.logits`, `[N, T, V]`. The inputs are `{"input_ids", "attention_mask"}`. A call raises `StructureError` when the inputs are not a mapping or the model does not return a `ModelOutput`. |

### health

``` python
health()
```

Check for `lk.health()` that `transformers` is installed, and `peft` if possible.

#### Returns

| Name | Type | Description |
|----|----|----|
|  | tuple\[lk.HealthCheck, …\] | One check per package. Each is `ok` with the version when the package is installed. Otherwise it is `error` for `transformers`, which is required, and `warning` for `peft`, which is optional. |

### laplace_lora

``` python
laplace_lora(
    model,
    data,
    *,
    task=CausalLM(),
    n_data=None,
    hessian_approx=None,
    prior=lk.priors.Isotropic(),
    hyper_tuner=lk.MarginalLikelihood(),
    generator=None,
)
```

Fit a Laplace approximation over the trainable parameters of a Hugging Face model.

This is Laplace-LoRA (Yang et al., 2024, https://arxiv.org/abs/2308.13111) on a causal LM or a sequence classifier, where the trainable parameters are the LoRA adapters. It runs `lk.laplace` with `subset=lk.subsets.trainable`.

With `task=CausalLM()`, it fits `causal_lm(model)` with `prepare_causal_lm` and `Categorical(mask_fn=padding_mask)`. The default `hessian_approx` is then one `DiagGGN(fisher="mc")` over all LoRA blocks. It takes one backward pass per batch, at next tokens drawn from the model, so it needs no Jacobian over the vocabulary, no per-example gradients and no `vmap`, and SDPA attention works.

With `task=SequenceClassification()`, it fits `sequence_classification(model)` with `prepare_sequence_classification` and `Categorical()`, and the batches carry `"labels"`, `[N]`. A peft model trains its new head when the head is listed in `modules_to_save` (`["score"]` for GPT-2 and Llama classifiers). The default `hessian_approx` is then one `KFAC()` over all trainable blocks, as in Laplace-LoRA, when three conditions hold: the probe’s module hooks reach each block’s layer, each block holds its layer’s weight, and no tensor is tied. Otherwise it is one `DiagGGN(fisher="mc")`. The per-block default of `lk.laplace` would give each small LoRA block the dense GGN, which is much slower on a large model.

Before the fit, `laplace_lora` reads one batch. It checks that the logits are `[N, K]` with $K \ge 2$ and, for the default `hessian_approx`, runs a forward pass on two of the batch’s examples to find the hooked layers. `data` is therefore iterated once more than by `lk.laplace`.

To load a saved posterior, pass the model the way the fit wrapped it: `lk.load(f, causal_lm(model))` or `lk.load(f, sequence_classification(model))`. `lk.load` checks every weight of the model, and with `modules_to_save`, that includes the head peft keeps as `original_module`. Its forward never uses that head, but `from_pretrained` draws a new random one in every process. So call `torch.manual_seed(...)` with the same seed before `from_pretrained` in the process that saves and in the one that loads.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| model | nn.Module | The model. The fit covers its trainable parameters (`requires_grad`), so load a saved adapter with `PeftModel.from_pretrained(..., is_trainable=True)`. | *required* |
| data | Iterable\[Mapping\[str, Tensor\]\] | Tokenizer batches, iterated once per pass. | *required* |
| task | CausalLM \| SequenceClassification | `CausalLM()` or `SequenceClassification()`. | `CausalLM()` |
| n_data | int \| None | The number of examples, which is the size of the training set when `data` is a subset of it, as in `lk.data.from_loader`. | `None` |
| hessian_approx | lk.core.HessianApprox\[Any\] \| None | As in `lk.laplace`, with the defaults above. | `None` |
| prior | lk.core.Prior | As in `lk.laplace`. | `lk.priors.Isotropic()` |
| hyper_tuner | lk.core.HyperTuner \| None | As in `lk.laplace`. | `lk.MarginalLikelihood()` |
| generator | torch.Generator \| None | As in `lk.laplace`. | `None` |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.LaplacePosterior\[Any, Any\] | The posterior over the trainable parameters, as from `lk.laplace`. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | Before any data is read, when `task` is neither `CausalLM()` nor `SequenceClassification()` or the model has no trainable parameter. Later, when a batch lacks the keys its `prepare_*` function needs or the model’s output is not a `ModelOutput`. With `SequenceClassification()`, also when the output has no logits, the logits of the first batch are not `[N, K]` for its N sequences, or $K < 2$. Otherwise as in `lk.laplace`. |
|  | CapabilityError | As in `lk.laplace`. |
|  | ValueError | The data has no batches, or as in `lk.laplace`. |
|  | TypeError | `data` is a one-shot iterator, or as in `lk.laplace`. |

### last_token

``` python
last_token(f, inputs, /)
```

The logits at each sequence’s last real token, with left or right padding.

Pass it as the `select` of `lk.predict` to predict the next token after each prompt.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| f | Outputs | The logits `[N, T, V]`. | *required* |
| inputs | Inputs | The inputs, a mapping with `attention_mask` `[N, T]`. | *required* |

#### Returns

| Name | Type   | Description          |
|------|--------|----------------------|
|      | Tensor | The logits `[N, V]`. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | `f` is not a tensor, `inputs` is not a mapping, or a row has no real token. The last check is skipped under `vmap`, because `lk.predict` has already run it on the whole batch. |

### padding_mask

``` python
padding_mask(f, inputs, /)
```

Mark the positions that count in a causal LM’s loss, as a `mask_fn` for `lk.Categorical`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| f | Outputs | The logits (unused). | *required* |
| inputs | Inputs | The inputs, a mapping with `attention_mask` `[N, T]`. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | Tensor | A bool tensor `[N, T]`, true at position `t` when tokens `t` and `t + 1` are both real. The last position is always false. |

#### Raises

| Name | Type           | Description                |
|------|----------------|----------------------------|
|      | StructureError | `inputs` is not a mapping. |

### prepare_causal_lm

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

Turn a tokenizer batch into a `Batch` for next-token prediction.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| raw | Mapping\[str, Tensor\] | The tokenizer’s output. Keys other than `input_ids` and `attention_mask` are dropped. | *required* |
| generator | torch.Generator | Unused: nothing is drawn. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.Batch | A `Batch` with the inputs `input_ids` and `attention_mask`, and with `input_ids` shifted left by one as targets. The last column has no next token, so it holds a placeholder 0, which `padding_mask` removes. |

#### Raises

| Name | Type           | Description                                  |
|------|----------------|----------------------------------------------|
|      | StructureError | `raw` lacks `input_ids` or `attention_mask`. |

### prepare_sequence_classification

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

Turn a tokenizer batch with `"labels"` into a `Batch` for sequence classification.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| raw | Mapping\[str, Tensor\] | The tokenizer’s output plus `"labels"` `[N]`. | *required* |
| generator | torch.Generator | Unused: nothing is drawn. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.Batch | A `Batch` with the labels as targets. Every other entry (`input_ids`, `attention_mask`, `token_type_ids`, …) becomes an input that the model receives as a keyword argument. |

#### Raises

| Name | Type           | Description                                            |
|------|----------------|--------------------------------------------------------|
|      | StructureError | `raw` lacks `input_ids`, `attention_mask` or `labels`. |

### sequence_classification

``` python
sequence_classification(model, /)
```

Wrap a Hugging Face sequence classifier as a `ModelFn` that returns the logits.

#### Parameters

| Name  | Type      | Description                                     | Default    |
|-------|-----------|-------------------------------------------------|------------|
| model | nn.Module | The sequence classifier, plain or peft-wrapped. | *required* |

#### Returns

| Name | Type | Description |
|----|----|----|
|  | lk.core.ModelFn | A `ModelFn` whose `forward(params, inputs)` calls `model(**inputs)` and returns its `.logits`, `[N, K]`. The inputs are a tokenizer’s output. A call raises `StructureError` when the inputs are not a mapping, or the output is not a `ModelOutput` with 2-D logits `[N, K]`. |
