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,945 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from typing import Any, cast
7
+
8
+ import torch
9
+ from torch import Tensor
10
+ from tqdm.auto import tqdm
11
+
12
+ from polyprobe.activations import ActivationStore, MemoryBackedActivationStore
13
+ from polyprobe.batching import BatchingMemoryException, BatchSizeManager
14
+ from polyprobe.config import RunConfig
15
+ from polyprobe.document import DocumentPiece
16
+ from polyprobe.lm_encoder import LMEncoder
17
+ from polyprobe.model import PolyprobeLabelEvaluation, PolyprobeLabelModel
18
+ from polyprobe.poolers.pooler import Pooler
19
+ from polyprobe.registry import PolyprobeRegistry
20
+ from polyprobe.scorers.scorer import Scorer
21
+ from polyprobe.util import (
22
+ empty_cache,
23
+ get_activation_tuples_representation,
24
+ get_batch_end,
25
+ get_index_tuple_boundaries,
26
+ get_probe_components,
27
+ get_probe_input_capacity,
28
+ get_required_activation_types,
29
+ )
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class LabelEvaluator:
35
+ """
36
+ Evaluates the performance of models during or after training.
37
+
38
+ max_wrong_examples_to_return: the maximum number of positive and negative examples to show.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ registry: PolyprobeRegistry,
44
+ lm_encoder: LMEncoder,
45
+ run_config: RunConfig,
46
+ probe_name: str,
47
+ probe_kwargs: dict[str, Any],
48
+ probe_component_names: list[str],
49
+ maximum_tensor_mebibytes: int,
50
+ device: torch.device,
51
+ ):
52
+ self.registry = registry
53
+ self.lm_encoder = lm_encoder
54
+ self.run_config = run_config
55
+ self.maximum_tensor_mebibytes = maximum_tensor_mebibytes
56
+ self.probe_type = registry.get_probe_type(probe_name)
57
+ self.probe_kwargs = probe_kwargs
58
+ self.probe_components = get_probe_components(registry, probe_component_names)
59
+ for probe_component in self.probe_components:
60
+ probe_component.check_lm_architecture(self.lm_encoder.architecture)
61
+ self.required_activation_types = get_required_activation_types(
62
+ self.probe_components
63
+ )
64
+ self.device = device
65
+
66
+ @torch.inference_mode()
67
+ def evaluate_heads(
68
+ self,
69
+ global_start_head: int,
70
+ weights: Tensor,
71
+ mbas: MemoryBackedActivationStore,
72
+ eval_start_piece_idx: int,
73
+ num_pieces: int,
74
+ index_tuples_list: list[Tensor],
75
+ truths_list: list[Tensor],
76
+ batch_size: list[int],
77
+ show_progress: bool,
78
+ ) -> list[PolyprobeLabelEvaluation]:
79
+ """Evaluates the performance of a list of potential models, one at each head, against a labelled list of document pieces
80
+ and returns a label evaluation object for each head. The batch size is specified by the caller.
81
+
82
+ global_start_head: the head at which to start evaluation. The head at which to end evaluation is derived from
83
+ this parameter and from the shape of *weights*.
84
+ weights: a (num_heads, probe dimension) weights tensor.
85
+ mbas: a memory-backed activation store containing the activations gathered when the document pieces to evaluate were encoded.
86
+ eval_start_piece_idx: the index within mbas where the evaluation pieces start.
87
+ index_tuples_list: a list of index tuples, corresponding by index to *pieces*,
88
+ specifying the index tuples for which to carry out inference for each piece.
89
+ truths_list: the groundtruth truth values corresponding to *index_tuples_list*.
90
+ batch_size: the [num_heads, num_index_tuples] batch size.
91
+ show_progress: whether or not to display a tqdm progress bar.
92
+
93
+ """
94
+ if weights.shape[1] <= 1:
95
+ raise ValueError("There must be more than one weight in each row.")
96
+ head_nums = list(range(global_start_head, global_start_head + weights.shape[0]))
97
+ head_batch_size = batch_size[0]
98
+ truths, num_pos = self._get_truths_and_num_pos(truths_list)
99
+ truths = truths.to(self.device)
100
+ index_tuple_boundaries = get_index_tuple_boundaries(index_tuples_list)
101
+ logits_list: list[Tensor] = []
102
+ pieces_start = 0
103
+ with tqdm(
104
+ total=num_pieces,
105
+ desc="Evaluating heads",
106
+ unit="piece",
107
+ leave=True,
108
+ disable=not show_progress,
109
+ ) as progress:
110
+ while pieces_start < num_pieces:
111
+ pieces_end = get_batch_end(
112
+ index_tuple_boundaries, batch_size[1], pieces_start
113
+ )
114
+ activation_store = mbas.read(
115
+ eval_start_piece_idx + pieces_start,
116
+ eval_start_piece_idx + pieces_end,
117
+ )
118
+ pieces_logits = self._get_logits(
119
+ activation_store,
120
+ index_tuples_list[pieces_start:pieces_end],
121
+ head_nums,
122
+ weights,
123
+ head_batch_size,
124
+ )
125
+
126
+ progress.update(pieces_end - pieces_start)
127
+ logits_list.append(pieces_logits)
128
+ del pieces_logits
129
+ pieces_start = pieces_end
130
+ del activation_store # release handle on temporary file
131
+ logits = torch.cat(logits_list, dim=1)
132
+ # Sort each head row from highest predicted score to lowest.
133
+ sorted_logits, sorted_idxs = torch.sort(logits, dim=1, descending=True)
134
+ sorted_truths = truths[sorted_idxs]
135
+ evaluations_list = self._evaluate_results(sorted_logits, sorted_truths, num_pos)
136
+ for head_num, evaluation in zip(head_nums, evaluations_list):
137
+ evaluation.head_nums = [head_num]
138
+ return evaluations_list
139
+
140
+ def evaluate_label_model_across_pooling_prefixes(
141
+ self,
142
+ label_model: PolyprobeLabelModel,
143
+ scorer: Scorer,
144
+ pieces: list[DocumentPiece],
145
+ index_tuples_list: list[Tensor],
146
+ truths_list: list[Tensor],
147
+ show_progress: bool,
148
+ progress_desc: str,
149
+ mbas: MemoryBackedActivationStore | None = None,
150
+ mbas_piece_start_idx: int | None = None,
151
+ ) -> tuple[list[PolyprobeLabelEvaluation], list[PolyprobeLabelEvaluation]]:
152
+ unpooled_evaluations, pooled_evaluations = cast(
153
+ tuple[list[PolyprobeLabelEvaluation], list[PolyprobeLabelEvaluation]],
154
+ self._evaluate_label_model(
155
+ label_model,
156
+ None,
157
+ scorer,
158
+ pieces,
159
+ index_tuples_list,
160
+ truths_list,
161
+ show_progress,
162
+ progress_desc,
163
+ mbas,
164
+ mbas_piece_start_idx,
165
+ ),
166
+ )
167
+ for idx, evaluation in enumerate(unpooled_evaluations):
168
+ evaluation.head_nums = [label_model.head_nums[idx]]
169
+ for idx, evaluation in enumerate(pooled_evaluations):
170
+ evaluation.head_nums = label_model.head_nums[: idx + 1]
171
+ return unpooled_evaluations, pooled_evaluations
172
+
173
+ def evaluate_label_model_at_selected_pooling(
174
+ self,
175
+ label_model: PolyprobeLabelModel,
176
+ pieces: list[DocumentPiece],
177
+ index_tuples_list: list[Tensor],
178
+ truths_list: list[Tensor],
179
+ show_progress: bool,
180
+ progress_desc: str,
181
+ ) -> PolyprobeLabelEvaluation:
182
+ evaluation = cast(
183
+ PolyprobeLabelEvaluation,
184
+ self._evaluate_label_model(
185
+ label_model,
186
+ label_model.num_head_results_to_pool,
187
+ None,
188
+ pieces,
189
+ index_tuples_list,
190
+ truths_list,
191
+ show_progress,
192
+ progress_desc,
193
+ None,
194
+ None,
195
+ ),
196
+ )
197
+ evaluation.head_nums = label_model.head_nums[
198
+ : label_model.num_head_results_to_pool
199
+ ]
200
+ return evaluation
201
+
202
+ @torch.inference_mode()
203
+ def _evaluate_label_model(
204
+ self,
205
+ label_model: PolyprobeLabelModel,
206
+ num_head_results: int | None,
207
+ scorer: Scorer | None,
208
+ pieces: list[DocumentPiece],
209
+ index_tuples_list: list[Tensor],
210
+ truths_list: list[Tensor],
211
+ show_progress: bool,
212
+ progress_desc: str,
213
+ mbas: MemoryBackedActivationStore | None = None,
214
+ mbas_piece_start_idx: int | None = None,
215
+ ) -> (
216
+ PolyprobeLabelEvaluation
217
+ | tuple[list[PolyprobeLabelEvaluation], list[PolyprobeLabelEvaluation]]
218
+ ):
219
+ """
220
+ Evaluates a label model against a labelled list of document pieces.
221
+
222
+ label_model: the label model to evaluate.
223
+ num_head_results: the number of head results to pool, or *None* if
224
+ evaluations should be collected for all possible pooling sizes
225
+ with the individual head models sorted in descending order by score.
226
+ scorer: the scorer with which to compare results with different numbers
227
+ of pooled head results, or *None* if *num_head_results* is set.
228
+ pieces: the document pieces.
229
+ index_tuples_list: a list of index tuples, corresponding by index to *pieces*,
230
+ specifying the index tuples for which to carry out inference for each piece.
231
+ truths_list: the groundtruth truth values corresponding to *index_tuples_list*.
232
+ show_progress: whether or not to display a tqdm progress bar.
233
+ progress_desc: the message to show at the beginning of any tqdm progress bar.
234
+ mbas: optionally, a memory-backed activation store containing activations for *pieces*.
235
+ mbas_piece_start_idx: optionally: the piece start index for *pieces* within *mbas*.
236
+
237
+
238
+ Returns a label evaluation object, if *num_head_results* is set, otherwise two ordered
239
+ lists of scored label evaluation objects, for unpooled and pooled results respectively.
240
+ """
241
+ if (mbas is None) != (mbas_piece_start_idx is None):
242
+ raise ValueError(
243
+ "mbas and mbas_piece_start_idx must be either both None or both not None."
244
+ )
245
+ if label_model.weights.shape[1] <= 1:
246
+ raise ValueError("There must be more than one weight in each row.")
247
+ if len(pieces) == 0:
248
+ raise ValueError("No document pieces supplied to evaluate_label_model().")
249
+ if (num_head_results is None) == (scorer is None):
250
+ raise ValueError("Exactly one of num_head_results and scorer must be set.")
251
+ if num_head_results is not None and num_head_results < 1:
252
+ raise ValueError("num_head_results must be a positive integer.")
253
+ if num_head_results is not None and num_head_results > label_model.num_heads:
254
+ raise ValueError(
255
+ f"num_head_results={num_head_results}, but the model only has "
256
+ f"{label_model.num_heads} head results."
257
+ )
258
+ if num_head_results is None:
259
+ num_heads_to_evaluate = min(
260
+ label_model.num_heads,
261
+ self.run_config.max_heads_to_pool,
262
+ )
263
+ else:
264
+ num_heads_to_evaluate = num_head_results
265
+
266
+ index_tuple_boundaries = get_index_tuple_boundaries(index_tuples_list)
267
+ truths, num_pos = self._get_truths_and_num_pos(truths_list)
268
+ num_index_tuples = truths.shape[0]
269
+ pooler = self.registry.get_pooler_type(label_model.pooler_name)(
270
+ **label_model.pooler_kwargs
271
+ )
272
+ num_pieces = len(pieces)
273
+ end_layer = label_model.get_stop_at_layer(
274
+ self.lm_encoder.head_infos, scorer is None
275
+ )
276
+ example_activation_store = self.lm_encoder.encode(
277
+ pieces[:1],
278
+ self.required_activation_types,
279
+ end_layer,
280
+ None,
281
+ )
282
+ probe_input_capacity = get_probe_input_capacity(
283
+ example_activation_store,
284
+ self.lm_encoder,
285
+ self.probe_type,
286
+ self.probe_kwargs,
287
+ self.probe_components,
288
+ self.maximum_tensor_mebibytes,
289
+ self.device,
290
+ )
291
+ del example_activation_store
292
+ if num_heads_to_evaluate > probe_input_capacity:
293
+ index_tuple_batch_size = 1
294
+ head_batch_size = probe_input_capacity
295
+ else:
296
+ head_batch_size = num_heads_to_evaluate
297
+ index_tuple_batch_size = min(
298
+ num_index_tuples,
299
+ probe_input_capacity // head_batch_size,
300
+ )
301
+
302
+ if mbas is None:
303
+ # if we are encoding the document pieces ourselves here, a batch can never contain more document
304
+ # pieces than can be encoded at one time, so we cap the attempted index-tuple batch size at 1.5
305
+ # times the mean number of index tuples per document piece since the only possible effect of a larger
306
+ # batch size would be unnecessary OOMs as it reduces.
307
+ index_tuples_per_document_piece = max(1, num_index_tuples // num_pieces)
308
+ index_tuple_batch_size = min(
309
+ index_tuple_batch_size,
310
+ int(
311
+ self.run_config.initial_document_encoding_batch_size
312
+ * 1.5
313
+ * index_tuples_per_document_piece
314
+ ),
315
+ )
316
+ maximum_batch_size_to_attempt = [
317
+ head_batch_size,
318
+ index_tuple_batch_size,
319
+ ]
320
+
321
+ batch_size_manager = BatchSizeManager(
322
+ [1, 0], ["heads", "index tuples"], self.device, "evaluation"
323
+ )
324
+
325
+ while True:
326
+ try:
327
+ with batch_size_manager.batch_size_to_attempt(
328
+ maximum_batch_size_to_attempt
329
+ ) as attempted_batch_size:
330
+ return self._evaluate_label_model_attempt(
331
+ label_model,
332
+ num_heads_to_evaluate,
333
+ scorer,
334
+ end_layer,
335
+ attempted_batch_size,
336
+ pieces,
337
+ index_tuples_list,
338
+ index_tuple_boundaries,
339
+ truths,
340
+ num_pos,
341
+ mbas,
342
+ mbas_piece_start_idx,
343
+ pooler,
344
+ show_progress,
345
+ progress_desc,
346
+ )
347
+ except BatchingMemoryException:
348
+ continue
349
+
350
+ def _get_truths_and_num_pos(self, truths_list: list[Tensor]) -> tuple[Tensor, int]:
351
+
352
+ truths = torch.cat(truths_list).to(dtype=torch.float32)
353
+ num_pos = int(truths.sum().item())
354
+ if num_pos == 0:
355
+ raise ValueError(
356
+ "Cannot evaluate label ranking metrics with zero positive labels."
357
+ )
358
+ num_index_tuples = truths.shape[0]
359
+ if num_pos == num_index_tuples:
360
+ raise ValueError(
361
+ "Cannot evaluate label ranking metrics with zero negative labels."
362
+ )
363
+ return truths, num_pos
364
+
365
+ def _evaluate_label_model_attempt(
366
+ self,
367
+ label_model: PolyprobeLabelModel,
368
+ num_heads_to_evaluate: int,
369
+ scorer: Scorer | None,
370
+ end_layer: int,
371
+ attempted_batch_size: list[int],
372
+ pieces: list[DocumentPiece],
373
+ index_tuples_list: list[Tensor],
374
+ index_tuple_boundaries: list[int],
375
+ truths: Tensor,
376
+ num_pos: int,
377
+ mbas: MemoryBackedActivationStore | None,
378
+ mbas_piece_start_idx: int | None,
379
+ pooler: Pooler,
380
+ show_progress: bool,
381
+ progress_desc: str,
382
+ ) -> (
383
+ PolyprobeLabelEvaluation
384
+ | tuple[list[PolyprobeLabelEvaluation], list[PolyprobeLabelEvaluation]]
385
+ ):
386
+ unpooled_logits_list: list[Tensor] = []
387
+ pooled_logits_list: list[Tensor] = []
388
+ head_batch_size, index_tuple_batch_size = attempted_batch_size
389
+ with tqdm(
390
+ total=len(pieces),
391
+ desc=progress_desc,
392
+ unit="piece",
393
+ leave=True,
394
+ disable=not show_progress,
395
+ ) as progress:
396
+ pieces_start = 0
397
+ while pieces_start < len(pieces):
398
+ pieces_end = get_batch_end(
399
+ index_tuple_boundaries,
400
+ index_tuple_batch_size,
401
+ pieces_start,
402
+ (
403
+ self.run_config.initial_document_encoding_batch_size
404
+ if mbas is None
405
+ else None
406
+ ),
407
+ )
408
+ if mbas is not None and mbas_piece_start_idx is not None:
409
+ activation_store = mbas.read(
410
+ mbas_piece_start_idx + pieces_start,
411
+ mbas_piece_start_idx + pieces_end,
412
+ )
413
+ else:
414
+ activation_store = self.lm_encoder.encode(
415
+ pieces[pieces_start:pieces_end],
416
+ self.required_activation_types,
417
+ end_layer,
418
+ None,
419
+ )
420
+ pieces_logits = self._get_logits(
421
+ activation_store,
422
+ index_tuples_list[pieces_start:pieces_end],
423
+ label_model.head_nums[:num_heads_to_evaluate],
424
+ label_model.weights[:num_heads_to_evaluate],
425
+ head_batch_size,
426
+ )
427
+ del activation_store # release handle on temporary file
428
+ if scorer is not None:
429
+ unpooled_logits_list.append(pieces_logits.cpu())
430
+ pooled_logits_list.append(
431
+ pooler.reduce_all_prefixes(pieces_logits).cpu()
432
+ )
433
+ else:
434
+ pooled_logits_list.append(
435
+ pooler.reduce(pieces_logits, num_heads_to_evaluate)
436
+ .unsqueeze(dim=0)
437
+ .cpu()
438
+ )
439
+ del pieces_logits
440
+ progress.update(pieces_end - pieces_start)
441
+ pieces_start = pieces_end
442
+ empty_cache(self.device)
443
+
444
+ if scorer is not None:
445
+ unpooled_evaluations = self._generate_evaluations(
446
+ unpooled_logits_list,
447
+ truths,
448
+ num_pos,
449
+ index_tuples_list,
450
+ pieces,
451
+ label_model,
452
+ scorer,
453
+ )
454
+ pooled_evaluations = self._generate_evaluations(
455
+ pooled_logits_list,
456
+ truths,
457
+ num_pos,
458
+ index_tuples_list,
459
+ pieces,
460
+ label_model,
461
+ scorer,
462
+ )
463
+ return unpooled_evaluations, pooled_evaluations
464
+ else:
465
+ pooled_evaluations = self._generate_evaluations(
466
+ pooled_logits_list,
467
+ truths,
468
+ num_pos,
469
+ index_tuples_list,
470
+ pieces,
471
+ label_model,
472
+ scorer,
473
+ )
474
+ return pooled_evaluations[0]
475
+
476
+ def _generate_evaluations(
477
+ self,
478
+ logits_list: list[Tensor],
479
+ truths: Tensor,
480
+ num_pos: int,
481
+ index_tuples_list: list[Tensor],
482
+ pieces: list[DocumentPiece],
483
+ label_model: PolyprobeLabelModel,
484
+ scorer: Scorer | None,
485
+ ) -> list[PolyprobeLabelEvaluation]:
486
+ logits = torch.cat(logits_list, dim=1)
487
+ truths = truths.to(logits.device)
488
+ # Sort each head row from highest predicted score to lowest.
489
+ sorted_logits, sorted_idxs = torch.sort(logits, dim=1, descending=True)
490
+ sorted_truths = truths[sorted_idxs]
491
+ evaluations = self._evaluate_results(sorted_logits, sorted_truths, num_pos)
492
+ highest_scoring_non_labelled_log_lines, lowest_scoring_labelled_log_lines = (
493
+ self._get_diagnostic_examples(
494
+ pieces, index_tuples_list, sorted_truths, sorted_idxs, label_model.order
495
+ )
496
+ )
497
+ for idx, evaluation in enumerate(evaluations):
498
+ if scorer is not None:
499
+ scorer.score_label_evaluation(evaluation)
500
+ evaluation.highest_scoring_non_labelled_log_lines = (
501
+ highest_scoring_non_labelled_log_lines[idx]
502
+ )
503
+ evaluation.lowest_scoring_labelled_log_lines = (
504
+ lowest_scoring_labelled_log_lines[idx]
505
+ )
506
+ return evaluations
507
+
508
+ def _get_logits(
509
+ self,
510
+ activation_store: ActivationStore,
511
+ index_tuples_list: list[Tensor],
512
+ head_nums: list[int],
513
+ weights: Tensor,
514
+ head_batch_size: int,
515
+ ) -> Tensor:
516
+ """Return logits with shape [heads, index tuples]."""
517
+ if not head_nums:
518
+ raise ValueError("At least one head must be supplied.")
519
+ if len(head_nums) != weights.shape[0]:
520
+ raise ValueError(
521
+ f"There are {len(head_nums)} head numbers, but weights has shape {weights.shape}."
522
+ )
523
+ if head_batch_size <= 0:
524
+ raise ValueError(
525
+ f"head_batch_size is {head_batch_size} but must be positive."
526
+ )
527
+ head_logits_chunks: list[Tensor] = []
528
+
529
+ for start_head_idx in range(0, len(head_nums), head_batch_size):
530
+ end_head_idx = min(
531
+ len(head_nums),
532
+ start_head_idx + head_batch_size,
533
+ )
534
+
535
+ probe = self.probe_type(
536
+ self.probe_components,
537
+ head_nums[start_head_idx:end_head_idx],
538
+ self.lm_encoder.head_infos,
539
+ self.device,
540
+ weights=weights[start_head_idx:end_head_idx],
541
+ **self.probe_kwargs,
542
+ )
543
+
544
+ batch_input = probe.build_input(
545
+ activation_store,
546
+ index_tuples_list,
547
+ ).to(self.device)
548
+
549
+ head_logits_chunks.append(probe(batch_input))
550
+ del batch_input
551
+
552
+ return torch.cat(head_logits_chunks, dim=0)
553
+
554
+ @torch.inference_mode()
555
+ def get_label_model_evaluation_log_lines(
556
+ self,
557
+ label_evaluation: PolyprobeLabelEvaluation,
558
+ ) -> list[str]:
559
+
560
+ log_lines: list[str] = []
561
+ log_lines.extend(
562
+ label_evaluation.get_overall_stats_log_lines(
563
+ self.run_config.log_recall_percent_stats
564
+ )
565
+ )
566
+ if self.run_config.log_incorrect_examples:
567
+ log_lines.append("")
568
+ log_lines.append("Highest scoring non-labelled:")
569
+ log_lines.extend(label_evaluation.highest_scoring_non_labelled_log_lines)
570
+ log_lines.append("")
571
+ log_lines.append("Lowest scoring labelled:")
572
+ log_lines.extend(label_evaluation.lowest_scoring_labelled_log_lines)
573
+ return log_lines
574
+
575
+ def _evaluate_results(
576
+ self,
577
+ sorted_logits: Tensor,
578
+ sorted_truths: Tensor,
579
+ num_pos: int,
580
+ ) -> list[PolyprobeLabelEvaluation]:
581
+ """
582
+ Evaluates the performance at one or more heads.
583
+
584
+ sorted_logits: (heads, index tuples): the logits returned for all head/index tuple combinations, in reverse order.
585
+ sorted_truths: (heads, truths): the truths values corresponding to *sorted_logits*.
586
+ num_pos: the number of positive truth values.
587
+ """
588
+ num_heads, num_index_tuples = sorted_truths.shape
589
+ device = sorted_logits.device
590
+ tp_at_k = torch.cumsum(sorted_truths, dim=1)
591
+
592
+ predicted_positive_at_k = torch.arange(
593
+ 1,
594
+ num_index_tuples + 1,
595
+ device=device,
596
+ dtype=tp_at_k.dtype,
597
+ ).unsqueeze(0)
598
+
599
+ precision_at_k = tp_at_k / predicted_positive_at_k
600
+ recall_at_k = tp_at_k / num_pos
601
+ # F1@k = 2TP / (predicted positives + actual positives)
602
+ # Equivalent to 2TP / (2TP + FP + FN)
603
+ f1_at_k = (2 * tp_at_k) / (predicted_positive_at_k + num_pos)
604
+
605
+ # Avoid choosing thresholds that split tied scores.
606
+ is_valid_threshold = torch.ones_like(sorted_logits, dtype=torch.bool)
607
+ is_valid_threshold[:, :-1] = sorted_logits[:, :-1] != sorted_logits[:, 1:]
608
+
609
+ f1_at_k = f1_at_k.masked_fill(~is_valid_threshold, -1.0)
610
+ best_f1s, best_ks = f1_at_k.max(dim=1)
611
+ row_ids = torch.arange(num_heads, device=device)
612
+ thresholds_at_best_f1 = sorted_logits[row_ids, best_ks]
613
+ precisions_at_best_f1 = precision_at_k[row_ids, best_ks]
614
+ recalls_at_best_f1 = recall_at_k[row_ids, best_ks]
615
+ best_f1_rank_fractions = (best_ks + 1) / num_index_tuples
616
+
617
+ # roc_auc and normalized_median_positive_rank_score are both 1.0
618
+ # in the best possible case and 0.0 in the worst possible case.
619
+ positions = torch.arange(num_index_tuples, device=device).expand(num_heads, -1)
620
+
621
+ # Boundaries of equal-score groups
622
+ group_starts = torch.ones_like(sorted_logits, dtype=torch.bool)
623
+ group_starts[:, 1:] = sorted_logits[:, 1:] != sorted_logits[:, :-1]
624
+ group_ends = is_valid_threshold
625
+
626
+ # For each element, find the start of its tie group
627
+ tie_starts = torch.where(group_starts, positions, 0)
628
+ tie_starts = torch.cummax(tie_starts, dim=1).values
629
+
630
+ # For each element, find the end of its tie group
631
+ tie_ends = torch.where(group_ends, positions, num_index_tuples - 1)
632
+ tie_ends = torch.flip(
633
+ torch.cummin(torch.flip(tie_ends, dims=[1]), dim=1).values,
634
+ dims=[1],
635
+ )
636
+
637
+ # Average Precision.
638
+ #
639
+ # Compute only at distinct score thresholds, making AP invariant to the
640
+ # arbitrary ordering of examples within tied-score groups.
641
+ tp_before = torch.cat(
642
+ [
643
+ torch.zeros(
644
+ num_heads,
645
+ 1,
646
+ device=device,
647
+ dtype=tp_at_k.dtype,
648
+ ),
649
+ tp_at_k[:, :-1],
650
+ ],
651
+ dim=1,
652
+ )
653
+
654
+ tp_before_group = torch.gather(tp_before, 1, tie_starts)
655
+
656
+ positives_in_group = torch.where(
657
+ group_ends,
658
+ tp_at_k - tp_before_group,
659
+ torch.zeros_like(tp_at_k),
660
+ )
661
+
662
+ average_precisions = (
663
+ (positives_in_group * precision_at_k).sum(dim=1) / num_pos
664
+ ).tolist()
665
+
666
+ # Use average ranks so results are invariant to ordering within score ties.
667
+ avg_descending_ranks = (tie_starts + tie_ends).to(torch.float32) / 2 + 1
668
+ avg_ascending_ranks = num_index_tuples + 1 - avg_descending_ranks
669
+
670
+ # ROC AUC via Mann-Whitney U.
671
+ pos_rank_sums = (avg_ascending_ranks * sorted_truths).sum(dim=1)
672
+
673
+ num_neg = num_index_tuples - num_pos
674
+
675
+ mann_whitney_u = pos_rank_sums - num_pos * (num_pos + 1) / 2
676
+
677
+ roc_aucs = (mann_whitney_u / (num_pos * num_neg)).tolist()
678
+
679
+ # Median positive rank.
680
+ lower_middle = (num_pos + 1) // 2
681
+ upper_middle = (num_pos + 2) // 2
682
+
683
+ middle_targets = (
684
+ torch.tensor(
685
+ [lower_middle, upper_middle],
686
+ device=device,
687
+ dtype=tp_at_k.dtype,
688
+ )
689
+ .unsqueeze(0)
690
+ .expand(num_heads, -1)
691
+ )
692
+
693
+ middle_positive_idxs = torch.searchsorted(
694
+ tp_at_k,
695
+ middle_targets.contiguous(),
696
+ )
697
+
698
+ middle_ranks = torch.gather(
699
+ avg_descending_ranks,
700
+ 1,
701
+ middle_positive_idxs,
702
+ )
703
+
704
+ median_positive_ranks = middle_ranks.mean(dim=1)
705
+
706
+ best_median_positive_rank = (num_pos + 1) / 2
707
+
708
+ normalized_median_positive_rank_scores = 1.0 - (
709
+ (median_positive_ranks - best_median_positive_rank) / num_neg
710
+ )
711
+
712
+ recall_percents = torch.arange(
713
+ 5,
714
+ 101,
715
+ 5,
716
+ device=device,
717
+ )
718
+ # Exact integer ceil(percent * num_pos / 100).
719
+ target_tps = (recall_percents * num_pos + 99) // 100
720
+
721
+ target_tps_2d = target_tps.unsqueeze(0).expand(num_heads, -1).contiguous()
722
+
723
+ k_idxs_at_recall = torch.searchsorted(
724
+ tp_at_k,
725
+ target_tps_2d,
726
+ )
727
+
728
+ # A threshold must include the entire tied-score group.
729
+ k_idxs_at_recall = torch.gather(tie_ends, 1, k_idxs_at_recall)
730
+
731
+ row_ids_2d = row_ids.unsqueeze(1)
732
+
733
+ thresholds_at_recall = sorted_logits[row_ids_2d, k_idxs_at_recall]
734
+ # [num_heads, num_recall_targets]
735
+ thresholds_at_recall_list = thresholds_at_recall.tolist()
736
+
737
+ rank_fractions_at_recall = (
738
+ k_idxs_at_recall.to(tp_at_k.dtype) + 1
739
+ ) / num_index_tuples
740
+ rank_fractions_at_recall_list = rank_fractions_at_recall.tolist()
741
+
742
+ actual_tps_at_recall = tp_at_k[row_ids_2d, k_idxs_at_recall]
743
+
744
+ precisions_at_recall = actual_tps_at_recall / (
745
+ k_idxs_at_recall.to(tp_at_k.dtype) + 1
746
+ )
747
+ precisions_at_recall_list = precisions_at_recall.tolist()
748
+
749
+ best_f1s_list = best_f1s.tolist()
750
+ precisions_at_best_f1_list = precisions_at_best_f1.tolist()
751
+ recalls_at_best_f1_list = recalls_at_best_f1.tolist()
752
+ best_f1_rank_fractions_list = best_f1_rank_fractions.tolist()
753
+ normalized_median_positive_rank_scores_list = (
754
+ normalized_median_positive_rank_scores.tolist()
755
+ )
756
+ thresholds_at_best_f1_list = thresholds_at_best_f1.tolist()
757
+
758
+ evaluations_list: list[PolyprobeLabelEvaluation] = []
759
+ recall_percents_list = recall_percents.tolist()
760
+ for local_head_idx in range(num_heads):
761
+ threshold_by_recall_percent = {
762
+ percent: threshold
763
+ for percent, threshold in zip(
764
+ recall_percents_list,
765
+ thresholds_at_recall_list[local_head_idx],
766
+ )
767
+ }
768
+
769
+ rank_fraction_by_recall_percent = {
770
+ percent: rank_fraction
771
+ for percent, rank_fraction in zip(
772
+ recall_percents_list,
773
+ rank_fractions_at_recall_list[local_head_idx],
774
+ )
775
+ }
776
+ precision_by_recall_percent = {
777
+ percent: precision
778
+ for percent, precision in zip(
779
+ recall_percents_list,
780
+ precisions_at_recall_list[local_head_idx],
781
+ )
782
+ }
783
+
784
+ evaluations_list.append(
785
+ PolyprobeLabelEvaluation(
786
+ num_index_tuples=num_index_tuples,
787
+ num_positive_index_tuples=num_pos,
788
+ roc_auc=roc_aucs[local_head_idx],
789
+ normalized_median_positive_rank_score=normalized_median_positive_rank_scores_list[
790
+ local_head_idx
791
+ ],
792
+ average_precision=average_precisions[local_head_idx],
793
+ best_f1=best_f1s_list[local_head_idx],
794
+ precision_at_best_f1=precisions_at_best_f1_list[local_head_idx],
795
+ recall_at_best_f1=recalls_at_best_f1_list[local_head_idx],
796
+ best_f1_rank_fraction=best_f1_rank_fractions_list[local_head_idx],
797
+ threshold_at_best_f1=thresholds_at_best_f1_list[local_head_idx],
798
+ threshold_by_recall_percent=threshold_by_recall_percent,
799
+ rank_fraction_by_recall_percent=rank_fraction_by_recall_percent,
800
+ precision_by_recall_percent=precision_by_recall_percent,
801
+ )
802
+ )
803
+ return evaluations_list
804
+
805
+ def _get_diagnostic_examples(
806
+ self,
807
+ pieces: list[DocumentPiece],
808
+ index_tuples_list: list[Tensor],
809
+ sorted_truths: Tensor,
810
+ sorted_idxs: Tensor,
811
+ order: tuple[int, ...],
812
+ ) -> tuple[
813
+ list[list[str]],
814
+ list[list[str]],
815
+ ]:
816
+ """
817
+ Return diagnostic examples for each evaluated model or pooling prefix.
818
+
819
+ Each row of sorted_truths and sorted_idxs represents one evaluated model.
820
+ For each row, returns log lines detailing the highest-scoring negative examples
821
+ and the lowest-scoring positive examples.
822
+ """
823
+ if sorted_truths.ndim != 2 or sorted_idxs.ndim != 2:
824
+ raise ValueError(
825
+ "sorted_truths and sorted_idxs must both be two-dimensional."
826
+ )
827
+
828
+ if sorted_truths.shape != sorted_idxs.shape:
829
+ raise ValueError(
830
+ "sorted_truths and sorted_idxs must have the same shape, "
831
+ f"but got {tuple(sorted_truths.shape)} and "
832
+ f"{tuple(sorted_idxs.shape)}."
833
+ )
834
+
835
+ num_evaluations, num_index_tuples = sorted_truths.shape
836
+
837
+ pair_refs: list[tuple[DocumentPiece, tuple[int, ...]]] = [
838
+ (piece, tuple(int(i) for i in index_tuple))
839
+ for piece, index_tuples in zip(pieces, index_tuples_list)
840
+ for index_tuple in index_tuples
841
+ ]
842
+
843
+ if len(pair_refs) != num_index_tuples:
844
+ raise ValueError(
845
+ f"Expected {num_index_tuples} pair refs, but got {len(pair_refs)}. "
846
+ f"len(pieces)={len(pieces)}, "
847
+ f"len(index_tuples_list)={len(index_tuples_list)}"
848
+ )
849
+
850
+ max_examples = self.run_config.max_wrong_examples_to_return
851
+
852
+ if max_examples == 0:
853
+ return (
854
+ [[] for _ in range(num_evaluations)],
855
+ [[] for _ in range(num_evaluations)],
856
+ )
857
+
858
+ # Every row contains the same truth values, only in a different order.
859
+ num_pos = int(sorted_truths[0].sum().item())
860
+ num_neg = num_index_tuples - num_pos
861
+
862
+ num_positive_examples = min(max_examples, num_pos)
863
+ num_negative_examples = min(max_examples, num_neg)
864
+
865
+ positions = (
866
+ torch.arange(
867
+ num_index_tuples,
868
+ device=sorted_truths.device,
869
+ )
870
+ .unsqueeze(0)
871
+ .expand(num_evaluations, -1)
872
+ )
873
+
874
+ # Highest-scoring negatives are the negative examples occurring at the
875
+ # earliest positions in each score-sorted row.
876
+ negative_positions = positions.masked_fill(
877
+ sorted_truths != 0,
878
+ num_index_tuples,
879
+ )
880
+ highest_negative_positions = negative_positions.topk(
881
+ num_negative_examples,
882
+ dim=1,
883
+ largest=False,
884
+ sorted=True,
885
+ ).values
886
+ highest_negative_idxs = torch.gather(
887
+ sorted_idxs,
888
+ dim=1,
889
+ index=highest_negative_positions,
890
+ )
891
+
892
+ # Lowest-scoring positives are the positive examples occurring at the
893
+ # latest positions in each score-sorted row.
894
+ positive_positions = positions.masked_fill(
895
+ sorted_truths != 1,
896
+ -1,
897
+ )
898
+ lowest_positive_positions = positive_positions.topk(
899
+ num_positive_examples,
900
+ dim=1,
901
+ largest=True,
902
+ sorted=True,
903
+ ).values
904
+ lowest_positive_idxs = torch.gather(
905
+ sorted_idxs,
906
+ dim=1,
907
+ index=lowest_positive_positions,
908
+ )
909
+
910
+ highest_negative_idxs_list = highest_negative_idxs.cpu().tolist()
911
+ lowest_positive_idxs_list = lowest_positive_idxs.cpu().tolist()
912
+
913
+ highest_scoring_non_labelled_log_lines = [
914
+ self._get_example_reprs(
915
+ [pair_refs[idx] for idx in row],
916
+ order,
917
+ )
918
+ for row in highest_negative_idxs_list
919
+ ]
920
+
921
+ lowest_scoring_labelled_log_lines = [
922
+ self._get_example_reprs(
923
+ [pair_refs[idx] for idx in row],
924
+ order,
925
+ )
926
+ for row in lowest_positive_idxs_list
927
+ ]
928
+
929
+ return (
930
+ highest_scoring_non_labelled_log_lines,
931
+ lowest_scoring_labelled_log_lines,
932
+ )
933
+
934
+ def _get_example_reprs(
935
+ self,
936
+ examples: list[tuple[DocumentPiece, tuple[int, ...]]],
937
+ order: tuple[int, ...],
938
+ ) -> list[str]:
939
+ example_reprs: list[str] = []
940
+ for piece, index_tuple in examples:
941
+ activation_tuples = [(index, index) for index in index_tuple]
942
+ example_reprs.append(
943
+ f"({piece.identifier}) {piece.text}: {get_activation_tuples_representation(piece, activation_tuples, order)}"
944
+ )
945
+ return example_reprs