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,368 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from abc import ABC
7
+
8
+ import torch
9
+ from torch import Tensor
10
+
11
+ from polyprobe.activations import ActivationStore, ActivationType
12
+
13
+ from .probe_component import ProbeComponent
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class IndexPairProbeComponent(ProbeComponent, ABC):
19
+ """
20
+ Index-pair probe components are probe components with arity 2.
21
+ """
22
+
23
+ @classmethod
24
+ def check_arity(cls, arity: int) -> None:
25
+ if arity != 2:
26
+ raise ValueError(f"{cls.__name__} expects index tuples with arity 2.")
27
+
28
+ @classmethod
29
+ def check_rope_supported(cls, lm_architecture: str | None) -> None:
30
+ """Implementations that depend on RoPE should call this method to check the
31
+ architecture uses it.
32
+ """
33
+ super().check_lm_architecture(lm_architecture)
34
+ if lm_architecture not in (
35
+ "Qwen3ForCausalLM",
36
+ "Qwen3_5ForCausalLM",
37
+ "Cohere2ForCausalLM",
38
+ ):
39
+ raise ValueError(
40
+ f"{cls.__name__} does not support {lm_architecture}. "
41
+ f"Please feel free to alter the code if {lm_architecture} "
42
+ "is a newly added architecture that uses RoPE."
43
+ )
44
+
45
+
46
+ class LeftKProbeComponent(IndexPairProbeComponent):
47
+ """
48
+ Returns the key vector of the lefthand token.
49
+ """
50
+
51
+ @classmethod
52
+ def get_required_activation_types(cls) -> set[ActivationType]:
53
+ return {"k"}
54
+
55
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
56
+ return activation_store.activations["k"].shape[2]
57
+
58
+ def get_element_size(self, activation_store: ActivationStore) -> int:
59
+ return activation_store.activations["k"].element_size()
60
+
61
+ def build_output(
62
+ self,
63
+ activation_store: ActivationStore,
64
+ index_tuples_list: list[Tensor],
65
+ heads: list[int],
66
+ ) -> Tensor:
67
+ keys_activation = activation_store.activations["k"]
68
+ relevant_keys = keys_activation[heads]
69
+
70
+ lefthand_positions = self.get_positions(
71
+ activation_store, index_tuples_list, 0, keys_activation.device
72
+ )
73
+ return relevant_keys[:, lefthand_positions, :]
74
+
75
+
76
+ class RightQProbeComponent(IndexPairProbeComponent):
77
+ """
78
+ Returns the query vector of the righthand token.
79
+ """
80
+
81
+ @classmethod
82
+ def get_required_activation_types(cls) -> set[ActivationType]:
83
+ return {"q"}
84
+
85
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
86
+ return activation_store.activations["q"].shape[2]
87
+
88
+ def get_element_size(self, activation_store: ActivationStore) -> int:
89
+ return activation_store.activations["q"].element_size()
90
+
91
+ def build_output(
92
+ self,
93
+ activation_store: ActivationStore,
94
+ index_tuples_list: list[Tensor],
95
+ heads: list[int],
96
+ ) -> Tensor:
97
+ queries_activation = activation_store.activations["q"]
98
+ relevant_queries = queries_activation[heads]
99
+
100
+ righthand_positions = self.get_positions(
101
+ activation_store, index_tuples_list, 1, queries_activation.device
102
+ )
103
+ return relevant_queries[:, righthand_positions, :]
104
+
105
+
106
+ class LeftVProbeComponent(IndexPairProbeComponent):
107
+ """
108
+ Returns the value vector of the lefthand token.
109
+ """
110
+
111
+ @classmethod
112
+ def get_required_activation_types(cls) -> set[ActivationType]:
113
+ return {"v"}
114
+
115
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
116
+ return activation_store.activations["v"].shape[2]
117
+
118
+ def get_element_size(self, activation_store: ActivationStore) -> int:
119
+ return activation_store.activations["v"].element_size()
120
+
121
+ def build_output(
122
+ self,
123
+ activation_store: ActivationStore,
124
+ index_tuples_list: list[Tensor],
125
+ heads: list[int],
126
+ ) -> Tensor:
127
+ values_activation = activation_store.activations["v"]
128
+ relevant_values = values_activation[heads]
129
+
130
+ lefthand_positions = self.get_positions(
131
+ activation_store, index_tuples_list, 0, values_activation.device
132
+ )
133
+ return relevant_values[:, lefthand_positions, :]
134
+
135
+
136
+ class RightVProbeComponent(IndexPairProbeComponent):
137
+ """
138
+ Returns the value vector of the righthand token.
139
+ """
140
+
141
+ @classmethod
142
+ def get_required_activation_types(cls) -> set[ActivationType]:
143
+ return {"v"}
144
+
145
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
146
+ return activation_store.activations["v"].shape[2]
147
+
148
+ def get_element_size(self, activation_store: ActivationStore) -> int:
149
+ return activation_store.activations["v"].element_size()
150
+
151
+ def build_output(
152
+ self,
153
+ activation_store: ActivationStore,
154
+ index_tuples_list: list[Tensor],
155
+ heads: list[int],
156
+ ) -> Tensor:
157
+ values_activation = activation_store.activations["v"]
158
+ relevant_values = values_activation[heads]
159
+
160
+ righthand_positions = self.get_positions(
161
+ activation_store, index_tuples_list, 1, values_activation.device
162
+ )
163
+ return relevant_values[:, righthand_positions, :]
164
+
165
+
166
+ class LeftRotKProbeComponent(IndexPairProbeComponent):
167
+ """
168
+ Returns the rotated key vector of the lefthand token.
169
+ """
170
+
171
+ @classmethod
172
+ def check_lm_architecture(cls, lm_architecture: str | None) -> None:
173
+ super().check_lm_architecture(lm_architecture)
174
+ cls.check_rope_supported(lm_architecture)
175
+
176
+ @classmethod
177
+ def get_required_activation_types(cls) -> set[ActivationType]:
178
+ return {"rot_k"}
179
+
180
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
181
+ return activation_store.activations["rot_k"].shape[2]
182
+
183
+ def get_element_size(self, activation_store: ActivationStore) -> int:
184
+ return activation_store.activations["rot_k"].element_size()
185
+
186
+ def build_output(
187
+ self,
188
+ activation_store: ActivationStore,
189
+ index_tuples_list: list[Tensor],
190
+ heads: list[int],
191
+ ) -> Tensor:
192
+ rot_keys_activation = activation_store.activations["rot_k"]
193
+ relevant_rot_keys = rot_keys_activation[heads]
194
+
195
+ lefthand_positions = self.get_positions(
196
+ activation_store, index_tuples_list, 0, rot_keys_activation.device
197
+ )
198
+ return relevant_rot_keys[:, lefthand_positions, :]
199
+
200
+
201
+ class RightRotQProbeComponent(IndexPairProbeComponent):
202
+ """
203
+ Returns the rotated query vector of the righthand token.
204
+ """
205
+
206
+ @classmethod
207
+ def check_lm_architecture(cls, lm_architecture: str | None) -> None:
208
+ super().check_lm_architecture(lm_architecture)
209
+ cls.check_rope_supported(lm_architecture)
210
+
211
+ @classmethod
212
+ def get_required_activation_types(cls) -> set[ActivationType]:
213
+ return {"rot_q"}
214
+
215
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
216
+ return activation_store.activations["rot_q"].shape[2]
217
+
218
+ def get_element_size(self, activation_store: ActivationStore) -> int:
219
+ return activation_store.activations["rot_q"].element_size()
220
+
221
+ def build_output(
222
+ self,
223
+ activation_store: ActivationStore,
224
+ index_tuples_list: list[Tensor],
225
+ heads: list[int],
226
+ ) -> Tensor:
227
+ rot_queries_activation = activation_store.activations["rot_q"]
228
+ relevant_rot_queries = rot_queries_activation[heads]
229
+
230
+ righthand_positions = self.get_positions(
231
+ activation_store, index_tuples_list, 1, rot_queries_activation.device
232
+ )
233
+ return relevant_rot_queries[:, righthand_positions, :]
234
+
235
+
236
+ class QxKProbeComponent(IndexPairProbeComponent):
237
+ """
238
+ Returns the Hadamard product of the query vector of the righthand token
239
+ and the key vector of the lefthand token.
240
+ """
241
+
242
+ @classmethod
243
+ def get_required_activation_types(cls) -> set[ActivationType]:
244
+ return {"q", "k"}
245
+
246
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
247
+ return activation_store.activations["q"].shape[2]
248
+
249
+ def get_element_size(self, activation_store: ActivationStore) -> int:
250
+ return activation_store.activations["q"].element_size()
251
+
252
+ def build_output(
253
+ self,
254
+ activation_store: ActivationStore,
255
+ index_tuples_list: list[Tensor],
256
+ heads: list[int],
257
+ ) -> Tensor:
258
+ keys_activation = activation_store.activations["k"]
259
+ queries_activation = activation_store.activations["q"]
260
+
261
+ relevant_keys = keys_activation[heads]
262
+ relevant_queries = queries_activation[heads]
263
+
264
+ lefthand_positions = self.get_positions(
265
+ activation_store, index_tuples_list, 0, keys_activation.device
266
+ )
267
+ righthand_positions = self.get_positions(
268
+ activation_store, index_tuples_list, 1, keys_activation.device
269
+ )
270
+
271
+ return (
272
+ relevant_keys[:, lefthand_positions, :]
273
+ * relevant_queries[:, righthand_positions, :]
274
+ )
275
+
276
+
277
+ class RotQxRotKProbeComponent(IndexPairProbeComponent):
278
+ """
279
+ Returns the Hadamard product of the rotated query vector of the righthand
280
+ token and the rotated key vector of the lefthand token.
281
+ """
282
+
283
+ @classmethod
284
+ def check_lm_architecture(cls, lm_architecture: str | None) -> None:
285
+ super().check_lm_architecture(lm_architecture)
286
+ cls.check_rope_supported(lm_architecture)
287
+
288
+ @classmethod
289
+ def get_required_activation_types(cls) -> set[ActivationType]:
290
+ return {"rot_q", "rot_k"}
291
+
292
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
293
+ return activation_store.activations["rot_q"].shape[2]
294
+
295
+ def get_element_size(self, activation_store: ActivationStore) -> int:
296
+ return activation_store.activations["rot_q"].element_size()
297
+
298
+ def build_output(
299
+ self,
300
+ activation_store: ActivationStore,
301
+ index_tuples_list: list[Tensor],
302
+ heads: list[int],
303
+ ) -> Tensor:
304
+ rot_keys_activation = activation_store.activations["rot_k"]
305
+ rot_queries_activation = activation_store.activations["rot_q"]
306
+
307
+ relevant_rot_keys = rot_keys_activation[heads]
308
+ relevant_rot_queries = rot_queries_activation[heads]
309
+
310
+ lefthand_positions = self.get_positions(
311
+ activation_store, index_tuples_list, 0, rot_keys_activation.device
312
+ )
313
+ righthand_positions = self.get_positions(
314
+ activation_store, index_tuples_list, 1, rot_keys_activation.device
315
+ )
316
+
317
+ return (
318
+ relevant_rot_keys[:, lefthand_positions, :]
319
+ * relevant_rot_queries[:, righthand_positions, :]
320
+ )
321
+
322
+
323
+ class AttnScoresProbeComponent(IndexPairProbeComponent):
324
+ """
325
+ Returns the attention score with which the righthand token attends to the lefthand token.
326
+ """
327
+
328
+ @classmethod
329
+ def get_required_activation_types(cls) -> set[ActivationType]:
330
+ return {"attn_scores"}
331
+
332
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
333
+ return 1
334
+
335
+ def get_element_size(self, activation_store: ActivationStore) -> int:
336
+ return activation_store.activations["attn_scores"].element_size()
337
+
338
+ def build_output(
339
+ self,
340
+ activation_store: ActivationStore,
341
+ index_tuples_list: list[Tensor],
342
+ heads: list[int],
343
+ ) -> Tensor:
344
+
345
+ score_offset = 0
346
+ attn_scores_list: list[Tensor] = []
347
+
348
+ attn_score_activation = activation_store.activations["attn_scores"]
349
+ for piece_idx, index_tuples in enumerate(index_tuples_list):
350
+ num_tokens = (
351
+ activation_store.piece_offsets[piece_idx + 1]
352
+ - activation_store.piece_offsets[piece_idx]
353
+ )
354
+ flattened_size = num_tokens * num_tokens
355
+
356
+ piece_scores = attn_score_activation[
357
+ :,
358
+ score_offset : score_offset + flattened_size,
359
+ ].reshape(attn_score_activation.shape[0], num_tokens, num_tokens)
360
+
361
+ left = index_tuples[:, 0].to(piece_scores.device, torch.long)
362
+ right = index_tuples[:, 1].to(piece_scores.device, torch.long)
363
+
364
+ attn_scores_list.append(piece_scores[heads][:, right, left])
365
+
366
+ score_offset += flattened_size
367
+
368
+ return torch.cat(attn_scores_list, dim=1).unsqueeze(-1)
@@ -0,0 +1,92 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from abc import ABC, abstractmethod
7
+
8
+ import torch
9
+ from torch import Tensor
10
+
11
+ from polyprobe.activations import ActivationStore, ActivationType
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class ProbeComponent(ABC):
17
+ """
18
+ A probe component supplies part of the material for probing. If multiple probe
19
+ components are specified, their outputs are concatenated. All probe components
20
+ used together must process index tuples with the same arity.
21
+ """
22
+
23
+ @classmethod
24
+ def check_arity(cls, arity: int) -> None:
25
+ """An implementation should override this method and raise a ValueError
26
+ if it is unable to process index tuples with the specified arity.
27
+ """
28
+
29
+ @classmethod
30
+ def check_lm_architecture(cls, lm_architecture: str | None) -> None:
31
+ """An implementation should override this method, call super().check_lm_architecture(),
32
+ and raise a ValueError if it is unsuitable for the specified LM architecture.
33
+ """
34
+ if lm_architecture is None:
35
+ raise ValueError("LMEncoder.lm_architecture is None.")
36
+
37
+ @abstractmethod
38
+ def get_output_dimension(self, activation_store: ActivationStore) -> int:
39
+ """Returns the last-dimension width of the tensors outputted
40
+ from the implementation.
41
+ """
42
+
43
+ @abstractmethod
44
+ def get_element_size(self, activation_store: ActivationStore) -> int:
45
+ """Returns the element size in bytes of the tensors outputted
46
+ from the implementation.
47
+ """
48
+
49
+ @classmethod
50
+ @abstractmethod
51
+ def get_required_activation_types(self) -> set[ActivationType]:
52
+ """Specifies the activations this probe component requires to be gathered from each head."""
53
+
54
+ @abstractmethod
55
+ def build_output(
56
+ self,
57
+ activation_store: ActivationStore,
58
+ index_tuples_list: list[Tensor],
59
+ heads: list[int],
60
+ ) -> Tensor:
61
+ """
62
+ Returns a tensor of shape [num_heads, total_num_index_tuples, vector_size]
63
+ where the vector_size dimension contains the information from each
64
+ head for this probe component.
65
+
66
+ The returned tensor must be on CPU; for memory management reasons, it may not retain any references
67
+ to the tensors within *activation_store*.
68
+
69
+ activation_store: encompasses the activations generated at each head during the encoding of each document piece by the LM.
70
+ index_tuples_list: a list of tensors of shape [num_tuples, arity] specifying the the index tuples to process.
71
+ """
72
+
73
+ def get_positions(
74
+ self,
75
+ activation_store: ActivationStore,
76
+ index_tuples_list: list[Tensor],
77
+ index_tuple_index: int,
78
+ device: torch.device,
79
+ ) -> Tensor:
80
+ """Returns a tensor containing all the positions in *activation_store* corresponding to the *index_tuple_index*
81
+ position within the index tuples within the members of *index_tuple_list*.
82
+ """
83
+ return torch.cat(
84
+ [
85
+ (
86
+ activation_store.piece_offsets[piece_idx]
87
+ + index_tuples[:, index_tuple_index]
88
+ ).to(device=device, dtype=torch.long)
89
+ for piece_idx, index_tuples in enumerate(index_tuples_list)
90
+ ],
91
+ dim=0,
92
+ )
@@ -0,0 +1,46 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from typing import cast
7
+
8
+ import torch
9
+ from torch import Tensor, nn
10
+
11
+ from .probe import Probe
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class LinearProbe(Probe):
17
+ """
18
+ A probe that performs logistic regression (no hidden layers).
19
+ """
20
+
21
+ def create_weights(self, input_dim: int) -> nn.Parameter:
22
+ return nn.Parameter(
23
+ torch.zeros(
24
+ (self.num_heads, input_dim + 1),
25
+ dtype=torch.float32,
26
+ device=self.device,
27
+ )
28
+ )
29
+
30
+ def check_weights(self, input_dim: int) -> None:
31
+ weights = cast(nn.Parameter, self.weights)
32
+ expected_width = input_dim + 1
33
+ if weights.shape != (self.num_heads, expected_width):
34
+ raise ValueError(
35
+ f"Linear probe weights have shape {tuple(weights.shape)}, "
36
+ f"expected {(self.num_heads, expected_width)}."
37
+ )
38
+
39
+ def forward(self, inputs: Tensor) -> torch.Tensor:
40
+ return torch.einsum(
41
+ "hv,hpv -> hp", self.weights[:, :-1], inputs.float() # type: ignore[index]
42
+ ) + self.weights[
43
+ :, -1
44
+ ].unsqueeze( # type: ignore[index]
45
+ 1
46
+ )