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
polyprobe/util.py
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Richard Paul Hudson
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import gc
|
|
6
|
+
import hashlib
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from bisect import bisect_right
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from itertools import accumulate, cycle
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, cast
|
|
15
|
+
|
|
16
|
+
import psutil
|
|
17
|
+
import torch
|
|
18
|
+
from torch import Tensor
|
|
19
|
+
|
|
20
|
+
from polyprobe.activations import ActivationStore, ActivationType
|
|
21
|
+
from polyprobe.config import EvaluationDatasetConfig
|
|
22
|
+
from polyprobe.document import DocumentPiece
|
|
23
|
+
from polyprobe.lm_encoder import LMEncoder
|
|
24
|
+
from polyprobe.model import DatasetSourceUsage, PolyprobeLabelModel
|
|
25
|
+
from polyprobe.probe_components.probe_component import ProbeComponent
|
|
26
|
+
from polyprobe.probes.probe import Probe
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
# The maximum proportion of available CPU or MPS memory the process may attempt to allocate to tensors
|
|
31
|
+
MEMORY_QUOTIENT = 0.7
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_device() -> torch.device:
|
|
35
|
+
"""
|
|
36
|
+
Returns the optimal device for training and evaluation on the available hardware.
|
|
37
|
+
"""
|
|
38
|
+
if sys.platform == "darwin" and torch.backends.mps.is_available():
|
|
39
|
+
device = "mps"
|
|
40
|
+
elif torch.cuda.is_available():
|
|
41
|
+
device = "cuda"
|
|
42
|
+
else:
|
|
43
|
+
device = "cpu"
|
|
44
|
+
logger.info(f"Using {device}.")
|
|
45
|
+
return torch.device(device)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def empty_cache(device: torch.device) -> None:
|
|
49
|
+
gc.collect()
|
|
50
|
+
match device.type:
|
|
51
|
+
case "cuda":
|
|
52
|
+
torch.cuda.empty_cache()
|
|
53
|
+
case "mps":
|
|
54
|
+
torch.mps.empty_cache()
|
|
55
|
+
case _: # cpu
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_index_of_first_head_on_or_above_layer(
|
|
60
|
+
head_infos: list[tuple[int, int]], layer: int, is_end: bool
|
|
61
|
+
) -> int:
|
|
62
|
+
"""Returns the index of the first head on or above a specified layer.
|
|
63
|
+
|
|
64
|
+
head_infos: a list of (<layer no>, <head no>) tuples describing the head at each head index.
|
|
65
|
+
In architectures where not all layers are attention layers, not every layer
|
|
66
|
+
will have entries in the list.
|
|
67
|
+
layer: the specified layer.
|
|
68
|
+
is_end: if *True*, the situation is supported where the specified layer is one more than
|
|
69
|
+
the highest available layer, enabling the index to be used for end of range.
|
|
70
|
+
"""
|
|
71
|
+
if is_end and head_infos[-1][0] + 1 == layer:
|
|
72
|
+
return len(head_infos)
|
|
73
|
+
index = next((i for i in range(len(head_infos)) if layer <= head_infos[i][0]), None)
|
|
74
|
+
if index is None:
|
|
75
|
+
raise ValueError(f"No heads on or above layer {layer} found.")
|
|
76
|
+
return index
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def describe_head_index(index: int, head_infos: list[tuple[int, int]]) -> str:
|
|
80
|
+
"""Returns the <layer.head> representation of a head number index."""
|
|
81
|
+
if not 0 <= index < len(head_infos):
|
|
82
|
+
raise ValueError(
|
|
83
|
+
f"Head index {index} was specified, but the document only has {len(head_infos)} heads."
|
|
84
|
+
)
|
|
85
|
+
return f"{head_infos[index][0]}.{head_infos[index][1]}"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
SPECIAL_CHAR_LABEL = "<special char>"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def get_activation_tuples_representation(
|
|
92
|
+
piece: DocumentPiece,
|
|
93
|
+
activation_tuples: list[tuple[int, int]],
|
|
94
|
+
order: tuple[int, ...],
|
|
95
|
+
) -> str:
|
|
96
|
+
"""Returns a human-readable representation of an attention relationship between 1..n activation tuples where
|
|
97
|
+
each activation tuple has the form (token start index, token end index).
|
|
98
|
+
|
|
99
|
+
piece: the containing document piece.
|
|
100
|
+
activation_tuples: the activation tuples taking part in the attention relationship.
|
|
101
|
+
order: the direction of the attention relationship.
|
|
102
|
+
"""
|
|
103
|
+
assert len(activation_tuples) == len(order)
|
|
104
|
+
dim_reprs: list[str] = []
|
|
105
|
+
for dim in order:
|
|
106
|
+
token_start, token_end = activation_tuples[dim]
|
|
107
|
+
start = piece.lm_offsets[token_start]
|
|
108
|
+
end = piece.lm_offsets[token_end]
|
|
109
|
+
text = piece.text[start[0] : end[1]]
|
|
110
|
+
if start[0] == start[1]:
|
|
111
|
+
if len(text) == 0:
|
|
112
|
+
text = SPECIAL_CHAR_LABEL
|
|
113
|
+
else:
|
|
114
|
+
text = f"{SPECIAL_CHAR_LABEL} {text}"
|
|
115
|
+
if token_start != token_end and end[0] == end[1]:
|
|
116
|
+
if len(text) == 0:
|
|
117
|
+
text = SPECIAL_CHAR_LABEL
|
|
118
|
+
else:
|
|
119
|
+
text = f"{text} {SPECIAL_CHAR_LABEL}"
|
|
120
|
+
dim_reprs.append(f"{text} ({start[0]}: {end[1]})")
|
|
121
|
+
return " -> ".join(dim_reprs)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def get_label_model_description_log_lines(
|
|
125
|
+
label_model: PolyprobeLabelModel, head_infos: list[tuple[int, int]]
|
|
126
|
+
) -> list[str]:
|
|
127
|
+
log_lines = [
|
|
128
|
+
f"Label model for label {label_model.label} and order {label_model.order}"
|
|
129
|
+
]
|
|
130
|
+
log_lines.append(
|
|
131
|
+
f"Probe {label_model.probe_name} with kwargs {label_model.probe_kwargs}"
|
|
132
|
+
)
|
|
133
|
+
log_lines.append(f"Probe components {label_model.probe_component_names}")
|
|
134
|
+
log_lines.append(
|
|
135
|
+
f"Pooler {label_model.pooler_name} with kwargs {label_model.pooler_kwargs}"
|
|
136
|
+
)
|
|
137
|
+
log_lines.append(
|
|
138
|
+
f"Index tuple selector {label_model.index_tuple_selector_name} with kwargs {label_model.index_tuple_selector_kwargs}"
|
|
139
|
+
)
|
|
140
|
+
log_lines.append(
|
|
141
|
+
f"Truther {label_model.truther_name} with kwargs {label_model.truther_kwargs}"
|
|
142
|
+
)
|
|
143
|
+
log_lines.append(
|
|
144
|
+
f"Scorer {label_model.scorer_name} with kwargs {label_model.scorer_kwargs}"
|
|
145
|
+
)
|
|
146
|
+
log_lines.append(
|
|
147
|
+
f"Using {label_model.num_head_results_to_pool} heads: "
|
|
148
|
+
+ "; ".join(
|
|
149
|
+
describe_head_index(head_num, head_infos)
|
|
150
|
+
for head_num in label_model.head_nums[
|
|
151
|
+
: label_model.num_head_results_to_pool
|
|
152
|
+
]
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
return log_lines
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def get_required_activation_types(
|
|
159
|
+
probe_components: list[ProbeComponent],
|
|
160
|
+
) -> set[ActivationType]:
|
|
161
|
+
"""
|
|
162
|
+
Returns the activation types required by a list of probe components.
|
|
163
|
+
"""
|
|
164
|
+
return set().union(*(pc.get_required_activation_types() for pc in probe_components))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def get_probe_components(
|
|
168
|
+
registry: "PolyprobeRegistry", component_names: list[str] # type: ignore[name-defined]
|
|
169
|
+
) -> list[ProbeComponent]:
|
|
170
|
+
"""
|
|
171
|
+
Returns the currently registered probe components.
|
|
172
|
+
"""
|
|
173
|
+
return [registry.get_probe_component_type(pcn)() for pcn in component_names]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def is_out_of_memory_error(e: RuntimeError) -> bool:
|
|
177
|
+
"""
|
|
178
|
+
Determines whether a runtime error is to be classified as an OOM based on its textual content.
|
|
179
|
+
"""
|
|
180
|
+
text = str(e).lower()
|
|
181
|
+
|
|
182
|
+
if "same device" in text:
|
|
183
|
+
return False
|
|
184
|
+
|
|
185
|
+
memory_error_patterns = (
|
|
186
|
+
"out of memory",
|
|
187
|
+
"not enough memory",
|
|
188
|
+
"can't allocate memory",
|
|
189
|
+
"defaultcpuallocator",
|
|
190
|
+
"invalid buffer size",
|
|
191
|
+
"mpsgraph does not support tensor dims larger than int_max",
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
return any(pattern in text for pattern in memory_error_patterns)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def get_index_tuple_boundaries(index_tuples_list: list[Tensor]) -> list[int]:
|
|
198
|
+
"""
|
|
199
|
+
Returns the cumulative offsets of the index tuples associated with a list of
|
|
200
|
+
document pieces, starting with 0 and ending with the end offset for the final document piece.
|
|
201
|
+
"""
|
|
202
|
+
return list(
|
|
203
|
+
accumulate(
|
|
204
|
+
(index_tuples.shape[0] for index_tuples in index_tuples_list),
|
|
205
|
+
initial=0,
|
|
206
|
+
)
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def get_batch_end(
|
|
211
|
+
index_tuple_boundaries: list[int],
|
|
212
|
+
index_tuple_batch_size: int,
|
|
213
|
+
start_piece_idx: int,
|
|
214
|
+
max_num_docs: int | None = None,
|
|
215
|
+
) -> int:
|
|
216
|
+
"""
|
|
217
|
+
Determines the exclusive end index of the final document piece in the next batch, taking into account the number of
|
|
218
|
+
index tuples associated with each document piece.
|
|
219
|
+
|
|
220
|
+
index_tuple_boundaries: the cumulative offsets of the index tuples for each document piece, starting with 0 and
|
|
221
|
+
ending with the end offset for the final document piece.
|
|
222
|
+
index_tuple_batch_size: the maximum number of index tuples permitted in a batch.
|
|
223
|
+
start_piece_idx: the index of the first document piece in the batch.
|
|
224
|
+
max_num_docs: an optional upper bound on the number of documents in the batch.
|
|
225
|
+
"""
|
|
226
|
+
target = index_tuple_boundaries[start_piece_idx] + index_tuple_batch_size
|
|
227
|
+
|
|
228
|
+
end_piece_idx = bisect_right(index_tuple_boundaries, target) - 1
|
|
229
|
+
if max_num_docs is not None and end_piece_idx - start_piece_idx > max_num_docs:
|
|
230
|
+
end_piece_idx = start_piece_idx + max_num_docs
|
|
231
|
+
if start_piece_idx == end_piece_idx:
|
|
232
|
+
raise ValueError(
|
|
233
|
+
"A single document piece contains more index tuples than the index-tuple batch size. Consider lowering the value of max_tokens in the dataset source."
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
return end_piece_idx
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def get_maximum_tensor_mebibytes(device: torch.device) -> int:
|
|
240
|
+
"""
|
|
241
|
+
Returns the number of mebibytes of memory that this process should attempt to
|
|
242
|
+
allocate to tensors.
|
|
243
|
+
|
|
244
|
+
The CPU result is constrained by both the operating system's currently available
|
|
245
|
+
memory and, on a best-effort basis, any applicable cgroup/container memory
|
|
246
|
+
limit. This allows the function to account for environments such as Kubernetes,
|
|
247
|
+
where the memory available to a container may be substantially less than the
|
|
248
|
+
host's available memory. Container limits are detected on a best-effort basis
|
|
249
|
+
because their availability and representation depend on the runtime and cgroup
|
|
250
|
+
configuration: if no applicable limit can be determined, the operating system's
|
|
251
|
+
available memory is returned. The CPU figure is multiplied by MEMORY_QUOTIENT to
|
|
252
|
+
reduce the likelihood of memory being exhausted, which could cause the process
|
|
253
|
+
to be killed or to hang.
|
|
254
|
+
|
|
255
|
+
On MPS, the available memory is also multiplied by MEMORY_QUOTIENT and the smaller
|
|
256
|
+
of the scaled CPU and scaled MPS figures is returned.
|
|
257
|
+
|
|
258
|
+
The CUDA result deliberately avoids using MEMORY_QUOTIENT, because the *BatchSizeManager*
|
|
259
|
+
progressively reduces the batch size until one is found that fits, and we wish
|
|
260
|
+
to use the GPU as efficiently as possible. For CUDA, the smaller of the scaled CPU
|
|
261
|
+
and non-scaled CUDA figures is returned. (The way the library is structured means
|
|
262
|
+
that it is unable to efficiently use setups where the available GPU memory exceeds
|
|
263
|
+
the available CPU memory.)
|
|
264
|
+
"""
|
|
265
|
+
available_bytes = psutil.virtual_memory().available
|
|
266
|
+
|
|
267
|
+
# Common cgroup-v2/container layout.
|
|
268
|
+
memory_max = Path("/sys/fs/cgroup/memory.max")
|
|
269
|
+
memory_current = Path("/sys/fs/cgroup/memory.current")
|
|
270
|
+
try:
|
|
271
|
+
if memory_max.exists() and memory_current.exists():
|
|
272
|
+
max_text = memory_max.read_text().strip()
|
|
273
|
+
|
|
274
|
+
if max_text != "max":
|
|
275
|
+
limit = int(max_text)
|
|
276
|
+
current = int(memory_current.read_text().strip())
|
|
277
|
+
cgroup_available = max(0, limit - current)
|
|
278
|
+
available_bytes = min(available_bytes, cgroup_available)
|
|
279
|
+
except (OSError, ValueError):
|
|
280
|
+
logger.debug(
|
|
281
|
+
"Could not determine cgroup memory availability; "
|
|
282
|
+
"using operating-system availability.",
|
|
283
|
+
exc_info=True,
|
|
284
|
+
)
|
|
285
|
+
available_bytes = int(available_bytes * MEMORY_QUOTIENT)
|
|
286
|
+
|
|
287
|
+
if device.type == "cuda":
|
|
288
|
+
free, total = torch.cuda.mem_get_info(device)
|
|
289
|
+
allocated = torch.cuda.memory_allocated(device)
|
|
290
|
+
reserved = torch.cuda.memory_reserved(device)
|
|
291
|
+
reusable_cache = max(0, reserved - allocated)
|
|
292
|
+
available_bytes = min(available_bytes, total, free + reusable_cache)
|
|
293
|
+
elif device.type == "mps":
|
|
294
|
+
free = int(
|
|
295
|
+
max(
|
|
296
|
+
0,
|
|
297
|
+
torch.mps.recommended_max_memory()
|
|
298
|
+
- torch.mps.driver_allocated_memory(),
|
|
299
|
+
)
|
|
300
|
+
* MEMORY_QUOTIENT
|
|
301
|
+
)
|
|
302
|
+
available_bytes = min(available_bytes, free)
|
|
303
|
+
|
|
304
|
+
return int(available_bytes / 1024 / 1024)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def get_probe_input_capacity(
|
|
308
|
+
activation_store: ActivationStore,
|
|
309
|
+
lm_encoder: LMEncoder,
|
|
310
|
+
probe_type: type[Probe],
|
|
311
|
+
probe_kwargs: dict[str, Any],
|
|
312
|
+
probe_components: list[ProbeComponent],
|
|
313
|
+
maximum_tensor_mebibytes: int,
|
|
314
|
+
device: torch.device,
|
|
315
|
+
) -> int:
|
|
316
|
+
"""
|
|
317
|
+
Ascertains the maximum value of heads * index_tuples to attempt as a batch size, taking into account a quirk of MPS
|
|
318
|
+
with respect to permissible tensor dimension sizes.
|
|
319
|
+
"""
|
|
320
|
+
probe = probe_type(
|
|
321
|
+
probe_components, [0], lm_encoder.head_infos, device, **probe_kwargs
|
|
322
|
+
)
|
|
323
|
+
probe_input_capacity = max(
|
|
324
|
+
1,
|
|
325
|
+
(maximum_tensor_mebibytes * 1024 * 1024)
|
|
326
|
+
// probe.get_total_component_byte_width(activation_store),
|
|
327
|
+
)
|
|
328
|
+
if device.type == "mps":
|
|
329
|
+
dim_constrained_probe_input_capacity = int(
|
|
330
|
+
torch.iinfo(torch.int32).max
|
|
331
|
+
/ probe.get_total_component_input_dimension(activation_store)
|
|
332
|
+
)
|
|
333
|
+
if dim_constrained_probe_input_capacity < probe_input_capacity:
|
|
334
|
+
logger.info(
|
|
335
|
+
f"Reducing the maximum permissible (heads * index_tuples) size from {probe_input_capacity} to {dim_constrained_probe_input_capacity} "
|
|
336
|
+
"because MPSGraph does not support tensor dims larger than INT_MAX."
|
|
337
|
+
)
|
|
338
|
+
probe_input_capacity = dim_constrained_probe_input_capacity
|
|
339
|
+
return probe_input_capacity
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def get_config_dict_log_lines(config_dict_label: str, config_dict: Any) -> list[str]:
|
|
343
|
+
"""Returns a textual representation of a configuration dictionary for logging."""
|
|
344
|
+
log_lines = [f"{config_dict_label}:"]
|
|
345
|
+
for k, v in config_dict.__dict__.items():
|
|
346
|
+
log_lines.append(f"\t{k}: {v}")
|
|
347
|
+
return log_lines
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def check_matplotlib_installed() -> None:
|
|
351
|
+
try:
|
|
352
|
+
import matplotlib
|
|
353
|
+
except ImportError:
|
|
354
|
+
raise RuntimeError(
|
|
355
|
+
"plots_dir was set, but matplotlib is not available. Please install the 'plot' optional dependencies."
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
@dataclass
|
|
360
|
+
class DatasetEvaluationWithLabelModel:
|
|
361
|
+
"""
|
|
362
|
+
The results of evaluating a dataset with a label model (not serializable, intended for
|
|
363
|
+
temporary use when evaluating a dataset and plotting curves).
|
|
364
|
+
|
|
365
|
+
dataset_config: the configuration of the dataset to evaluate.
|
|
366
|
+
unpooled_evaluation_scores: the scores achieved at individual heads; index-matched to the
|
|
367
|
+
head_nums in the label model.
|
|
368
|
+
pooled_evaluation_scores: the scores achieved by pooling the logits returned at the first
|
|
369
|
+
n heads; index-matched to the head nums in the label model.
|
|
370
|
+
num_positive_index_tuples: the number of positively labelled index tuples in the dataset.
|
|
371
|
+
positive_prevalence: the proportion of positively labelled index tuples in the dataset.
|
|
372
|
+
"""
|
|
373
|
+
|
|
374
|
+
dataset_config: EvaluationDatasetConfig
|
|
375
|
+
unpooled_evaluation_scores: list[float]
|
|
376
|
+
pooled_evaluation_scores: list[float]
|
|
377
|
+
num_positive_index_tuples: int
|
|
378
|
+
positive_prevalence: float
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def plot_label_model_evaluation_curves(
|
|
382
|
+
output_dir: Path,
|
|
383
|
+
label_model: PolyprobeLabelModel,
|
|
384
|
+
head_infos: list[tuple[int, int]],
|
|
385
|
+
description: str | None,
|
|
386
|
+
scorer_label: str,
|
|
387
|
+
dataset_evaluations: list[DatasetEvaluationWithLabelModel] | None = None,
|
|
388
|
+
) -> None:
|
|
389
|
+
"""
|
|
390
|
+
Plot individual-head and cumulative pooled evaluation curves as both PNG and SVG.
|
|
391
|
+
|
|
392
|
+
Train, dev and test scores are taken from *label_model*.
|
|
393
|
+
|
|
394
|
+
Optionally, one or additional pairs of unpooled/pooled score curves can be
|
|
395
|
+
supplied showing evaluation against external datasets.
|
|
396
|
+
"""
|
|
397
|
+
|
|
398
|
+
def get_split_name_legend(split_name: str) -> str:
|
|
399
|
+
if split_name in ("train", "dev", "test"):
|
|
400
|
+
return f"{split_name} ({label_model.num_positive_index_tuples[cast(DatasetSourceUsage, split_name)]} / {label_model.positive_prevalences[cast(DatasetSourceUsage, split_name)]:.5f})"
|
|
401
|
+
else:
|
|
402
|
+
dataset_evaluation = split_names_to_dataset_evaluations[split_name]
|
|
403
|
+
return f"{split_name} ({dataset_evaluation.num_positive_index_tuples} / {dataset_evaluation.positive_prevalence:.5f})"
|
|
404
|
+
|
|
405
|
+
import matplotlib.pyplot as plt
|
|
406
|
+
from matplotlib.colors import TABLEAU_COLORS
|
|
407
|
+
from matplotlib.lines import Line2D
|
|
408
|
+
|
|
409
|
+
order_repr = "-".join(str(i) for i in label_model.order)
|
|
410
|
+
filename_stem = f"{label_model.label}-{order_repr}"
|
|
411
|
+
if re.fullmatch(r"[A-Za-z0-9_-]{1,200}", filename_stem) is None:
|
|
412
|
+
digest = hashlib.sha256(filename_stem.encode("utf-8")).hexdigest()
|
|
413
|
+
filename_stem = f"label-model.{digest}"
|
|
414
|
+
title = f"{label_model.label} — order {label_model.order}"
|
|
415
|
+
if description:
|
|
416
|
+
title = f"{description}\n{title}"
|
|
417
|
+
|
|
418
|
+
split_scores = {
|
|
419
|
+
"train": (
|
|
420
|
+
label_model.unpooled_evaluation_scores["train"],
|
|
421
|
+
label_model.pooled_evaluation_scores["train"],
|
|
422
|
+
),
|
|
423
|
+
"dev": (
|
|
424
|
+
label_model.unpooled_evaluation_scores["dev"],
|
|
425
|
+
label_model.pooled_evaluation_scores["dev"],
|
|
426
|
+
),
|
|
427
|
+
"test": (
|
|
428
|
+
label_model.unpooled_evaluation_scores["test"],
|
|
429
|
+
label_model.pooled_evaluation_scores["test"],
|
|
430
|
+
),
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
colors = {
|
|
434
|
+
"train": "tab:blue",
|
|
435
|
+
"dev": "tab:orange",
|
|
436
|
+
"test": "tab:green",
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
extra_color_cycle = cycle(
|
|
440
|
+
color
|
|
441
|
+
for color in TABLEAU_COLORS
|
|
442
|
+
if color not in {"tab:blue", "tab:orange", "tab:green", "tab:red"}
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
split_names_to_dataset_evaluations: dict[str, DatasetEvaluationWithLabelModel] = {}
|
|
446
|
+
if dataset_evaluations is not None:
|
|
447
|
+
for dataset_evaluation in dataset_evaluations:
|
|
448
|
+
split_names_to_dataset_evaluations[
|
|
449
|
+
dataset_evaluation.dataset_config.label
|
|
450
|
+
] = dataset_evaluation
|
|
451
|
+
split_scores[dataset_evaluation.dataset_config.label] = (
|
|
452
|
+
dataset_evaluation.unpooled_evaluation_scores,
|
|
453
|
+
dataset_evaluation.pooled_evaluation_scores,
|
|
454
|
+
)
|
|
455
|
+
colors[dataset_evaluation.dataset_config.label] = next(extra_color_cycle)
|
|
456
|
+
|
|
457
|
+
for split_name, (unpooled, pooled) in split_scores.items():
|
|
458
|
+
if not unpooled or not pooled:
|
|
459
|
+
raise ValueError(
|
|
460
|
+
f"Cannot plot evaluation curves with no scores for {split_name}."
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
num_heads = max(
|
|
464
|
+
len(series) for curves in split_scores.values() for series in curves
|
|
465
|
+
)
|
|
466
|
+
if num_heads > len(label_model.head_nums):
|
|
467
|
+
raise ValueError(
|
|
468
|
+
f"There are {num_heads} evaluation scores but the label model "
|
|
469
|
+
f"contains only {len(label_model.head_nums)} heads."
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
head_nums = label_model.head_nums[:num_heads]
|
|
473
|
+
head_labels = [describe_head_index(head_num, head_infos) for head_num in head_nums]
|
|
474
|
+
|
|
475
|
+
x = list(range(num_heads))
|
|
476
|
+
|
|
477
|
+
# Around 20 inches for the normal 100-head case. This is deliberately
|
|
478
|
+
# wide so every head label can remain visible when rotated vertically.
|
|
479
|
+
figure_width = max(12.0, min(24.0, num_heads * 0.20))
|
|
480
|
+
figure_height = 7.0
|
|
481
|
+
|
|
482
|
+
fig, ax = plt.subplots(
|
|
483
|
+
figsize=(figure_width, figure_height),
|
|
484
|
+
)
|
|
485
|
+
ax.set_title(
|
|
486
|
+
title,
|
|
487
|
+
fontsize=14,
|
|
488
|
+
pad=12,
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
for split_name, (unpooled_scores, pooled_scores) in split_scores.items():
|
|
492
|
+
color = colors[split_name]
|
|
493
|
+
for scores, linestyle, linewidth in (
|
|
494
|
+
(pooled_scores, "-", 1.8),
|
|
495
|
+
(unpooled_scores, ":", 1.5),
|
|
496
|
+
):
|
|
497
|
+
ax.plot(
|
|
498
|
+
range(len(scores)),
|
|
499
|
+
scores,
|
|
500
|
+
color=color,
|
|
501
|
+
marker="o" if len(scores) == 1 else None,
|
|
502
|
+
linestyle=linestyle,
|
|
503
|
+
linewidth=linewidth,
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
selected_idx = label_model.num_head_results_to_pool - 1
|
|
507
|
+
|
|
508
|
+
if 0 <= selected_idx < num_heads:
|
|
509
|
+
ax.axvline(
|
|
510
|
+
selected_idx,
|
|
511
|
+
linestyle="--",
|
|
512
|
+
linewidth=1.2,
|
|
513
|
+
alpha=0.7,
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
ax.set_xlabel("head")
|
|
517
|
+
ax.set_ylabel(scorer_label)
|
|
518
|
+
|
|
519
|
+
ax.set_xticks(x)
|
|
520
|
+
ax.set_xticklabels(
|
|
521
|
+
head_labels,
|
|
522
|
+
rotation=90,
|
|
523
|
+
fontsize=7,
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
ax.grid(
|
|
527
|
+
axis="y",
|
|
528
|
+
alpha=0.25,
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
split_handles = [
|
|
532
|
+
Line2D(
|
|
533
|
+
[0],
|
|
534
|
+
[0],
|
|
535
|
+
color=colors[split_name],
|
|
536
|
+
linewidth=2,
|
|
537
|
+
label=get_split_name_legend(split_name),
|
|
538
|
+
)
|
|
539
|
+
for split_name in split_scores
|
|
540
|
+
]
|
|
541
|
+
|
|
542
|
+
type_handles = [
|
|
543
|
+
Line2D(
|
|
544
|
+
[0],
|
|
545
|
+
[0],
|
|
546
|
+
linestyle="-",
|
|
547
|
+
linewidth=2,
|
|
548
|
+
label="Cumulative pooled",
|
|
549
|
+
),
|
|
550
|
+
Line2D(
|
|
551
|
+
[0],
|
|
552
|
+
[0],
|
|
553
|
+
linestyle=":",
|
|
554
|
+
linewidth=2,
|
|
555
|
+
label="Individual head",
|
|
556
|
+
),
|
|
557
|
+
Line2D(
|
|
558
|
+
[0],
|
|
559
|
+
[0],
|
|
560
|
+
linestyle="--",
|
|
561
|
+
linewidth=1.2,
|
|
562
|
+
label="Dev-selected pool size",
|
|
563
|
+
),
|
|
564
|
+
]
|
|
565
|
+
|
|
566
|
+
split_legend = ax.legend(
|
|
567
|
+
handles=split_handles,
|
|
568
|
+
title="Dataset (num pos / pos prev)",
|
|
569
|
+
loc="upper right",
|
|
570
|
+
)
|
|
571
|
+
ax.add_artist(split_legend)
|
|
572
|
+
|
|
573
|
+
ax.legend(
|
|
574
|
+
handles=type_handles,
|
|
575
|
+
title="Result",
|
|
576
|
+
loc="lower right",
|
|
577
|
+
)
|
|
578
|
+
|
|
579
|
+
fig.tight_layout()
|
|
580
|
+
|
|
581
|
+
output_dir.mkdir(
|
|
582
|
+
parents=True,
|
|
583
|
+
exist_ok=True,
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
png_path = output_dir / f"{filename_stem}.png"
|
|
587
|
+
svg_path = output_dir / f"{filename_stem}.svg"
|
|
588
|
+
|
|
589
|
+
fig.savefig(
|
|
590
|
+
png_path,
|
|
591
|
+
dpi=150,
|
|
592
|
+
bbox_inches="tight",
|
|
593
|
+
)
|
|
594
|
+
fig.savefig(
|
|
595
|
+
svg_path,
|
|
596
|
+
bbox_inches="tight",
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
plt.close(fig)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: polyprobe
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A research library for training and evaluating probes of information processed by transformer attention heads.
|
|
5
|
+
Author-email: Richard Paul Hudson <info@richardpaulhudson.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/richardpaulhudson/polyprobe
|
|
8
|
+
Project-URL: Issues, https://github.com/richardpaulhudson/polyprobe/issues
|
|
9
|
+
Keywords: transformers,probing,linear-probes,interpretability,mechanistic-interpretability,attention,attention-heads,representation-analysis,model-analysis,machine-learning,pytorch,linguistics,nlp
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Requires-Python: !=3.14.1,<3.15,>=3.11
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
License-File: LICENSE-CC-BY-4.0
|
|
26
|
+
Requires-Dist: transformers<6.0.0,>=5.17.0
|
|
27
|
+
Requires-Dist: torch<3.0.0,>=2.14.0
|
|
28
|
+
Requires-Dist: transformer-lens>=4.2.0
|
|
29
|
+
Requires-Dist: tqdm<5.0.0,>=4.70.1
|
|
30
|
+
Requires-Dist: conllu<7.0.0,>=6.0.0
|
|
31
|
+
Requires-Dist: psutil<8.0.0,>=7.2.2
|
|
32
|
+
Provides-Extra: plot
|
|
33
|
+
Requires-Dist: matplotlib<4.0.0,>=3.11.2; extra == "plot"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
Polyprobe is a research library for training and evaluating lightweight binary-classification probes over representations within language-model attention heads. While many prior probing studies have been implemented as task-specific experiments, Polyprobe provides reusable infrastructure for:
|
|
37
|
+
|
|
38
|
+
- efficient training of independent probes across hundreds of attention heads;
|
|
39
|
+
- memory-mapped activation storage and GPU-aware batching;
|
|
40
|
+
- head ranking and model selection;
|
|
41
|
+
- evaluation and interactive inference.
|
|
42
|
+
|
|
43
|
+
The details of individual experiments, on the other hand, are specified via a number of swappable abstractions that can either be selected from what the library already has to offer or registered at runtime:
|
|
44
|
+
|
|
45
|
+
- the architecture of the language model being investigated;
|
|
46
|
+
- the features to learn;
|
|
47
|
+
- the source of the training data;
|
|
48
|
+
- the definition of positive and negative examples;
|
|
49
|
+
- the vector representations to probe;
|
|
50
|
+
- the type of probe to use;
|
|
51
|
+
- the metric to use to select probe results;
|
|
52
|
+
- optionally, how probe results are pooled.
|
|
53
|
+
|
|
54
|
+
I am currently using Polyprobe to investigate how grammatical dependencies are represented and processed by language models. On held-out English Web Treebank data, pooled Qwen3-4B probes reached 82.28% average precision for subject-before-head dependencies and 83.57% for head-before-object dependencies against positive prevalences of 0.49% and 0.29% respectively. The probes can be tested against user-entered sentences via a simple analysis console:
|
|
55
|
+
|
|
56
|
+
```text
|
|
57
|
+
The dog saw the cat
|
|
58
|
+
|
|
59
|
+
nsubj: dog (3: 7) -> saw (7: 11) (strictest met threshold: 25%)
|
|
60
|
+
obj: cat (15: 19) -> saw (7: 11) (strictest met threshold: 15%)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
For more information, please see the [main documentation on GitHub](https://github.com/richardpaulhudson/polyprobe).
|