pyhighlights 0.2.0__tar.gz → 0.4.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.
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/PKG-INFO +2 -2
- pyhighlights-0.4.0/pyhighlights/__init__.py +1 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/analyzers.py +38 -8
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/data.py +42 -19
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/faithfulness.py +1 -8
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/base.py +19 -6
- pyhighlights-0.4.0/pyhighlights/components/models/data.py +103 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/base.py +111 -8
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/genspp.py +1 -11
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/grat.py +3 -5
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/mcd.py +14 -5
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/tasks.py +17 -14
- pyhighlights-0.4.0/pyhighlights/configurations/backbones.py +57 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/base.py +7 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/benchmarks.py +40 -56
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/datasets.py +33 -53
- pyhighlights-0.4.0/pyhighlights/configurations/fr.py +27 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/genspp.py +52 -81
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/grat.py +26 -41
- pyhighlights-0.4.0/pyhighlights/configurations/losses.py +175 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/mcd.py +13 -21
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/metrics.py +98 -159
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/mgr.py +13 -17
- pyhighlights-0.4.0/pyhighlights/configurations/optimizers.py +14 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/preprocessors.py +39 -61
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/tasks.py +25 -34
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights.egg-info/PKG-INFO +2 -2
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights.egg-info/requires.txt +1 -1
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights_benchmarks/genspp2025/configurations/hatexplain.py +152 -237
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights_benchmarks/genspp2025/configurations/toy.py +112 -177
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyproject.toml +1 -1
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_benchmarks.py +43 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_data.py +97 -3
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_losses.py +19 -0
- pyhighlights-0.2.0/pyhighlights/__init__.py +0 -1
- pyhighlights-0.2.0/pyhighlights/components/models/data.py +0 -62
- pyhighlights-0.2.0/pyhighlights/configurations/backbones.py +0 -73
- pyhighlights-0.2.0/pyhighlights/configurations/fr.py +0 -36
- pyhighlights-0.2.0/pyhighlights/configurations/losses.py +0 -244
- pyhighlights-0.2.0/pyhighlights/configurations/optimizers.py +0 -21
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/LICENSE +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/README.md +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/__init__.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/benchmarks.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/leakage.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/loaders.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/__init__.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/__init__.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/data.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/fr.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/implementations.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/models/spp/mgr.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/components/preprocessors.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/__init__.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/configurations/keys.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/utility/__init__.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/utility/embeddings.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/utility/io.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/utility/losses.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/utility/manifest.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/utility/metrics.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights/utility/statistics.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights.egg-info/SOURCES.txt +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights.egg-info/dependency_links.txt +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights.egg-info/top_level.txt +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights_benchmarks/__init__.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights_benchmarks/genspp2025/__init__.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights_benchmarks/genspp2025/configurations/__init__.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights_benchmarks/genspp2025/configurations/common.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights_benchmarks/genspp2025/configurations/keys.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/pyhighlights_benchmarks/genspp2025/corpora.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/setup.cfg +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_configurations.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_documentation.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_embeddings.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_faithfulness.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_fr.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_genspp.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_genspp2025.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_grat.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_imports.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_io.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_leakage.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_loaders.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_manifest.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_metrics.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_preprocessors.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_statistics.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_tasks.py +0 -0
- {pyhighlights-0.2.0 → pyhighlights-0.4.0}/tests/test_transformer_configurations.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyhighlights
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: A simple library implementing Select-Then-Predict (SPP) models.
|
|
5
5
|
Author-email: Federico Ruggeri <federico.ruggeri6@unibo.it>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -20,7 +20,7 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
|
20
20
|
Requires-Python: >=3.10
|
|
21
21
|
Description-Content-Type: text/markdown
|
|
22
22
|
License-File: LICENSE
|
|
23
|
-
Requires-Dist: cinnamon-core<3,>=2.0
|
|
23
|
+
Requires-Dist: cinnamon-core<3,>=2.1.0
|
|
24
24
|
Requires-Dist: pandas>=2.0.0
|
|
25
25
|
Requires-Dist: lightning>=2.0.0
|
|
26
26
|
Requires-Dist: torch>=2.0.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.4.0"
|
|
@@ -210,6 +210,8 @@ class HighlightPositionAnalyzer(Analyzer):
|
|
|
210
210
|
model keying on the first tokens of every document scores like a model that
|
|
211
211
|
found the rationale, until you look at where it selected.
|
|
212
212
|
|
|
213
|
+
Positions are word positions, since that is what a selection is made over.
|
|
214
|
+
|
|
213
215
|
Positions are reported as a share of the document, so documents of
|
|
214
216
|
different lengths are comparable. ``absolute`` reports word positions
|
|
215
217
|
instead, which is the other question: a model keying on the first three
|
|
@@ -283,9 +285,12 @@ class PredictionAnalyzer(Analyzer):
|
|
|
283
285
|
the loader and the preprocessor that produced it, and those keys are what
|
|
284
286
|
get built here: a corpus loaded from anywhere else is a different corpus.
|
|
285
287
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
288
|
+
A selection is made over words, so it is already in the unit a person
|
|
289
|
+
reads: a row lists word positions and the words at them. A run that
|
|
290
|
+
selected over subtokens instead is folded back through the ``word_ids``
|
|
291
|
+
the batch carries, and a word counts as selected when any of its subtokens
|
|
292
|
+
was -- which is why that setting cannot say what the predictor actually
|
|
293
|
+
read, and why it is not the default.
|
|
289
294
|
|
|
290
295
|
A task builds its loader and its preprocessor from their keys alone, with
|
|
291
296
|
no overrides, so rebuilding those keys rebuilds exactly the corpus the run
|
|
@@ -349,6 +354,10 @@ class PredictionAnalyzer(Analyzer):
|
|
|
349
354
|
predicted = reported_head(predicted)
|
|
350
355
|
predicted = predicted.argmax(-1)
|
|
351
356
|
|
|
357
|
+
# A selection over words is already word-indexed; one over
|
|
358
|
+
# subtokens is as wide as the encoding and has to be folded.
|
|
359
|
+
over_subtokens = masks.shape[1] == word_ids.shape[1]
|
|
360
|
+
|
|
352
361
|
for index, sample_id in enumerate(batch["sample_ids"]):
|
|
353
362
|
example = examples.get(int(sample_id))
|
|
354
363
|
if example is None:
|
|
@@ -357,7 +366,12 @@ class PredictionAnalyzer(Analyzer):
|
|
|
357
366
|
# split is more use than refusing all of it.
|
|
358
367
|
continue
|
|
359
368
|
tokens = list(example.tokens)
|
|
360
|
-
|
|
369
|
+
kept = valid[index] & (masks[index] > 0)
|
|
370
|
+
words = (
|
|
371
|
+
word_ids[index][kept]
|
|
372
|
+
if over_subtokens
|
|
373
|
+
else np.flatnonzero(kept)
|
|
374
|
+
)
|
|
361
375
|
if words.size and words.max() >= len(tokens):
|
|
362
376
|
# The corpus places this sample's words differently
|
|
363
377
|
# than the run did. Folding the selection against it
|
|
@@ -470,9 +484,18 @@ class LabelStudioExporter(PredictionAnalyzer):
|
|
|
470
484
|
per run, pre-annotated with what the model selected, so the reading is a
|
|
471
485
|
review rather than a fresh annotation.
|
|
472
486
|
|
|
473
|
-
``only`` narrows the export to samples of one
|
|
474
|
-
|
|
475
|
-
|
|
487
|
+
``only`` narrows the export to samples of one class, which is what a corpus
|
|
488
|
+
annotated for a rare one needs: the negatives are 97% of it and the
|
|
489
|
+
interesting highlights are all on the positives.
|
|
490
|
+
|
|
491
|
+
``column`` decides *which* class that is, and the two answers are different
|
|
492
|
+
questions. ``"label"`` selects the samples that carry the class, and asks
|
|
493
|
+
whether the model found the right words in them. ``"predicted"`` selects
|
|
494
|
+
the samples the model *called* that class, and asks whether the words it
|
|
495
|
+
kept justify the call -- which is the only one of the two available on a
|
|
496
|
+
corpus with no annotation to select by, and the one that surfaces a
|
|
497
|
+
confident mistake. Any column
|
|
498
|
+
:class:`PredictionAnalyzer` reports may be named.
|
|
476
499
|
|
|
477
500
|
One file per seed, beside the predictions it came from. A run's seeds are
|
|
478
501
|
separate predictions of the same samples, so merging them would show the
|
|
@@ -488,19 +511,26 @@ class LabelStudioExporter(PredictionAnalyzer):
|
|
|
488
511
|
model_version: str = "pyhighlights",
|
|
489
512
|
labels: Sequence[str] = ("highlight",),
|
|
490
513
|
only: int | None = None,
|
|
514
|
+
column: str = "label",
|
|
491
515
|
stem: str = "label-studio",
|
|
492
516
|
):
|
|
493
517
|
super().__init__(directory=directory, pattern=pattern, split=split)
|
|
494
518
|
self.model_version = model_version
|
|
495
519
|
self.labels = list(labels)
|
|
496
520
|
self.only = only
|
|
521
|
+
self.column = column
|
|
497
522
|
self.stem = stem
|
|
498
523
|
|
|
499
524
|
def selected(self, frame: pd.DataFrame) -> pd.DataFrame:
|
|
500
525
|
"""The rows this export is about."""
|
|
501
526
|
if self.only is None or frame.empty:
|
|
502
527
|
return frame
|
|
503
|
-
|
|
528
|
+
if self.column not in frame.columns:
|
|
529
|
+
raise KeyError(
|
|
530
|
+
f"cannot narrow the export by {self.column!r}: a prediction row "
|
|
531
|
+
f"carries {sorted(frame.columns)}"
|
|
532
|
+
)
|
|
533
|
+
return frame[frame[self.column] == self.only].reset_index(drop=True)
|
|
504
534
|
|
|
505
535
|
def analyze(self) -> pd.DataFrame:
|
|
506
536
|
return self.selected(super().analyze())
|
|
@@ -100,7 +100,22 @@ class VocabularyTokenizer:
|
|
|
100
100
|
class HuggingFaceTokenizer:
|
|
101
101
|
"""Fast-tokenizer adapter preserving source-token alignment."""
|
|
102
102
|
|
|
103
|
-
def __init__(
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
pretrained_model_card: str,
|
|
106
|
+
add_special_tokens: bool = True,
|
|
107
|
+
**tokenizer_kwargs,
|
|
108
|
+
):
|
|
109
|
+
"""``add_special_tokens`` keeps ``[CLS]`` and ``[SEP]``, and it should.
|
|
110
|
+
|
|
111
|
+
A pretrained encoder was trained with them and reads worse without: on
|
|
112
|
+
legal text, dropping them moves Legal-BERT's token states to a cosine
|
|
113
|
+
of 0.83 against what it would otherwise produce. They carry no word,
|
|
114
|
+
so ``word_ids`` is ``None`` there and a selector never sees them --
|
|
115
|
+
removing them from the input was never what kept them unselectable.
|
|
116
|
+
|
|
117
|
+
``False`` reproduces a run made before this was a choice.
|
|
118
|
+
"""
|
|
104
119
|
try:
|
|
105
120
|
from transformers import AutoTokenizer
|
|
106
121
|
except ImportError as error:
|
|
@@ -110,6 +125,7 @@ class HuggingFaceTokenizer:
|
|
|
110
125
|
|
|
111
126
|
if tokenizer_kwargs.pop("use_fast", True) is not True:
|
|
112
127
|
raise ValueError("HuggingFaceTokenizer requires a fast tokenizer")
|
|
128
|
+
self.add_special_tokens = add_special_tokens
|
|
113
129
|
self.tokenizer = AutoTokenizer.from_pretrained(
|
|
114
130
|
pretrained_model_card, use_fast=True, **tokenizer_kwargs
|
|
115
131
|
)
|
|
@@ -124,7 +140,7 @@ class HuggingFaceTokenizer:
|
|
|
124
140
|
) -> TokenizedExample:
|
|
125
141
|
kwargs = {
|
|
126
142
|
"is_split_into_words": True,
|
|
127
|
-
"add_special_tokens":
|
|
143
|
+
"add_special_tokens": self.add_special_tokens,
|
|
128
144
|
"return_attention_mask": False,
|
|
129
145
|
}
|
|
130
146
|
if max_length is not None:
|
|
@@ -184,8 +200,7 @@ class HighlightCollator:
|
|
|
184
200
|
width = max(max(len(item.input_ids) for item in encoded), 1)
|
|
185
201
|
|
|
186
202
|
features = []
|
|
187
|
-
|
|
188
|
-
highlights = []
|
|
203
|
+
attention = []
|
|
189
204
|
sources = []
|
|
190
205
|
for example, item in zip(examples, encoded):
|
|
191
206
|
input_ids = list(item.input_ids[:width])
|
|
@@ -196,26 +211,33 @@ class HighlightCollator:
|
|
|
196
211
|
|
|
197
212
|
padding = width - len(input_ids)
|
|
198
213
|
features.append(input_ids + [self.tokenizer.pad_token_id] * padding)
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
)
|
|
202
|
-
highlights.append(
|
|
203
|
-
[
|
|
204
|
-
-1
|
|
205
|
-
if word_id is None or example.highlights is None
|
|
206
|
-
else example.highlights[word_id]
|
|
207
|
-
for word_id in word_ids
|
|
208
|
-
]
|
|
209
|
-
+ [-1] * padding
|
|
210
|
-
)
|
|
211
|
-
# Kept rather than discarded with the encoding: a selection is made
|
|
212
|
-
# over these positions, and only the word behind each one makes it
|
|
213
|
-
# readable once the run is over.
|
|
214
|
+
# Every encoded position, special tokens included: they carry no
|
|
215
|
+
# word, but the encoder was pretrained reading them.
|
|
216
|
+
attention.append([True] * len(input_ids) + [False] * padding)
|
|
214
217
|
sources.append(
|
|
215
218
|
[-1 if word_id is None else word_id for word_id in word_ids]
|
|
216
219
|
+ [-1] * padding
|
|
217
220
|
)
|
|
218
221
|
|
|
222
|
+
# The word axis is as wide as the longest *surviving* word count, not
|
|
223
|
+
# as the longest document: truncation cuts a clause off mid-way, and a
|
|
224
|
+
# word past the cut was never encoded and cannot be selected.
|
|
225
|
+
words = [
|
|
226
|
+
max((word_id + 1 for word_id in row if word_id >= 0), default=0)
|
|
227
|
+
for row in sources
|
|
228
|
+
]
|
|
229
|
+
span = max(max(words), 1)
|
|
230
|
+
|
|
231
|
+
masks = []
|
|
232
|
+
highlights = []
|
|
233
|
+
for example, kept in zip(examples, words):
|
|
234
|
+
masks.append([True] * kept + [False] * (span - kept))
|
|
235
|
+
highlights.append(
|
|
236
|
+
[-1] * span
|
|
237
|
+
if example.highlights is None
|
|
238
|
+
else list(example.highlights[:kept]) + [-1] * (span - kept)
|
|
239
|
+
)
|
|
240
|
+
|
|
219
241
|
return InputData(
|
|
220
242
|
features=th.tensor(features, dtype=th.long),
|
|
221
243
|
mask=th.tensor(masks, dtype=th.float32),
|
|
@@ -223,4 +245,5 @@ class HighlightCollator:
|
|
|
223
245
|
y_true=th.tensor([example.label for example in examples]),
|
|
224
246
|
highlight_true=th.tensor(highlights, dtype=th.long),
|
|
225
247
|
word_ids=th.tensor(sources, dtype=th.long),
|
|
248
|
+
attention_mask=th.tensor(attention, dtype=th.float32),
|
|
226
249
|
)
|
|
@@ -81,14 +81,7 @@ def evaluate(model: Model, loader: DataLoader) -> Dict[str, float]:
|
|
|
81
81
|
try:
|
|
82
82
|
with th.no_grad():
|
|
83
83
|
for batch in loader:
|
|
84
|
-
batch =
|
|
85
|
-
**{
|
|
86
|
-
name: value.to(model.device)
|
|
87
|
-
if isinstance(value, th.Tensor)
|
|
88
|
-
else value
|
|
89
|
-
for name, value in batch.as_dict().items()
|
|
90
|
-
}
|
|
91
|
-
)
|
|
84
|
+
batch = batch.to(model.device)
|
|
92
85
|
terms = model.faithfulness(batch, model.test_forward(batch))
|
|
93
86
|
for name, value in terms.items():
|
|
94
87
|
totals[name] = totals.get(name, 0.0) + float(value.sum())
|
|
@@ -137,12 +137,20 @@ class Model(L.LightningModule, abc.ABC, Generic[OutputT]):
|
|
|
137
137
|
def test_forward(self, batch: InputData) -> OutputT:
|
|
138
138
|
return self.training_forward(batch=batch)
|
|
139
139
|
|
|
140
|
-
def
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
140
|
+
def record(
|
|
141
|
+
self,
|
|
142
|
+
split: Split,
|
|
143
|
+
batch: InputData,
|
|
144
|
+
output_data: OutputT,
|
|
145
|
+
total_loss: th.Tensor,
|
|
146
|
+
losses: Dict[str, th.Tensor],
|
|
147
|
+
) -> None:
|
|
148
|
+
"""Log the losses, update the metrics, keep the predictions if asked.
|
|
145
149
|
|
|
150
|
+
What every step does once its loss is known, however it got there: a
|
|
151
|
+
model driving its own optimizers computes that loss in phases, but has
|
|
152
|
+
the same record to write afterwards.
|
|
153
|
+
"""
|
|
146
154
|
self.log_metrics(
|
|
147
155
|
split=split,
|
|
148
156
|
total_loss=total_loss,
|
|
@@ -150,10 +158,15 @@ class Model(L.LightningModule, abc.ABC, Generic[OutputT]):
|
|
|
150
158
|
batch_size=batch.y_true.shape[0],
|
|
151
159
|
)
|
|
152
160
|
self.update_metrics(split=split, input_data=batch, output_data=output_data)
|
|
153
|
-
|
|
154
161
|
if self.store_predictions:
|
|
155
162
|
self.predictions.append({**batch.as_numpy(), **output_data.as_numpy()})
|
|
156
163
|
|
|
164
|
+
def _step(self, batch: InputData, batch_idx: int, split: Split) -> th.Tensor:
|
|
165
|
+
output_data = self.forward_mapping[split](batch)
|
|
166
|
+
total_loss, losses = self.compute_loss(
|
|
167
|
+
input_data=batch, output_data=output_data
|
|
168
|
+
)
|
|
169
|
+
self.record(split, batch, output_data, total_loss, losses)
|
|
157
170
|
return total_loss
|
|
158
171
|
|
|
159
172
|
def training_step(self, batch: InputData, batch_idx: int):
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, fields
|
|
4
|
+
from typing import Generator, TypeVar
|
|
5
|
+
|
|
6
|
+
import torch as th
|
|
7
|
+
|
|
8
|
+
D = TypeVar("D", bound="ModelData")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class ModelData:
|
|
13
|
+
def as_dict(self):
|
|
14
|
+
return {field.name: getattr(self, field.name) for field in fields(self)}
|
|
15
|
+
|
|
16
|
+
def as_numpy(self):
|
|
17
|
+
return {
|
|
18
|
+
field.name: value.detach().cpu().numpy()
|
|
19
|
+
for field in fields(self)
|
|
20
|
+
if isinstance((value := getattr(self, field.name)), th.Tensor)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
def to(self: D, device: th.device | str) -> D:
|
|
24
|
+
"""The same record with every tensor on ``device``, non-tensors as they are."""
|
|
25
|
+
return type(self)(
|
|
26
|
+
**{
|
|
27
|
+
name: value.to(device) if isinstance(value, th.Tensor) else value
|
|
28
|
+
for name, value in self.as_dict().items()
|
|
29
|
+
}
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
def unbind(self: D, dim: int = 0) -> Generator[D, None, None]:
|
|
33
|
+
tensor_fields = {
|
|
34
|
+
field.name: th.unbind(value, dim=dim)
|
|
35
|
+
for field in fields(self)
|
|
36
|
+
if isinstance((value := getattr(self, field.name)), th.Tensor)
|
|
37
|
+
}
|
|
38
|
+
sizes = {len(values) for values in tensor_fields.values()}
|
|
39
|
+
if not sizes:
|
|
40
|
+
raise RuntimeError("No tensors found to unbind")
|
|
41
|
+
if len(sizes) != 1:
|
|
42
|
+
raise RuntimeError("Cannot unbind tensors of different sizes")
|
|
43
|
+
|
|
44
|
+
for index in range(sizes.pop()):
|
|
45
|
+
yield type(self)(
|
|
46
|
+
**{
|
|
47
|
+
field.name: tensor_fields[field.name][index]
|
|
48
|
+
if field.name in tensor_fields
|
|
49
|
+
else getattr(self, field.name)
|
|
50
|
+
for field in fields(self)
|
|
51
|
+
}
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class InputData(ModelData):
|
|
57
|
+
"""A batch on two axes, and which one a field lives on matters.
|
|
58
|
+
|
|
59
|
+
The **subtoken axis** ``[B, T]`` is what the encoder reads: ``features``,
|
|
60
|
+
``attention_mask`` and ``word_ids``. A backbone tokenizes however it likes,
|
|
61
|
+
so ``T`` is its business.
|
|
62
|
+
|
|
63
|
+
The **word axis** ``[B, W]`` is what a person reads and what a selection is
|
|
64
|
+
made over: ``mask`` and ``highlight_true``. A word is the unit the corpus
|
|
65
|
+
annotates, the unit a sparsity target is a fraction of, and the unit an
|
|
66
|
+
export shows -- and it is the same unit whichever backbone read the text,
|
|
67
|
+
which is what makes two backbones comparable in one table.
|
|
68
|
+
|
|
69
|
+
``word_ids`` is the map between them. For a vocabulary tokenizer the two
|
|
70
|
+
axes coincide and it is the identity.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
features: th.Tensor
|
|
74
|
+
#: Word axis: which word slots hold a word. Losses and metrics bind here.
|
|
75
|
+
mask: th.Tensor
|
|
76
|
+
sample_ids: th.Tensor
|
|
77
|
+
y_true: th.Tensor
|
|
78
|
+
#: Word axis: the annotation, ``-1`` where a split carries none.
|
|
79
|
+
highlight_true: th.Tensor
|
|
80
|
+
#: Subtoken axis: which word each position came from, ``-1`` for a special
|
|
81
|
+
#: token or padding. The map between the axes, and what turns a selection
|
|
82
|
+
#: back into something readable.
|
|
83
|
+
word_ids: th.Tensor | None = None
|
|
84
|
+
#: Subtoken axis: what the encoder attends over -- every real subtoken
|
|
85
|
+
#: *and* every special token, since a backbone was pretrained with those
|
|
86
|
+
#: and reads worse without them. Distinct from ``mask``, which says what
|
|
87
|
+
#: may be selected: ``[CLS]`` is not a word and is never a choice, but it
|
|
88
|
+
#: is always seen. Defaults to every non-padding position when a batch is
|
|
89
|
+
#: assembled by hand.
|
|
90
|
+
attention_mask: th.Tensor | None = None
|
|
91
|
+
|
|
92
|
+
def attention(self) -> th.Tensor:
|
|
93
|
+
"""What the encoder attends over, whether or not the batch said."""
|
|
94
|
+
if self.attention_mask is not None:
|
|
95
|
+
return self.attention_mask
|
|
96
|
+
if self.word_ids is not None:
|
|
97
|
+
return (self.word_ids >= 0).to(self.features.dtype)
|
|
98
|
+
return th.ones_like(self.features, dtype=th.get_default_dtype())
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass
|
|
102
|
+
class OutputData(ModelData):
|
|
103
|
+
class_logits: th.Tensor
|
|
@@ -2,7 +2,7 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import abc
|
|
4
4
|
import math
|
|
5
|
-
from typing import Dict, List, Tuple, Union
|
|
5
|
+
from typing import Dict, List, Literal, Tuple, Union
|
|
6
6
|
|
|
7
7
|
import torch as th
|
|
8
8
|
from cinnamon.registry import RegistrationKey, Registry
|
|
@@ -82,6 +82,7 @@ class SPP(Model[SPPOutput]):
|
|
|
82
82
|
predictor_backbone: RegistrationKey[SPPBackbone] | None = None,
|
|
83
83
|
aggregator: RegistrationKey[SPPAggregator] | None = None,
|
|
84
84
|
temperature: float = 1.0,
|
|
85
|
+
select_over: Literal["word", "subtoken"] = "word",
|
|
85
86
|
supervise_highlights: bool = False,
|
|
86
87
|
highlight_loss: RegistrationKey[Loss] | None = None,
|
|
87
88
|
highlight_coefficient: float = 1.0,
|
|
@@ -149,11 +150,107 @@ class SPP(Model[SPPOutput]):
|
|
|
149
150
|
if not math.isfinite(temperature) or temperature <= 0:
|
|
150
151
|
raise ValueError("temperature must be finite and greater than zero")
|
|
151
152
|
self.temperature = temperature
|
|
153
|
+
if select_over not in ("word", "subtoken"):
|
|
154
|
+
raise ValueError("select_over must be 'word' or 'subtoken'")
|
|
155
|
+
# A word is what the corpus annotates, what a sparsity target is a
|
|
156
|
+
# fraction of, and what an export shows -- and it is the same unit
|
|
157
|
+
# whichever backbone read the text. `subtoken` is the older behaviour,
|
|
158
|
+
# kept so the difference can be measured rather than argued about.
|
|
159
|
+
self.select_over = select_over
|
|
152
160
|
|
|
153
161
|
@property
|
|
154
162
|
def selector_backbone(self) -> SPPBackbone:
|
|
155
163
|
return self.selector_backbones[0]
|
|
156
164
|
|
|
165
|
+
def selection_valid(self, data: InputData) -> th.Tensor:
|
|
166
|
+
"""Which positions of the selection axis hold something selectable.
|
|
167
|
+
|
|
168
|
+
The word axis says so directly. On the subtoken axis a special token
|
|
169
|
+
is not a word and is never a choice, so it is excluded here even
|
|
170
|
+
though the encoder always attends over it.
|
|
171
|
+
"""
|
|
172
|
+
if self.select_over == "word" or data.word_ids is None:
|
|
173
|
+
return data.mask
|
|
174
|
+
return (data.word_ids >= 0).to(data.mask.dtype)
|
|
175
|
+
|
|
176
|
+
def selection_truth(self, data: InputData) -> th.Tensor:
|
|
177
|
+
"""The annotation on the selection axis, ``-1`` where there is none."""
|
|
178
|
+
if self.select_over == "word" or data.word_ids is None:
|
|
179
|
+
return data.highlight_true
|
|
180
|
+
index = data.word_ids.clamp_min(0)
|
|
181
|
+
spread = data.highlight_true.gather(1, index)
|
|
182
|
+
return th.where(data.word_ids >= 0, spread, th.full_like(spread, -1))
|
|
183
|
+
|
|
184
|
+
def namespace(
|
|
185
|
+
self, input_data: InputData, output_data, **extra: th.Tensor
|
|
186
|
+
) -> Dict[str, th.Tensor]:
|
|
187
|
+
"""The batch as losses and metrics see it, on the selection axis.
|
|
188
|
+
|
|
189
|
+
``mask`` and ``highlight_true`` arrive on the word axis, which is the
|
|
190
|
+
selection axis unless a model was told otherwise. A model selecting
|
|
191
|
+
over subtokens gets them spread onto that axis instead, so a loss
|
|
192
|
+
binds the same field name either way and always scores the unit the
|
|
193
|
+
selection was made in.
|
|
194
|
+
"""
|
|
195
|
+
values = super().namespace(input_data, output_data, **extra)
|
|
196
|
+
if self.select_over == "subtoken":
|
|
197
|
+
values["mask"] = self.selection_valid(input_data)
|
|
198
|
+
values["highlight_true"] = self.selection_truth(input_data)
|
|
199
|
+
return values
|
|
200
|
+
|
|
201
|
+
def to_words(self, states: th.Tensor, data: InputData) -> th.Tensor:
|
|
202
|
+
"""Average each word's subtoken states into one state for the word.
|
|
203
|
+
|
|
204
|
+
A selection is made over these, so it is made over the unit a person
|
|
205
|
+
reads and the corpus annotates. Selecting over subtokens instead lets
|
|
206
|
+
a model keep ``un`` and drop ``##fair``, which the export then reports
|
|
207
|
+
as the word ``unfair`` -- a highlight that is not what the predictor
|
|
208
|
+
read, in a library whose whole claim is that it is.
|
|
209
|
+
|
|
210
|
+
Pooling happens *after* the encoder, never before: the backbone still
|
|
211
|
+
attends over its own subtokens and stays on the distribution it was
|
|
212
|
+
pretrained on. For a vocabulary tokenizer the axes coincide and this
|
|
213
|
+
is the identity.
|
|
214
|
+
"""
|
|
215
|
+
# No word ids means the axes already coincide -- a vocabulary
|
|
216
|
+
# tokenizer, or a batch assembled by hand in a test.
|
|
217
|
+
if self.select_over == "subtoken" or data.word_ids is None:
|
|
218
|
+
return states
|
|
219
|
+
word_ids, width = data.word_ids, data.mask.shape[1]
|
|
220
|
+
# -1 marks a special token or padding; folding those into slot 0 would
|
|
221
|
+
# mix `[CLS]` into the first word, so they are sent to a slot past the
|
|
222
|
+
# end and dropped with the slice.
|
|
223
|
+
index = word_ids.clamp_min(-1).masked_fill(word_ids < 0, width)
|
|
224
|
+
pooled = states.new_zeros((states.shape[0], width + 1, states.shape[2]))
|
|
225
|
+
pooled.scatter_reduce_(
|
|
226
|
+
dim=1,
|
|
227
|
+
index=index.unsqueeze(-1).expand_as(states),
|
|
228
|
+
src=states,
|
|
229
|
+
reduce="mean",
|
|
230
|
+
include_self=False,
|
|
231
|
+
)
|
|
232
|
+
return pooled[:, :width]
|
|
233
|
+
|
|
234
|
+
def to_subtokens(self, selection: th.Tensor, data: InputData) -> th.Tensor:
|
|
235
|
+
"""Spread a word's decision back over the subtokens that spell it.
|
|
236
|
+
|
|
237
|
+
The predictor reads subtokens, so a word-level selection has to become
|
|
238
|
+
one. Every position of a selected word is kept and every position of a
|
|
239
|
+
dropped word is dropped, which is what makes the exported highlight
|
|
240
|
+
exactly the predictor's input rather than an approximation of it.
|
|
241
|
+
|
|
242
|
+
A special token belongs to no word and is always kept: it is not
|
|
243
|
+
content, so it is never a choice, but the encoder was pretrained
|
|
244
|
+
reading it.
|
|
245
|
+
"""
|
|
246
|
+
if self.select_over == "subtoken" or data.word_ids is None:
|
|
247
|
+
return selection
|
|
248
|
+
word_ids = data.word_ids
|
|
249
|
+
index = word_ids.clamp_min(0)
|
|
250
|
+
spread = selection.gather(1, index)
|
|
251
|
+
special = (word_ids < 0) & data.attention().bool()
|
|
252
|
+
return th.where(special, th.ones_like(spread), spread * (word_ids >= 0))
|
|
253
|
+
|
|
157
254
|
def load_embeddings(self, matrix: th.Tensor) -> None:
|
|
158
255
|
"""Hand the same pretrained table to every backbone.
|
|
159
256
|
|
|
@@ -179,10 +276,10 @@ class SPP(Model[SPPOutput]):
|
|
|
179
276
|
selector: SPPSelector,
|
|
180
277
|
backbone: SPPBackbone,
|
|
181
278
|
) -> Tuple[th.Tensor, th.Tensor]:
|
|
182
|
-
states = backbone.encode(data.features, data.
|
|
279
|
+
states = self.to_words(backbone.encode(data.features, data.attention()), data)
|
|
183
280
|
highlight_logits = selector(states)
|
|
184
281
|
highlight_mask = self.select_activation(highlight_logits)
|
|
185
|
-
valid = data.
|
|
282
|
+
valid = self.selection_valid(data).bool()
|
|
186
283
|
highlight_mask = highlight_mask * valid.to(highlight_mask.dtype)
|
|
187
284
|
|
|
188
285
|
# A sample whose selector marks no valid token would leave the
|
|
@@ -206,11 +303,15 @@ class SPP(Model[SPPOutput]):
|
|
|
206
303
|
return highlight_logits, highlight_mask
|
|
207
304
|
|
|
208
305
|
def predict(self, data: InputData, highlight_mask: th.Tensor) -> th.Tensor:
|
|
209
|
-
|
|
306
|
+
selection = self.selection_valid(data).to(highlight_mask.dtype) * highlight_mask
|
|
307
|
+
# Onto the axis the encoder reads, where a special token is always
|
|
308
|
+
# attended and a dropped word is gone in every piece of itself.
|
|
309
|
+
prediction_mask = self.to_subtokens(selection, data)
|
|
310
|
+
attention = data.attention().to(prediction_mask.dtype)
|
|
210
311
|
states = self.predictor_backbone.encode(
|
|
211
|
-
data.features,
|
|
312
|
+
data.features, attention, selection_mask=prediction_mask
|
|
212
313
|
)
|
|
213
|
-
pooled = self.predictor_backbone.pool(states, prediction_mask)
|
|
314
|
+
pooled = self.predictor_backbone.pool(states, attention * prediction_mask)
|
|
214
315
|
return self.predictor(pooled)
|
|
215
316
|
|
|
216
317
|
def predict_full(self, data: InputData) -> th.Tensor:
|
|
@@ -220,7 +321,9 @@ class SPP(Model[SPPOutput]):
|
|
|
220
321
|
the highlight and only the highlight. MCD trains this pass on purpose,
|
|
221
322
|
and the faithfulness terms need it as their reference point.
|
|
222
323
|
"""
|
|
223
|
-
return self.predict(
|
|
324
|
+
return self.predict(
|
|
325
|
+
data=data, highlight_mask=th.ones_like(self.selection_valid(data))
|
|
326
|
+
)
|
|
224
327
|
|
|
225
328
|
def faithfulness(
|
|
226
329
|
self, input_data: InputData, output_data: SPPOutput
|
|
@@ -240,7 +343,7 @@ class SPP(Model[SPPOutput]):
|
|
|
240
343
|
everything, not a case to repair.
|
|
241
344
|
"""
|
|
242
345
|
head = self.aggregator(output_data)
|
|
243
|
-
valid = input_data.
|
|
346
|
+
valid = self.selection_valid(input_data).to(head.highlight_mask.dtype)
|
|
244
347
|
highlight = head.highlight_mask * valid
|
|
245
348
|
|
|
246
349
|
def probability(logits: th.Tensor, of: th.Tensor) -> th.Tensor:
|
|
@@ -395,7 +395,7 @@ class GenSPPTrainer:
|
|
|
395
395
|
|
|
396
396
|
with th.no_grad():
|
|
397
397
|
for batch in val_loader:
|
|
398
|
-
batch = self.
|
|
398
|
+
batch = batch.to(self.device)
|
|
399
399
|
output = model(batch)
|
|
400
400
|
batch_size = batch.y_true.shape[0]
|
|
401
401
|
loss, _ = model.compute_loss(batch, output)
|
|
@@ -473,13 +473,3 @@ class GenSPPTrainer:
|
|
|
473
473
|
@staticmethod
|
|
474
474
|
def _chromosome(model: GenSPP) -> th.Tensor:
|
|
475
475
|
return th.nn.utils.parameters_to_vector(model.generator_parameters()).detach()
|
|
476
|
-
|
|
477
|
-
def _move_batch(self, batch: InputData) -> InputData:
|
|
478
|
-
if self.device.type == "cpu":
|
|
479
|
-
return batch
|
|
480
|
-
return InputData(
|
|
481
|
-
**{
|
|
482
|
-
name: value.to(self.device) if isinstance(value, th.Tensor) else value
|
|
483
|
-
for name, value in batch.as_dict().items()
|
|
484
|
-
}
|
|
485
|
-
)
|
|
@@ -210,16 +210,14 @@ class GRAT(SPP):
|
|
|
210
210
|
self._model_steps.add_(1)
|
|
211
211
|
|
|
212
212
|
total = model_total.detach()
|
|
213
|
-
self.
|
|
213
|
+
self.record(
|
|
214
214
|
split="train",
|
|
215
|
+
batch=batch,
|
|
216
|
+
output_data=output,
|
|
215
217
|
total_loss=total,
|
|
216
218
|
losses={
|
|
217
219
|
**{f"guider_{name}": value for name, value in guider_losses.items()},
|
|
218
220
|
**model_losses,
|
|
219
221
|
},
|
|
220
|
-
batch_size=batch.y_true.shape[0],
|
|
221
222
|
)
|
|
222
|
-
self.update_metrics(split="train", input_data=batch, output_data=output)
|
|
223
|
-
if self.store_predictions:
|
|
224
|
-
self.predictions.append({**batch.as_numpy(), **output.as_numpy()})
|
|
225
223
|
return total
|
|
@@ -46,6 +46,17 @@ class MCD(SPP):
|
|
|
46
46
|
):
|
|
47
47
|
if predictor_backbone is None:
|
|
48
48
|
raise ValueError("MCD requires a separate predictor backbone")
|
|
49
|
+
# MCD groups its losses per training phase and replaces the flat list
|
|
50
|
+
# SPP builds, so a supervision loss appended to that list would be
|
|
51
|
+
# dropped before the first batch. Refused rather than silently ignored:
|
|
52
|
+
# a run that reports itself as the supervised ceiling and trains
|
|
53
|
+
# unsupervised is a number nobody can read as wrong.
|
|
54
|
+
if kwargs.get("supervise_highlights"):
|
|
55
|
+
raise ValueError(
|
|
56
|
+
"MCD scores its losses per training phase, so highlight "
|
|
57
|
+
"supervision has to name the phase it belongs to; put the "
|
|
58
|
+
"highlight loss in rationale_losses instead"
|
|
59
|
+
)
|
|
49
60
|
super().__init__(
|
|
50
61
|
selector_backbones=selector_backbones,
|
|
51
62
|
selectors=selectors,
|
|
@@ -155,8 +166,10 @@ class MCD(SPP):
|
|
|
155
166
|
generator_optimizer.zero_grad()
|
|
156
167
|
|
|
157
168
|
total = classifier_total.detach() + generator_total.detach()
|
|
158
|
-
self.
|
|
169
|
+
self.record(
|
|
159
170
|
split="train",
|
|
171
|
+
batch=batch,
|
|
172
|
+
output_data=output,
|
|
160
173
|
total_loss=total,
|
|
161
174
|
losses={
|
|
162
175
|
**{
|
|
@@ -168,9 +181,5 @@ class MCD(SPP):
|
|
|
168
181
|
for name, value in generator_losses.items()
|
|
169
182
|
},
|
|
170
183
|
},
|
|
171
|
-
batch_size=batch.y_true.shape[0],
|
|
172
184
|
)
|
|
173
|
-
self.update_metrics(split="train", input_data=batch, output_data=output)
|
|
174
|
-
if self.store_predictions:
|
|
175
|
-
self.predictions.append({**batch.as_numpy(), **output.as_numpy()})
|
|
176
185
|
return total
|