polyprobe 1.0.0__py3-none-any.whl

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.

Potentially problematic release.


This version of polyprobe might be problematic. Click here for more details.

Files changed (48) hide show
  1. polyprobe/__init__.py +8 -0
  2. polyprobe/activations.py +353 -0
  3. polyprobe/architecture_encoders/architecture_encoder.py +71 -0
  4. polyprobe/architecture_encoders/gqa.py +77 -0
  5. polyprobe/architecture_encoders/opt.py +51 -0
  6. polyprobe/architecture_encoders/qwen3_5.py +100 -0
  7. polyprobe/batching.py +133 -0
  8. polyprobe/config.py +101 -0
  9. polyprobe/document.py +138 -0
  10. polyprobe/evaluation.py +945 -0
  11. polyprobe/index_tuple_selectors/causal_combinatorial.py +49 -0
  12. polyprobe/index_tuple_selectors/index_tuple_selector.py +23 -0
  13. polyprobe/inferrer.py +480 -0
  14. polyprobe/lm_encoder.py +218 -0
  15. polyprobe/logging_utils.py +82 -0
  16. polyprobe/manager.py +607 -0
  17. polyprobe/model.py +342 -0
  18. polyprobe/poolers/max.py +23 -0
  19. polyprobe/poolers/mean.py +34 -0
  20. polyprobe/poolers/passthrough.py +21 -0
  21. polyprobe/poolers/pooler.py +88 -0
  22. polyprobe/probe_components/index_pair.py +368 -0
  23. polyprobe/probe_components/probe_component.py +92 -0
  24. polyprobe/probes/linear.py +46 -0
  25. polyprobe/probes/neural.py +220 -0
  26. polyprobe/probes/probe.py +164 -0
  27. polyprobe/py.typed +0 -0
  28. polyprobe/registry.py +248 -0
  29. polyprobe/scorers/average_precision.py +27 -0
  30. polyprobe/scorers/f1.py +24 -0
  31. polyprobe/scorers/roc-auc.py +28 -0
  32. polyprobe/scorers/scorer.py +43 -0
  33. polyprobe/training/config.py +127 -0
  34. polyprobe/training/dataset_sources/dataset_source.py +142 -0
  35. polyprobe/training/dataset_sources/ud_dependency_dataset_source.py +517 -0
  36. polyprobe/training/runner.py +951 -0
  37. polyprobe/training/training_data.py +180 -0
  38. polyprobe/training/truthers/direct.py +206 -0
  39. polyprobe/training/truthers/random.py +63 -0
  40. polyprobe/training/truthers/subword.py +49 -0
  41. polyprobe/training/truthers/truther.py +96 -0
  42. polyprobe/util.py +599 -0
  43. polyprobe-1.0.0.dist-info/METADATA +63 -0
  44. polyprobe-1.0.0.dist-info/RECORD +48 -0
  45. polyprobe-1.0.0.dist-info/WHEEL +5 -0
  46. polyprobe-1.0.0.dist-info/licenses/LICENSE +73 -0
  47. polyprobe-1.0.0.dist-info/licenses/LICENSE-CC-BY-4.0 +395 -0
  48. polyprobe-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,180 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from torch import Tensor
