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/manager.py
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import cast
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
from torch import Tensor
|
|
11
|
+
|
|
12
|
+
from polyprobe.architecture_encoders.architecture_encoder import ArchitectureEncoder
|
|
13
|
+
from polyprobe.config import EvaluationDatasetSourceConfig, RunConfig
|
|
14
|
+
from polyprobe.evaluation import LabelEvaluator
|
|
15
|
+
from polyprobe.inferrer import PolyprobeInferrer
|
|
16
|
+
from polyprobe.lm_encoder import LMEncoder
|
|
17
|
+
from polyprobe.logging_utils import setup_console_logging
|
|
18
|
+
from polyprobe.model import PolyprobeModel
|
|
19
|
+
from polyprobe.registry import PolyprobeRegistry
|
|
20
|
+
from polyprobe.training.config import TrainingConfig, TrainingDatasetSourceConfig
|
|
21
|
+
from polyprobe.training.runner import PolyprobeTrainingRunner
|
|
22
|
+
from polyprobe.util import (
|
|
23
|
+
DatasetEvaluationWithLabelModel,
|
|
24
|
+
check_matplotlib_installed,
|
|
25
|
+
empty_cache,
|
|
26
|
+
get_device,
|
|
27
|
+
get_label_model_description_log_lines,
|
|
28
|
+
get_maximum_tensor_mebibytes,
|
|
29
|
+
is_out_of_memory_error,
|
|
30
|
+
plot_label_model_evaluation_curves,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PolyprobeManager:
|
|
37
|
+
"""
|
|
38
|
+
The facade class for Polyprobe training and inference.
|
|
39
|
+
|
|
40
|
+
Documents are identified and manipulated by user-assigned tags. The labelling command select lists of documents via tag prefix,
|
|
41
|
+
so it is important to structure the tag namespace in a conscious fashion: for example, if a document is assigned the tag "mydoc"
|
|
42
|
+
and there are other documents assigned the tags "mydoc1" and "mydoc2", it will not be possible to specify labelling
|
|
43
|
+
"mydoc" without also specifying "mydoc1" and "mydoc2".
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
lm_name: str,
|
|
49
|
+
*,
|
|
50
|
+
device: torch.device | str | None = None,
|
|
51
|
+
console_log_level: int = logging.INFO,
|
|
52
|
+
architecture_encoder_types: set[type[ArchitectureEncoder]] | None = None,
|
|
53
|
+
architectures_to_architecture_encoder_names: dict[str, str] | None = None,
|
|
54
|
+
) -> None:
|
|
55
|
+
"""
|
|
56
|
+
lm_name: the HuggingFace name of the LM, e.g. "Qwen/Qwen3-4B".
|
|
57
|
+
console_log_level: the log level for console output.
|
|
58
|
+
(The log-file log level is determined when the logging_to_file() context manager is called.)
|
|
59
|
+
architecture_encoder_types: a set of architecture encoder implementations to register before the
|
|
60
|
+
language model is loaded.
|
|
61
|
+
architectures_to_architecture_encoder_names: a dictionary containing the required mappings, or *None* to use the default dictionary.
|
|
62
|
+
Must be set if *architecture_encoder_types* contains one or more classes.
|
|
63
|
+
"""
|
|
64
|
+
setup_console_logging(level=console_log_level)
|
|
65
|
+
if (
|
|
66
|
+
architecture_encoder_types
|
|
67
|
+
and architectures_to_architecture_encoder_names is None
|
|
68
|
+
):
|
|
69
|
+
raise ValueError(
|
|
70
|
+
"architectures_to_architecture_encoder_names is required when architecture_encoder_types is specified."
|
|
71
|
+
)
|
|
72
|
+
if device and isinstance(device, str):
|
|
73
|
+
device = torch.device(device)
|
|
74
|
+
self.device = device if device else get_device()
|
|
75
|
+
self.registry = PolyprobeRegistry()
|
|
76
|
+
if architecture_encoder_types:
|
|
77
|
+
for architecture_encoder_type in architecture_encoder_types:
|
|
78
|
+
self.registry.register(architecture_encoder_type)
|
|
79
|
+
self.lm_name = lm_name
|
|
80
|
+
self.model: PolyprobeModel | None = None
|
|
81
|
+
self.lm_encoder = LMEncoder(
|
|
82
|
+
self.registry,
|
|
83
|
+
self.lm_name,
|
|
84
|
+
self.device,
|
|
85
|
+
architectures_to_architecture_encoder_names,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def set_model(self, model: PolyprobeModel) -> PolyprobeModel:
|
|
89
|
+
"""
|
|
90
|
+
Sets the current model on this object. It must be based on the same LM as this object,
|
|
91
|
+
otherwise a new Manager instance must be created.
|
|
92
|
+
"""
|
|
93
|
+
self._check_same_lm(model.lm_name)
|
|
94
|
+
self.model = model
|
|
95
|
+
logger.info("Set model on manager.")
|
|
96
|
+
return self.model
|
|
97
|
+
|
|
98
|
+
def merge_model(self, second_model: PolyprobeModel) -> PolyprobeModel:
|
|
99
|
+
"""
|
|
100
|
+
Merges a second model into the current model on this object. The two models must be
|
|
101
|
+
based on the same LM and may not have any label models with the same labels and orders.
|
|
102
|
+
The description of the current model remains unchanged.
|
|
103
|
+
"""
|
|
104
|
+
if self.model is None:
|
|
105
|
+
raise ValueError("There is no loaded model to merge into.")
|
|
106
|
+
self._check_same_lm(second_model.lm_name)
|
|
107
|
+
existing_labels_and_orders = {
|
|
108
|
+
(lm.label, lm.order) for lm in self.model.label_models
|
|
109
|
+
}
|
|
110
|
+
new_labels_and_orders = {
|
|
111
|
+
(lm.label, lm.order) for lm in second_model.label_models
|
|
112
|
+
}
|
|
113
|
+
common_labels_and_orders = set.intersection(
|
|
114
|
+
existing_labels_and_orders, new_labels_and_orders
|
|
115
|
+
)
|
|
116
|
+
if len(common_labels_and_orders) > 0:
|
|
117
|
+
raise ValueError(
|
|
118
|
+
f"The two models cannot be merged because they have the following labels/orders in common: {common_labels_and_orders}"
|
|
119
|
+
)
|
|
120
|
+
head_infos = (
|
|
121
|
+
second_model.head_infos
|
|
122
|
+
if len(second_model.head_infos) > len(self.model.head_infos)
|
|
123
|
+
else self.model.head_infos
|
|
124
|
+
)
|
|
125
|
+
label_models = [*self.model.label_models, *second_model.label_models]
|
|
126
|
+
self.model = PolyprobeModel(
|
|
127
|
+
self.model.lm_name, head_infos, label_models, self.model.description
|
|
128
|
+
)
|
|
129
|
+
logger.info("Merged models.")
|
|
130
|
+
return self.model
|
|
131
|
+
|
|
132
|
+
def save_model(
|
|
133
|
+
self, filename: Path | str, save_incorrect_examples: bool = True
|
|
134
|
+
) -> None:
|
|
135
|
+
"""
|
|
136
|
+
Saves the current model to a file.
|
|
137
|
+
|
|
138
|
+
save_incorrect_examples: whether or not to save the highest-scoring negative examples and lowest-scoring positive examples alongside evaluation statistics.
|
|
139
|
+
Should be set to *False* if you intend to share the model and do not own the copyright on the training data.
|
|
140
|
+
"""
|
|
141
|
+
if self.model is None:
|
|
142
|
+
raise ValueError("There is no loaded model to save.")
|
|
143
|
+
model_dict = self.model.to_dict()
|
|
144
|
+
if not save_incorrect_examples:
|
|
145
|
+
for label_model in model_dict["label_models"]:
|
|
146
|
+
evaluation = label_model["test_evaluation"]
|
|
147
|
+
evaluation["highest_scoring_non_labelled_log_lines"] = []
|
|
148
|
+
evaluation["lowest_scoring_labelled_log_lines"] = []
|
|
149
|
+
torch.save(model_dict, filename)
|
|
150
|
+
logger.info(f"Saved model to {filename}")
|
|
151
|
+
|
|
152
|
+
def load_model(self, filename: Path | str, set: bool = True) -> PolyprobeModel:
|
|
153
|
+
"""
|
|
154
|
+
Loads a model from a file and returns it. It must be based on the same LM as this object.
|
|
155
|
+
|
|
156
|
+
set: if *True*, the loaded model is set on this object.
|
|
157
|
+
"""
|
|
158
|
+
data = torch.load(filename, map_location="cpu", weights_only=True)
|
|
159
|
+
self._check_same_lm(data["lm_name"])
|
|
160
|
+
model = PolyprobeModel.from_dict(data)
|
|
161
|
+
logger.info(f"Loaded model from {filename}")
|
|
162
|
+
if set:
|
|
163
|
+
self.set_model(model)
|
|
164
|
+
return model
|
|
165
|
+
|
|
166
|
+
def train(
|
|
167
|
+
self,
|
|
168
|
+
*,
|
|
169
|
+
description: str | None = None,
|
|
170
|
+
temp_dir: Path | str | None = None,
|
|
171
|
+
run_config: RunConfig,
|
|
172
|
+
training_dataset_source_config: TrainingDatasetSourceConfig,
|
|
173
|
+
training_config: TrainingConfig,
|
|
174
|
+
plots_dir: Path | str | None = None,
|
|
175
|
+
) -> PolyprobeModel | None:
|
|
176
|
+
"""
|
|
177
|
+
Trains a new model consisting of label models for whatever label/order combinations have been applied to the specified documents.
|
|
178
|
+
Returns *None* if none of the specified labels occurred sufficiently often
|
|
179
|
+
in the corpus to allow training.
|
|
180
|
+
|
|
181
|
+
description: an optional textual description of the training run to store on the generated models for display at inference time
|
|
182
|
+
and for inclusion in log files.
|
|
183
|
+
temp_dir: the directory to which to write the training and evaluation activations. For best results, this directory should be on an SSD.
|
|
184
|
+
If temp_dir is *None*, the operating-system standard location for temporary files is used.
|
|
185
|
+
run_config: the configuration with parameters shared with the evaluate() method.
|
|
186
|
+
training_dataset_source_config: the configuration describing the training data.
|
|
187
|
+
training_config: the configuration describing model training.
|
|
188
|
+
plots_dir: the directory to which to save evaluation plots, or *None* if none are required. If this parameter is
|
|
189
|
+
set, the matplotlib library must be available in the environment.
|
|
190
|
+
"""
|
|
191
|
+
if plots_dir is not None:
|
|
192
|
+
check_matplotlib_installed()
|
|
193
|
+
if isinstance(plots_dir, str):
|
|
194
|
+
plots_dir = Path(plots_dir)
|
|
195
|
+
maximum_tensor_mebibytes = self._get_maximum_tensor_mebibytes(
|
|
196
|
+
run_config.specified_maximum_tensor_mebibytes
|
|
197
|
+
)
|
|
198
|
+
if description:
|
|
199
|
+
logger.info(f"Training run: {description}")
|
|
200
|
+
else:
|
|
201
|
+
logger.info("Training run")
|
|
202
|
+
end_layer = (
|
|
203
|
+
self.lm_encoder.head_infos[-1][0] + 1
|
|
204
|
+
if training_config.end_layer is None
|
|
205
|
+
else training_config.end_layer
|
|
206
|
+
)
|
|
207
|
+
if temp_dir is not None and isinstance(temp_dir, str):
|
|
208
|
+
temp_dir = Path(temp_dir)
|
|
209
|
+
runner = PolyprobeTrainingRunner(
|
|
210
|
+
description=description,
|
|
211
|
+
temp_dir=temp_dir,
|
|
212
|
+
registry=self.registry,
|
|
213
|
+
lm_encoder=self.lm_encoder,
|
|
214
|
+
run_config=run_config,
|
|
215
|
+
training_config=training_config,
|
|
216
|
+
training_dataset_source_config=training_dataset_source_config,
|
|
217
|
+
plots_dir=plots_dir,
|
|
218
|
+
maximum_tensor_mebibytes=maximum_tensor_mebibytes,
|
|
219
|
+
end_layer=end_layer,
|
|
220
|
+
device=self.device,
|
|
221
|
+
)
|
|
222
|
+
model = runner.train()
|
|
223
|
+
logger.debug("Model training complete")
|
|
224
|
+
if model is None:
|
|
225
|
+
logger.warning("No model was generated.")
|
|
226
|
+
else:
|
|
227
|
+
self.set_model(model)
|
|
228
|
+
return model
|
|
229
|
+
|
|
230
|
+
def plot(self, plots_dir: Path | str, *, description: str | None = None) -> None:
|
|
231
|
+
"""
|
|
232
|
+
Saves evaluation plots for the currently loaded model. If this method is called, the matplotlib library
|
|
233
|
+
must be available in the environment.
|
|
234
|
+
plots_dir: the directory to which to save evaluation plots.
|
|
235
|
+
description: a description to use for the plot titles, or *None* to use the description from the model.
|
|
236
|
+
"""
|
|
237
|
+
if self.model is None:
|
|
238
|
+
raise ValueError("No model has been set on the manager.")
|
|
239
|
+
check_matplotlib_installed()
|
|
240
|
+
if isinstance(plots_dir, str):
|
|
241
|
+
plots_dir = Path(plots_dir)
|
|
242
|
+
if description is None:
|
|
243
|
+
description = self.model.description
|
|
244
|
+
if description is None:
|
|
245
|
+
description = ""
|
|
246
|
+
for label_model in self.model.label_models:
|
|
247
|
+
logger.info(
|
|
248
|
+
f"Plotting curves for label {label_model.label} with order {label_model.order}"
|
|
249
|
+
)
|
|
250
|
+
scorer = self.registry.get_scorer_type(label_model.scorer_name)(
|
|
251
|
+
**label_model.scorer_kwargs
|
|
252
|
+
)
|
|
253
|
+
plot_label_model_evaluation_curves(
|
|
254
|
+
plots_dir,
|
|
255
|
+
label_model,
|
|
256
|
+
self.lm_encoder.head_infos,
|
|
257
|
+
description,
|
|
258
|
+
scorer.get_score_label(),
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def evaluate(
|
|
262
|
+
self,
|
|
263
|
+
*,
|
|
264
|
+
description: str | None = None,
|
|
265
|
+
run_config: RunConfig,
|
|
266
|
+
evaluation_dataset_source_config: EvaluationDatasetSourceConfig,
|
|
267
|
+
plots_dir: Path | str | None = None,
|
|
268
|
+
) -> None:
|
|
269
|
+
"""
|
|
270
|
+
Evaluates a test dataset using the currently loaded model.
|
|
271
|
+
|
|
272
|
+
description: a textual description of the evaluation run to include in log files.
|
|
273
|
+
run_config: the configuration containing parameters shared with the train() method.
|
|
274
|
+
evaluation_dataset_source_config: the configuration containing parameters describing the evaluation data.
|
|
275
|
+
plots_dir: the directory to which to save evaluation plots, or *None* if none are required. If this parameter is
|
|
276
|
+
set, the matplotlib library must be available in the environment.
|
|
277
|
+
"""
|
|
278
|
+
with torch.inference_mode():
|
|
279
|
+
if self.model is None:
|
|
280
|
+
raise ValueError("No model has been set on the manager.")
|
|
281
|
+
for label_model in self.model.label_models:
|
|
282
|
+
if label_model.num_head_results_to_pool < 1:
|
|
283
|
+
raise ValueError(
|
|
284
|
+
f"Cannot evaluate label {label_model.label!r}: "
|
|
285
|
+
f"num_head_results_to_pool must be positive, "
|
|
286
|
+
f"got {label_model.num_head_results_to_pool}."
|
|
287
|
+
)
|
|
288
|
+
maximum_tensor_mebibytes = self._get_maximum_tensor_mebibytes(
|
|
289
|
+
run_config.specified_maximum_tensor_mebibytes
|
|
290
|
+
)
|
|
291
|
+
if description:
|
|
292
|
+
logger.info(f"Evaluation run: {description}")
|
|
293
|
+
else:
|
|
294
|
+
logger.info("Evaluation run")
|
|
295
|
+
if plots_dir is not None:
|
|
296
|
+
check_matplotlib_installed()
|
|
297
|
+
if isinstance(plots_dir, str):
|
|
298
|
+
plots_dir = Path(plots_dir)
|
|
299
|
+
labels = list(
|
|
300
|
+
{label_model.label for label_model in self.model.label_models}
|
|
301
|
+
)
|
|
302
|
+
trained_on_dataset_descriptions = set().union(
|
|
303
|
+
*[
|
|
304
|
+
label_model.trained_on_dataset_descriptions
|
|
305
|
+
for label_model in self.model.label_models
|
|
306
|
+
]
|
|
307
|
+
)
|
|
308
|
+
dataset_source = self.registry.get_dataset_source_type(
|
|
309
|
+
evaluation_dataset_source_config.dataset_source_name
|
|
310
|
+
)(
|
|
311
|
+
self.lm_encoder,
|
|
312
|
+
run_config.seed,
|
|
313
|
+
evaluation_dataset_source_config.dataset_source_kwargs,
|
|
314
|
+
)
|
|
315
|
+
test_piece_lists = [
|
|
316
|
+
dataset_source.get_test_dataset(
|
|
317
|
+
dataset_config.identifier,
|
|
318
|
+
evaluation_dataset_source_config.num_test_sentences,
|
|
319
|
+
labels,
|
|
320
|
+
trained_on_dataset_descriptions,
|
|
321
|
+
)
|
|
322
|
+
for dataset_config in evaluation_dataset_source_config.dataset_configs
|
|
323
|
+
]
|
|
324
|
+
|
|
325
|
+
for label_model in self.model.label_models:
|
|
326
|
+
index_tuple_selector = self.registry.get_index_tuple_selector_type(
|
|
327
|
+
label_model.index_tuple_selector_name
|
|
328
|
+
)(**label_model.index_tuple_selector_kwargs)
|
|
329
|
+
scorer = self.registry.get_scorer_type(label_model.scorer_name)(
|
|
330
|
+
**label_model.scorer_kwargs
|
|
331
|
+
)
|
|
332
|
+
truther = self.registry.get_truther_type(label_model.truther_name)(
|
|
333
|
+
**label_model.truther_kwargs
|
|
334
|
+
)
|
|
335
|
+
truther.check_label_and_order(label_model.label, label_model.order)
|
|
336
|
+
label_evaluator = LabelEvaluator(
|
|
337
|
+
self.registry,
|
|
338
|
+
self.lm_encoder,
|
|
339
|
+
run_config,
|
|
340
|
+
label_model.probe_name,
|
|
341
|
+
label_model.probe_kwargs,
|
|
342
|
+
label_model.probe_component_names,
|
|
343
|
+
maximum_tensor_mebibytes,
|
|
344
|
+
self.device,
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
dataset_evaluations: list[DatasetEvaluationWithLabelModel] = []
|
|
348
|
+
for dataset_config_idx, dataset_config in enumerate(
|
|
349
|
+
evaluation_dataset_source_config.dataset_configs
|
|
350
|
+
):
|
|
351
|
+
logger.info(
|
|
352
|
+
f"Evaluating dataset {dataset_config.label} with label {label_model.label} and order {label_model.order}:"
|
|
353
|
+
)
|
|
354
|
+
index_tuples_list: list[Tensor] = []
|
|
355
|
+
truths_list: list[Tensor] = []
|
|
356
|
+
found = False
|
|
357
|
+
pieces = test_piece_lists[dataset_config_idx].pieces
|
|
358
|
+
for piece in pieces:
|
|
359
|
+
training_labels = piece.get_training_labels(
|
|
360
|
+
label_model.label, label_model.order
|
|
361
|
+
)
|
|
362
|
+
this_piece_index_tuples = index_tuple_selector.get_index_tuples(
|
|
363
|
+
piece, len(label_model.order)
|
|
364
|
+
)
|
|
365
|
+
this_piece_truths, this_piece_index_tuples = truther.get_truths(
|
|
366
|
+
piece, this_piece_index_tuples, training_labels
|
|
367
|
+
)
|
|
368
|
+
this_piece_found = this_piece_truths.sum() > 0
|
|
369
|
+
if this_piece_found:
|
|
370
|
+
found = True
|
|
371
|
+
index_tuples_list.append(this_piece_index_tuples)
|
|
372
|
+
truths_list.append(this_piece_truths)
|
|
373
|
+
if found:
|
|
374
|
+
for log_line in get_label_model_description_log_lines(
|
|
375
|
+
label_model, self.lm_encoder.head_infos
|
|
376
|
+
):
|
|
377
|
+
logger.info(log_line)
|
|
378
|
+
|
|
379
|
+
if plots_dir is not None:
|
|
380
|
+
max_heads_to_pool = min(
|
|
381
|
+
run_config.max_heads_to_pool, label_model.num_heads
|
|
382
|
+
)
|
|
383
|
+
if max_heads_to_pool > label_model.num_head_results_to_pool:
|
|
384
|
+
logger.info(
|
|
385
|
+
f"The first {max_heads_to_pool} heads will be evaluated in order to plot the curves."
|
|
386
|
+
)
|
|
387
|
+
progress_desc = "Evaluating label model"
|
|
388
|
+
label_evaluation = None
|
|
389
|
+
if plots_dir is not None:
|
|
390
|
+
unpooled_evaluations, pooled_evaluations = (
|
|
391
|
+
label_evaluator.evaluate_label_model_across_pooling_prefixes(
|
|
392
|
+
label_model,
|
|
393
|
+
scorer,
|
|
394
|
+
pieces,
|
|
395
|
+
index_tuples_list,
|
|
396
|
+
truths_list,
|
|
397
|
+
run_config.show_progress,
|
|
398
|
+
progress_desc,
|
|
399
|
+
)
|
|
400
|
+
)
|
|
401
|
+
dataset_evaluations.append(
|
|
402
|
+
DatasetEvaluationWithLabelModel(
|
|
403
|
+
dataset_config,
|
|
404
|
+
[e.score for e in unpooled_evaluations],
|
|
405
|
+
[e.score for e in pooled_evaluations],
|
|
406
|
+
pooled_evaluations[0].num_positive_index_tuples,
|
|
407
|
+
pooled_evaluations[0].positive_prevalence,
|
|
408
|
+
)
|
|
409
|
+
)
|
|
410
|
+
selected = label_model.num_head_results_to_pool
|
|
411
|
+
if selected <= len(pooled_evaluations):
|
|
412
|
+
label_evaluation = pooled_evaluations[selected - 1]
|
|
413
|
+
if label_evaluation is None:
|
|
414
|
+
label_evaluation = label_evaluator.evaluate_label_model_at_selected_pooling(
|
|
415
|
+
label_model,
|
|
416
|
+
pieces,
|
|
417
|
+
index_tuples_list,
|
|
418
|
+
truths_list,
|
|
419
|
+
run_config.show_progress,
|
|
420
|
+
progress_desc,
|
|
421
|
+
)
|
|
422
|
+
log_lines = (
|
|
423
|
+
label_evaluator.get_label_model_evaluation_log_lines(
|
|
424
|
+
label_evaluation,
|
|
425
|
+
)
|
|
426
|
+
)
|
|
427
|
+
for log_line in log_lines:
|
|
428
|
+
logger.info(log_line)
|
|
429
|
+
|
|
430
|
+
else:
|
|
431
|
+
logger.info(
|
|
432
|
+
f"No document pieces were found with label {label_model.label} and order {label_model.order}"
|
|
433
|
+
)
|
|
434
|
+
if plots_dir is not None:
|
|
435
|
+
plot_label_model_evaluation_curves(
|
|
436
|
+
plots_dir,
|
|
437
|
+
label_model,
|
|
438
|
+
self.lm_encoder.head_infos,
|
|
439
|
+
description,
|
|
440
|
+
scorer.get_score_label(),
|
|
441
|
+
dataset_evaluations,
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
def inference_console(
|
|
445
|
+
self,
|
|
446
|
+
recall_threshold_overrides: dict[str, int] | None = None,
|
|
447
|
+
*,
|
|
448
|
+
expand_subwords: bool = True,
|
|
449
|
+
merge_adjacent_findings: bool = False,
|
|
450
|
+
max_chars: int = 500,
|
|
451
|
+
) -> None:
|
|
452
|
+
"""
|
|
453
|
+
Opens an interactive console where entered texts are analyzed using the currently loaded model: displays all positions within each text where each label model scores higher
|
|
454
|
+
than a specified percentage recall threshold, merging together contiguous findings such as two tokens within a word that both attend to some other token.
|
|
455
|
+
|
|
456
|
+
recall_threshold_overrides: a dictionary from labels to thresholds. Each specified threshold must be a multiple
|
|
457
|
+
of 5 up to 100; for example, a threshold of 30 means 'the logit above which the top 30% of positive index tuples in
|
|
458
|
+
the test split scored'. For labels for which no threshold is specified, the threshold is used where the best f1
|
|
459
|
+
score was obtained for the test split. These cutoffs determine only which findings are displayed for new sentences
|
|
460
|
+
entered into the inference console; they do not affect probe training, model selection or reported average precision.
|
|
461
|
+
For this purpose, the test split serves as a calibration set for a fourth, independently supplied set of data
|
|
462
|
+
consisting of sentences entered ad hoc by the inference-console user. The dictionary may not specify labels for
|
|
463
|
+
which there are no label models in the model.
|
|
464
|
+
expand_subwords: *True* if subwords in results should be expanded to the words that contain them provided
|
|
465
|
+
that other dimensions do not contain subwords with the same containing word; only has an effect if
|
|
466
|
+
*model* contains a label model with label '_subword'; findings that become identical after expansion are
|
|
467
|
+
deduplicated, retaining the strictest threshold met; *False* if label models with label '_subword' should
|
|
468
|
+
be ignored.
|
|
469
|
+
merge_adjacent_findings: *True* if findings should be merged that are identical in all dimensions except one,
|
|
470
|
+
and adjacent in that dimension; *False* otherwise.
|
|
471
|
+
max_chars: the maximum number of characters accepted as an input sentence: necessary to avoid the process being killed because of
|
|
472
|
+
an OOM.
|
|
473
|
+
"""
|
|
474
|
+
if self.model is None:
|
|
475
|
+
raise ValueError("There is no model loaded.")
|
|
476
|
+
inferrer = PolyprobeInferrer(
|
|
477
|
+
self.registry,
|
|
478
|
+
self.lm_encoder,
|
|
479
|
+
self.model,
|
|
480
|
+
expand_subwords,
|
|
481
|
+
merge_adjacent_findings,
|
|
482
|
+
self.device,
|
|
483
|
+
)
|
|
484
|
+
self._print_model_info(
|
|
485
|
+
recall_threshold_overrides, expand_subwords, merge_adjacent_findings
|
|
486
|
+
)
|
|
487
|
+
print("Enter the text to analyze, or exit() to exit")
|
|
488
|
+
print()
|
|
489
|
+
while True:
|
|
490
|
+
input_text = input()
|
|
491
|
+
if input_text == "exit()":
|
|
492
|
+
break
|
|
493
|
+
if len(input_text) > max_chars:
|
|
494
|
+
print(
|
|
495
|
+
f"Console input is {len(input_text)} characters long; the maximum is {max_chars} characters. "
|
|
496
|
+
"You can alter the maximum via the max_chars parameter when calling console(), "
|
|
497
|
+
"although very long sentences are liable to lead to the process being killed because of memory exhaustion."
|
|
498
|
+
)
|
|
499
|
+
print()
|
|
500
|
+
continue
|
|
501
|
+
try:
|
|
502
|
+
input_text.encode("utf-8", errors="strict")
|
|
503
|
+
except UnicodeEncodeError:
|
|
504
|
+
print(
|
|
505
|
+
"Console input contains invalid Unicode, probably caused by "
|
|
506
|
+
"deleting a multibyte character in the terminal.\nTip: when "
|
|
507
|
+
"you delete an accented character, delete the character before "
|
|
508
|
+
"it as well before continuing typing."
|
|
509
|
+
)
|
|
510
|
+
print()
|
|
511
|
+
continue
|
|
512
|
+
|
|
513
|
+
print()
|
|
514
|
+
piece = self.lm_encoder.create_document_piece(input_text, "")
|
|
515
|
+
with torch.inference_mode():
|
|
516
|
+
try:
|
|
517
|
+
compressed_findings_list = inferrer.analyze(
|
|
518
|
+
piece, recall_threshold_overrides
|
|
519
|
+
)
|
|
520
|
+
except RuntimeError as e:
|
|
521
|
+
if is_out_of_memory_error(e):
|
|
522
|
+
print("Out of memory (probably because sentence was too long).")
|
|
523
|
+
print()
|
|
524
|
+
empty_cache(self.device)
|
|
525
|
+
continue
|
|
526
|
+
else:
|
|
527
|
+
raise
|
|
528
|
+
if len(compressed_findings_list) == 0:
|
|
529
|
+
print("Nothing found")
|
|
530
|
+
else:
|
|
531
|
+
for compressed_finding in compressed_findings_list:
|
|
532
|
+
print(compressed_finding)
|
|
533
|
+
print()
|
|
534
|
+
|
|
535
|
+
def _print_model_info(
|
|
536
|
+
self,
|
|
537
|
+
recall_threshold_overrides: dict[str, int] | None,
|
|
538
|
+
expand_subwords: bool,
|
|
539
|
+
merge_adjacent_findings: bool,
|
|
540
|
+
) -> None:
|
|
541
|
+
model = cast(PolyprobeModel, self.model)
|
|
542
|
+
if model.description is not None:
|
|
543
|
+
print(f"Model description: {model.description}")
|
|
544
|
+
print(
|
|
545
|
+
"Adjacent findings, i.e. findings that are identical in all dimensions but one, and adjacent in that dimension, are "
|
|
546
|
+
+ ("being merged." if merge_adjacent_findings else "NOT being merged.")
|
|
547
|
+
)
|
|
548
|
+
for label_model in model.label_models:
|
|
549
|
+
for log_line in get_label_model_description_log_lines(
|
|
550
|
+
label_model, self.lm_encoder.head_infos
|
|
551
|
+
):
|
|
552
|
+
print(log_line)
|
|
553
|
+
if label_model.label == "_subword":
|
|
554
|
+
if expand_subwords:
|
|
555
|
+
print("Subwords are being expanded to their containing words.")
|
|
556
|
+
else:
|
|
557
|
+
print(
|
|
558
|
+
"Subwords are not being expanded to their containing words, i.e. this model is being ignored."
|
|
559
|
+
)
|
|
560
|
+
if label_model.num_head_results_to_pool != len(
|
|
561
|
+
label_model.test_evaluation.head_nums
|
|
562
|
+
):
|
|
563
|
+
print(
|
|
564
|
+
"Not displaying evaluation statistics as the number of heads being pooled does not correspond to the test evaluation."
|
|
565
|
+
)
|
|
566
|
+
else:
|
|
567
|
+
if (
|
|
568
|
+
recall_threshold_overrides is not None
|
|
569
|
+
and label_model.label in recall_threshold_overrides
|
|
570
|
+
):
|
|
571
|
+
percent_threshold = recall_threshold_overrides[label_model.label]
|
|
572
|
+
else:
|
|
573
|
+
percent_threshold = None
|
|
574
|
+
|
|
575
|
+
if percent_threshold is not None:
|
|
576
|
+
print(
|
|
577
|
+
label_model.test_evaluation.get_stats_log_line_for_recall_threshold(
|
|
578
|
+
percent_threshold
|
|
579
|
+
)
|
|
580
|
+
)
|
|
581
|
+
else:
|
|
582
|
+
for (
|
|
583
|
+
log_line
|
|
584
|
+
) in label_model.test_evaluation.get_overall_stats_log_lines(False):
|
|
585
|
+
print(log_line)
|
|
586
|
+
print()
|
|
587
|
+
|
|
588
|
+
def _check_same_lm(self, loaded_lm_name: str) -> None:
|
|
589
|
+
if self.lm_name != loaded_lm_name:
|
|
590
|
+
raise ValueError(
|
|
591
|
+
f"Manager is for LM {self.lm_name}, but the loaded model is for LM {loaded_lm_name}"
|
|
592
|
+
)
|
|
593
|
+
|
|
594
|
+
def _get_maximum_tensor_mebibytes(
|
|
595
|
+
self, specified_maximum_tensor_mebibytes: int | None
|
|
596
|
+
) -> int:
|
|
597
|
+
if specified_maximum_tensor_mebibytes is not None:
|
|
598
|
+
logger.info(
|
|
599
|
+
f"Maximum tensor memory specified as {specified_maximum_tensor_mebibytes}MiB."
|
|
600
|
+
)
|
|
601
|
+
return specified_maximum_tensor_mebibytes
|
|
602
|
+
else:
|
|
603
|
+
maximum_tensor_mebibytes = get_maximum_tensor_mebibytes(self.device)
|
|
604
|
+
logger.info(
|
|
605
|
+
f"Maximum tensor memory measured as {maximum_tensor_mebibytes}MiB."
|
|
606
|
+
)
|
|
607
|
+
return maximum_tensor_mebibytes
|