laplacekit-transformers 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- laplacekit_transformers-1.0.0/PKG-INFO +12 -0
- laplacekit_transformers-1.0.0/pyproject.toml +27 -0
- laplacekit_transformers-1.0.0/pyproject.toml.orig +24 -0
- laplacekit_transformers-1.0.0/src/laplacekit_transformers/__init__.py +94 -0
- laplacekit_transformers-1.0.0/src/laplacekit_transformers/answers.py +115 -0
- laplacekit_transformers-1.0.0/src/laplacekit_transformers/lora.py +188 -0
- laplacekit_transformers-1.0.0/src/laplacekit_transformers/py.typed +0 -0
- laplacekit_transformers-1.0.0/src/laplacekit_transformers/tasks.py +264 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: laplacekit-transformers
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Hugging Face transformers presets for laplacekit: Laplace-LoRA on causal language models and sequence classifiers
|
|
5
|
+
Author: Agustinus Kristiadi
|
|
6
|
+
Author-email: Agustinus Kristiadi <agustinus@kristia.de>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Requires-Dist: laplacekit>=1.0,<2
|
|
9
|
+
Requires-Dist: transformers>=5.23.0
|
|
10
|
+
Requires-Dist: peft>=0.21.3 ; extra == 'peft'
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Provides-Extra: peft
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "laplacekit-transformers"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Hugging Face transformers presets for laplacekit: Laplace-LoRA on causal language models and sequence classifiers"
|
|
5
|
+
license = "MIT"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"laplacekit>=1.0,<2",
|
|
9
|
+
"transformers>=5.23.0",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
[[project.authors]]
|
|
13
|
+
name = "Agustinus Kristiadi"
|
|
14
|
+
email = "agustinus@kristia.de"
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
peft = ["peft>=0.21.3"]
|
|
18
|
+
|
|
19
|
+
[project.entry-points."laplacekit.plugins"]
|
|
20
|
+
laplacekit_transformers = "laplacekit_transformers:plugin"
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["uv_build>=0.13.0,<0.14"]
|
|
24
|
+
build-backend = "uv_build"
|
|
25
|
+
|
|
26
|
+
[tool.uv.sources.laplacekit]
|
|
27
|
+
workspace = true
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "laplacekit-transformers"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Hugging Face transformers presets for laplacekit: Laplace-LoRA on causal language models and sequence classifiers"
|
|
5
|
+
authors = [{ name = "Agustinus Kristiadi", email = "agustinus@kristia.de" }]
|
|
6
|
+
license = "MIT"
|
|
7
|
+
requires-python = ">=3.11"
|
|
8
|
+
dependencies = [
|
|
9
|
+
"laplacekit>=1.0,<2",
|
|
10
|
+
"transformers>=5.23.0",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
peft = ["peft>=0.21.3"]
|
|
15
|
+
|
|
16
|
+
[project.entry-points."laplacekit.plugins"]
|
|
17
|
+
laplacekit_transformers = "laplacekit_transformers:plugin"
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["uv_build>=0.13.0,<0.14"]
|
|
21
|
+
build-backend = "uv_build"
|
|
22
|
+
|
|
23
|
+
[tool.uv.sources]
|
|
24
|
+
laplacekit = { workspace = true }
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
r"""Laplace-LoRA on Hugging Face `transformers` models: causal LMs and sequence classifiers.
|
|
2
|
+
|
|
3
|
+
`laplace_lora` fits a Laplace approximation over the LoRA adapters of a peft model:
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
task = lk.transformers.SequenceClassification()
|
|
7
|
+
post = lk.transformers.laplace_lora(model, batches, task=task, n_data=len(train))
|
|
8
|
+
probs = lk.predict(post, inputs).probs # linearized over the K class logits
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
For a causal LM, a batch is a tokenizer's output, `{"input_ids", "attention_mask"}`, each
|
|
12
|
+
`[N, T]`. The model predicts token `t + 1` from the tokens up to `t`, so position `t`
|
|
13
|
+
counts when both tokens are real (`padding_mask`). Right padding then changes neither the
|
|
14
|
+
curvature nor the data-fit term. Masked positions still enter the Jacobian, and a
|
|
15
|
+
non-finite activation there leaks through, since `0 * NaN` is NaN. Left padding with eager
|
|
16
|
+
attention in float64 gives such NaNs, so pad on the right for the fit.
|
|
17
|
+
|
|
18
|
+
`transformers` loads models with SDPA attention by default, and the fit works with it.
|
|
19
|
+
The linearized predictive, the default of `lk.predict`, differentiates the model's
|
|
20
|
+
backward pass, which SDPA does not support, so it raises `CapabilityError`. Load the model
|
|
21
|
+
with `attn_implementation="eager"`, or predict with `lk.WeightSamples()`.
|
|
22
|
+
|
|
23
|
+
A causal LM's logits span the vocabulary. To predict among a few answers, such as
|
|
24
|
+
$P(\text{True})$ or a multiple-choice letter, `answer_logits` selects their logits at the
|
|
25
|
+
last real token. A sequence classifier (`SequenceClassification()`) has $K$ logits per
|
|
26
|
+
sequence to begin with.
|
|
27
|
+
|
|
28
|
+
Code reaches this package as `lk.transformers`, which imports it on first use.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from importlib import metadata
|
|
32
|
+
from typing import Literal
|
|
33
|
+
|
|
34
|
+
import laplacekit as lk
|
|
35
|
+
from laplacekit_transformers.answers import Tokenizer, answer_logits
|
|
36
|
+
from laplacekit_transformers.lora import laplace_lora
|
|
37
|
+
from laplacekit_transformers.tasks import (
|
|
38
|
+
CausalLM,
|
|
39
|
+
SequenceClassification,
|
|
40
|
+
causal_lm,
|
|
41
|
+
last_token,
|
|
42
|
+
padding_mask,
|
|
43
|
+
prepare_causal_lm,
|
|
44
|
+
prepare_sequence_classification,
|
|
45
|
+
sequence_classification,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
__all__ = [
|
|
49
|
+
"CausalLM",
|
|
50
|
+
"SequenceClassification",
|
|
51
|
+
"Tokenizer",
|
|
52
|
+
"answer_logits",
|
|
53
|
+
"causal_lm",
|
|
54
|
+
"health",
|
|
55
|
+
"laplace_lora",
|
|
56
|
+
"last_token",
|
|
57
|
+
"padding_mask",
|
|
58
|
+
"prepare_causal_lm",
|
|
59
|
+
"prepare_sequence_classification",
|
|
60
|
+
"sequence_classification",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
_OPTIONAL = {
|
|
65
|
+
"peft": "LoRA adapters for laplace_lora",
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def health() -> tuple[lk.HealthCheck, ...]:
|
|
70
|
+
"""Check for `lk.health()` that `transformers` is installed, and `peft` if possible.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
One check per package. Each is `ok` with the version when the package is
|
|
74
|
+
installed. Otherwise it is `error` for `transformers`, which is required, and
|
|
75
|
+
`warning` for `peft`, which is optional.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
checks = [_installed("transformers", "error", "required")]
|
|
79
|
+
checks += [
|
|
80
|
+
_installed(dist, "warning", f"optional, for {use}") for dist, use in _OPTIONAL.items()
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
return tuple(checks)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _installed(dist: str, missing: Literal["warning", "error"], why: str) -> lk.HealthCheck:
|
|
87
|
+
try:
|
|
88
|
+
return lk.HealthCheck(dist, "ok", metadata.version(dist))
|
|
89
|
+
except metadata.PackageNotFoundError:
|
|
90
|
+
return lk.HealthCheck(dist, missing, f"not installed ({why})")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
plugin = lk.Plugin(supports=">=1.0,<2", health=health)
|
|
94
|
+
"""The record behind the `laplacekit.plugins` entry point."""
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Select a causal LM's logits for a few answers, so the predictive covers only those."""
|
|
2
|
+
|
|
3
|
+
from abc import abstractmethod
|
|
4
|
+
from collections.abc import Callable, Sequence
|
|
5
|
+
from typing import Protocol, runtime_checkable
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
import laplacekit as lk
|
|
10
|
+
from laplacekit.core import (
|
|
11
|
+
Inputs,
|
|
12
|
+
Outputs,
|
|
13
|
+
)
|
|
14
|
+
from laplacekit_transformers.tasks import last_token
|
|
15
|
+
|
|
16
|
+
__all__ = ["Tokenizer", "answer_logits"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@runtime_checkable
|
|
20
|
+
class Tokenizer(Protocol):
|
|
21
|
+
"""A tokenizer for `answer_logits`, which only needs its `encode` method.
|
|
22
|
+
|
|
23
|
+
Every Hugging Face tokenizer has it, and so can any other object.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def encode(self, text: str, /, *, add_special_tokens: bool = True) -> list[int]:
|
|
28
|
+
"""Encode `text` as token ids.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
text: The text.
|
|
32
|
+
add_special_tokens: Whether to add the tokenizer's special tokens.
|
|
33
|
+
`answer_logits` passes `False`.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
The token ids of `text`.
|
|
37
|
+
"""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def answer_logits(
|
|
42
|
+
tokenizer: Tokenizer, answers: Sequence[str], /
|
|
43
|
+
) -> Callable[[Outputs, Inputs], Outputs]:
|
|
44
|
+
"""Build a `select` for `lk.predict` that keeps the logits of `answers` at the last real token.
|
|
45
|
+
|
|
46
|
+
With it, the linearized predictive covers only those logits instead of the whole
|
|
47
|
+
vocabulary:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
select = lk.transformers.answer_logits(tokenizer, [" True", " False"])
|
|
51
|
+
probs = lk.predict(post, inputs, select=select).probs # [N, 2]
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
tokenizer: A `Tokenizer`.
|
|
56
|
+
answers: The answers, as a sequence of strings. Each is encoded as given, without
|
|
57
|
+
special tokens, and must be exactly one token. A leading space is part of the
|
|
58
|
+
answer, as in `" True"` for most BPE tokenizers.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
A function that maps causal LM logits `[N, T, V]` to `[N, len(answers)]`, in the
|
|
62
|
+
order of `answers`, through `last_token`. Errors from `last_token` pass through.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
StructureError: `tokenizer` has no `encode` method, `answers` is a single string
|
|
66
|
+
or empty, an answer encodes to zero or several tokens, or two answers encode
|
|
67
|
+
to the same token. The messages of the last two name the tokens. All of these
|
|
68
|
+
checks run before any call of the model.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
if not isinstance(tokenizer, Tokenizer):
|
|
72
|
+
raise lk.StructureError(
|
|
73
|
+
f"answer_logits needs a tokenizer with encode(text, add_special_tokens=False), "
|
|
74
|
+
f"got {type(tokenizer).__name__}"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
if isinstance(answers, str):
|
|
78
|
+
raise lk.StructureError(
|
|
79
|
+
f"answer_logits needs a sequence of answers, got the string {answers!r}; pass "
|
|
80
|
+
f"[{answers!r}] for one answer"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
if not answers:
|
|
84
|
+
raise lk.StructureError("answer_logits needs at least one answer")
|
|
85
|
+
|
|
86
|
+
ids: list[int] = []
|
|
87
|
+
seen: dict[int, str] = {}
|
|
88
|
+
|
|
89
|
+
for answer in answers:
|
|
90
|
+
tokens = list(tokenizer.encode(answer, add_special_tokens=False))
|
|
91
|
+
|
|
92
|
+
if len(tokens) != 1:
|
|
93
|
+
raise lk.StructureError(
|
|
94
|
+
f"answer_logits needs answers of one token each; {answer!r} encodes to "
|
|
95
|
+
f"{len(tokens)} tokens {tokens}"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
(token,) = tokens
|
|
99
|
+
|
|
100
|
+
if token in seen:
|
|
101
|
+
raise lk.StructureError(
|
|
102
|
+
f"answer_logits needs distinct answers; {seen[token]!r} and {answer!r} both "
|
|
103
|
+
f"encode to token {token}"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
seen[token] = answer
|
|
107
|
+
ids.append(token)
|
|
108
|
+
|
|
109
|
+
def select(f: Outputs, inputs: Inputs) -> Outputs:
|
|
110
|
+
last = last_token(f, inputs)
|
|
111
|
+
index = torch.tensor(ids, device=last.device)
|
|
112
|
+
|
|
113
|
+
return last.index_select(-1, index)
|
|
114
|
+
|
|
115
|
+
return select
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Laplace-LoRA (Yang et al., 2024) on a causal LM or a sequence classifier.
|
|
2
|
+
|
|
3
|
+
`laplace_lora` runs `lk.laplace` over the trainable parameters, which are the LoRA
|
|
4
|
+
adapters and any head in `modules_to_save`. For a causal LM, the default curvature is one
|
|
5
|
+
`DiagGGN(fisher="mc")`. For a sequence classifier, it is one `KFAC()` when the probe's
|
|
6
|
+
module hooks reach every trainable block, and one `DiagGGN(fisher="mc")` otherwise.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Iterable, Mapping
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
from torch import Tensor, nn
|
|
14
|
+
|
|
15
|
+
import laplacekit as lk
|
|
16
|
+
from laplacekit_transformers.tasks import (
|
|
17
|
+
CausalLM,
|
|
18
|
+
SequenceClassification,
|
|
19
|
+
causal_lm,
|
|
20
|
+
padding_mask,
|
|
21
|
+
prepare_causal_lm,
|
|
22
|
+
prepare_sequence_classification,
|
|
23
|
+
sequence_classification,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = ["laplace_lora"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def laplace_lora(
|
|
30
|
+
model: nn.Module,
|
|
31
|
+
data: Iterable[Mapping[str, Tensor]],
|
|
32
|
+
*,
|
|
33
|
+
task: CausalLM | SequenceClassification = CausalLM(),
|
|
34
|
+
n_data: int | None = None,
|
|
35
|
+
hessian_approx: lk.core.HessianApprox[Any] | None = None,
|
|
36
|
+
prior: lk.core.Prior = lk.priors.Isotropic(), # noqa: B008 # immutable
|
|
37
|
+
hyper_tuner: lk.core.HyperTuner | None = lk.MarginalLikelihood(), # noqa: B008 # immutable
|
|
38
|
+
generator: torch.Generator | None = None,
|
|
39
|
+
) -> lk.LaplacePosterior[Any, Any]:
|
|
40
|
+
r"""Fit a Laplace approximation over the trainable parameters of a Hugging Face model.
|
|
41
|
+
|
|
42
|
+
This is Laplace-LoRA (Yang et al., 2024, https://arxiv.org/abs/2308.13111) on a causal
|
|
43
|
+
LM or a sequence classifier, where the trainable parameters are the LoRA adapters. It
|
|
44
|
+
runs `lk.laplace` with `subset=lk.subsets.trainable`.
|
|
45
|
+
|
|
46
|
+
With `task=CausalLM()`, it fits `causal_lm(model)` with `prepare_causal_lm` and
|
|
47
|
+
`Categorical(mask_fn=padding_mask)`. The default `hessian_approx` is then one
|
|
48
|
+
`DiagGGN(fisher="mc")` over all LoRA blocks. It takes one backward pass per batch, at
|
|
49
|
+
next tokens drawn from the model, so it needs no Jacobian over the vocabulary, no
|
|
50
|
+
per-example gradients and no `vmap`, and SDPA attention works.
|
|
51
|
+
|
|
52
|
+
With `task=SequenceClassification()`, it fits `sequence_classification(model)` with
|
|
53
|
+
`prepare_sequence_classification` and `Categorical()`, and the batches carry
|
|
54
|
+
`"labels"`, `[N]`. A peft model trains its new head when the head is listed in
|
|
55
|
+
`modules_to_save` (`["score"]` for GPT-2 and Llama classifiers). The default `hessian_approx`
|
|
56
|
+
is then one `KFAC()` over all trainable blocks, as in Laplace-LoRA, when three
|
|
57
|
+
conditions hold: the probe's module hooks reach each block's layer, each block holds
|
|
58
|
+
its layer's weight, and no tensor is tied. Otherwise it is one `DiagGGN(fisher="mc")`.
|
|
59
|
+
The per-block default of `lk.laplace` would give each small LoRA block the dense GGN,
|
|
60
|
+
which is much slower on a large model.
|
|
61
|
+
|
|
62
|
+
Before the fit, `laplace_lora` reads one batch. It checks that the logits are `[N, K]`
|
|
63
|
+
with $K \ge 2$ and, for the default `hessian_approx`, runs a forward pass on two of the
|
|
64
|
+
batch's examples to find the hooked layers. `data` is therefore iterated once more
|
|
65
|
+
than by `lk.laplace`.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
model: The model. The fit covers its trainable parameters (`requires_grad`), so
|
|
69
|
+
load a saved adapter with `PeftModel.from_pretrained(..., is_trainable=True)`.
|
|
70
|
+
data: Tokenizer batches, iterated once per pass.
|
|
71
|
+
task: `CausalLM()` or `SequenceClassification()`.
|
|
72
|
+
n_data: The number of examples, which is the size of the training set when `data`
|
|
73
|
+
is a subset of it, as in `lk.data.from_loader`.
|
|
74
|
+
hessian_approx: As in `lk.laplace`, with the defaults above.
|
|
75
|
+
prior: As in `lk.laplace`.
|
|
76
|
+
hyper_tuner: As in `lk.laplace`.
|
|
77
|
+
generator: As in `lk.laplace`.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
The posterior over the trainable parameters, as from `lk.laplace`.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
StructureError: Before any data is read, when `task` is neither `CausalLM()` nor
|
|
84
|
+
`SequenceClassification()` or the model has no trainable parameter. Later,
|
|
85
|
+
when a batch lacks the keys its `prepare_*` function needs or the model's
|
|
86
|
+
output is not a `ModelOutput`. With `SequenceClassification()`, also when the
|
|
87
|
+
output has no logits, the logits of the first batch are not `[N, K]` for its
|
|
88
|
+
N sequences, or $K < 2$. Otherwise as in `lk.laplace`.
|
|
89
|
+
CapabilityError: As in `lk.laplace`.
|
|
90
|
+
ValueError: The data has no batches, or as in `lk.laplace`.
|
|
91
|
+
TypeError: `data` is a one-shot iterator, or as in `lk.laplace`.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
if isinstance(task, CausalLM):
|
|
95
|
+
fn = causal_lm(model)
|
|
96
|
+
elif isinstance(task, SequenceClassification):
|
|
97
|
+
fn = sequence_classification(model)
|
|
98
|
+
else:
|
|
99
|
+
raise lk.StructureError(
|
|
100
|
+
f"laplace_lora needs task=CausalLM() or SequenceClassification(), got "
|
|
101
|
+
f"{type(task).__name__}"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# `trainable` reads only the module, so it needs no probe.
|
|
105
|
+
if not lk.subsets.trainable(fn, lk.core.Capabilities()):
|
|
106
|
+
raise lk.StructureError(
|
|
107
|
+
"laplace_lora found no trainable parameters; add LoRA adapters (peft), load a "
|
|
108
|
+
"saved adapter with PeftModel.from_pretrained(..., is_trainable=True), or set "
|
|
109
|
+
"requires_grad on the parameters to fit"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
if isinstance(task, CausalLM):
|
|
113
|
+
src = lk.data.from_loader(data, prepare=prepare_causal_lm, n_data=n_data)
|
|
114
|
+
likelihood = lk.Categorical(mask_fn=padding_mask)
|
|
115
|
+
|
|
116
|
+
# One method over all blocks: one backward per batch, not one per block.
|
|
117
|
+
chosen = lk.DiagGGN(fisher="mc") if hessian_approx is None else hessian_approx
|
|
118
|
+
else:
|
|
119
|
+
src = lk.data.from_loader(data, prepare=prepare_sequence_classification, n_data=n_data)
|
|
120
|
+
likelihood = lk.Categorical()
|
|
121
|
+
first = _check_classifier(fn, src)
|
|
122
|
+
chosen = (
|
|
123
|
+
_classifier_default(fn, likelihood, first) if hessian_approx is None else hessian_approx
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
return lk.laplace(
|
|
127
|
+
fn,
|
|
128
|
+
src,
|
|
129
|
+
likelihood,
|
|
130
|
+
subset=lk.subsets.trainable,
|
|
131
|
+
hessian_approx=chosen,
|
|
132
|
+
prior=prior,
|
|
133
|
+
hyper_tuner=hyper_tuner,
|
|
134
|
+
generator=generator,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _check_classifier(fn: lk.core.ModelFn, src: lk.data.Data) -> lk.Batch:
|
|
139
|
+
"""Run one batch through `fn` before the fit and check for logits `[N, K]`.
|
|
140
|
+
|
|
141
|
+
Returns the batch. Its `prepare` draws nothing, so a fixed generator reads it.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
first = next(iter(src(torch.Generator())), None)
|
|
145
|
+
|
|
146
|
+
if first is None:
|
|
147
|
+
raise ValueError("laplace_lora: the data yielded no batches")
|
|
148
|
+
|
|
149
|
+
with torch.no_grad():
|
|
150
|
+
logits = cast(Tensor, fn({}, first.inputs))
|
|
151
|
+
|
|
152
|
+
if logits.ndim != 2 or logits.shape[0] != first.size:
|
|
153
|
+
raise lk.StructureError(
|
|
154
|
+
f"sequence_classification needs logits [N, K] for N = {first.size} sequences, got "
|
|
155
|
+
f"{tuple(logits.shape)}"
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
# One class has no curvature: the posterior would be the prior.
|
|
159
|
+
if logits.shape[1] < 2:
|
|
160
|
+
raise lk.StructureError(
|
|
161
|
+
f"sequence_classification needs K >= 2 classes, got K = {logits.shape[1]}; set "
|
|
162
|
+
f"num_labels >= 2 in the model config"
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
return first
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _classifier_default(
|
|
169
|
+
fn: lk.core.ModelFn, likelihood: lk.Categorical, first: lk.Batch
|
|
170
|
+
) -> lk.core.HessianApprox[Any]:
|
|
171
|
+
"""`KFAC()` if the capabilities allow it on every trainable block, else `DiagGGN(fisher="mc")`.
|
|
172
|
+
|
|
173
|
+
The probe's order pass, one forward pass on two examples without transforms, records
|
|
174
|
+
which layers the module hooks reach. KFAC needs those hooks on each block's layer,
|
|
175
|
+
each block to hold its layer's weight, and no tied tensor.
|
|
176
|
+
"""
|
|
177
|
+
|
|
178
|
+
caps = lk.core.probe(fn, likelihood, first, params={})
|
|
179
|
+
params = lk.subsets.trainable(fn, caps)
|
|
180
|
+
blocks = lk.core.Layout.by_module(params).blocks
|
|
181
|
+
kfac = lk.KFAC()
|
|
182
|
+
req = kfac.requires
|
|
183
|
+
|
|
184
|
+
hooked = all(b in caps.hooked and issubclass(caps.hooked_types[b], req.hooks) for b in blocks)
|
|
185
|
+
weights = all(f"{b}.weight" in names for b, names in blocks.items())
|
|
186
|
+
fits = req.satisfies(caps) and hooked and weights and lk.KFAC.supports(likelihood, caps, params)
|
|
187
|
+
|
|
188
|
+
return kfac if fits else lk.DiagGGN(fisher="mc")
|
|
File without changes
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""Causal LMs and sequence classifiers as `ModelFn`s, with their batches and masks.
|
|
2
|
+
|
|
3
|
+
`CausalLM` and `SequenceClassification` name the two tasks. `causal_lm` and
|
|
4
|
+
`sequence_classification` wrap a model so that it returns its logits, and the `prepare_*`
|
|
5
|
+
functions turn tokenizer batches into a `Batch`. `padding_mask` removes from a causal
|
|
6
|
+
LM's loss the positions where the token or the next token is padding. `last_token`
|
|
7
|
+
selects the logits at each sequence's last real token.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, cast
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
from torch import Tensor, nn
|
|
16
|
+
from transformers.utils import ModelOutput
|
|
17
|
+
|
|
18
|
+
import laplacekit as lk
|
|
19
|
+
from laplacekit.core import (
|
|
20
|
+
Inputs,
|
|
21
|
+
Outputs,
|
|
22
|
+
Params,
|
|
23
|
+
is_transformed,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"CausalLM",
|
|
28
|
+
"SequenceClassification",
|
|
29
|
+
"causal_lm",
|
|
30
|
+
"last_token",
|
|
31
|
+
"padding_mask",
|
|
32
|
+
"prepare_causal_lm",
|
|
33
|
+
"prepare_sequence_classification",
|
|
34
|
+
"sequence_classification",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_INPUTS = ("input_ids", "attention_mask")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class CausalLM:
|
|
43
|
+
"""The task of `laplace_lora` for a causal LM (`AutoModelForCausalLM`).
|
|
44
|
+
|
|
45
|
+
The model predicts each next token, with logits `[N, T, V]` over the vocabulary.
|
|
46
|
+
`laplace_lora` then uses `causal_lm`, `prepare_causal_lm` and `padding_mask`.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class SequenceClassification:
|
|
52
|
+
"""The task of `laplace_lora` for a sequence classifier (`AutoModelForSequenceClassification`).
|
|
53
|
+
|
|
54
|
+
The model predicts one of $K$ labels per sequence, with logits `[N, K]`. The batches
|
|
55
|
+
carry `"labels"`, and `laplace_lora` uses `sequence_classification` and
|
|
56
|
+
`prepare_sequence_classification`.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def causal_lm(model: nn.Module, /) -> lk.core.ModelFn:
|
|
61
|
+
"""Wrap a Hugging Face causal LM as a `ModelFn` that returns the logits.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
model: The causal LM, plain or peft-wrapped.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
A `ModelFn` whose `forward(params, inputs)` calls
|
|
68
|
+
`model(**inputs, use_cache=False)` and returns its `.logits`, `[N, T, V]`. The
|
|
69
|
+
inputs are `{"input_ids", "attention_mask"}`. A call raises `StructureError` when
|
|
70
|
+
the inputs are not a mapping or the model does not return a `ModelOutput`.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
call = lk.core.ModelFn.from_module(model)
|
|
74
|
+
|
|
75
|
+
def forward(params: Params, inputs: Inputs) -> Outputs:
|
|
76
|
+
# from_module passes a mapping's entries as keyword arguments, so the flag rides
|
|
77
|
+
# along with the tensors; this inner call is never vmapped.
|
|
78
|
+
kwargs = cast(Inputs, {**_mapping(inputs, "causal_lm"), "use_cache": False})
|
|
79
|
+
out = call(params, kwargs)
|
|
80
|
+
|
|
81
|
+
if not isinstance(out, ModelOutput):
|
|
82
|
+
raise lk.StructureError(
|
|
83
|
+
f"causal_lm needs a model that returns a transformers ModelOutput, got "
|
|
84
|
+
f"{type(out).__name__}"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
return out["logits"]
|
|
88
|
+
|
|
89
|
+
return lk.core.ModelFn(forward, model)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def prepare_causal_lm(raw: Mapping[str, Tensor], generator: torch.Generator, /) -> lk.Batch:
|
|
93
|
+
"""Turn a tokenizer batch into a `Batch` for next-token prediction.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
raw: The tokenizer's output. Keys other than `input_ids` and `attention_mask` are
|
|
97
|
+
dropped.
|
|
98
|
+
generator: Unused: nothing is drawn.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
A `Batch` with the inputs `input_ids` and `attention_mask`, and with `input_ids`
|
|
102
|
+
shifted left by one as targets. The last column has no next token, so it holds a
|
|
103
|
+
placeholder 0, which `padding_mask` removes.
|
|
104
|
+
|
|
105
|
+
Raises:
|
|
106
|
+
StructureError: `raw` lacks `input_ids` or `attention_mask`.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
del generator
|
|
110
|
+
missing = [k for k in _INPUTS if k not in raw]
|
|
111
|
+
|
|
112
|
+
if missing:
|
|
113
|
+
raise lk.StructureError(f"prepare_causal_lm needs {', '.join(missing)} in the batch")
|
|
114
|
+
|
|
115
|
+
ids = raw["input_ids"]
|
|
116
|
+
targets = torch.cat([ids[:, 1:], torch.zeros_like(ids[:, :1])], dim=1)
|
|
117
|
+
inputs = {"input_ids": ids, "attention_mask": raw["attention_mask"]}
|
|
118
|
+
|
|
119
|
+
return lk.Batch(inputs, targets)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def sequence_classification(model: nn.Module, /) -> lk.core.ModelFn:
|
|
123
|
+
"""Wrap a Hugging Face sequence classifier as a `ModelFn` that returns the logits.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
model: The sequence classifier, plain or peft-wrapped.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
A `ModelFn` whose `forward(params, inputs)` calls `model(**inputs)` and returns
|
|
130
|
+
its `.logits`, `[N, K]`. The inputs are a tokenizer's output. A call raises
|
|
131
|
+
`StructureError` when the inputs are not a mapping, or the output is not a
|
|
132
|
+
`ModelOutput` with 2-D logits `[N, K]`.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
call = lk.core.ModelFn.from_module(model)
|
|
136
|
+
|
|
137
|
+
def forward(params: Params, inputs: Inputs) -> Outputs:
|
|
138
|
+
out = call(params, _mapping(inputs, "sequence_classification"))
|
|
139
|
+
|
|
140
|
+
if not isinstance(out, ModelOutput) or "logits" not in out:
|
|
141
|
+
raise lk.StructureError(
|
|
142
|
+
f"sequence_classification needs a model that returns a transformers ModelOutput "
|
|
143
|
+
f"with logits, got {type(out).__name__}"
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
logits = out["logits"]
|
|
147
|
+
|
|
148
|
+
if not isinstance(logits, Tensor) or logits.ndim != 2:
|
|
149
|
+
shape = tuple(logits.shape) if isinstance(logits, Tensor) else type(logits).__name__
|
|
150
|
+
|
|
151
|
+
raise lk.StructureError(
|
|
152
|
+
f"sequence_classification needs logits [N, K], got {shape}; a causal LM goes "
|
|
153
|
+
f"with CausalLM() and answer_logits"
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
return logits
|
|
157
|
+
|
|
158
|
+
return lk.core.ModelFn(forward, model)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def prepare_sequence_classification(
|
|
162
|
+
raw: Mapping[str, Tensor], generator: torch.Generator, /
|
|
163
|
+
) -> lk.Batch:
|
|
164
|
+
"""Turn a tokenizer batch with `"labels"` into a `Batch` for sequence classification.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
raw: The tokenizer's output plus `"labels"` `[N]`.
|
|
168
|
+
generator: Unused: nothing is drawn.
|
|
169
|
+
|
|
170
|
+
Returns:
|
|
171
|
+
A `Batch` with the labels as targets. Every other entry (`input_ids`,
|
|
172
|
+
`attention_mask`, `token_type_ids`, ...) becomes an input that the model receives
|
|
173
|
+
as a keyword argument.
|
|
174
|
+
|
|
175
|
+
Raises:
|
|
176
|
+
StructureError: `raw` lacks `input_ids`, `attention_mask` or `labels`.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
del generator
|
|
180
|
+
missing = [k for k in (*_INPUTS, "labels") if k not in raw]
|
|
181
|
+
|
|
182
|
+
if missing:
|
|
183
|
+
raise lk.StructureError(
|
|
184
|
+
f"prepare_sequence_classification needs {', '.join(missing)} in the batch"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
inputs = {k: v for k, v in raw.items() if k != "labels"}
|
|
188
|
+
|
|
189
|
+
return lk.Batch(inputs, raw["labels"])
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@lk.core.serializable
|
|
193
|
+
def padding_mask(f: Outputs, inputs: Inputs, /) -> Tensor:
|
|
194
|
+
"""Mark the positions that count in a causal LM's loss, as a `mask_fn` for `lk.Categorical`.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
f: The logits (unused).
|
|
198
|
+
inputs: The inputs, a mapping with `attention_mask` `[N, T]`.
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
A bool tensor `[N, T]`, true at position `t` when tokens `t` and `t + 1` are both
|
|
202
|
+
real. The last position is always false.
|
|
203
|
+
|
|
204
|
+
Raises:
|
|
205
|
+
StructureError: `inputs` is not a mapping.
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
del f
|
|
209
|
+
real = _mapping(inputs, "padding_mask")["attention_mask"].bool()
|
|
210
|
+
both = real[:, :-1] & real[:, 1:]
|
|
211
|
+
|
|
212
|
+
return torch.cat([both, torch.zeros_like(real[:, :1])], dim=1)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def last_token(f: Outputs, inputs: Inputs, /) -> Tensor:
|
|
216
|
+
"""The logits at each sequence's last real token, with left or right padding.
|
|
217
|
+
|
|
218
|
+
Pass it as the `select` of `lk.predict` to predict the next token after each prompt.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
f: The logits `[N, T, V]`.
|
|
222
|
+
inputs: The inputs, a mapping with `attention_mask` `[N, T]`.
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
The logits `[N, V]`.
|
|
226
|
+
|
|
227
|
+
Raises:
|
|
228
|
+
StructureError: `f` is not a tensor, `inputs` is not a mapping, or a row has no
|
|
229
|
+
real token. The last check is skipped under `vmap`, because `lk.predict` has
|
|
230
|
+
already run it on the whole batch.
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
if not isinstance(f, Tensor):
|
|
234
|
+
raise lk.StructureError(f"last_token needs logits [N, T, V], got {type(f).__name__}")
|
|
235
|
+
|
|
236
|
+
real = _mapping(inputs, "last_token")["attention_mask"].bool()
|
|
237
|
+
|
|
238
|
+
# Under vmap the mask can't be read. `lk.predict` calls `select` on the whole batch
|
|
239
|
+
# first, so the check has run by then.
|
|
240
|
+
if not is_transformed(real):
|
|
241
|
+
empty = (~real.any(dim=1)).nonzero().flatten().tolist()
|
|
242
|
+
|
|
243
|
+
if empty:
|
|
244
|
+
rows = ", ".join(str(i) for i in empty)
|
|
245
|
+
noun = "row" if len(empty) == 1 else "rows"
|
|
246
|
+
|
|
247
|
+
raise lk.StructureError(
|
|
248
|
+
f"last_token needs a real token in every row; none in {noun} {rows}"
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
positions = torch.arange(real.shape[1], device=real.device)
|
|
252
|
+
last = torch.where(real, positions, 0).amax(dim=1)
|
|
253
|
+
index = last[:, None, None].expand(-1, 1, f.shape[-1])
|
|
254
|
+
|
|
255
|
+
return f.gather(1, index).squeeze(1)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _mapping(inputs: Inputs, what: str) -> Mapping[str, Any]:
|
|
259
|
+
if not isinstance(inputs, Mapping):
|
|
260
|
+
raise lk.StructureError(
|
|
261
|
+
f"{what} needs inputs {{'input_ids', 'attention_mask'}}, got {type(inputs).__name__}"
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
return inputs
|