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,220 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ import math
7
+ from typing import cast
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch import Tensor, nn
12
+
13
+ from polyprobe.probe_components.probe_component import ProbeComponent
14
+
15
+ logger = logging.getLogger(__name__)
16
+ from .probe import Probe
17
+
18
+
19
+ class DenseFeedForwardProbe(Probe):
20
+ """
21
+ A probe with a configurable number of hidden layers and hidden-layer width.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ components: list[ProbeComponent],
27
+ heads: list[int] | tuple[int, int],
28
+ head_infos: list[tuple[int, int]],
29
+ device: torch.device,
30
+ *,
31
+ weights: Tensor | None = None,
32
+ seed: int | None = None,
33
+ hidden_layer_shape: tuple[int, int],
34
+ ):
35
+ """
36
+ probe_components: the list of probe components providing the input to probe.
37
+ heads: either a list of head indices, or a (start, end) range of head indices which is
38
+ converted to a list of head indices before being copied to *self*.
39
+ head_infos: a list of (<layer no>, <head no>) tuples describing the head at each head index.
40
+ seed: required for reproducibility when weights are initialised within a neural probe during training.
41
+ hidden_layer_shape: a (num_layers, width) tuple.
42
+ """
43
+ super().__init__(
44
+ components, heads, head_infos, device, weights=weights, seed=seed
45
+ )
46
+ if type(hidden_layer_shape) != tuple:
47
+ raise ValueError("hidden_layer_shape must contain positive integers.")
48
+ if len(hidden_layer_shape) != 2:
49
+ raise ValueError("hidden_layer_shape must be a (num_layers, width) tuple.")
50
+ if (
51
+ type(hidden_layer_shape[0]) != int
52
+ or type(hidden_layer_shape[1]) != int
53
+ or hidden_layer_shape[0] < 1
54
+ or hidden_layer_shape[1] < 1
55
+ ):
56
+ raise ValueError("hidden_layer_shape must contain positive integers.")
57
+ self.hidden_layer_shape = hidden_layer_shape
58
+
59
+ def create_weights(self, input_dim: int) -> nn.Parameter:
60
+ num_hidden_layers, hidden_layer_width = self.hidden_layer_shape
61
+
62
+ if self.seed is None:
63
+ raise ValueError(
64
+ "A seed is required when initialising neural-probe weights."
65
+ )
66
+
67
+ torch_rng = torch.Generator(device=self.device)
68
+ torch_rng.manual_seed(self.seed)
69
+
70
+ weights_initial_layer = torch.empty(
71
+ (self.num_heads, hidden_layer_width, input_dim + 1),
72
+ dtype=torch.float32,
73
+ device=self.device,
74
+ )
75
+ weights_intermediate_layers = [
76
+ torch.empty(
77
+ (self.num_heads, hidden_layer_width, hidden_layer_width + 1),
78
+ dtype=torch.float32,
79
+ device=self.device,
80
+ )
81
+ for _ in range(num_hidden_layers - 1)
82
+ ]
83
+ weights_final_layer = torch.empty(
84
+ (self.num_heads, hidden_layer_width + 1),
85
+ dtype=torch.float32,
86
+ device=self.device,
87
+ )
88
+ # PyTorch does not define calculate_gain("gelu"), so we use gain 1.
89
+ first_layer_bound = math.sqrt(6.0 / (input_dim + hidden_layer_width))
90
+ intermediate_layer_bound = math.sqrt(6.0 / (hidden_layer_width * 2))
91
+ final_layer_bound = math.sqrt(6.0 / (hidden_layer_width + 1))
92
+
93
+ # Initial-layer weights
94
+ weights_initial_layer[:, :, :-1].uniform_(
95
+ -first_layer_bound,
96
+ first_layer_bound,
97
+ generator=torch_rng,
98
+ )
99
+ # Initial-layer biases
100
+ weights_initial_layer[:, :, -1].zero_()
101
+
102
+ for layer_weights in weights_intermediate_layers:
103
+ # Intermediate-layer weights
104
+ layer_weights[:, :, :-1].uniform_(
105
+ -intermediate_layer_bound,
106
+ intermediate_layer_bound,
107
+ generator=torch_rng,
108
+ )
109
+ # Intermediate-layer biases.
110
+ layer_weights[:, :, -1].zero_()
111
+
112
+ # Final-layer weights.
113
+ weights_final_layer[:, :-1].uniform_(
114
+ -final_layer_bound,
115
+ final_layer_bound,
116
+ generator=torch_rng,
117
+ )
118
+
119
+ # Final-layer biases.
120
+ weights_final_layer[:, -1].zero_()
121
+
122
+ weights = [weights_initial_layer.flatten(start_dim=1)]
123
+ weights.extend(
124
+ [
125
+ weights_intermediate_layer.flatten(start_dim=1)
126
+ for weights_intermediate_layer in weights_intermediate_layers
127
+ ]
128
+ )
129
+ weights.append(weights_final_layer)
130
+
131
+ # Flatten all layers for each head into one parameter vector.
132
+ return nn.Parameter(torch.cat(weights, dim=1))
133
+
134
+ def check_weights(self, input_dim: int) -> None:
135
+ weights = cast(nn.Parameter, self.weights)
136
+ (
137
+ initial,
138
+ intermediate,
139
+ final,
140
+ ) = self._get_layer_widths(input_dim)
141
+
142
+ expected_width = (
143
+ initial + intermediate * (self.hidden_layer_shape[0] - 1) + final
144
+ )
145
+ if weights.shape != (self.num_heads, expected_width):
146
+ raise ValueError(
147
+ f"DenseFeedForwardProbe weights have shape {tuple(weights.shape)}, "
148
+ f"expected {(self.num_heads, expected_width)}."
149
+ )
150
+
151
+ def forward(self, inputs: Tensor) -> torch.Tensor:
152
+ weights = cast(nn.Parameter, self.weights)
153
+ float_inputs = inputs.float()
154
+
155
+ num_hidden_layers, hidden_layer_width = self.hidden_layer_shape
156
+ input_dim = inputs.shape[2]
157
+ (
158
+ initial_layer_weights_width,
159
+ intermediate_layer_weights_width,
160
+ final_layer_width,
161
+ ) = self._get_layer_widths(input_dim)
162
+
163
+ weights_initial_layer = weights[:, :initial_layer_weights_width].reshape(
164
+ self.num_heads,
165
+ hidden_layer_width,
166
+ input_dim + 1,
167
+ )
168
+ cursor = initial_layer_weights_width
169
+
170
+ weights_intermediate_layers: list[Tensor] = []
171
+ for _ in range(num_hidden_layers - 1):
172
+ weights_intermediate_layers.append(
173
+ weights[:, cursor : cursor + intermediate_layer_weights_width].reshape(
174
+ self.num_heads,
175
+ hidden_layer_width,
176
+ hidden_layer_width + 1,
177
+ )
178
+ )
179
+ cursor += intermediate_layer_weights_width
180
+
181
+ assert cursor + final_layer_width == weights.shape[1]
182
+ final_layer_weights = weights[:, cursor:]
183
+
184
+ hidden = torch.einsum(
185
+ "hki,hpi->hpk",
186
+ weights_initial_layer[:, :, :-1],
187
+ float_inputs,
188
+ )
189
+
190
+ hidden = hidden + weights_initial_layer[:, :, -1].unsqueeze(1)
191
+ hidden = F.gelu(hidden)
192
+
193
+ for weights_intermediate_layer in weights_intermediate_layers:
194
+ hidden = torch.einsum(
195
+ "hki,hpi->hpk",
196
+ weights_intermediate_layer[:, :, :-1],
197
+ hidden,
198
+ )
199
+ hidden = hidden + weights_intermediate_layer[:, :, -1].unsqueeze(1)
200
+ hidden = F.gelu(hidden)
201
+
202
+ outputs = torch.einsum(
203
+ "hk,hpk->hp",
204
+ final_layer_weights[:, :-1],
205
+ hidden,
206
+ )
207
+ outputs += final_layer_weights[:, -1].unsqueeze(1)
208
+
209
+ return outputs
210
+
211
+ def _get_layer_widths(self, input_dim: int) -> tuple[int, int, int]:
212
+ _, hidden_layer_width = self.hidden_layer_shape
213
+ initial_layer_weights_width = hidden_layer_width * (input_dim + 1)
214
+ intermediate_layer_weights_width = hidden_layer_width * (hidden_layer_width + 1)
215
+ final_layer_width = hidden_layer_width + 1
216
+ return (
217
+ initial_layer_weights_width,
218
+ intermediate_layer_weights_width,
219
+ final_layer_width,
220
+ )
@@ -0,0 +1,164 @@
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
+
8
+ import torch
9
+ from torch import Tensor, nn
10
+
11
+ from polyprobe.activations import ActivationStore, ActivationType
12
+ from polyprobe.probe_components.probe_component import ProbeComponent
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class Probe(nn.Module):
18
+ """
19
+ A probe is a simple model that is applied to the defined index tuples for each
20
+ document piece to search for index tuples that correspond to a labelled feature.
21
+ Both during training and during inference, Aa probe is typically applied
22
+ at multiple heads in parallel.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ components: list[ProbeComponent],
28
+ heads: list[int] | tuple[int, int],
29
+ head_infos: list[tuple[int, int]],
30
+ device: torch.device,
31
+ *,
32
+ weights: Tensor | None = None,
33
+ seed: int | None = None,
34
+ ):
35
+ """
36
+ components: the list of probe components providing the input to probe.
37
+ heads: either a list of head indices, or a (start, end) range of head indices which is
38
+ converted to a list of head indices before being copied to *self*.
39
+ head_infos: a list of (<layer no>, <head no>) tuples describing the head at each head index.
40
+ weights: the weights, if a probe is being instantiated for inference, or *None* if the weights have still to be trained.
41
+ seed: required for reproducibility when weights are initialised within a neural probe during training.
42
+ """
43
+ super().__init__()
44
+ if not components:
45
+ raise ValueError("No probe components were specified.")
46
+ if len([type(c) for c in components]) != len({type(c) for c in components}):
47
+ raise ValueError("There is one or more duplicate probe components.")
48
+ self.components = components
49
+ self.device = device
50
+ if type(heads) is list:
51
+ self.heads: list[int] = heads
52
+ else:
53
+ self.heads = list(range(heads[0], heads[1]))
54
+ self.num_heads = len(self.heads)
55
+ self.head_infos = head_infos
56
+ if weights is not None:
57
+ assert weights.shape[0] == self.num_heads
58
+ self.weights: nn.Parameter | None = (
59
+ nn.Parameter(weights.to(self.device)) if weights is not None else None
60
+ )
61
+ self.seed = seed
62
+
63
+ def get_total_component_input_dimension(
64
+ self, activation_store: ActivationStore
65
+ ) -> int:
66
+ """Returns the total element width of all the features required from the activation store by the
67
+ probe components.
68
+ """
69
+ return sum(pc.get_output_dimension(activation_store) for pc in self.components)
70
+
71
+ def get_total_component_byte_width(self, activation_store: ActivationStore) -> int:
72
+ """Returns the total byte width of all the features required from the activation store by the
73
+ probe components.
74
+ """
75
+ return sum(
76
+ pc.get_output_dimension(activation_store)
77
+ * pc.get_element_size(activation_store)
78
+ for pc in self.components
79
+ )
80
+
81
+ def get_required_activation_types(self) -> set[ActivationType]:
82
+ """Specifies all activations required by the probe components."""
83
+ return set().union(
84
+ *(pc.get_required_activation_types() for pc in self.components)
85
+ )
86
+
87
+ def build_input(
88
+ self, activation_store: ActivationStore, index_tuples_list: list[Tensor]
89
+ ) -> Tensor:
90
+ """Builds the input to forward(), using the probe components to copy the relevant
91
+ data from the activation store for the specified index tuples; if no weights
92
+ exist, creates them; if weights exist, verifies that they match the generated input.
93
+ """
94
+ if len(index_tuples_list) != len(activation_store.piece_offsets) - 1:
95
+ raise ValueError(
96
+ "Length mismatch between activation_store and index_tuples_list."
97
+ )
98
+ if len(index_tuples_list) == 0:
99
+ raise ValueError(
100
+ "No activations have been supplied from which to build input."
101
+ )
102
+ for pc in self.components:
103
+ pc.check_arity(index_tuples_list[0].shape[1])
104
+
105
+ input_dim = self.get_total_component_input_dimension(activation_store)
106
+ cursor = 0
107
+ inputs: Tensor = None # type: ignore[assignment]
108
+
109
+ # Make sure to only materialize one component at a time
110
+ for component in self.components:
111
+ component_output = component.build_output(
112
+ activation_store, index_tuples_list, self.heads
113
+ )
114
+ if inputs is None:
115
+ inputs = torch.empty(
116
+ (
117
+ self.num_heads,
118
+ sum(it.shape[0] for it in index_tuples_list),
119
+ input_dim,
120
+ ),
121
+ dtype=component_output.dtype,
122
+ device=component_output.device,
123
+ )
124
+ else:
125
+ assert inputs.dtype == component_output.dtype
126
+ assert inputs.device == component_output.device
127
+
128
+ component_output_dim = component_output.shape[2]
129
+ inputs[:, :, cursor : cursor + component_output_dim].copy_(component_output)
130
+ cursor += component_output_dim
131
+ del component_output
132
+ assert cursor == input_dim
133
+
134
+ if self.weights is None:
135
+ self.weights = self.create_weights(input_dim)
136
+ else:
137
+ self.check_weights(input_dim)
138
+ return inputs
139
+
140
+ @abstractmethod
141
+ def create_weights(self, input_dim: int) -> nn.Parameter:
142
+ """
143
+ Creates the probe weights.
144
+
145
+ input_dim: the combined width of the tensors returned by the probe components.
146
+ """
147
+
148
+ @abstractmethod
149
+ def check_weights(self, input_dim: int) -> None:
150
+ """
151
+ Checks that pre-existing probe weights match the dimensions of newly generated inputs.
152
+
153
+ input_dim: the combined width of the tensors returned by the probe components.
154
+ """
155
+
156
+ @abstractmethod
157
+ def forward(self, inputs: Tensor) -> torch.Tensor:
158
+ """
159
+ inputs: a tensor of shape [num_heads, total_num_index_tuples, vector_size]
160
+
161
+ returns a tensor of shape [num_heads, total_num_index_tuples] where the values
162
+ are logits expressing how well each index tuple corresponds to the feature being
163
+ searched.
164
+ """
polyprobe/py.typed ADDED
File without changes
polyprobe/registry.py ADDED
@@ -0,0 +1,248 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import importlib
6
+ import inspect
7
+ import logging
8
+ import os
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, TypeVar, cast
11
+
12
+ from polyprobe.architecture_encoders.architecture_encoder import ArchitectureEncoder
13
+ from polyprobe.index_tuple_selectors.index_tuple_selector import IndexTupleSelector
14
+ from polyprobe.poolers.pooler import Pooler
15
+ from polyprobe.probe_components.probe_component import ProbeComponent
16
+ from polyprobe.probes.probe import Probe
17
+ from polyprobe.scorers.scorer import Scorer
18
+ from polyprobe.training.dataset_sources.dataset_source import DatasetSource
19
+ from polyprobe.training.truthers.truther import Truther
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ ImplementationType = TypeVar("ImplementationType")
24
+
25
+
26
+ @dataclass
27
+ class CategoryRegistry:
28
+ """A registry for a specific supertype."""
29
+
30
+ superclass: type[Any]
31
+ module_name: str
32
+ type_dict: dict[str, type[Any]] = field(default_factory=dict)
33
+
34
+
35
+ class PolyprobeRegistry:
36
+ """Registry for implementations of the various supertypes supported by the library,
37
+ also supporting registration of external implementations at runtime.
38
+ """
39
+
40
+ def __init__(self) -> None:
41
+ self._category_registries = {
42
+ "probe": CategoryRegistry(Probe, ".probes"),
43
+ "probe component": CategoryRegistry(ProbeComponent, ".probe_components"),
44
+ "pooler": CategoryRegistry(Pooler, ".poolers"),
45
+ "index tuple selector": CategoryRegistry(
46
+ IndexTupleSelector, ".index_tuple_selectors"
47
+ ),
48
+ "architecture encoder": CategoryRegistry(
49
+ ArchitectureEncoder, ".architecture_encoders"
50
+ ),
51
+ "truther": CategoryRegistry(Truther, ".training.truthers"),
52
+ "scorer": CategoryRegistry(Scorer, ".scorers"),
53
+ "dataset source": CategoryRegistry(
54
+ DatasetSource, ".training.dataset_sources"
55
+ ),
56
+ }
57
+ self._externals: dict[str, set[str]] = {}
58
+
59
+ for category_name, category_registry in self._category_registries.items():
60
+ category_registry.type_dict = self.load_type(
61
+ category_registry.module_name, category_registry.superclass
62
+ )
63
+ self._externals[category_name] = set()
64
+
65
+ def load_type(
66
+ self, module_name: str, superclass: type[ImplementationType]
67
+ ) -> dict[str, type[ImplementationType]]:
68
+ """
69
+ Dynamically loads all types from the module.
70
+ """
71
+ found_classes: dict[str, type[ImplementationType]] = {}
72
+ module = importlib.import_module(module_name, package="polyprobe")
73
+ root_dir = module.__path__[0]
74
+ for _, _, files in os.walk(root_dir):
75
+ for file in files:
76
+ if file.endswith(".py") and not file.startswith("__"):
77
+ submodule_name = os.path.splitext(file)[0]
78
+ module = importlib.import_module(
79
+ f"{module_name}.{submodule_name}", package="polyprobe"
80
+ )
81
+ for cls in dir(module):
82
+ obj = getattr(module, cls)
83
+ if (
84
+ isinstance(obj, type)
85
+ and issubclass(obj, superclass)
86
+ and obj is not superclass
87
+ and not inspect.isabstract(obj)
88
+ ):
89
+ found_classes[cls] = obj
90
+ return found_classes
91
+
92
+ def register(
93
+ self,
94
+ new_type: type[Any],
95
+ ) -> None:
96
+ """Register a concrete implementation under its class name.
97
+
98
+ Raise TypeError for non-class arguments, or ValueError for abstract
99
+ classes, unsupported classes, and names already used in the category.
100
+ Existing registrations are never replaced.
101
+ """
102
+ if not isinstance(new_type, type):
103
+ raise TypeError(f"Expected a class, got {new_type!r}.")
104
+ if inspect.isabstract(new_type):
105
+ raise ValueError(
106
+ f"Type {new_type.__name__} is abstract and cannot be registered."
107
+ )
108
+
109
+ for category_name, category_registry in self._category_registries.items():
110
+ if issubclass(new_type, category_registry.superclass):
111
+ if new_type.__name__ in category_registry.type_dict:
112
+ raise ValueError(
113
+ f"A {category_name} named {new_type.__name__} is already registered."
114
+ )
115
+ category_registry.type_dict[new_type.__name__] = new_type
116
+ self._externals[category_name].add(new_type.__name__)
117
+ logger.info(f"Registered external {category_name} {new_type.__name__}")
118
+ return
119
+ raise ValueError(
120
+ f"Type {new_type.__name__} is not a subclass of any supported type."
121
+ )
122
+
123
+ def get_logging_repr(self, implementation: Any) -> str:
124
+ """Returns a human-readable representation of a registered type."""
125
+ if not isinstance(implementation, type):
126
+ implementation = type(implementation)
127
+
128
+ for category_name, category_registry in self._category_registries.items():
129
+ if (
130
+ issubclass(implementation, category_registry.superclass)
131
+ and implementation in category_registry.type_dict.values()
132
+ ):
133
+ if implementation.__name__ in self._externals[category_name]:
134
+ return f"{category_name} {implementation.__name__} (externally supplied)"
135
+ else:
136
+ return f"{category_name} {implementation.__name__}"
137
+ raise ValueError(f"Type {implementation.__name__} is not registered.")
138
+
139
+ def get_probe_types(
140
+ self,
141
+ ) -> dict[str, type[Probe]]:
142
+ return cast(
143
+ dict[str, type[Probe]],
144
+ self._category_registries["probe"].type_dict,
145
+ )
146
+
147
+ def get_probe_type(self, name: str) -> type[Probe]:
148
+ probe_types = self.get_probe_types()
149
+ if name not in probe_types:
150
+ raise ValueError(f"There is no registered probe {name}")
151
+ return probe_types[name]
152
+
153
+ def get_probe_component_types(
154
+ self,
155
+ ) -> dict[str, type[ProbeComponent]]:
156
+ return cast(
157
+ dict[str, type[ProbeComponent]],
158
+ self._category_registries["probe component"].type_dict,
159
+ )
160
+
161
+ def get_probe_component_type(self, name: str) -> type[ProbeComponent]:
162
+ probe_component_types = self.get_probe_component_types()
163
+ if name not in probe_component_types:
164
+ raise ValueError(f"There is no registered probe component {name}")
165
+ return probe_component_types[name]
166
+
167
+ def get_pooler_types(
168
+ self,
169
+ ) -> dict[str, type[Pooler]]:
170
+ return cast(
171
+ dict[str, type[Pooler]], self._category_registries["pooler"].type_dict
172
+ )
173
+
174
+ def get_pooler_type(self, name: str) -> type[Pooler]:
175
+ pooler_types = self.get_pooler_types()
176
+ if name not in pooler_types:
177
+ raise ValueError(f"There is no registered pooler {name}")
178
+ return pooler_types[name]
179
+
180
+ def get_index_tuple_selector_types(
181
+ self,
182
+ ) -> dict[str, type[IndexTupleSelector]]:
183
+ return cast(
184
+ dict[str, type[IndexTupleSelector]],
185
+ self._category_registries["index tuple selector"].type_dict,
186
+ )
187
+
188
+ def get_index_tuple_selector_type(self, name: str) -> type[IndexTupleSelector]:
189
+ index_tuple_selector_types = self.get_index_tuple_selector_types()
190
+ if name not in index_tuple_selector_types:
191
+ raise ValueError(f"There is no registered index tuple selector {name}")
192
+ return index_tuple_selector_types[name]
193
+
194
+ def get_architecture_encoder_types(
195
+ self,
196
+ ) -> dict[str, type[ArchitectureEncoder]]:
197
+ return cast(
198
+ dict[str, type[ArchitectureEncoder]],
199
+ self._category_registries["architecture encoder"].type_dict,
200
+ )
201
+
202
+ def get_architecture_encoder_type(self, name: str) -> type[ArchitectureEncoder]:
203
+ architecture_encoder_types = self.get_architecture_encoder_types()
204
+ if name not in architecture_encoder_types:
205
+ raise ValueError(f"There is no registered architecture encoder {name}")
206
+ return architecture_encoder_types[name]
207
+
208
+ def get_truther_types(
209
+ self,
210
+ ) -> dict[str, type[Truther]]:
211
+ return cast(
212
+ dict[str, type[Truther]],
213
+ self._category_registries["truther"].type_dict,
214
+ )
215
+
216
+ def get_truther_type(self, name: str) -> type[Truther]:
217
+ truther_types = self.get_truther_types()
218
+ if name not in truther_types:
219
+ raise ValueError(f"There is no registered truther {name}")
220
+ return truther_types[name]
221
+
222
+ def get_scorer_types(
223
+ self,
224
+ ) -> dict[str, type[Scorer]]:
225
+ return cast(
226
+ dict[str, type[Scorer]],
227
+ self._category_registries["scorer"].type_dict,
228
+ )
229
+
230
+ def get_scorer_type(self, name: str) -> type[Scorer]:
231
+ scorer_types = self.get_scorer_types()
232
+ if name not in scorer_types:
233
+ raise ValueError(f"There is no registered scorer {name}")
234
+ return scorer_types[name]
235
+
236
+ def get_dataset_source_types(
237
+ self,
238
+ ) -> dict[str, type[DatasetSource]]:
239
+ return cast(
240
+ dict[str, type[DatasetSource]],
241
+ self._category_registries["dataset source"].type_dict,
242
+ )
243
+
244
+ def get_dataset_source_type(self, name: str) -> type[DatasetSource]:
245
+ dataset_source_types = self.get_dataset_source_types()
246
+ if name not in dataset_source_types:
247
+ raise ValueError(f"There is no registered dataset source {name}")
248
+ return dataset_source_types[name]
@@ -0,0 +1,27 @@
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 AveragePrecisionScorer(Scorer):
15
+ """Scores according to average precision (AP), which summarizes the precision-recall curve
16
+ as the weighted sum of precision values at distinct score thresholds, with each value
17
+ weighted by the increase in recall from the preceding threshold.
18
+ """
19
+
20
+ @classmethod
21
+ def get_score_label(cls) -> str:
22
+ return "average precision"
23
+
24
+ def score_label_evaluation_impl(
25
+ self, label_evaluation: PolyprobeLabelEvaluation
26
+ ) -> None:
27
+ label_evaluation.score = label_evaluation.average_precision
@@ -0,0 +1,24 @@
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 F1Scorer(Scorer):
15
+ """Scores according to the maximum F1 achieved over the evaluated score thresholds."""
16
+
17
+ @classmethod
18
+ def get_score_label(cls) -> str:
19
+ return "F1"
20
+
21
+ def score_label_evaluation_impl(
22
+ self, label_evaluation: PolyprobeLabelEvaluation
23
+ ) -> None:
24
+ label_evaluation.score = label_evaluation.best_f1