8
+
9
+ from polyprobe.document import DocumentPiece, DocumentPieceList
10
+ from polyprobe.index_tuple_selectors.index_tuple_selector import IndexTupleSelector
11
+ from polyprobe.model import DatasetSourceUsage, PolyprobeLabelEvaluation
12
+ from polyprobe.training.truthers.truther import Truther
13
+
14
+
15
+ @dataclass
16
+ class TrainingDatasetGroup:
17
+ """Train, dev and test document-piece lists used to build training data."""
18
+
19
+ train: DocumentPieceList
20
+ dev: DocumentPieceList
21
+ test: DocumentPieceList
22
+
23
+ @property
24
+ def all_pieces(self) -> list[DocumentPiece]:
25
+ """Return a new list of all pieces in train, dev, then test order.
26
+
27
+ The document pieces themselves are shared with the original splits.
28
+ """
29
+ return self.train.pieces + self.dev.pieces + self.test.pieces
30
+
31
+
32
+ @dataclass(slots=True)
33
+ class LabelModelSplit:
34
+ """Prepared data for one label/order combination within a dataset split.
35
+
36
+ pieces, index_tuples_list and truths_list are aligned by list position.
37
+ Each index-tuple tensor has shape (num_candidates, arity); its corresponding
38
+ boolean truths tensor has shape (num_candidates,). Candidate counts may
39
+ differ between pieces, including zero for individual pieces.
40
+
41
+ num_pos_labels is the total number of positive candidate tuples across
42
+ all pieces, rather than the number of source training labels.
43
+ """
44
+
45
+ pieces: list[DocumentPiece]
46
+ index_tuples_list: list[Tensor]
47
+ truths_list: list[Tensor]
48
+ num_pos_labels: int
49
+
50
+
51
+ class LabelModelTrainingData:
52
+ """Prepares train, dev and test candidates and truths for one label and order.
53
+
54
+ For each piece, selects candidate LM-token index tuples and passes the matching
55
+ training labels to the truther. Stores the returned truths and candidate
56
+ tuples, including any reduction performed by the truther.
57
+
58
+ Every split must retain at least one candidate tuple. Individual splits
59
+ may contain no positive candidates, but at least one positive candidate
60
+ must exist across the three splits.
61
+ """
62
+
63
+ train: LabelModelSplit
64
+ dev: LabelModelSplit
65
+ test: LabelModelSplit
66
+
67
+ def __init__(
68
+ self,
69
+ index_tuple_selector: IndexTupleSelector,
70
+ truther: Truther,
71
+ training_dataset_group: TrainingDatasetGroup,
72
+ label: str,
73
+ order: tuple[int, ...],
74
+ ) -> None:
75
+ """Build all three splits for the specified label and order.
76
+
77
+ Raises ValueError if any split retains no candidates or if no positive
78
+ candidates remain across all splits. Raises RuntimeError if returned
79
+ truths and candidate tensors have incompatible shapes.
80
+ """
81
+ for usage in ("train", "dev", "test"):
82
+ dataset = getattr(training_dataset_group, usage)
83
+ split = self._build_split(
84
+ index_tuple_selector, truther, dataset.pieces, label, order, usage
85
+ )
86
+ setattr(self, usage, split)
87
+ if (
88
+ self.train.num_pos_labels == 0
89
+ and self.dev.num_pos_labels == 0
90
+ and self.test.num_pos_labels == 0
91
+ ):
92
+ raise ValueError(
93
+ f"No pieces with label {label} and order {order} " "found in documents"
94
+ )
95
+
96
+ def _build_split(
97
+ self,
98
+ index_tuple_selector: IndexTupleSelector,
99
+ truther: Truther,
100
+ pieces: list[DocumentPiece],
101
+ label: str,
102
+ order: tuple[int, ...],
103
+ usage: str,
104
+ ) -> LabelModelSplit:
105
+ index_tuples_list = []
106
+ truths_list = []
107
+
108
+ arity = len(order)
109
+ for piece_idx, piece in enumerate(pieces):
110
+ training_labels = piece.get_training_labels(label, order)
111
+
112
+ index_tuples = index_tuple_selector.get_index_tuples(piece, arity)
113
+
114
+ truths, index_tuples = truther.get_truths(
115
+ piece,
116
+ index_tuples,
117
+ training_labels,
118
+ )
119
+
120
+ if truths.ndim != 1:
121
+ raise RuntimeError(
122
+ f"Building {usage}, expected one-dimensional truths for piece {piece_idx}, "
123
+ f"but got shape {tuple(truths.shape)}"
124
+ )
125
+ if index_tuples.ndim != 2:
126
+ raise RuntimeError(
127
+ f"Building {usage}, expected two-dimensional index tuples for piece {piece_idx}, "
128
+ f"but got shape {tuple(index_tuples.shape)}"
129
+ )
130
+ if index_tuples.shape[1] != arity:
131
+ raise RuntimeError(
132
+ f"Building {usage}, expected index tuples with arity {arity} for piece {piece_idx}, "
133
+ f"but got shape {tuple(index_tuples.shape)}"
134
+ )
135
+ if index_tuples.shape[0] != truths.shape[0]:
136
+ raise RuntimeError(
137
+ f"Building {usage}, piece {piece_idx} has {index_tuples.shape[0]} index tuples "
138
+ f"but {truths.shape[0]} truths"
139
+ )
140
+
141
+ index_tuples_list.append(index_tuples)
142
+ truths_list.append(truths)
143
+
144
+ if len(index_tuples_list) != len(pieces):
145
+ raise RuntimeError(
146
+ f"Building {usage}, expected one index-tuple tensor per document piece: "
147
+ f"pieces={len(pieces)}, "
148
+ f"index tensors={len(index_tuples_list)}"
149
+ )
150
+
151
+ if len(truths_list) != len(pieces):
152
+ raise RuntimeError(
153
+ f"Building {usage}, expected one truth tensor per document piece: "
154
+ f"pieces={len(pieces)}, "
155
+ f"truth tensors={len(truths_list)}"
156
+ )
157
+
158
+ if sum(t.shape[0] for t in index_tuples_list) == 0:
159
+ raise ValueError("At least one index-tuple tensor is required")
160
+
161
+ return LabelModelSplit(
162
+ pieces=pieces,
163
+ index_tuples_list=index_tuples_list,
164
+ truths_list=truths_list,
165
+ num_pos_labels=sum(int(truths.sum().item()) for truths in truths_list),
166
+ )
167
+
168
+ @property
169
+ def splits(self) -> dict[DatasetSourceUsage, LabelModelSplit]:
170
+ """Return a new mapping from split names to the existing split objects."""
171
+ return {"train": self.train, "dev": self.dev, "test": self.test}
172
+
173
+
174
+ @dataclass
175
+ class HeadModelDataWrapper:
176
+ """Holds a head model's evaluation, weights and non-improvement counter."""
177
+
178
+ evaluation: PolyprobeLabelEvaluation
179
+ evaluations_without_improvement: int
180
+ weights: Tensor
@@ -0,0 +1,206 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from abc import abstractmethod
7
+ from itertools import product
8
+
9
+ import torch
10
+ from torch import Tensor
11
+
12
+ from polyprobe.document import DocumentPiece, MatchedTrainingToken, TrainingLabel
13
+
14
+ from .truther import Truther
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class DirectTruther(Truther):
20
+ """
21
+ Direct truther implementations cover the typical case where the index tuples
22
+ labelled as true correspond to the labels from the dataset source.
23
+
24
+ The implementations differ by which index tuples corresponding to a training label are labelled
25
+ as true, remembering that each training token may correspond to multiple LM tokens.
26
+ """
27
+
28
+ def __init__(self, neutralize: bool = False) -> None:
29
+ """
30
+ neutralize: if *True*, index tuples corresponding to a labelled tuple but not marked
31
+ as true are removed, unless another label marks them as positive; if *False*, other index
32
+ tuples corresponding to a labelled tuple but not marked as true are retained as false.
33
+ """
34
+ self.neutralize = neutralize
35
+
36
+ def get_truths_impl(
37
+ self,
38
+ piece: DocumentPiece,
39
+ index_tuples: Tensor,
40
+ training_labels: list[TrainingLabel],
41
+ candidate_to_row: dict[tuple[int, ...], int],
42
+ ) -> tuple[Tensor, Tensor]:
43
+
44
+ truths = torch.zeros(
45
+ index_tuples.shape[0], dtype=torch.bool, device=index_tuples.device
46
+ )
47
+
48
+ this_piece_training_tokens = piece.training_tokens
49
+
50
+ neutral_matching_combinations: list[tuple[int, ...]] = []
51
+ for training_label in training_labels:
52
+ all_matching_combinations = list(
53
+ product(
54
+ *[
55
+ this_piece_training_tokens[
56
+ training_token_idx
57
+ ].matching_lm_token_idxs
58
+ for training_token_idx in training_label.training_token_idxs
59
+ ]
60
+ )
61
+ )
62
+ for mc in all_matching_combinations:
63
+ if mc not in candidate_to_row:
64
+ raise ValueError(
65
+ f"The training label combination {mc} does not correspond to an index tuple, which is not supported by direct truthers."
66
+ )
67
+ pos_matching_combinations = set(
68
+ product(
69
+ *self.get_pos_lm_token_idx_combinations(
70
+ this_piece_training_tokens, training_label
71
+ )
72
+ )
73
+ )
74
+ neutral_matching_combinations.extend(
75
+ mc
76
+ for mc in all_matching_combinations
77
+ if mc not in pos_matching_combinations
78
+ )
79
+
80
+ for mc in pos_matching_combinations:
81
+ row_idx = candidate_to_row[mc]
82
+ truths[row_idx] = True
83
+
84
+ if self.neutralize:
85
+ neutral_row_idxs = [
86
+ candidate_to_row[mc] for mc in neutral_matching_combinations
87
+ ]
88
+ mask = torch.ones_like(truths, dtype=torch.bool, device=truths.device)
89
+ mask[neutral_row_idxs] = False
90
+ mask |= truths
91
+ truths = truths[mask]
92
+ index_tuples = index_tuples[mask]
93
+ return truths, index_tuples
94
+
95
+ @abstractmethod
96
+ def get_pos_lm_token_idx_combinations(
97
+ self,
98
+ training_tokens: dict[int, MatchedTrainingToken],
99
+ training_label: TrainingLabel,
100
+ ) -> list[list[int]]:
101
+ pass
102
+
103
+ def check_label_and_order(self, label: str, order: tuple[int, ...]) -> None:
104
+ if label == "_subword":
105
+ raise ValueError(f"{type(self)} cannot process label {label}")
106
+
107
+
108
+ class AllToAllTruther(DirectTruther):
109
+ """Each labelled training token within a labelled tuple corresponds to n LM tokens.
110
+ Here index tuples are labelled positive for all combinations of LM tokens within all
111
+ training tokens.
112
+
113
+ e.g. if there is a relationship between LM tokens (2, 3) and LM tokens (6, 7),
114
+ the positive index tuples will be (2, 6), (2, 7), (3, 6) and (3, 7).
115
+ """
116
+
117
+ def get_pos_lm_token_idx_combinations(
118
+ self,
119
+ training_tokens: dict[int, MatchedTrainingToken],
120
+ training_label: TrainingLabel,
121
+ ) -> list[list[int]]:
122
+ return [
123
+ training_tokens[training_token_idx].matching_lm_token_idxs
124
+ for training_token_idx in training_label.training_token_idxs
125
+ ]
126
+
127
+
128
+ class LastToLastTruther(DirectTruther):
129
+ """Each labelled training token within a labelled tuple corresponds to n LM tokens.
130
+ Here a single index tuple is labelled positive connecting the rightmost LM tokens corresponding
131
+ to each training token.
132
+
133
+ e.g. if there is a relationship between LM tokens (2, 3) and LM tokens (6, 7),
134
+ the single positive index tuple will be (3, 7).
135
+ """
136
+
137
+ def get_pos_lm_token_idx_combinations(
138
+ self,
139
+ training_tokens: dict[int, MatchedTrainingToken],
140
+ training_label: TrainingLabel,
141
+ ) -> list[list[int]]:
142
+
143
+ return [
144
+ [training_tokens[training_token_idx].last_matching_lm_token_idx]
145
+ for training_token_idx in training_label.training_token_idxs
146
+ ]
147
+
148
+
149
+ class LastToAllTruther(DirectTruther):
150
+ """Each labelled training token within a labelled tuple corresponds to n LM tokens.
151
+ Here index tuples are labelled positive including only the rightmost LM token corresponding
152
+ to the rightmost training token but all LM tokens corresponding to each training
153
+ token further left. This truther is available for all arities but is only likely
154
+ to make sense when arity==2.
155
+
156
+ e.g. if there is a relationship between LM tokens (2, 3) and LM tokens (6, 7),
157
+ the positive index tuples will be (2, 7) and (3, 7).
158
+ """
159
+
160
+ def get_pos_lm_token_idx_combinations(
161
+ self,
162
+ training_tokens: dict[int, MatchedTrainingToken],
163
+ training_label: TrainingLabel,
164
+ ) -> list[list[int]]:
165
+
166
+ lm_token_idxss: list[list[int]] = []
167
+ for idx, training_token_idx in enumerate(training_label.training_token_idxs):
168
+ if idx + 1 < len(training_label.training_token_idxs):
169
+ lm_token_idxss.append(
170
+ training_tokens[training_token_idx].matching_lm_token_idxs
171
+ )
172
+ else:
173
+ lm_token_idxss.append(
174
+ [training_tokens[training_token_idx].last_matching_lm_token_idx]
175
+ )
176
+ return lm_token_idxss
177
+
178
+
179
+ class AllToLastTruther(DirectTruther):
180
+ """Each labelled training token within a labelled tuple corresponds to n LM tokens.
181
+ Here index tuples are labelled positive including all LM tokens corresponding to the
182
+ rightmost training token but only the rightmost LM token corresponding to
183
+ each training token further left. This truther is available for all arities
184
+ but is only likely to make sense when arity==2.
185
+
186
+ e.g. if there is a relationship between LM tokens (2, 3) and LM tokens (6, 7),
187
+ the positive index tuples will be (3, 6) and (3, 7).
188
+ """
189
+
190
+ def get_pos_lm_token_idx_combinations(
191
+ self,
192
+ training_tokens: dict[int, MatchedTrainingToken],
193
+ training_label: TrainingLabel,
194
+ ) -> list[list[int]]:
195
+
196
+ lm_token_idxss: list[list[int]] = []
197
+ for idx, training_token_idx in enumerate(training_label.training_token_idxs):
198
+ if idx + 1 < len(training_label.training_token_idxs):
199
+ lm_token_idxss.append(
200
+ [training_tokens[training_token_idx].last_matching_lm_token_idx]
201
+ )
202
+ else:
203
+ lm_token_idxss.append(
204
+ training_tokens[training_token_idx].matching_lm_token_idxs
205
+ )
206
+ return lm_token_idxss
@@ -0,0 +1,63 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import hashlib
6
+ import logging
7
+
8
+ import torch
9
+ from torch import Tensor
10
+
11
+ from polyprobe.document import DocumentPiece, TrainingLabel
12
+
13
+ from .truther import Truther
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class RandomTruther(Truther):
19
+ """
20
+ The random truther is used for experimental controls. However many positive training labels
21
+ there are in the genuine training data, a corresponding number of index tuples are sampled randomly
22
+ and marked as true. This generates a baseline corresponding to *LastToLastTruther*. The seed,
23
+ piece text, and identifier determine a repeatable permutation for a fixed candidate list on the
24
+ same backend. Note that a significant selection effect remains
25
+ (see https://github.com/richardpaulhudson/polyprobe#13-methodological-notes).
26
+ """
27
+
28
+ def __init__(self, seed: int = 4711) -> None:
29
+ super().__init__()
30
+ self.seed = seed
31
+
32
+ def get_truths_impl(
33
+ self,
34
+ piece: DocumentPiece,
35
+ index_tuples: Tensor,
36
+ training_labels: list[TrainingLabel],
37
+ candidate_to_row: dict[tuple[int, ...], int],
38
+ ) -> tuple[Tensor, Tensor]:
39
+ truths = torch.zeros(
40
+ index_tuples.shape[0], dtype=torch.bool, device=index_tuples.device
41
+ )
42
+
43
+ n_truths = len(training_labels)
44
+ if n_truths > index_tuples.shape[0]:
45
+ raise ValueError(
46
+ f"There are {n_truths} training labels, but only "
47
+ f"{index_tuples.shape[0]} candidate index tuples."
48
+ )
49
+
50
+ seed_material = f"{self.seed}:{piece.text}:{piece.identifier}".encode("utf-8")
51
+ digest = hashlib.blake2b(seed_material, digest_size=8).digest()
52
+ seed = int.from_bytes(digest, "big")
53
+ generator = torch.Generator(device=index_tuples.device).manual_seed(seed)
54
+ random_rows = torch.randperm(
55
+ index_tuples.shape[0], device=index_tuples.device, generator=generator
56
+ )[:n_truths]
57
+
58
+ truths[random_rows] = True
59
+
60
+ return truths, index_tuples
61
+
62
+ def check_label_and_order(self, label: str, order: tuple[int, ...]) -> None:
63
+ pass
@@ -0,0 +1,49 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+
7
+ import torch
8
+ from torch import Tensor
9
+
10
+ from polyprobe.document import DocumentPiece, TrainingLabel
11
+
12
+ from .truther import Truther
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class SubwordTruther(Truther):
18
+ """
19
+ The subword truther labels an index pair as true when the lefthand language-model token
20
+ immediately precedes the righthand token and both belong to the same MatchedTrainingToken.
21
+ """
22
+
23
+ def get_truths_impl(
24
+ self,
25
+ piece: DocumentPiece,
26
+ index_tuples: Tensor,
27
+ training_labels: list[TrainingLabel],
28
+ candidate_to_row: dict[tuple[int, ...], int],
29
+ ) -> tuple[Tensor, Tensor]:
30
+ truths = torch.zeros(
31
+ index_tuples.shape[0], dtype=torch.bool, device=index_tuples.device
32
+ )
33
+
34
+ for training_token in piece.training_tokens.values():
35
+ for token_idx_idx in range(1, len(training_token.matching_lm_token_idxs)):
36
+ row = candidate_to_row[
37
+ (
38
+ training_token.matching_lm_token_idxs[token_idx_idx - 1],
39
+ training_token.matching_lm_token_idxs[token_idx_idx],
40
+ )
41
+ ]
42
+ truths[row] = True
43
+ return truths, index_tuples
44
+
45
+ def check_label_and_order(self, label: str, order: tuple[int, ...]) -> None:
46
+ if label != "_subword" or order != (0, 1):
47
+ raise ValueError(
48
+ f"{type(self)} cannot process label {label} with order {order}"
49
+ )
@@ -0,0 +1,96 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from abc import ABC, abstractmethod
7
+
8
+ import torch
9
+ from torch import Tensor
10
+
11
+ from polyprobe.document import DocumentPiece, TrainingLabel
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class Truther(ABC):
17
+ """
18
+ Using the information added to a document piece by a training labeller, a truther
19
+ marks one or more index tuples as having the label in question for probe training
20
+ and evaluation. Additionally, it may remove index tuples from the supplied list,
21
+ thereby excluding these index tuples from training and evaluation, which is
22
+ equivalent to marking them as neutral, i.e. neither positive nor negative.
23
+
24
+ In the most obvious case, the truther will mark as true one or more of the tokens
25
+ or relations specified by the dataset source. However, other cases are conceivable:
26
+ for example, a dataset source might yield negative verbs within document pieces,
27
+ and a truther could investigate whether the negation is recoverable from the final token
28
+ within each piece, rather than more obviously from the piece corresponding to the verb.
29
+
30
+ Returns a (truths, potentially reduced index tuples) tuple.
31
+ """
32
+
33
+ def get_truths(
34
+ self,
35
+ piece: DocumentPiece,
36
+ index_tuples: Tensor,
37
+ training_labels: list[TrainingLabel],
38
+ ) -> tuple[Tensor, Tensor]:
39
+ arity = index_tuples.shape[1]
40
+ index_tuples_list = [tuple(i) for i in index_tuples.tolist()]
41
+ if len(set(index_tuples_list)) != len(index_tuples_list):
42
+ raise ValueError("index_tuples_list contains one or more duplicate values.")
43
+ for training_label in training_labels:
44
+ if len(training_label.order) != arity:
45
+ raise ValueError(
46
+ f"Training label {training_label.name} does not have the same arity {arity} as the supplied index tuples."
47
+ )
48
+ candidate_to_row: dict[tuple[int, ...], int] = {
49
+ tuple(int(x) for x in index_tuple.tolist()): row_idx
50
+ for row_idx, index_tuple in enumerate(index_tuples)
51
+ }
52
+ truths, index_tuples = self.get_truths_impl(
53
+ piece, index_tuples, training_labels, candidate_to_row
54
+ )
55
+ if truths.dtype != torch.bool:
56
+ raise ValueError("The truths tensor must have dtype bool.")
57
+ return truths, index_tuples
58
+
59
+ @abstractmethod
60
+ def get_truths_impl(
61
+ self,
62
+ piece: DocumentPiece,
63
+ index_tuples: Tensor,
64
+ training_labels: list[TrainingLabel],
65
+ candidate_to_row: dict[tuple[int, ...], int],
66
+ ) -> tuple[Tensor, Tensor]:
67
+ """
68
+ Assign truth values to candidate LM-token index tuples, optionally removing
69
+ candidates that should be excluded from training and evaluation.
70
+
71
+ piece: the document piece, including its training tokens and their mappings
72
+ to LM-token indices.
73
+ index_tuples: a tensor of shape (num_candidates, arity), with each row
74
+ containing a candidate tuple of LM-token indices.
75
+ training_labels: the training labels to process. Their interpretation
76
+ depends on the truther implementation.
77
+ candidate_to_row: a mapping from candidate tuples to their row indices in
78
+ the supplied index_tuples tensor, before any candidates are removed.
79
+
80
+ Returns (truths, retained_index_tuples), where:
81
+ truths is a boolean tensor of shape (num_retained,).
82
+ retained_index_tuples has shape (num_retained, arity).
83
+
84
+ Each truths[r] describes retained_index_tuples[r]: True marks a positive
85
+ example and False marks a negative example. Removed candidates are neutral
86
+ and do not participate in training or evaluation.
87
+
88
+ The returned tensors remain on the input index_tuples device. Retained
89
+ candidates preserve their original order.
90
+ """
91
+
92
+ @abstractmethod
93
+ def check_label_and_order(self, label: str, order: tuple[int, ...]) -> None:
94
+ """
95
+ Raises a *ValueError* if this truther implementation cannot process this label/order combination.
96
+ """