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
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
from polyprobe.model import PolyprobeLabelEvaluation
|
|
8
|
+
|
|
9
|
+
from .scorer import Scorer
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ROCAUCScorer(Scorer):
|
|
15
|
+
"""Scores according to ROC-AUC, i.e. the fraction of all positive-negative
|
|
16
|
+
index-tuple pairs for which the model assigns a higher logit to the positive tuple,
|
|
17
|
+
with ties counting as half a correctly ordered pair. Higher ROC-AUC values indicate
|
|
18
|
+
better ranking.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def get_score_label(cls) -> str:
|
|
23
|
+
return "ROC-AUC"
|
|
24
|
+
|
|
25
|
+
def score_label_evaluation_impl(
|
|
26
|
+
self, label_evaluation: PolyprobeLabelEvaluation
|
|
27
|
+
) -> None:
|
|
28
|
+
label_evaluation.score = label_evaluation.roc_auc
|
|
@@ -0,0 +1,43 @@
|
|
|
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
|
+
from polyprobe.model import PolyprobeLabelEvaluation
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Scorer(ABC):
|
|
14
|
+
"""A scorer uses one or more evaluation metrics to order
|
|
15
|
+
individual head results or pooled head results.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def format_score(cls, score: float) -> str:
|
|
20
|
+
"""Formats a raw float score as a percentage."""
|
|
21
|
+
return f"{score * 100:.2f}%"
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
@abstractmethod
|
|
25
|
+
def get_score_label(cls) -> str:
|
|
26
|
+
"""Returns a label characterising the score, e.g. 'f1'."""
|
|
27
|
+
|
|
28
|
+
def score_label_evaluation(
|
|
29
|
+
self, label_evaluation: PolyprobeLabelEvaluation
|
|
30
|
+
) -> float:
|
|
31
|
+
"""Assigns a score to a label evaluation and returns it.
|
|
32
|
+
A higher score indicates higher predictive capability.
|
|
33
|
+
"""
|
|
34
|
+
self.score_label_evaluation_impl(label_evaluation)
|
|
35
|
+
return label_evaluation.score
|
|
36
|
+
|
|
37
|
+
@abstractmethod
|
|
38
|
+
def score_label_evaluation_impl(
|
|
39
|
+
self, label_evaluation: PolyprobeLabelEvaluation
|
|
40
|
+
) -> None:
|
|
41
|
+
"""Assigns a score to a label evaluation.
|
|
42
|
+
A higher score indicates higher predictive capability.
|
|
43
|
+
"""
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class TrainingDatasetSourceConfig:
|
|
11
|
+
"""
|
|
12
|
+
Configuration parameters describing the training data.
|
|
13
|
+
|
|
14
|
+
dataset_identifiers: the identifiers of the datasets to use; with Universal Dependency dataset sources, the
|
|
15
|
+
repository names, e.g. ["UD_English-EWT", "UD_Welsh-CCG"]
|
|
16
|
+
labels: the labels for which to train models, e.g. ["nsubj", "obj"].
|
|
17
|
+
dataset_source_name: the name of the dataset source implementation.
|
|
18
|
+
dataset_source_kwargs: a dictionary of named arguments to pass to the class' _init__() method when creating the instance,
|
|
19
|
+
or {} if no init parameters are required.
|
|
20
|
+
num_train_sentences_per_dataset: the number of train sentences to attempt to sample per dataset. Sentences can
|
|
21
|
+
be skipped if there are issues with extracting the data, resulting in a lower number being sampled than specified.
|
|
22
|
+
num_dev_sentences_per_dataset: the number of dev sentences to attempt to sample per dataset. Sentences can
|
|
23
|
+
be skipped if there are issues with extracting the data, resulting in a lower number being sampled than specified.
|
|
24
|
+
num_test_sentences_per_dataset: the number of test sentences to attempt to sample per dataset. Sentences can
|
|
25
|
+
be skipped if there are issues with extracting the data, resulting in a lower number being sampled than specified.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
dataset_identifiers: list[str]
|
|
29
|
+
labels: list[str]
|
|
30
|
+
dataset_source_name: str = "UDDependencyCausalDatasetSource"
|
|
31
|
+
dataset_source_kwargs: dict[str, Any] = field(default_factory=dict)
|
|
32
|
+
num_train_sentences_per_dataset: int = 2000
|
|
33
|
+
num_dev_sentences_per_dataset: int = 500
|
|
34
|
+
num_test_sentences_per_dataset: int = 500
|
|
35
|
+
|
|
36
|
+
def __post_init__(self) -> None:
|
|
37
|
+
if not self.dataset_identifiers:
|
|
38
|
+
raise ValueError("At least one dataset identifier must be specified.")
|
|
39
|
+
if (
|
|
40
|
+
self.num_train_sentences_per_dataset < 1
|
|
41
|
+
or self.num_dev_sentences_per_dataset < 1
|
|
42
|
+
or self.num_test_sentences_per_dataset < 1
|
|
43
|
+
):
|
|
44
|
+
raise ValueError(
|
|
45
|
+
f"Each of train, dev and test must contain at least one sentence, but the caller specified {self.num_train_sentences_per_dataset} train, {self.num_dev_sentences_per_dataset} dev and {self.num_test_sentences_per_dataset} test."
|
|
46
|
+
)
|
|
47
|
+
if not self.labels:
|
|
48
|
+
raise ValueError("At least one label must be specified.")
|
|
49
|
+
|
|
50
|
+
def get_dataset_descriptions(self) -> set[tuple[str, str]]:
|
|
51
|
+
"""
|
|
52
|
+
Returns a set of (dataset source, dataset identifier) tuples
|
|
53
|
+
specifying the configured datasets.
|
|
54
|
+
"""
|
|
55
|
+
return {
|
|
56
|
+
(self.dataset_source_name, dataset_identifier)
|
|
57
|
+
for dataset_identifier in self.dataset_identifiers
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class TrainingConfig:
|
|
63
|
+
"""
|
|
64
|
+
Configuration parameters describing model training.
|
|
65
|
+
|
|
66
|
+
probe_name / probe_component_names / pooler_name / index_tuple_selector_name / scorer_name / truther_name:
|
|
67
|
+
the names of the registered objects to use in training. These objects are used for all label models.
|
|
68
|
+
If it is desired to create a model with label models that use different registered objects,
|
|
69
|
+
train separate models then merge them.
|
|
70
|
+
probe_kwargs / pooler_kwargs / index_tuple_selector_kwargs / scorer_kwargs / truther_kwargs:
|
|
71
|
+
dictionaries of named arguments to pass to the class' __init__() method when creating the instance,
|
|
72
|
+
or {} if no init parameters are required.
|
|
73
|
+
learning_rate: the learning rate.
|
|
74
|
+
weight_decay: the coefficient applied to shrink weights each step.
|
|
75
|
+
max_epochs: the number of epochs after which training ends even if the model has not converged.
|
|
76
|
+
start_layer: the LM layer at which to start probing.
|
|
77
|
+
end_layer: the LM layer at which to end probing.
|
|
78
|
+
evaluate_every_n_epochs: the evaluation frequency.
|
|
79
|
+
max_evaluations_without_improvement: the number of evaluations without improvement after which to stop training a batch.
|
|
80
|
+
min_evaluation_delta: the minimum score delta that counts as an improvement.
|
|
81
|
+
min_pos_labels: the minimum number of positive labels where label model generation is attempted.
|
|
82
|
+
num_heads_to_log: the number of promising heads to log before the label models are generated and evaluated for each label/order tuple.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
probe_name: str = "LinearProbe"
|
|
86
|
+
probe_kwargs: dict[str, Any] = field(default_factory=dict)
|
|
87
|
+
probe_component_names: tuple[str, ...] = (
|
|
88
|
+
"LeftKProbeComponent",
|
|
89
|
+
"RightQProbeComponent",
|
|
90
|
+
"RotQxRotKProbeComponent",
|
|
91
|
+
)
|
|
92
|
+
pooler_name: str = "MeanPooler"
|
|
93
|
+
pooler_kwargs: dict[str, Any] = field(default_factory=dict)
|
|
94
|
+
index_tuple_selector_name: str = "CausalCombinatorialIndexTupleSelector"
|
|
95
|
+
index_tuple_selector_kwargs: dict[str, Any] = field(default_factory=dict)
|
|
96
|
+
truther_name: str = "LastToLastTruther"
|
|
97
|
+
truther_kwargs: dict[str, Any] = field(default_factory=dict)
|
|
98
|
+
scorer_name: str = "AveragePrecisionScorer"
|
|
99
|
+
scorer_kwargs: dict[str, Any] = field(default_factory=dict)
|
|
100
|
+
learning_rate: float = 0.0005
|
|
101
|
+
weight_decay: float = 1e-2
|
|
102
|
+
max_epochs: int = 100000
|
|
103
|
+
start_layer: int = 0
|
|
104
|
+
end_layer: int | None = None
|
|
105
|
+
evaluate_every_n_epochs: int = 1000
|
|
106
|
+
max_evaluations_without_improvement: int = 3
|
|
107
|
+
min_evaluation_delta: float = 1e-5
|
|
108
|
+
min_pos_labels: int = 50
|
|
109
|
+
num_heads_to_log: int = 5
|
|
110
|
+
|
|
111
|
+
def __post_init__(self) -> None:
|
|
112
|
+
if self.learning_rate <= 0.0:
|
|
113
|
+
raise ValueError("learning_rate must be positive.")
|
|
114
|
+
if self.weight_decay < 0.0:
|
|
115
|
+
raise ValueError("weight_decay may not be negative.")
|
|
116
|
+
if self.max_epochs <= 0:
|
|
117
|
+
raise ValueError("max_epochs must be positive.")
|
|
118
|
+
if self.evaluate_every_n_epochs <= 0:
|
|
119
|
+
raise ValueError("evaluate_every_n_epochs must be positive.")
|
|
120
|
+
if self.max_evaluations_without_improvement <= 0:
|
|
121
|
+
raise ValueError("max_evaluations_without_improvement must be positive.")
|
|
122
|
+
if self.min_evaluation_delta <= 0.0:
|
|
123
|
+
raise ValueError("min_evaluation_delta must be positive.")
|
|
124
|
+
if self.min_pos_labels < 0:
|
|
125
|
+
raise ValueError("min_pos_labels may not be negative.")
|
|
126
|
+
if self.num_heads_to_log < 0:
|
|
127
|
+
raise ValueError("num_heads_to_log may not be negative.")
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from random import Random
|
|
7
|
+
from typing import Any, cast
|
|
8
|
+
|
|
9
|
+
from polyprobe.document import DocumentPieceList
|
|
10
|
+
from polyprobe.training.config import TrainingDatasetSourceConfig
|
|
11
|
+
from polyprobe.training.training_data import TrainingDatasetGroup
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DatasetSource(ABC):
|
|
15
|
+
"""
|
|
16
|
+
A dataset source extracts and labels train/dev/test lists of document pieces from a
|
|
17
|
+
gold or silver source. Labels are used as the basis for training and evaluation.
|
|
18
|
+
|
|
19
|
+
Because most silver or gold data points to words, but the LM encodes wordpieces,
|
|
20
|
+
a single label will frequently correspond to multiple LM tokens. In such cases,
|
|
21
|
+
the consecutive range of LM tokens is labelled, and the truther is responsible for
|
|
22
|
+
how each of these tokens is then treated during training and evaluation.
|
|
23
|
+
|
|
24
|
+
Distinct training tokens may map to the same LM token; their associated labels are retained.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self, lm_encoder: "LMEncoder", seed: int, kwargs: dict[str, Any] # type: ignore[name-defined]
|
|
29
|
+
) -> None:
|
|
30
|
+
"""
|
|
31
|
+
lm_encoder: the LM Encoder instance.
|
|
32
|
+
seed: a seed for selecting sentences, assigning them to the train/eval/test split and shuffling the resulting lists.
|
|
33
|
+
kwargs: a dictionary of arguments specific to the dataset source type being instantiated.
|
|
34
|
+
"""
|
|
35
|
+
self.lm_encoder = lm_encoder
|
|
36
|
+
self.seed = seed
|
|
37
|
+
|
|
38
|
+
def get_document_piece_splits(
|
|
39
|
+
self,
|
|
40
|
+
training_dataset_source_config: TrainingDatasetSourceConfig,
|
|
41
|
+
) -> TrainingDatasetGroup:
|
|
42
|
+
"""Returns train, dev and test document piece lists for training sampled from one or more datasets."""
|
|
43
|
+
for dataset_identifier_idx, dataset_identifier in enumerate(
|
|
44
|
+
training_dataset_source_config.dataset_identifiers
|
|
45
|
+
):
|
|
46
|
+
(
|
|
47
|
+
dataset_train_piece_list,
|
|
48
|
+
dataset_dev_piece_list,
|
|
49
|
+
dataset_test_piece_list,
|
|
50
|
+
) = self.get_dataset(
|
|
51
|
+
dataset_identifier,
|
|
52
|
+
training_dataset_source_config.num_train_sentences_per_dataset,
|
|
53
|
+
training_dataset_source_config.num_dev_sentences_per_dataset,
|
|
54
|
+
training_dataset_source_config.num_test_sentences_per_dataset,
|
|
55
|
+
training_dataset_source_config.labels,
|
|
56
|
+
set(),
|
|
57
|
+
)
|
|
58
|
+
if dataset_identifier_idx == 0:
|
|
59
|
+
train_piece_list = cast(DocumentPieceList, dataset_train_piece_list)
|
|
60
|
+
dev_piece_list = cast(DocumentPieceList, dataset_dev_piece_list)
|
|
61
|
+
test_piece_list = cast(DocumentPieceList, dataset_test_piece_list)
|
|
62
|
+
else:
|
|
63
|
+
train_piece_list.merge(
|
|
64
|
+
cast(DocumentPieceList, dataset_train_piece_list)
|
|
65
|
+
)
|
|
66
|
+
dev_piece_list.merge(cast(DocumentPieceList, dataset_dev_piece_list))
|
|
67
|
+
test_piece_list.merge(cast(DocumentPieceList, dataset_test_piece_list))
|
|
68
|
+
|
|
69
|
+
if (
|
|
70
|
+
len(train_piece_list) == 0
|
|
71
|
+
or len(dev_piece_list) == 0
|
|
72
|
+
or len(test_piece_list) == 0
|
|
73
|
+
):
|
|
74
|
+
raise ValueError(
|
|
75
|
+
"Not enough document pieces for the requested train/dev/test split."
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
rng = Random(self.seed)
|
|
79
|
+
train_piece_list.shuffle(rng)
|
|
80
|
+
dev_piece_list.shuffle(rng)
|
|
81
|
+
test_piece_list.shuffle(rng)
|
|
82
|
+
return TrainingDatasetGroup(train_piece_list, dev_piece_list, test_piece_list)
|
|
83
|
+
|
|
84
|
+
def get_test_dataset(
|
|
85
|
+
self,
|
|
86
|
+
dataset_identifier: str,
|
|
87
|
+
num_sentences: int,
|
|
88
|
+
labels: list[str],
|
|
89
|
+
trained_on_dataset_descriptions: set[tuple[str, str]],
|
|
90
|
+
) -> DocumentPieceList:
|
|
91
|
+
"""Returns a document piece list sampled from a given test dataset.
|
|
92
|
+
|
|
93
|
+
num_sentences: the number of sentences for which to attempt sampling.
|
|
94
|
+
trained_on_dataset_descriptions: a set of (dataset source, dataset identifier) tuples
|
|
95
|
+
specifying the datasets on which the model being evaluated was trained.
|
|
96
|
+
"""
|
|
97
|
+
if num_sentences < 1:
|
|
98
|
+
raise ValueError("num_sentences must be a positive integer.")
|
|
99
|
+
_, _, test_dataset = self.get_dataset(
|
|
100
|
+
dataset_identifier,
|
|
101
|
+
0,
|
|
102
|
+
0,
|
|
103
|
+
num_sentences,
|
|
104
|
+
labels,
|
|
105
|
+
trained_on_dataset_descriptions,
|
|
106
|
+
)
|
|
107
|
+
return cast(DocumentPieceList, test_dataset)
|
|
108
|
+
|
|
109
|
+
@abstractmethod
|
|
110
|
+
def get_dataset(
|
|
111
|
+
self,
|
|
112
|
+
dataset_identifier: str,
|
|
113
|
+
num_train_sentences: int,
|
|
114
|
+
num_dev_sentences: int,
|
|
115
|
+
num_test_sentences: int,
|
|
116
|
+
labels: list[str],
|
|
117
|
+
trained_on_dataset_descriptions: set[tuple[str, str]],
|
|
118
|
+
) -> tuple[
|
|
119
|
+
DocumentPieceList | None,
|
|
120
|
+
DocumentPieceList | None,
|
|
121
|
+
DocumentPieceList | None,
|
|
122
|
+
]:
|
|
123
|
+
"""
|
|
124
|
+
Returns a tuple containing whichever of train, dev and test dataset splits are requested, or *None*
|
|
125
|
+
for dataset splits that were not requested.
|
|
126
|
+
|
|
127
|
+
dataset_identifier: an identifier for the dataset.
|
|
128
|
+
num_train_sentences: the number of sentences for which to attempt sampling into the train dataset split,
|
|
129
|
+
or *0* if no train dataset split is required.
|
|
130
|
+
num_dev_sentences: the number of sentences for which to attempt sampling into the dev dataset split,
|
|
131
|
+
or *0* if no dev dataset split is required.
|
|
132
|
+
num_test_sentences: the number of sentences for which to attempt sampling into the test dataset split,
|
|
133
|
+
or *0* if no test dataset split is required.
|
|
134
|
+
labels: the dependency labels to capture.
|
|
135
|
+
trained_on_dataset_descriptions: a set of (dataset source, dataset identifier) tuples
|
|
136
|
+
specifying the datasets on which the model being evaluated was trained. Only
|
|
137
|
+
contains elements when the method is called from *get_test_dataset()*
|
|
138
|
+
Where an implementation derives train/dev/test splits itself, it must
|
|
139
|
+
ensure that sentences that end up one split on one occasion cannot end up
|
|
140
|
+
in another split on another occasion, and raise an exception if this cannot
|
|
141
|
+
be guaranteed.
|
|
142
|
+
"""
|