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
polyprobe/batching.py ADDED
@@ -0,0 +1,133 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from collections.abc import Generator
7
+ from contextlib import contextmanager
8
+ from typing import cast
9
+
10
+ import torch
11
+
12
+ from polyprobe.util import empty_cache, is_out_of_memory_error
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class BatchingMemoryException(Exception):
18
+ pass
19
+
20
+
21
+ class BatchSizeManager:
22
+ """Attempts different batch sizes across n dimensions, gradually reducing each dimension in the specified order
23
+ until a batch size is found that fits in the available memory.
24
+
25
+ Consecutive calls to batch_size_to_attempt() retain information about the maximum batch size derived from previous
26
+ failed attempts, in order that e.g. the same batch size manager may be used to train multiple labels without having
27
+ to derive the correct batch size for each one. To reset the learned dimension sizes, instantiate a new batch size
28
+ manager.
29
+
30
+ dims_to_reduce: the dimensions to reduce in the order to try, e.g. [1, 0]
31
+ dim_labels: labels for all dimensions, including non-reducible dimensions, at least up to the highest value in *dims_to_reduce*,
32
+ ordered by their indices rather than by *dims_to_reduce*.
33
+ caller_label: a label specifying what the manager is being used for, e.g. 'evaluation'.
34
+ reduce_factor: the decimal by which the batch size in a dimension is multiplied after an OOM.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ dims_to_reduce: list[int],
40
+ dim_labels: list[str],
41
+ device: torch.device,
42
+ caller_label: str,
43
+ *,
44
+ reduce_factor: float = 0.95,
45
+ ):
46
+ if len(set(dims_to_reduce)) != len(dims_to_reduce):
47
+ raise ValueError(
48
+ f"Dims_to_reduce {dims_to_reduce} may not contain duplicate values."
49
+ )
50
+ if len(set(dim_labels)) != len(dim_labels):
51
+ raise ValueError(
52
+ f"Dim_labels {dim_labels} may not contain duplicate values."
53
+ )
54
+
55
+ if max(dims_to_reduce) >= len(dim_labels):
56
+ raise ValueError(
57
+ f"Dims_to_reduce specifies at least {max(dims_to_reduce)} dimension(s); dim_labels contains only {len(dim_labels)} value(s)."
58
+ )
59
+ self.dims_to_reduce = dims_to_reduce[:]
60
+ self.dim_labels = dim_labels[:]
61
+ self.device = device
62
+ self.caller_label = caller_label
63
+ self.batch_shape: list[int] | None = None
64
+ if reduce_factor <= 0.0 or reduce_factor >= 1.0:
65
+ raise ValueError("reduce_factor must be a float value 0<x<1.")
66
+ self.reduce_factor = reduce_factor
67
+ self.has_failed = False
68
+
69
+ def _notify_failure(self, e: Exception) -> None:
70
+ e.__traceback__ = None
71
+ del e
72
+ empty_cache(self.device)
73
+ self.has_failed = True
74
+ batch_shape = cast(list[int], self.batch_shape)
75
+ original_batch_shape = batch_shape[:]
76
+ for dim_to_reduce in self.dims_to_reduce:
77
+ if batch_shape[dim_to_reduce] == 1:
78
+ continue
79
+ potential_dim_size = int(batch_shape[dim_to_reduce] * self.reduce_factor)
80
+ batch_shape[dim_to_reduce] = max(1, potential_dim_size)
81
+ break
82
+ else:
83
+ raise ValueError(
84
+ f"The batch shape {original_batch_shape} has caused an OOM and cannot be reduced further."
85
+ )
86
+ logger.info(
87
+ f"An OOM occurred for {self.caller_label} with batch size {self._get_repr(original_batch_shape)}, reducing batch size to {self._get_repr(batch_shape)}."
88
+ )
89
+
90
+ @contextmanager
91
+ def batch_size_to_attempt(
92
+ self, full_shape: list[int]
93
+ ) -> Generator[list[int], None, None]:
94
+ """Called with the shape of the data to process; yields the batch size to attempt,
95
+ which is progressively reduced following OOMs until the data fits.
96
+
97
+ As long as batching is being attempted for the same data, the value of *full_shape*
98
+ should remain the same.
99
+ """
100
+ if any(d >= len(full_shape) for d in self.dims_to_reduce):
101
+ raise ValueError(
102
+ f"Dims to reduce {self.dims_to_reduce} specify more dimensions than full shape {full_shape}."
103
+ )
104
+ shape_to_return = full_shape[:]
105
+ if not self.batch_shape:
106
+ self.batch_shape = full_shape[:]
107
+ logger.info(
108
+ f"Initial batch shape for {self.caller_label} is {self._get_repr(self.batch_shape)}."
109
+ )
110
+ else:
111
+ for dim in range(len(shape_to_return)):
112
+ if (
113
+ dim in self.dims_to_reduce
114
+ and self.batch_shape[dim] < shape_to_return[dim]
115
+ ):
116
+ shape_to_return[dim] = self.batch_shape[dim]
117
+ try:
118
+ yield shape_to_return
119
+ except torch.OutOfMemoryError as e:
120
+ self._notify_failure(e)
121
+ raise BatchingMemoryException() from None
122
+ except RuntimeError as e:
123
+ if is_out_of_memory_error(e):
124
+ self._notify_failure(e)
125
+ raise BatchingMemoryException() from None
126
+ raise
127
+
128
+ def _get_repr(self, batch_shape: list[int]) -> str:
129
+ batch_repr = ", ".join(
130
+ f"{dim} {self.dim_labels[idx]}" for idx, dim in enumerate(batch_shape)
131
+ )
132
+
133
+ return f"({batch_repr})" if len(batch_shape) > 1 else batch_repr
polyprobe/config.py ADDED
@@ -0,0 +1,101 @@
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 RunConfig:
11
+ """
12
+ Configuration parameters common to the train() and evaluate() methods.
13
+
14
+ initial_document_encoding_batch_size: the initially attempted batch size for encoding the document pieces for train/eval/test.
15
+ specified_maximum_tensor_mebibytes: the maximum number of mebibytes the process may try to assign to tensors. The value should
16
+ typically be left as the default *None*, in which case an estimate is derived from the measured available CPU and (where appropriate)
17
+ CUDA memory. However, if the process is killed or hangs, consider setting a lower value than the measured one reported at the
18
+ beginning of the log file; and if CUDA is being used and no OOMs are logged at the beginning of a substantial training run when
19
+ the optimum batch size is being ascertained (suggesting that the GPU may not be being used as efficiently as it could be),
20
+ consider setting a higher value than the measured one reported at the beginning of the log file.
21
+ max_heads_to_pool: the maximum top n heads for which to generate pooled evaluation results.
22
+ log_recall_percent_stats: *True* if detailed stats on the rank fraction and precision at each available recall percent value
23
+ for each head are required, otherwise *False*.
24
+ log_incorrect_examples: whether the highest-scoring negative and the lowest-scoring positive examples should be logged along with the
25
+ evaluation statistics.
26
+ max_wrong_examples_to_return: the maximum number of positive and negative examples to show, if log_incorrect_examples is *True*.
27
+ seed: a seed for sampling sentences from dataset sources and for shuffling when creating the train/eval/test split.
28
+ show_progress: whether or not to display a tqdm progress bar.
29
+ """
30
+
31
+ initial_document_encoding_batch_size: int = 100
32
+ specified_maximum_tensor_mebibytes: int | None = None
33
+ max_heads_to_pool: int = 100
34
+ log_recall_percent_stats: bool = True
35
+ log_incorrect_examples: bool = True
36
+ max_wrong_examples_to_return: int = 5
37
+ seed: int = 4711
38
+ show_progress: bool = True
39
+
40
+ def __post_init__(self) -> None:
41
+ if self.initial_document_encoding_batch_size <= 0:
42
+ raise ValueError("initial_document_encoding_batch_size must be positive.")
43
+ if self.max_heads_to_pool <= 0:
44
+ raise ValueError("max_heads_to_pool must be positive.")
45
+ if (
46
+ self.specified_maximum_tensor_mebibytes is not None
47
+ and self.specified_maximum_tensor_mebibytes <= 0
48
+ ):
49
+ raise ValueError("specified_maximum_tensor_mebibytes must be positive.")
50
+ if self.max_wrong_examples_to_return <= 0:
51
+ raise ValueError("max_wrong_examples_to_return must be positive.")
52
+
53
+
54
+ @dataclass
55
+ class EvaluationDatasetConfig:
56
+ """
57
+ Configuration parameters describing a single evaluation dataset.
58
+ identifier: the identifier; with Universal Dependency dataset sources, the repository name,
59
+ e.g. "UD_English-EWT", "UD_Welsh-CCG".
60
+ label: a description of the dataset to use e.g. in charts, e.g "English", "Welsh".
61
+ """
62
+
63
+ identifier: str
64
+ label: str
65
+
66
+ def __post_init__(self) -> None:
67
+ if self.label in ("train", "dev", "test"):
68
+ raise ValueError(
69
+ "train, dev and test are forbidden as evaluation dataset labels."
70
+ )
71
+
72
+
73
+ @dataclass
74
+ class EvaluationDatasetSourceConfig:
75
+ """
76
+ Configuration parameters describing the evaluation data.
77
+ dataset_configs: the configurations of one or more datasets to evaluate, each with a unique label.
78
+ dataset_source_name: the name of the dataset source implementation.
79
+ dataset_source_kwargs: a dictionary of named arguments to pass to the class' _init__() method when creating the instance,
80
+ or {} if no init parameters are required.
81
+ num_test_sentences: the number of test sentences to attempt to sample. Sentences can be skipped if there are issues with
82
+ extracting the data, resulting in a lower number being sampled than specified.
83
+ """
84
+
85
+ dataset_configs: list[EvaluationDatasetConfig]
86
+ dataset_source_name: str = "UDDependencyCausalDatasetSource"
87
+ dataset_source_kwargs: dict[str, Any] = field(default_factory=dict)
88
+ num_test_sentences: int = 500
89
+
90
+ def __post_init__(self) -> None:
91
+ if len(self.dataset_configs) == 0:
92
+ raise ValueError("At least one dataset is required.")
93
+ labels: set[str] = set()
94
+ for dataset in self.dataset_configs:
95
+ if dataset.label in labels:
96
+ raise ValueError(
97
+ f"Duplicate evaluation dataset label: {dataset.label!r}."
98
+ )
99
+ labels.add(dataset.label)
100
+ if self.num_test_sentences < 1:
101
+ raise ValueError("num_test_sentences must be a positive integer.")
polyprobe/document.py ADDED
@@ -0,0 +1,138 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from dataclasses import dataclass, field
7
+ from random import Random
8
+
9
+ from torch import Tensor
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class TrainingLabel:
16
+ """A source annotation referencing training-token IDs within a document piece.
17
+
18
+ name: the label name, which may be shared by different dataset sources.
19
+ training_token_idxs: IDs of the training tokens taking part in the
20
+ labelled relationship; these are not LM-token indices.
21
+ order: the relationship's direction relative to training_token_idxs.
22
+ For a pair (4, 6), order (0, 1) means 4 points to 6, while (1, 0)
23
+ means 6 points to 4.
24
+ """
25
+
26
+ name: str
27
+ training_token_idxs: tuple[int, ...]
28
+ order: tuple[int, ...]
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class MatchedTrainingToken:
33
+ """A training token aligned to one or more LM tokens in a piece.
34
+
35
+ idx: the training-token ID referenced by TrainingLabel and used as the
36
+ key in DocumentPiece.training_tokens.
37
+ training_offsets: the character span (start inclusive, end exclusive)
38
+ within the piece's text.
39
+ matching_lm_token_idxs: matching LM-token indices in text order.
40
+ Distinct training tokens may share LM-token indices.
41
+
42
+ Freezing prevents field reassignment; the contained list remains mutable.
43
+ """
44
+
45
+ idx: int
46
+ training_offsets: tuple[int, int]
47
+ matching_lm_token_idxs: list[int]
48
+
49
+ @property
50
+ def last_matching_lm_token_idx(self) -> int:
51
+ """Return the final entry in matching_lm_token_idxs.
52
+
53
+ The list must be nonempty and ordered by token position for this
54
+ to identify the rightmost matching LM token.
55
+ """
56
+ return self.matching_lm_token_idxs[-1]
57
+
58
+
59
+ @dataclass
60
+ class DocumentPiece:
61
+ """A tokenized stretch of document text, typically a sentence.
62
+
63
+ text: the text of this piece.
64
+ input_ids: the LM token IDs encoding this piece.
65
+ lm_offsets: character spans (start inclusive, end exclusive) relative
66
+ to text, aligned with the LM-token sequence.
67
+ identifier: a display identifier for training and evaluation.
68
+ training_tokens: training tokens keyed by their training-token IDs.
69
+ training_labels: labels referencing those training-token IDs.
70
+
71
+ Training annotations default to empty collections.
72
+ """
73
+
74
+ text: str
75
+ input_ids: Tensor
76
+ lm_offsets: list[tuple[int, int]]
77
+ identifier: str
78
+ training_tokens: dict[int, MatchedTrainingToken] = field(default_factory=dict)
79
+ training_labels: set[TrainingLabel] = field(default_factory=set)
80
+
81
+ def get_training_labels(
82
+ self, label: str, order: tuple[int, ...]
83
+ ) -> list[TrainingLabel]:
84
+ """Return labels whose name and order exactly match the supplied values.
85
+
86
+ Result order is unspecified because training_labels is a set.
87
+ Assert that each matching label contains one training-token ID per
88
+ position in order.
89
+ """
90
+ training_labels = [
91
+ tl for tl in self.training_labels if tl.name == label and tl.order == order
92
+ ]
93
+ for training_label in training_labels:
94
+ assert len(training_label.training_token_idxs) == len(order)
95
+ return training_labels
96
+
97
+
98
+ @dataclass
99
+ class DocumentPieceList:
100
+ """Document pieces tokenized for a specific language model.
101
+
102
+ Pieces may form a consecutive document or be sampled from a corpus.
103
+
104
+ pieces: the document pieces in their current order.
105
+ lm_name: the LM identifier, e.g. "Qwen/Qwen3-4B".
106
+ assigned_training_labels_and_orders: label/order combinations assigned
107
+ to this collection, or an empty set for unannotated data. This
108
+ metadata is maintained by callers and is not recomputed from pieces.
109
+ """
110
+
111
+ pieces: list[DocumentPiece]
112
+ lm_name: str
113
+ assigned_training_labels_and_orders: set[tuple[str, tuple[int, ...]]] = field(
114
+ default_factory=set
115
+ )
116
+
117
+ def merge(self, other: "DocumentPieceList") -> None:
118
+ """Append another list's pieces and union its label/order metadata in place.
119
+
120
+ Document pieces are shared with the other list rather than copied.
121
+ Raise ValueError without modifying this list if the LM names differ.
122
+ """
123
+ if self.lm_name != other.lm_name:
124
+ raise ValueError(
125
+ "Only document piece lists from the same language model can be merged."
126
+ )
127
+ self.pieces.extend(other.pieces)
128
+ self.assigned_training_labels_and_orders.update(
129
+ other.assigned_training_labels_and_orders
130
+ )
131
+
132
+ def shuffle(self, rng: Random) -> None:
133
+ """Shuffle pieces in place using rng, leaving label/order metadata unchanged."""
134
+ rng.shuffle(self.pieces)
135
+
136
+ def __len__(self) -> int:
137
+ """Return the number of document pieces."""
138
+ return len(self.pieces)