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,49 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import torch
6
+ from torch import Tensor
7
+
8
+ from polyprobe.document import DocumentPiece
9
+ from polyprobe.index_tuple_selectors.index_tuple_selector import IndexTupleSelector
10
+
11
+
12
+ class CausalCombinatorialIndexTupleSelector(IndexTupleSelector):
13
+ """
14
+ Returns all index tuples of the specified arity that combine the token indexes
15
+ within the document piece where indices further left are not greater than
16
+ indices further right, i.e.
17
+
18
+ For arity == 1:
19
+ (i,)
20
+
21
+ For arity == 2:
22
+ (i, j) where i <= j
23
+
24
+ For arity == 3:
25
+ (i, j, k) where i <= j <= k
26
+
27
+ """
28
+
29
+ def get_index_tuples(self, piece: DocumentPiece, arity: int) -> Tensor:
30
+ input_ids_range = torch.arange(
31
+ piece.input_ids.shape[1], device=piece.input_ids.device
32
+ )
33
+ if arity == 1:
34
+ return input_ids_range.unsqueeze(1)
35
+
36
+ all_tuples = torch.cartesian_prod(*[input_ids_range for _ in range(arity)])
37
+
38
+ # Keep only canonical unordered tuples with replacement:
39
+ # i0 <= i1 <= i2 <= ...
40
+ mask = torch.ones(
41
+ all_tuples.shape[0],
42
+ dtype=torch.bool,
43
+ device=all_tuples.device,
44
+ )
45
+
46
+ for dim in range(arity - 1):
47
+ mask &= all_tuples[:, dim] <= all_tuples[:, dim + 1]
48
+
49
+ return all_tuples[mask]
@@ -0,0 +1,23 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from abc import ABC, abstractmethod
6
+
7
+ from torch import Tensor
8
+
9
+ from polyprobe.document import DocumentPiece
10
+
11
+
12
+ class IndexTupleSelector(ABC):
13
+ """A document piece is encoded with zero-indexed tokens. An index tuple selector
14
+ returns a list of index tuples, all of which must have the same arity, to
15
+ be investigated by a suitable probe."""
16
+
17
+ @abstractmethod
18
+ def get_index_tuples(self, piece: DocumentPiece, arity: int) -> Tensor:
19
+ """
20
+ arity — the arity of the returned index tuples. Implementations may not necessarily
21
+ support all values and may raise an exception if the specified arity does
22
+ not correspond to what they are able to return.
23
+ """
polyprobe/inferrer.py ADDED
@@ -0,0 +1,480 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from collections import defaultdict
7
+ from dataclasses import dataclass
8
+
9
+ import torch
10
+
11
+ from polyprobe.activations import ActivationStore, ActivationType
12
+ from polyprobe.document import DocumentPiece
13
+ from polyprobe.index_tuple_selectors.index_tuple_selector import IndexTupleSelector
14
+ from polyprobe.lm_encoder import LMEncoder
15
+ from polyprobe.model import PolyprobeLabelModel, PolyprobeModel
16
+ from polyprobe.poolers.pooler import Pooler
17
+ from polyprobe.probes.probe import Probe
18
+ from polyprobe.registry import PolyprobeRegistry
19
+ from polyprobe.util import get_activation_tuples_representation, get_probe_components
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ @dataclass
25
+ class Finding:
26
+ """A match against some label.
27
+
28
+ index_tuple: the LM indices that matched.
29
+ strictest_met_threshold: the strictest met percentage threshold.
30
+ """
31
+
32
+ index_tuple: tuple[int, ...]
33
+ strictest_met_threshold: int
34
+
35
+
36
+ @dataclass
37
+ class MergedFinding:
38
+ """A combination of one or more Findings that are contiguous in all order dimensions.
39
+
40
+ label: the found label
41
+ order: specifies the direction of the labelled relationship with
42
+ respect to training_token_idxs, e.g. order (0, 1) with training_token_idxs
43
+ (4, 6) means that index 4 points to index 6; order (1, 0) with
44
+ training_token_idxs (4, 6) means that index 6 points to index 4.
45
+ piece: the document piece in which the label was inferred.
46
+ activation_tuples: a list of (start, end) tuples with LM token indices for each dimension in *order*. Note
47
+ that the numbering is end-inclusive.
48
+ strictest_met_threshold: the strictest met percentage threshold.
49
+ """
50
+
51
+ label: str
52
+ order: tuple[int, ...]
53
+ piece: DocumentPiece
54
+ activation_tuples: list[tuple[int, int]]
55
+ strictest_met_threshold: int
56
+
57
+ def __repr__(self) -> str:
58
+ return f"{self.label}: {get_activation_tuples_representation(self.piece, self.activation_tuples, self.order)} (strictest met threshold: {self.strictest_met_threshold}%)"
59
+
60
+
61
+ def _strictest_met_threshold(
62
+ logit: float,
63
+ thresholds: dict[int, float],
64
+ ) -> int:
65
+ """Find the strictest threshold (with the lowest percentage but the highest logit) that the finding's logit equals or exceeds."""
66
+ met_threshold_percents = [
67
+ percent for percent, threshold in thresholds.items() if logit >= threshold
68
+ ]
69
+
70
+ if not met_threshold_percents:
71
+ raise ValueError(f"Logit {logit} did not meet any threshold.")
72
+
73
+ return min(met_threshold_percents)
74
+
75
+
76
+ def _conflate_subwords(findings: list[Finding]) -> list[tuple[int, int]]:
77
+ """
78
+ Given a list of findings from a '_subword' label model, returns a
79
+ list of end-inclusive (start, end) activation tuples representing
80
+ the found words.
81
+ """
82
+ pairs: list[tuple[int, int]] = []
83
+
84
+ for finding in findings:
85
+ if len(finding.index_tuple) != 2:
86
+ raise ValueError("Subword index tuples must have arity 2.")
87
+
88
+ start, end = finding.index_tuple
89
+ if start + 1 == end:
90
+ pairs.append((start, end))
91
+
92
+ pairs.sort()
93
+ activation_tuples: list[tuple[int, int]] = []
94
+
95
+ for start, end in pairs:
96
+ if activation_tuples and start <= activation_tuples[-1][1]:
97
+ previous_start, previous_end = activation_tuples[-1]
98
+ activation_tuples[-1] = (
99
+ previous_start,
100
+ max(previous_end, end),
101
+ )
102
+ else:
103
+ activation_tuples.append((start, end))
104
+
105
+ return activation_tuples
106
+
107
+
108
+ def _overlaps(a: tuple[int, int], b: tuple[int, int]) -> bool:
109
+ return max(a[0], b[0]) <= min(a[1], b[1])
110
+
111
+
112
+ def _merge_findings(
113
+ findings: list[Finding],
114
+ label: str,
115
+ order: tuple[int, ...],
116
+ piece: DocumentPiece,
117
+ merge_adjacent_findings: bool,
118
+ word_activation_tuples: list[tuple[int, int]] | None,
119
+ ) -> list[MergedFinding]:
120
+ """
121
+ If merge_adjacent_findings is *True*:
122
+ merge findings that are identical in all dimensions except one, and
123
+ adjacent in that dimension.
124
+
125
+ If word_activation_tuples is set:
126
+ expand the subwords in all findings dimensions to their containing words.
127
+
128
+ findings: the Finding instances to merge.
129
+ label: the found label
130
+ order: specifies the direction of the labelled relationship with
131
+ respect to training_token_idxs, e.g. order (0, 1) with training_token_idxs
132
+ (4, 6) means that index 4 points to index 6; order (1, 0) with
133
+ training_token_idxs (4, 6) means that index 6 points to index 4.
134
+ piece: the document piece in which the label was inferred.
135
+ word_activation_tuples: word activation tuples supplied by a '_subword' label model,
136
+ or *None* if the model does not contain such a label model.
137
+ """
138
+ if len(findings) == 0:
139
+ return []
140
+ arity = len(findings[0].index_tuple)
141
+
142
+ findings = sorted(findings, key=lambda finding: finding.index_tuple)
143
+
144
+ for finding in findings:
145
+ if len(finding.index_tuple) != arity:
146
+ raise ValueError(
147
+ f"Expected all findings to have arity {arity}, "
148
+ f"but got {finding.index_tuple} with arity {len(finding.index_tuple)}"
149
+ )
150
+
151
+ merged_findings = [
152
+ MergedFinding(
153
+ label,
154
+ order,
155
+ piece,
156
+ [(coord, coord) for coord in finding.index_tuple],
157
+ finding.strictest_met_threshold,
158
+ )
159
+ for finding in findings
160
+ ]
161
+
162
+ if merge_adjacent_findings:
163
+ # Repeatedly merge boxes that are identical in all dimensions except one,
164
+ # and adjacent or overlapping in that dimension.
165
+ changed = True
166
+
167
+ while changed:
168
+ changed = False
169
+
170
+ for dim in range(arity):
171
+ groups: dict[tuple[tuple[int, int], ...], list[MergedFinding]] = (
172
+ defaultdict(list)
173
+ )
174
+
175
+ for other in merged_findings:
176
+ key = tuple(
177
+ other.activation_tuples[:dim]
178
+ + other.activation_tuples[dim + 1 :]
179
+ )
180
+ groups[key].append(other)
181
+
182
+ next_merged_findings: list[MergedFinding] = []
183
+
184
+ for group in groups.values():
185
+ group = sorted(group, key=lambda cf: cf.activation_tuples[dim][0])
186
+
187
+ current = group[0]
188
+
189
+ for other in group[1:]:
190
+ current_start, current_end = current.activation_tuples[dim]
191
+ next_start, next_end = other.activation_tuples[dim]
192
+
193
+ if next_start <= current_end + 1:
194
+ current.activation_tuples[dim] = (
195
+ current_start,
196
+ max(current_end, next_end),
197
+ )
198
+ # we want the lowest strictest met threshold met anywhere in the finding
199
+ current.strictest_met_threshold = min(
200
+ current.strictest_met_threshold,
201
+ other.strictest_met_threshold,
202
+ )
203
+ changed = True
204
+ else:
205
+ next_merged_findings.append(current)
206
+ current = other
207
+
208
+ next_merged_findings.append(current)
209
+
210
+ merged_findings = next_merged_findings
211
+
212
+ # If there are word activation tuples supplied by a '_subword' label model,
213
+ # extend each activation tuple in a merged finding that overlaps a word activation
214
+ # tuple where there is no other activation tuple in the same merged finding that
215
+ # overlaps the same word activation tuple.
216
+ if word_activation_tuples:
217
+ for merged_finding in merged_findings:
218
+ for word_activation_tuple in word_activation_tuples:
219
+ for dim in range(arity):
220
+ merged_finding_activation_tuple = merged_finding.activation_tuples[
221
+ dim
222
+ ]
223
+ if _overlaps(
224
+ merged_finding_activation_tuple, word_activation_tuple
225
+ ):
226
+ if any(
227
+ other_dim != dim
228
+ and _overlaps(other_tuple, word_activation_tuple)
229
+ for other_dim, other_tuple in enumerate(
230
+ merged_finding.activation_tuples
231
+ )
232
+ ):
233
+ continue
234
+
235
+ merged_finding.activation_tuples[dim] = (
236
+ min(
237
+ merged_finding_activation_tuple[0],
238
+ word_activation_tuple[0],
239
+ ),
240
+ max(
241
+ merged_finding_activation_tuple[1],
242
+ word_activation_tuple[1],
243
+ ),
244
+ )
245
+ break
246
+
247
+ if word_activation_tuples:
248
+ # Subword expansion can cause multiple token-level findings to collapse
249
+ # on to the same word-level activation tuples. Deduplicate these, retaining
250
+ # the strictest threshold met by any of the original findings.
251
+
252
+ dedup_merged_findings: dict[tuple[tuple[int, int], ...], MergedFinding] = {}
253
+
254
+ for merged_finding in merged_findings:
255
+ key = tuple(merged_finding.activation_tuples)
256
+
257
+ if key not in dedup_merged_findings:
258
+ dedup_merged_findings[key] = merged_finding
259
+ else:
260
+ existing = dedup_merged_findings[key]
261
+ existing.strictest_met_threshold = min(
262
+ existing.strictest_met_threshold,
263
+ merged_finding.strictest_met_threshold,
264
+ )
265
+
266
+ merged_findings = list(dedup_merged_findings.values())
267
+
268
+ return merged_findings
269
+
270
+
271
+ class PolyprobeInferrer:
272
+ """
273
+ Uses a model to analyze one or more document pieces, assigning labels where the logits inferred by
274
+ the respective label models exceed a specified recall threshold, specified as the logit above
275
+ which the top %threshold of training data scored. Where adjacent tokens receive the same label,
276
+ the findings are merged, i.e. if tokens 6 and 7 both take part in a labelled relationship with tokens 2 and 3,
277
+ (6-7, 2-3) will be inferred.
278
+
279
+ expand_subwords: *True* if subwords in results should be expanded to the words that contain them provided
280
+ that other dimensions do not contain subwords with the same containing word; only has an effect if
281
+ *model* contains a label model with label '_subword'; findings that become identical after expansion are
282
+ deduplicated, retaining the strictest threshold met; *False* if label models with label '_subword' should
283
+ be ignored.
284
+ merge_adjacent_findings: *True* if findings should be merged that are identical in all dimensions except one,
285
+ and adjacent in that dimension; *False* otherwise.
286
+ """
287
+
288
+ def __init__(
289
+ self,
290
+ registry: PolyprobeRegistry,
291
+ lm_encoder: LMEncoder,
292
+ model: PolyprobeModel,
293
+ expand_subwords: bool,
294
+ merge_adjacent_findings: bool,
295
+ device: torch.device,
296
+ ):
297
+ self.lm_encoder = lm_encoder
298
+ self.expand_subwords = expand_subwords
299
+ self.merge_adjacent_findings = merge_adjacent_findings
300
+ self.device = device
301
+ # if there is a subword model, it must be at position 0
302
+ self.label_models = model.label_models[:]
303
+ self.label_models.sort(key=lambda lm: lm.label != "_subword")
304
+
305
+ if len(self.label_models) > 1 and self.label_models[1].label == "_subword":
306
+ raise ValueError("There may only be one subword label model in a model.")
307
+
308
+ self.label_model_probes: list[Probe] = []
309
+ self.label_model_poolers: list[Pooler] = []
310
+ self.label_model_index_tuple_selectors: list[IndexTupleSelector] = []
311
+ self.required_activation_types: set[ActivationType] = set()
312
+ self.stop_at_layer = 0
313
+ for label_model in self.label_models:
314
+ probe_type = registry.get_probe_type(label_model.probe_name)
315
+ probe_components = get_probe_components(
316
+ registry, label_model.probe_component_names
317
+ )
318
+ probe = probe_type(
319
+ probe_components,
320
+ label_model.head_nums[: label_model.num_head_results_to_pool],
321
+ model.head_infos,
322
+ self.device,
323
+ weights=label_model.weights[: label_model.num_head_results_to_pool, :],
324
+ **label_model.probe_kwargs,
325
+ )
326
+ self.label_model_probes.append(probe)
327
+ self.required_activation_types.update(probe.get_required_activation_types())
328
+ self.stop_at_layer = max(
329
+ self.stop_at_layer,
330
+ label_model.get_stop_at_layer(self.lm_encoder.head_infos, True),
331
+ )
332
+ self.label_model_poolers.append(
333
+ registry.get_pooler_type(label_model.pooler_name)(
334
+ **label_model.pooler_kwargs
335
+ )
336
+ )
337
+
338
+ self.label_model_index_tuple_selectors.append(
339
+ registry.get_index_tuple_selector_type(
340
+ label_model.index_tuple_selector_name
341
+ )(**label_model.index_tuple_selector_kwargs)
342
+ )
343
+
344
+ @torch.inference_mode()
345
+ def analyze(
346
+ self,
347
+ piece: DocumentPiece,
348
+ recall_threshold_overrides: dict[str, int] | None,
349
+ ) -> list[MergedFinding]:
350
+ """
351
+ piece: a document piece.
352
+ recall_threshold_overrides: a dictionary from labels to thresholds. Each specified threshold must
353
+ be a multiple of 5 up to 100; for example, a threshold of 30 means 'the logit above which the top
354
+ 30% of positive index tuples in the test split scored'. For labels for which no threshold is
355
+ specified, the threshold is used where the best f1 score was obtained for the test split.
356
+ These cutoffs determine only which findings are displayed for new sentences entered into the
357
+ inference console; they do not affect probe training, model selection or reported average precision.
358
+ For this purpose, the test split serves as a calibration set for a fourth, independently supplied set
359
+ of data consisting of sentences entered ad hoc by the inference-console user. The dictionary may not
360
+ specify labels for which there are no label models in the model.
361
+
362
+ Returns a list of merged findings. If *self.expand_subword = True* and the model contains a label
363
+ model with label '_subword', all subwords in each dimension of the merged finding list will be
364
+ expanded to its containing word. Findings that become identical after expansion are deduplicated,
365
+ retaining the strictest threshold met.
366
+ """
367
+ if len(piece.input_ids[0]) == 0:
368
+ return []
369
+ if recall_threshold_overrides is not None:
370
+ supported_labels = {lm.label for lm in self.label_models}
371
+ unsupported_overrides = {
372
+ label
373
+ for label in recall_threshold_overrides
374
+ if label not in supported_labels
375
+ }
376
+ if unsupported_overrides:
377
+ raise ValueError(
378
+ f"recall_threshold_overrides specifies at least one unsupported label: {unsupported_overrides}"
379
+ )
380
+
381
+ merged_findings_list: list[MergedFinding] = []
382
+
383
+ activation_container = self.lm_encoder.encode(
384
+ [piece],
385
+ self.required_activation_types,
386
+ self.stop_at_layer,
387
+ None,
388
+ )
389
+
390
+ word_activation_tuples: list[tuple[int, int]] | None = None
391
+ for label_model_idx, label_model in enumerate(self.label_models):
392
+ if not self.expand_subwords and label_model.label == "_subword":
393
+ continue
394
+
395
+ probe = self.label_model_probes[label_model_idx]
396
+ pooler = self.label_model_poolers[label_model_idx]
397
+ index_tuple_selector = self.label_model_index_tuple_selectors[
398
+ label_model_idx
399
+ ]
400
+
401
+ if (
402
+ recall_threshold_overrides is not None
403
+ and label_model.label in recall_threshold_overrides
404
+ ):
405
+ percent_threshold = recall_threshold_overrides[label_model.label]
406
+ else:
407
+ percent_threshold = None
408
+
409
+ findings = self._analyze_label_model(
410
+ piece,
411
+ activation_container,
412
+ label_model,
413
+ probe,
414
+ pooler,
415
+ index_tuple_selector,
416
+ percent_threshold,
417
+ )
418
+
419
+ if label_model.label == "_subword":
420
+ word_activation_tuples = _conflate_subwords(findings)
421
+ else:
422
+ merged_findings_list.extend(
423
+ _merge_findings(
424
+ findings,
425
+ label_model.label,
426
+ label_model.order,
427
+ piece,
428
+ self.merge_adjacent_findings,
429
+ word_activation_tuples,
430
+ )
431
+ )
432
+ del activation_container
433
+ return merged_findings_list
434
+
435
+ def _analyze_label_model(
436
+ self,
437
+ piece: DocumentPiece,
438
+ activation_container: ActivationStore,
439
+ label_model: PolyprobeLabelModel,
440
+ probe: Probe,
441
+ pooler: Pooler,
442
+ index_tuple_selector: IndexTupleSelector,
443
+ percent_threshold: int | None,
444
+ ) -> list[Finding]:
445
+ thresholds = label_model.test_evaluation.threshold_by_recall_percent
446
+ if percent_threshold is not None:
447
+ if percent_threshold not in thresholds:
448
+ raise ValueError(
449
+ f"Percent threshold {percent_threshold} is not available. Available percent threshold values are {thresholds.keys()}"
450
+ )
451
+ threshold = thresholds[percent_threshold]
452
+ else:
453
+ threshold = label_model.test_evaluation.threshold_at_best_f1
454
+
455
+ index_tuples = index_tuple_selector.get_index_tuples(
456
+ piece, len(label_model.order)
457
+ )
458
+ if index_tuples.shape[0] == 0:
459
+ return []
460
+
461
+ inputs = probe.build_input(activation_container, [index_tuples]).to(self.device)
462
+ logits = probe(inputs)
463
+ pooled_logits = pooler.reduce(
464
+ logits, label_model.num_head_results_to_pool
465
+ ).cpu()
466
+ assert pooled_logits.shape[0] == index_tuples.shape[0]
467
+ del inputs, logits
468
+ truths = pooled_logits >= threshold
469
+
470
+ finding_index_tuples = index_tuples[truths].tolist()
471
+
472
+ finding_logits = pooled_logits[truths].tolist()
473
+ findings = [
474
+ Finding(
475
+ tuple(it),
476
+ _strictest_met_threshold(logit, thresholds),
477
+ )
478
+ for it, logit in zip(finding_index_tuples, finding_logits)
479
+ ]
480
+ return findings