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.
- polyprobe/__init__.py +8 -0
- polyprobe/activations.py +353 -0
- polyprobe/architecture_encoders/architecture_encoder.py +71 -0
- polyprobe/architecture_encoders/gqa.py +77 -0
- polyprobe/architecture_encoders/opt.py +51 -0
- polyprobe/architecture_encoders/qwen3_5.py +100 -0
- polyprobe/batching.py +133 -0
- polyprobe/config.py +101 -0
- polyprobe/document.py +138 -0
- polyprobe/evaluation.py +945 -0
- polyprobe/index_tuple_selectors/causal_combinatorial.py +49 -0
- polyprobe/index_tuple_selectors/index_tuple_selector.py +23 -0
- polyprobe/inferrer.py +480 -0
- polyprobe/lm_encoder.py +218 -0
- polyprobe/logging_utils.py +82 -0
- polyprobe/manager.py +607 -0
- polyprobe/model.py +342 -0
- polyprobe/poolers/max.py +23 -0
- polyprobe/poolers/mean.py +34 -0
- polyprobe/poolers/passthrough.py +21 -0
- polyprobe/poolers/pooler.py +88 -0
- polyprobe/probe_components/index_pair.py +368 -0
- polyprobe/probe_components/probe_component.py +92 -0
- polyprobe/probes/linear.py +46 -0
- polyprobe/probes/neural.py +220 -0
- polyprobe/probes/probe.py +164 -0
- polyprobe/py.typed +0 -0
- polyprobe/registry.py +248 -0
- polyprobe/scorers/average_precision.py +27 -0
- polyprobe/scorers/f1.py +24 -0
- polyprobe/scorers/roc-auc.py +28 -0
- polyprobe/scorers/scorer.py +43 -0
- polyprobe/training/config.py +127 -0
- polyprobe/training/dataset_sources/dataset_source.py +142 -0
- polyprobe/training/dataset_sources/ud_dependency_dataset_source.py +517 -0
- polyprobe/training/runner.py +951 -0
- polyprobe/training/training_data.py +180 -0
- polyprobe/training/truthers/direct.py +206 -0
- polyprobe/training/truthers/random.py +63 -0
- polyprobe/training/truthers/subword.py +49 -0
- polyprobe/training/truthers/truther.py +96 -0
- polyprobe/util.py +599 -0
- polyprobe-1.0.0.dist-info/METADATA +63 -0
- polyprobe-1.0.0.dist-info/RECORD +48 -0
- polyprobe-1.0.0.dist-info/WHEEL +5 -0
- polyprobe-1.0.0.dist-info/licenses/LICENSE +73 -0
- polyprobe-1.0.0.dist-info/licenses/LICENSE-CC-BY-4.0 +395 -0
- polyprobe-1.0.0.dist-info/top_level.txt +1 -0
polyprobe/model.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
from torch import Tensor
|
|
9
|
+
|
|
10
|
+
DatasetSourceUsage = Literal["train", "dev", "test"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class PolyprobeLabelEvaluation:
|
|
15
|
+
"""The evaluation results of a head or pooled collection of heads.
|
|
16
|
+
|
|
17
|
+
num_index_tuples: the number of index tuples in the groundtruth (positive and negative).
|
|
18
|
+
num_positive_index_tuples: the number of positive index tuples in the groundtruth.
|
|
19
|
+
best_f1: the best f1 result achieved, expressed as a float between 0 and 1.
|
|
20
|
+
precision_at_best_f1: the precision component of the best f1 result achieved, expressed as a float between 0 and 1.
|
|
21
|
+
recall_at_best_f1: the recall component of the best f1 result achieved, expressed as a float between 0 and 1.
|
|
22
|
+
best_f1_rank_fraction: the fraction of all index tuples predicted positive at the threshold where best_f1 is achieved.
|
|
23
|
+
roc_auc: ordering all index tuples by logit, a score expressing the extent to which positive-labelled index tuples score more highly
|
|
24
|
+
or less highly than negative-labelled ones. 1.0 and 0.0 are perfect separations with the positive-labelled index tuples scoring respectively
|
|
25
|
+
higher or lower than the negative-labelled index tuples; a random model would be expected to yield values around 0.5. The score is based
|
|
26
|
+
on the mean fraction of positive-labelled index tuples.
|
|
27
|
+
normalized_median_positive_rank_score: ordering all index tuples by logit, a score expressing the extent to which positive-labelled index tuples score more highly
|
|
28
|
+
or less highly than negative-labelled ones. 1.0 and 0.0 are perfect separations with the positive-labelled index tuples scoring respectively
|
|
29
|
+
higher or lower than the negative-labelled index tuples; a random model would be expected to yield values around slightly above 0.5. The score is based
|
|
30
|
+
on the median rank of positive-labelled index tuples, averaging the two middle ranks when their count is even.
|
|
31
|
+
average_precision: a score summarizing the precision-recall curve. It is the weighted average of precision values achieved as more positive-labelled
|
|
32
|
+
index tuples are retrieved, with each precision weighted by the corresponding increase in recall. 1.0 is perfect, and higher values are better.
|
|
33
|
+
threshold_at_best_f1: the logit value at which the best f1 result is achieved.
|
|
34
|
+
threshold_by_recall_percent: a dictionary from percentage values (all multiples of 5 up to 100) to the logit values where this percentage of the document
|
|
35
|
+
pairs that are positive in the groundtruth emerge with a greater to or equal than logit value.
|
|
36
|
+
rank_fraction_by_recall_percent: a dictionary from percentage values (all multiples of 5 up to 100) to the proportions of all index tuples that have
|
|
37
|
+
to be retrieved to retrieve this proportion of index tuples that are positive in the groundtruth.
|
|
38
|
+
precision_by_recall_percent: a dictionary from percentage values (all multiples of 5 up to 100) to the precisions achieved at the thresholds where
|
|
39
|
+
this proportion of index tuples that are positive in the groundtruth are retrieved.
|
|
40
|
+
head_nums: the number of the head or heads that were evaluated.
|
|
41
|
+
epoch: the epoch at which training stopped, where the evaluation was generated for a single head during training, otherwise -1.
|
|
42
|
+
score: the score assigned to the evaluation, where a higher score indicates better predictive capability. -1.0 indicates that no score has yet been set or that
|
|
43
|
+
the evaluation is not being used in a train/dev context.
|
|
44
|
+
highest_scoring_non_labelled_log_lines: diagnostic examples where non-labelled index tuples received the highest scores.
|
|
45
|
+
lowest_scoring_labelled_log_lines: diagnostic examples where labelled index tuples received the lowest scores.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
num_index_tuples: int
|
|
49
|
+
num_positive_index_tuples: int
|
|
50
|
+
best_f1: float
|
|
51
|
+
precision_at_best_f1: float
|
|
52
|
+
recall_at_best_f1: float
|
|
53
|
+
best_f1_rank_fraction: float
|
|
54
|
+
roc_auc: float
|
|
55
|
+
normalized_median_positive_rank_score: float
|
|
56
|
+
average_precision: float
|
|
57
|
+
threshold_at_best_f1: float
|
|
58
|
+
threshold_by_recall_percent: dict[int, float]
|
|
59
|
+
rank_fraction_by_recall_percent: dict[int, float]
|
|
60
|
+
precision_by_recall_percent: dict[int, float]
|
|
61
|
+
head_nums: list[int] = field(default_factory=list)
|
|
62
|
+
epoch: int = -1
|
|
63
|
+
score: float = -1.0
|
|
64
|
+
highest_scoring_non_labelled_log_lines: list[str] = field(default_factory=list)
|
|
65
|
+
lowest_scoring_labelled_log_lines: list[str] = field(default_factory=list)
|
|
66
|
+
|
|
67
|
+
def get_short_repr(self) -> str:
|
|
68
|
+
return f"AP: {self.average_precision * 100:.2f}%; ROC-AUC: {self.roc_auc:.4f}; best f1: {self.best_f1 * 100:.2f}%"
|
|
69
|
+
|
|
70
|
+
def get_overall_stats_log_lines(self, log_recall_percent_stats: bool) -> list[str]:
|
|
71
|
+
"""
|
|
72
|
+
log_recall_percent_stats: *True* if detailed stats on the rank fraction and precision at each available recall percent value are required, otherwise *False*.
|
|
73
|
+
"""
|
|
74
|
+
log_lines: list[str] = []
|
|
75
|
+
log_lines.append(
|
|
76
|
+
f"Best f1: {self.best_f1 * 100:.2f}%; precision at best f1: {self.precision_at_best_f1 * 100:.2f}%; recall at best f1: {self.recall_at_best_f1 * 100:.2f}%; rank fraction at best f1: {self.best_f1_rank_fraction * 100:.2f}%"
|
|
77
|
+
)
|
|
78
|
+
log_lines.append(
|
|
79
|
+
f"Average precision: {self.average_precision * 100:.2f}%; ROC-AUC: {self.roc_auc:.4f}; normalized median positive rank score: {self.normalized_median_positive_rank_score:.4f}; num positive index tuples: {self.num_positive_index_tuples}; positive prevalence: {self.positive_prevalence * 100:.2f}%"
|
|
80
|
+
)
|
|
81
|
+
if log_recall_percent_stats:
|
|
82
|
+
log_lines.append(
|
|
83
|
+
f'Rank fractions at recall percentages: {"; ".join(f"{r}%: {100 * rf:6.2f}%" for r, rf in self.rank_fraction_by_recall_percent.items())}'
|
|
84
|
+
)
|
|
85
|
+
log_lines.append(
|
|
86
|
+
f'Precisions at recall percentages: {"; ".join(f"{r}%: {100 * p:6.2f}%" for r, p in self.precision_by_recall_percent.items())}'
|
|
87
|
+
)
|
|
88
|
+
return log_lines
|
|
89
|
+
|
|
90
|
+
def get_stats_log_line_for_recall_threshold(self, recall_percent: int) -> str:
|
|
91
|
+
"""Returns the most important statistics for a specific threshold specified by the caller.
|
|
92
|
+
|
|
93
|
+
recall_percent: an integer multiple of 5 between 5 and 100.
|
|
94
|
+
"""
|
|
95
|
+
if recall_percent not in self.threshold_by_recall_percent:
|
|
96
|
+
raise ValueError(
|
|
97
|
+
f"There is no threshold for recall percent {recall_percent}. There are available thresholds for recall percent values {self.threshold_by_recall_percent.keys()}"
|
|
98
|
+
)
|
|
99
|
+
precision = self.precision_by_recall_percent[recall_percent]
|
|
100
|
+
return f"specified recall threshold: {recall_percent}%; evaluated precision: {precision * 100:.2f}%; num positive index tuples: {self.num_positive_index_tuples}; positive prevalence: {self.positive_prevalence * 100:.2f}%"
|
|
101
|
+
|
|
102
|
+
def to_dict(self) -> dict[str, Any]:
|
|
103
|
+
return asdict(self)
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def from_dict(cls, data: dict[str, Any]) -> "PolyprobeLabelEvaluation":
|
|
107
|
+
return cls(
|
|
108
|
+
num_index_tuples=data["num_index_tuples"],
|
|
109
|
+
num_positive_index_tuples=data["num_positive_index_tuples"],
|
|
110
|
+
best_f1=data["best_f1"],
|
|
111
|
+
precision_at_best_f1=data["precision_at_best_f1"],
|
|
112
|
+
recall_at_best_f1=data["recall_at_best_f1"],
|
|
113
|
+
best_f1_rank_fraction=data["best_f1_rank_fraction"],
|
|
114
|
+
roc_auc=data["roc_auc"],
|
|
115
|
+
normalized_median_positive_rank_score=data[
|
|
116
|
+
"normalized_median_positive_rank_score"
|
|
117
|
+
],
|
|
118
|
+
average_precision=data["average_precision"],
|
|
119
|
+
threshold_at_best_f1=data["threshold_at_best_f1"],
|
|
120
|
+
threshold_by_recall_percent=data["threshold_by_recall_percent"],
|
|
121
|
+
rank_fraction_by_recall_percent=data["rank_fraction_by_recall_percent"],
|
|
122
|
+
precision_by_recall_percent=data["precision_by_recall_percent"],
|
|
123
|
+
head_nums=data["head_nums"],
|
|
124
|
+
epoch=data["epoch"],
|
|
125
|
+
score=data["score"],
|
|
126
|
+
highest_scoring_non_labelled_log_lines=data[
|
|
127
|
+
"highest_scoring_non_labelled_log_lines"
|
|
128
|
+
],
|
|
129
|
+
lowest_scoring_labelled_log_lines=data["lowest_scoring_labelled_log_lines"],
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def head_num(self) -> int:
|
|
134
|
+
if len(self.head_nums) != 1:
|
|
135
|
+
raise ValueError(
|
|
136
|
+
"head_num() may only be called where an evaluation declares a single head number, "
|
|
137
|
+
"which is normally when it refers to a single head result rather than a pooled result."
|
|
138
|
+
)
|
|
139
|
+
return self.head_nums[0]
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def positive_prevalence(self) -> float:
|
|
143
|
+
return self.num_positive_index_tuples / self.num_index_tuples
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass
|
|
147
|
+
class PolyprobeLabelModel:
|
|
148
|
+
"""
|
|
149
|
+
A model for a single label/order combination.
|
|
150
|
+
|
|
151
|
+
label: the found label
|
|
152
|
+
order: specifies the direction of the labelled relationship with
|
|
153
|
+
respect to training_token_idxs, e.g. order (0, 1) with training_token_idxs
|
|
154
|
+
(4, 6) means that index 4 points to index 6; order (1, 0) with
|
|
155
|
+
training_token_idxs (4, 6) means that index 6 points to index 4.
|
|
156
|
+
probe_name, probe_component_names, pooler_name, index_tuple_selector_name,
|
|
157
|
+
scorer_name, truther_name: the names of the registered objects to use. If any of
|
|
158
|
+
these objects are external (code registered outside the library and used when the
|
|
159
|
+
model was trained), they must be re-registered to enable inference.
|
|
160
|
+
probe_kwargs, pooler_kwargs, index_tuple_selector_kwargs,
|
|
161
|
+
scorer_kwargs, truther_kwargs:
|
|
162
|
+
dictionaries of initialization parameters for the objects.
|
|
163
|
+
head_nums: the indices of the heads to whose values to apply *weights*, corresponding
|
|
164
|
+
to *EncodedDocument.head_infos()* and *PolyprobeModel.head_infos()*, in descending
|
|
165
|
+
order by the scores obtained with the dev dataset.
|
|
166
|
+
weights: the model weights, whose semantics depend on the probe components.
|
|
167
|
+
trained_on_dataset_descriptions: a set of (dataset source, dataset identifier) tuples
|
|
168
|
+
specifying the training datasets. Used to prevent a situation where
|
|
169
|
+
train/dev/test splits are derived ad-hoc from a dataset source that does not
|
|
170
|
+
have all three splits once at training time and then again during a later evaluation,
|
|
171
|
+
which could lead to test data becoming polluted with train or dev data. Some older
|
|
172
|
+
persisted models lack this field, but none of them were trained with datasets that are
|
|
173
|
+
affected by the issue.
|
|
174
|
+
num_head_results_to_pool: the number of heads from the beginning of head_nums/weights
|
|
175
|
+
that yielded the best score with the dev dataset when their results were pooled
|
|
176
|
+
using pooler_name with pooler_kwargs, or 0 where the optimal number has not yet
|
|
177
|
+
been established.
|
|
178
|
+
unpooled_evaluation_scores: a dictionary from dataset split names to the scores achieved at
|
|
179
|
+
individual heads; index-matched to head_nums.
|
|
180
|
+
pooled_evaluation_scores: a dictionary from dataset split names to scores achieved by pooling
|
|
181
|
+
the logits returned at the first n heads; index-matched to head nums.
|
|
182
|
+
num_positive_index_tuples: a dictionary from dataset split names to the number of positively
|
|
183
|
+
labelled index tuples in each.
|
|
184
|
+
positive_prevalences: a dictionary from dataset split names to the proportion of positively
|
|
185
|
+
labelled index tuples in each.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
label: str
|
|
189
|
+
order: tuple[int, ...]
|
|
190
|
+
probe_name: str
|
|
191
|
+
probe_kwargs: dict[str, Any]
|
|
192
|
+
probe_component_names: list[str]
|
|
193
|
+
pooler_name: str
|
|
194
|
+
pooler_kwargs: dict[str, Any]
|
|
195
|
+
index_tuple_selector_name: str
|
|
196
|
+
index_tuple_selector_kwargs: dict[str, Any]
|
|
197
|
+
scorer_name: str
|
|
198
|
+
scorer_kwargs: dict[str, Any]
|
|
199
|
+
truther_name: str
|
|
200
|
+
truther_kwargs: dict[str, Any]
|
|
201
|
+
head_nums: list[int]
|
|
202
|
+
weights: Tensor
|
|
203
|
+
trained_on_dataset_descriptions: set[tuple[str, str]]
|
|
204
|
+
test_evaluation: PolyprobeLabelEvaluation
|
|
205
|
+
num_head_results_to_pool: int = 0
|
|
206
|
+
unpooled_evaluation_scores: dict[DatasetSourceUsage, list[float]] = field(
|
|
207
|
+
default_factory=dict
|
|
208
|
+
)
|
|
209
|
+
pooled_evaluation_scores: dict[DatasetSourceUsage, list[float]] = field(
|
|
210
|
+
default_factory=dict
|
|
211
|
+
)
|
|
212
|
+
num_positive_index_tuples: dict[DatasetSourceUsage, int] = field(
|
|
213
|
+
default_factory=dict
|
|
214
|
+
)
|
|
215
|
+
positive_prevalences: dict[DatasetSourceUsage, float] = field(default_factory=dict)
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def num_heads(self) -> int:
|
|
219
|
+
return len(self.head_nums)
|
|
220
|
+
|
|
221
|
+
def to_dict(self) -> dict[str, Any]:
|
|
222
|
+
return {
|
|
223
|
+
"label": self.label,
|
|
224
|
+
"order": self.order,
|
|
225
|
+
"probe_name": self.probe_name,
|
|
226
|
+
"probe_kwargs": self.probe_kwargs,
|
|
227
|
+
"probe_component_names": self.probe_component_names,
|
|
228
|
+
"pooler_name": self.pooler_name,
|
|
229
|
+
"pooler_kwargs": self.pooler_kwargs,
|
|
230
|
+
"index_tuple_selector_name": self.index_tuple_selector_name,
|
|
231
|
+
"index_tuple_selector_kwargs": self.index_tuple_selector_kwargs,
|
|
232
|
+
"scorer_name": self.scorer_name,
|
|
233
|
+
"scorer_kwargs": self.scorer_kwargs,
|
|
234
|
+
"truther_name": self.truther_name,
|
|
235
|
+
"truther_kwargs": self.truther_kwargs,
|
|
236
|
+
"head_nums": self.head_nums,
|
|
237
|
+
"weights": self.weights,
|
|
238
|
+
"trained_on_dataset_descriptions": self.trained_on_dataset_descriptions,
|
|
239
|
+
"num_head_results_to_pool": self.num_head_results_to_pool,
|
|
240
|
+
"unpooled_evaluation_scores": self.unpooled_evaluation_scores,
|
|
241
|
+
"pooled_evaluation_scores": self.pooled_evaluation_scores,
|
|
242
|
+
"num_positive_index_tuples": self.num_positive_index_tuples,
|
|
243
|
+
"positive_prevalences": self.positive_prevalences,
|
|
244
|
+
"test_evaluation": self.test_evaluation.to_dict(),
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
@classmethod
|
|
248
|
+
def from_dict(cls, data: dict[str, Any]) -> "PolyprobeLabelModel":
|
|
249
|
+
|
|
250
|
+
return cls(
|
|
251
|
+
label=data["label"],
|
|
252
|
+
order=data["order"],
|
|
253
|
+
probe_name=data["probe_name"],
|
|
254
|
+
probe_kwargs=data["probe_kwargs"],
|
|
255
|
+
probe_component_names=data["probe_component_names"],
|
|
256
|
+
pooler_name=data["pooler_name"],
|
|
257
|
+
pooler_kwargs=data["pooler_kwargs"],
|
|
258
|
+
index_tuple_selector_name=data["index_tuple_selector_name"],
|
|
259
|
+
index_tuple_selector_kwargs=data["index_tuple_selector_kwargs"],
|
|
260
|
+
scorer_name=data["scorer_name"],
|
|
261
|
+
scorer_kwargs=data["scorer_kwargs"],
|
|
262
|
+
truther_name=data["truther_name"],
|
|
263
|
+
truther_kwargs=data["truther_kwargs"],
|
|
264
|
+
head_nums=data["head_nums"],
|
|
265
|
+
weights=data["weights"],
|
|
266
|
+
trained_on_dataset_descriptions=data.get(
|
|
267
|
+
"trained_on_dataset_descriptions", set()
|
|
268
|
+
),
|
|
269
|
+
num_head_results_to_pool=data["num_head_results_to_pool"],
|
|
270
|
+
unpooled_evaluation_scores=data["unpooled_evaluation_scores"],
|
|
271
|
+
pooled_evaluation_scores=data["pooled_evaluation_scores"],
|
|
272
|
+
num_positive_index_tuples=data["num_positive_index_tuples"],
|
|
273
|
+
positive_prevalences=data["positive_prevalences"],
|
|
274
|
+
test_evaluation=PolyprobeLabelEvaluation.from_dict(data["test_evaluation"]),
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
def get_stop_at_layer(
|
|
278
|
+
self, head_infos: list[tuple[int, int]], stop_at_num_head_results_to_pool: bool
|
|
279
|
+
) -> int:
|
|
280
|
+
"""Returns the number of layers that need to be encoded to service this label model."""
|
|
281
|
+
head_nums = self.head_nums
|
|
282
|
+
if stop_at_num_head_results_to_pool and self.num_head_results_to_pool > 0:
|
|
283
|
+
head_nums = head_nums[: self.num_head_results_to_pool]
|
|
284
|
+
return head_infos[max(head_nums)][0] + 1
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@dataclass
|
|
288
|
+
class PolyprobeModel:
|
|
289
|
+
"""
|
|
290
|
+
A model loadable by the library, containing one or more label models.
|
|
291
|
+
|
|
292
|
+
lm_name: the Hugging Face name of the LM, e.g. "Qwen/Qwen3-4B".
|
|
293
|
+
head_infos: a list of (<layer no>, <head no>) tuples describing the head at each head index.
|
|
294
|
+
In architectures where not all layers are attention layers, not every layer
|
|
295
|
+
will have entries in the list.
|
|
296
|
+
label_models: the label models.
|
|
297
|
+
description: an optional textual description supplied by the user at training time.
|
|
298
|
+
"""
|
|
299
|
+
|
|
300
|
+
lm_name: str
|
|
301
|
+
head_infos: list[tuple[int, int]]
|
|
302
|
+
label_models: list[PolyprobeLabelModel]
|
|
303
|
+
description: str | None
|
|
304
|
+
|
|
305
|
+
def to_dict(self) -> dict[str, Any]:
|
|
306
|
+
return {
|
|
307
|
+
"lm_name": self.lm_name,
|
|
308
|
+
"head_infos": self.head_infos,
|
|
309
|
+
"label_models": [
|
|
310
|
+
label_model.to_dict() for label_model in self.label_models
|
|
311
|
+
],
|
|
312
|
+
"description": self.description,
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
@property
|
|
316
|
+
def min_stop_at_layer(self) -> int:
|
|
317
|
+
"""
|
|
318
|
+
min_stop_at_layer: the minimum number of layers over which a document must be encoded
|
|
319
|
+
for this model to carry out inference on it.
|
|
320
|
+
"""
|
|
321
|
+
return max(
|
|
322
|
+
label_model.get_stop_at_layer(self.head_infos, True)
|
|
323
|
+
for label_model in self.label_models
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
@classmethod
|
|
327
|
+
def from_dict(cls, data: dict[str, Any]) -> "PolyprobeModel":
|
|
328
|
+
return cls(
|
|
329
|
+
lm_name=data["lm_name"],
|
|
330
|
+
head_infos=data["head_infos"],
|
|
331
|
+
label_models=[
|
|
332
|
+
PolyprobeLabelModel.from_dict(label_model_data)
|
|
333
|
+
for label_model_data in data["label_models"]
|
|
334
|
+
],
|
|
335
|
+
description=data["description"],
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
@property
|
|
339
|
+
def pooler_name(self) -> str:
|
|
340
|
+
if len(self.label_models) < 1:
|
|
341
|
+
raise ValueError("Model does not contain any label models.")
|
|
342
|
+
return self.label_models[0].pooler_name
|
polyprobe/poolers/max.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
from torch import Tensor
|
|
8
|
+
|
|
9
|
+
from .pooler import Pooler
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MaxPooler(Pooler):
|
|
15
|
+
"""Returns the maximum logit from each list of probe results generated at
|
|
16
|
+
different heads during processing of the same index tuple.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def reduce_impl(self, logits: Tensor, num_head_results: int) -> Tensor:
|
|
20
|
+
return logits[:num_head_results, :].amax(dim=0)
|
|
21
|
+
|
|
22
|
+
def reduce_all_prefixes_impl(self, logits: Tensor) -> Tensor:
|
|
23
|
+
return logits.cummax(dim=0).values
|
|
@@ -0,0 +1,34 @@
|
|
|
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 .pooler import Pooler
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MeanPooler(Pooler):
|
|
16
|
+
"""Returns the mean logit from each list of probe results generated at
|
|
17
|
+
different heads during processing of the same index tuple.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def reduce_impl(self, logits: Tensor, num_head_results: int) -> Tensor:
|
|
21
|
+
return logits[:num_head_results, :].mean(dim=0)
|
|
22
|
+
|
|
23
|
+
def reduce_all_prefixes_impl(
|
|
24
|
+
self,
|
|
25
|
+
logits: Tensor,
|
|
26
|
+
) -> Tensor:
|
|
27
|
+
divisors = torch.arange(
|
|
28
|
+
1,
|
|
29
|
+
logits.shape[0] + 1,
|
|
30
|
+
device=logits.device,
|
|
31
|
+
dtype=logits.dtype,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return logits.cumsum(dim=0) / divisors[:, None]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
from torch import Tensor
|
|
8
|
+
|
|
9
|
+
from .pooler import Pooler
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PassthroughPooler(Pooler):
|
|
15
|
+
"""The pooler implementation that is used where pooling is not required."""
|
|
16
|
+
|
|
17
|
+
def get_max_num_head_results(self) -> int:
|
|
18
|
+
return 1
|
|
19
|
+
|
|
20
|
+
def reduce_impl(self, logits: Tensor, num_head_results: int) -> Tensor:
|
|
21
|
+
return logits[0]
|
|
@@ -0,0 +1,88 @@
|
|
|
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
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Pooler(ABC):
|
|
15
|
+
"""A pooler combines the logits from probes at one or more heads. The *PassthroughPooler*
|
|
16
|
+
implementation returns the first head when a single head is requested.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def get_max_num_head_results(self) -> int | None:
|
|
20
|
+
"""
|
|
21
|
+
If an implementation is not able to pool all numbers of head results, it should
|
|
22
|
+
override this method and return the maximum number.
|
|
23
|
+
"""
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
def _validate_logits(self, logits: Tensor) -> None:
|
|
27
|
+
logits_dim = len(logits.shape)
|
|
28
|
+
if logits_dim != 2:
|
|
29
|
+
raise ValueError(
|
|
30
|
+
f"Poolers expect a 2D logit tensor, but the input was {logits_dim}D."
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def reduce(self, logits: Tensor, num_head_results: int) -> Tensor:
|
|
34
|
+
self._validate_logits(logits)
|
|
35
|
+
max_num_head_results = self.get_max_num_head_results()
|
|
36
|
+
if max_num_head_results is not None and max_num_head_results < num_head_results:
|
|
37
|
+
raise ValueError(
|
|
38
|
+
f"num_head_results=={num_head_results}, but the pooler {type(self).__name__} "
|
|
39
|
+
f"can pool a maximum of {max_num_head_results} head results."
|
|
40
|
+
)
|
|
41
|
+
if num_head_results > logits.shape[0]:
|
|
42
|
+
raise ValueError(
|
|
43
|
+
f"num_head_results=={num_head_results}, but there are only {logits.shape[0]} "
|
|
44
|
+
"head results to pool."
|
|
45
|
+
)
|
|
46
|
+
elif num_head_results < 1:
|
|
47
|
+
raise ValueError(
|
|
48
|
+
f"num_head_results=={num_head_results}, but must be a positive integer."
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
return self.reduce_impl(logits, num_head_results)
|
|
52
|
+
|
|
53
|
+
@abstractmethod
|
|
54
|
+
def reduce_impl(self, logits: Tensor, num_head_results: int) -> Tensor:
|
|
55
|
+
"""Reduce the first num_head_results rows of logits to one value per candidate."""
|
|
56
|
+
|
|
57
|
+
def reduce_all_prefixes(self, logits: Tensor) -> Tensor:
|
|
58
|
+
self._validate_logits(logits)
|
|
59
|
+
return self.reduce_all_prefixes_impl(logits)
|
|
60
|
+
|
|
61
|
+
def reduce_all_prefixes_impl(self, logits: Tensor) -> Tensor:
|
|
62
|
+
"""
|
|
63
|
+
Pool logits over every non-empty prefix of heads.
|
|
64
|
+
|
|
65
|
+
For an input whose first dimension indexes heads, returns the pooled
|
|
66
|
+
logits obtained from the first head, the first two heads, and so on up
|
|
67
|
+
to all heads. The first dimension of the returned tensor therefore
|
|
68
|
+
indexes the number of heads pooled.
|
|
69
|
+
|
|
70
|
+
Subclasses may override this method with a more efficient implementation.
|
|
71
|
+
The default implementation calls *reduce()* repeatedly.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
logits: Per-head logits, with heads along the first dimension.
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
A tensor whose first dimension has size ``logits.shape[0]``, where
|
|
78
|
+
element ``i`` contains the result of pooling the first ``i + 1`` heads.
|
|
79
|
+
"""
|
|
80
|
+
max_num_head_results = self.get_max_num_head_results()
|
|
81
|
+
if max_num_head_results:
|
|
82
|
+
logits = logits[:max_num_head_results, :]
|
|
83
|
+
return torch.stack(
|
|
84
|
+
[
|
|
85
|
+
self.reduce(logits, num_head_results)
|
|
86
|
+
for num_head_results in range(1, logits.shape[0] + 1)
|
|
87
|
+
]
|
|
88
|
+
)
|