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,951 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ import os
7
+ import tempfile
8
+ from pathlib import Path
9
+ from statistics import mean, stdev
10
+ from typing import cast
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch import Tensor
15
+ from tqdm.auto import tqdm as Tqdm
16
+
17
+ from polyprobe.activations import ActivationStore, MemoryBackedActivationStore
18
+ from polyprobe.batching import BatchingMemoryException, BatchSizeManager
19
+ from polyprobe.config import RunConfig
20
+ from polyprobe.document import DocumentPiece
21
+ from polyprobe.evaluation import LabelEvaluator
22
+ from polyprobe.lm_encoder import LMEncoder
23
+ from polyprobe.model import (
24
+ DatasetSourceUsage,
25
+ PolyprobeLabelEvaluation,
26
+ PolyprobeLabelModel,
27
+ PolyprobeModel,
28
+ )
29
+ from polyprobe.registry import PolyprobeRegistry
30
+ from polyprobe.training.config import TrainingConfig, TrainingDatasetSourceConfig
31
+ from polyprobe.training.training_data import (
32
+ HeadModelDataWrapper,
33
+ LabelModelTrainingData,
34
+ TrainingDatasetGroup,
35
+ )
36
+ from polyprobe.util import (
37
+ describe_head_index,
38
+ empty_cache,
39
+ get_batch_end,
40
+ get_config_dict_log_lines,
41
+ get_index_of_first_head_on_or_above_layer,
42
+ get_index_tuple_boundaries,
43
+ get_label_model_description_log_lines,
44
+ get_probe_components,
45
+ get_probe_input_capacity,
46
+ get_required_activation_types,
47
+ plot_label_model_evaluation_curves,
48
+ )
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+
53
+ class PolyprobeTrainingRunner:
54
+ """Executes a training run."""
55
+
56
+ def __init__(
57
+ self,
58
+ description: str | None,
59
+ temp_dir: Path | None,
60
+ registry: PolyprobeRegistry,
61
+ lm_encoder: LMEncoder,
62
+ run_config: RunConfig,
63
+ training_config: TrainingConfig,
64
+ training_dataset_source_config: TrainingDatasetSourceConfig,
65
+ plots_dir: Path | None,
66
+ maximum_tensor_mebibytes: int,
67
+ end_layer: int,
68
+ device: torch.device,
69
+ ):
70
+ self.registry = registry
71
+ self.lm_encoder = lm_encoder
72
+ self.head_infos = lm_encoder.head_infos
73
+ self.run_config = run_config
74
+ self.training_config = training_config
75
+ self.training_dataset_source_config = training_dataset_source_config
76
+ self.plots_dir = plots_dir
77
+ self.maximum_tensor_mebibytes = maximum_tensor_mebibytes
78
+ self.end_layer = end_layer
79
+ self.device = device
80
+ self.temp_dir = temp_dir
81
+ self.probe_type = registry.get_probe_type(self.training_config.probe_name)
82
+ self.probe_component_names = list(self.training_config.probe_component_names)
83
+ self.probe_components = get_probe_components(
84
+ registry, self.probe_component_names
85
+ )
86
+ for pc in self.probe_components:
87
+ pc.check_lm_architecture(self.lm_encoder.architecture)
88
+ self.required_activation_types = get_required_activation_types(
89
+ self.probe_components
90
+ )
91
+ self.index_tuple_selector = registry.get_index_tuple_selector_type(
92
+ self.training_config.index_tuple_selector_name
93
+ )(**self.training_config.index_tuple_selector_kwargs)
94
+ self.pooler = registry.get_pooler_type(self.training_config.pooler_name)(
95
+ **self.training_config.pooler_kwargs
96
+ )
97
+ self.truther = registry.get_truther_type(self.training_config.truther_name)(
98
+ **self.training_config.truther_kwargs
99
+ )
100
+ self.scorer = registry.get_scorer_type(self.training_config.scorer_name)(
101
+ **self.training_config.scorer_kwargs
102
+ )
103
+ self.label_evaluator = LabelEvaluator(
104
+ self.registry,
105
+ self.lm_encoder,
106
+ self.run_config,
107
+ self.training_config.probe_name,
108
+ self.training_config.probe_kwargs,
109
+ self.probe_component_names,
110
+ self.maximum_tensor_mebibytes,
111
+ self.device,
112
+ )
113
+ self.description = description
114
+ logger.info(f"Using LM {self.lm_encoder.lm_name}")
115
+ self.dataset_source = registry.get_dataset_source_type(
116
+ self.training_dataset_source_config.dataset_source_name
117
+ )(
118
+ lm_encoder,
119
+ self.run_config.seed,
120
+ self.training_dataset_source_config.dataset_source_kwargs,
121
+ )
122
+ log_lines: list[str] = []
123
+ log_lines.extend(get_config_dict_log_lines("Run config", self.run_config))
124
+ log_lines.extend(
125
+ get_config_dict_log_lines(
126
+ "Training dataset source config", self.training_dataset_source_config
127
+ )
128
+ )
129
+ log_lines.extend(
130
+ get_config_dict_log_lines("Training config", self.training_config)
131
+ )
132
+ for log_line in log_lines:
133
+ logger.info(log_line)
134
+
135
+ def train(
136
+ self,
137
+ ) -> PolyprobeModel | None:
138
+ """
139
+ Returns a model, or *None* if none of the specified labels occurred sufficiently often in the corpus to allow training.
140
+ """
141
+ start_head = get_index_of_first_head_on_or_above_layer(
142
+ self.head_infos, self.training_config.start_layer, is_end=False
143
+ )
144
+ end_head = get_index_of_first_head_on_or_above_layer(
145
+ self.head_infos, self.end_layer, is_end=True
146
+ )
147
+ if end_head - start_head < 1:
148
+ raise ValueError(
149
+ f"No heads found between layer {self.training_config.start_layer} and {self.end_layer}."
150
+ )
151
+
152
+ training_dataset_group = self.dataset_source.get_document_piece_splits(
153
+ self.training_dataset_source_config
154
+ )
155
+
156
+ example_activation_store = self._get_example_activation_store(
157
+ training_dataset_group
158
+ )
159
+
160
+ with MemoryBackedActivationStore(
161
+ example_activation_store, training_dataset_group.all_pieces, self.temp_dir
162
+ ) as mbas:
163
+ self._encode_pieces(mbas, training_dataset_group.all_pieces)
164
+ probe_input_capacity = get_probe_input_capacity(
165
+ mbas.read(0, 1),
166
+ self.lm_encoder,
167
+ self.probe_type,
168
+ self.training_config.probe_kwargs,
169
+ self.probe_components,
170
+ self.maximum_tensor_mebibytes,
171
+ self.device,
172
+ )
173
+
174
+ labels_and_orders = self._get_sorted_labels_and_orders(
175
+ training_dataset_group
176
+ )
177
+ label_models: list[PolyprobeLabelModel] = []
178
+ for label, order in labels_and_orders:
179
+ self.truther.check_label_and_order(label, order)
180
+ logger.info(f"Training label {label} with order {order}")
181
+ label_model_training_data = LabelModelTrainingData(
182
+ self.index_tuple_selector,
183
+ self.truther,
184
+ training_dataset_group,
185
+ label,
186
+ order,
187
+ )
188
+
189
+ if (
190
+ label_model_training_data.train.num_pos_labels
191
+ < self.training_config.min_pos_labels
192
+ ):
193
+ logger.info(
194
+ f"Skipping as only {label_model_training_data.train.num_pos_labels} positive label(s) found, min_pos_labels={self.training_config.min_pos_labels}"
195
+ )
196
+ continue
197
+
198
+ if not self._all_splits_have_pos_and_neg(label_model_training_data):
199
+ continue
200
+
201
+ label_model = self._train_label_and_order(
202
+ label,
203
+ order,
204
+ probe_input_capacity,
205
+ mbas,
206
+ label_model_training_data,
207
+ start_head,
208
+ end_head,
209
+ )
210
+ label_models.append(label_model)
211
+
212
+ if not label_models:
213
+ return None
214
+ else:
215
+ return PolyprobeModel(
216
+ lm_name=self.lm_encoder.lm_name,
217
+ head_infos=self.head_infos,
218
+ label_models=label_models,
219
+ description=self.description,
220
+ )
221
+
222
+ def _encode_pieces(
223
+ self, mbas: MemoryBackedActivationStore, pieces: list[DocumentPiece]
224
+ ) -> None:
225
+ encoding_batch_size_manager = BatchSizeManager(
226
+ [0], ["document pieces"], self.device, "encoding"
227
+ )
228
+ while True:
229
+ try:
230
+ with encoding_batch_size_manager.batch_size_to_attempt(
231
+ [self.run_config.initial_document_encoding_batch_size]
232
+ ) as attempted_encoding_batch_size:
233
+ piece_iter = Tqdm(
234
+ pieces,
235
+ desc="Encoding documents",
236
+ unit="piece",
237
+ leave=False,
238
+ disable=not self.run_config.show_progress,
239
+ )
240
+ for pieces_start_idx in range(
241
+ 0, len(pieces), attempted_encoding_batch_size[0]
242
+ ):
243
+ pieces_end_idx = min(
244
+ len(pieces),
245
+ pieces_start_idx + attempted_encoding_batch_size[0],
246
+ )
247
+ activation_store = self.lm_encoder.encode(
248
+ pieces[pieces_start_idx:pieces_end_idx],
249
+ self.required_activation_types,
250
+ self.end_layer,
251
+ piece_iter,
252
+ )
253
+ mbas.write(activation_store, pieces_start_idx, pieces_end_idx)
254
+ return
255
+ except BatchingMemoryException:
256
+ continue
257
+
258
+ def _all_splits_have_pos_and_neg(
259
+ self, label_model_training_data: LabelModelTrainingData
260
+ ) -> bool:
261
+ for split_name, split in label_model_training_data.splits.items():
262
+ num_total = sum(t.numel() for t in split.truths_list)
263
+ if split.num_pos_labels == num_total:
264
+ logger.info(
265
+ f"Skipping as all index tuples in {split_name} are positive."
266
+ )
267
+ return False
268
+ if split.num_pos_labels == 0:
269
+ logger.info(
270
+ f"Skipping as all index tuples in {split_name} are negative."
271
+ )
272
+ return False
273
+ return True
274
+
275
+ def _train_label_and_order(
276
+ self,
277
+ label: str,
278
+ order: tuple[int, ...],
279
+ probe_input_capacity: int,
280
+ mbas: MemoryBackedActivationStore,
281
+ label_model_training_data: LabelModelTrainingData,
282
+ start_head: int,
283
+ end_head: int,
284
+ ) -> PolyprobeLabelModel:
285
+
286
+ batch_size_manager = BatchSizeManager(
287
+ [0, 1],
288
+ ["heads", "index tuples"],
289
+ self.device,
290
+ "training",
291
+ reduce_factor=0.95,
292
+ )
293
+ num_train_index_tuples = sum(
294
+ it.shape[0] for it in label_model_training_data.train.index_tuples_list
295
+ )
296
+ num_heads = end_head - start_head
297
+ index_tuple_boundaries = get_index_tuple_boundaries(
298
+ label_model_training_data.train.index_tuples_list
299
+ )
300
+ if num_train_index_tuples > probe_input_capacity:
301
+ head_batch_size = 1
302
+ index_tuple_batch_size = probe_input_capacity
303
+ else:
304
+ index_tuple_batch_size = num_train_index_tuples
305
+ head_batch_size = min(
306
+ num_heads,
307
+ probe_input_capacity // index_tuple_batch_size,
308
+ )
309
+ maximum_batch_size_to_attempt = [
310
+ head_batch_size,
311
+ index_tuple_batch_size,
312
+ ]
313
+ while True:
314
+ try:
315
+ with batch_size_manager.batch_size_to_attempt(
316
+ maximum_batch_size_to_attempt
317
+ ) as attempted_batch_size:
318
+ head_model_data_wrappers: list[HeadModelDataWrapper] = []
319
+ for batch_start_head in range(
320
+ start_head, end_head, attempted_batch_size[0]
321
+ ):
322
+ batch_end_head = min(
323
+ end_head, batch_start_head + attempted_batch_size[0]
324
+ )
325
+ this_batch_head_model_data_wrappers = self._train_label_batch(
326
+ mbas,
327
+ label_model_training_data,
328
+ batch_start_head,
329
+ batch_end_head,
330
+ index_tuple_boundaries,
331
+ attempted_batch_size,
332
+ )
333
+ head_model_data_wrappers.extend(
334
+ this_batch_head_model_data_wrappers
335
+ )
336
+ empty_cache(self.device)
337
+ if (
338
+ self.run_config.specified_maximum_tensor_mebibytes
339
+ is not None
340
+ and self.device.type == "cuda"
341
+ and batch_start_head == start_head
342
+ and batch_end_head != end_head
343
+ and not batch_size_manager.has_failed
344
+ ):
345
+ logger.warning(
346
+ f"Training worked straight away with maximum tensor memory {self.maximum_tensor_mebibytes}MiB. "
347
+ "Normally the aim is for the maximum tensor memory to be slightly higher than the available GPU capacity so the optimum tensor memory "
348
+ "can be found by gradual reduction following successive OOMs. It may be that the available GPU is not being used optimally. "
349
+ "Consider rerunning and specifying a higher value of maximum_tensor_mebibytes."
350
+ )
351
+ if all(
352
+ hmdw.evaluations_without_improvement
353
+ == self.training_config.max_evaluations_without_improvement
354
+ for hmdw in head_model_data_wrappers
355
+ ):
356
+ mean_epochs = mean(
357
+ [hmdw.evaluation.epoch for hmdw in head_model_data_wrappers]
358
+ )
359
+ logger.info(f"Mean epoch of best evaluation: {mean_epochs:.2f}")
360
+ head_model_data_wrappers.sort(
361
+ key=lambda hmdw: hmdw.evaluation.score,
362
+ reverse=True,
363
+ )
364
+ head_nums = [
365
+ hmdw.evaluation.head_num for hmdw in head_model_data_wrappers
366
+ ]
367
+
368
+ weights = torch.stack(
369
+ [hmdw.weights for hmdw in head_model_data_wrappers]
370
+ ).cpu()
371
+ head_evaluations_list = [
372
+ hmdw.evaluation for hmdw in head_model_data_wrappers
373
+ ]
374
+
375
+ if weights.shape[0] != len(head_evaluations_list):
376
+ raise ValueError(
377
+ f"Weights shape {weights.shape[0]} does not correspond to {len(head_evaluations_list)} evaluations."
378
+ )
379
+ self._log_head_evaluation(head_evaluations_list)
380
+
381
+ with torch.inference_mode():
382
+ logger.info("")
383
+ logger.info(
384
+ f"Generating and evaluating label model with pooler {self.training_config.pooler_name}"
385
+ )
386
+ label_model = PolyprobeLabelModel(
387
+ label,
388
+ order,
389
+ self.training_config.probe_name,
390
+ self.training_config.probe_kwargs,
391
+ self.probe_component_names,
392
+ self.training_config.pooler_name,
393
+ self.training_config.pooler_kwargs,
394
+ self.training_config.index_tuple_selector_name,
395
+ self.training_config.index_tuple_selector_kwargs,
396
+ self.training_config.scorer_name,
397
+ self.training_config.scorer_kwargs,
398
+ self.training_config.truther_name,
399
+ self.training_config.truther_kwargs,
400
+ head_nums,
401
+ weights,
402
+ self.training_dataset_source_config.get_dataset_descriptions(),
403
+ # set in _evaluate_pooling_and_add_results_to_label_model()
404
+ test_evaluation=None, # type: ignore[arg-type]
405
+ )
406
+ self._evaluate_pooling_and_add_results_to_label_model(
407
+ label_model, label_model_training_data, mbas
408
+ )
409
+ if self.plots_dir is not None:
410
+ plot_label_model_evaluation_curves(
411
+ self.plots_dir,
412
+ label_model,
413
+ self.head_infos,
414
+ self.description,
415
+ self.scorer.get_score_label(),
416
+ )
417
+ return label_model
418
+ except BatchingMemoryException:
419
+ continue
420
+
421
+ def _train_label_batch(
422
+ self,
423
+ mbas: MemoryBackedActivationStore,
424
+ label_model_training_data: LabelModelTrainingData,
425
+ batch_start_head: int,
426
+ batch_end_head: int,
427
+ index_tuple_boundaries: list[int],
428
+ batch_size: list[int],
429
+ ) -> list[HeadModelDataWrapper]:
430
+
431
+ index_tuple_batch_size = batch_size[1]
432
+ if index_tuple_batch_size <= 0:
433
+ raise ValueError("index_tuple_batch_size must be greater than zero")
434
+
435
+ this_batch_probe = self.probe_type(
436
+ self.probe_components,
437
+ (batch_start_head, batch_end_head),
438
+ self.head_infos,
439
+ self.device,
440
+ seed=self.run_config.seed,
441
+ **self.training_config.probe_kwargs,
442
+ )
443
+
444
+ # required so the probe generates weights to supply to the optimizer
445
+ example_activation_store = mbas.read(0, 1)
446
+ example_input = this_batch_probe.build_input(
447
+ example_activation_store,
448
+ label_model_training_data.train.index_tuples_list[0:1],
449
+ )
450
+ del example_activation_store, example_input
451
+
452
+ with tempfile.TemporaryDirectory(
453
+ prefix="polyprobe-inputs-",
454
+ dir=self.temp_dir,
455
+ ) as inputs_temp_dir:
456
+
457
+ document_piece_batch_starts_to_mmaps: dict[int, Tensor] = {}
458
+
459
+ document_piece_batch_inputs: Tensor | None = None
460
+ document_piece_batch_truths: Tensor | None = None
461
+
462
+ try:
463
+ head_model_data_wrappers: list[HeadModelDataWrapper] = []
464
+
465
+ inputs_temp_dir_path = Path(inputs_temp_dir)
466
+
467
+ if index_tuple_boundaries[-1] > index_tuple_batch_size:
468
+ logger.warning(
469
+ "Because all training index tuples do not fit in one batch, "
470
+ "the inputs have to be moved from CPU to GPU batch by batch "
471
+ "within each epoch, which will lead to increased training time. "
472
+ "Each batch will also trigger a separate "
473
+ "optimizer step, so training results may differ substantially "
474
+ "from single-batch training."
475
+ )
476
+
477
+ optimizer = torch.optim.AdamW(
478
+ this_batch_probe.parameters(),
479
+ lr=self.training_config.learning_rate,
480
+ weight_decay=self.training_config.weight_decay,
481
+ )
482
+
483
+ if batch_end_head - batch_start_head == 1:
484
+ batch_repr = (
485
+ "Probing head "
486
+ f"{describe_head_index(batch_start_head, self.head_infos)}"
487
+ )
488
+ else:
489
+ batch_repr = (
490
+ "Probing heads "
491
+ f"{describe_head_index(batch_start_head, self.head_infos)}"
492
+ f"-{describe_head_index(batch_end_head - 1, self.head_infos)}"
493
+ )
494
+
495
+ logger.info(batch_repr)
496
+ epoch_iter = Tqdm(
497
+ range(self.training_config.max_epochs),
498
+ desc=batch_repr,
499
+ unit="epoch",
500
+ leave=False,
501
+ disable=not self.run_config.show_progress,
502
+ )
503
+
504
+ # Tracking the current batch in GPU enables it to be reused across epochs
505
+ # without reloading when the whole corpus fits in a single batch.
506
+ inputs_in_gpu_document_piece_batch_start: int | None = None
507
+
508
+ eval_repr = ""
509
+ min_unimproved_evals = 0
510
+ for epoch in epoch_iter:
511
+
512
+ epoch_loss_sum = 0.0
513
+ epoch_loss_element_count = 0
514
+ document_piece_batch_start = 0
515
+ while document_piece_batch_start < len(
516
+ label_model_training_data.train.pieces
517
+ ):
518
+
519
+ document_piece_batch_end = min(
520
+ len(label_model_training_data.train.pieces),
521
+ get_batch_end(
522
+ index_tuple_boundaries,
523
+ index_tuple_batch_size,
524
+ document_piece_batch_start,
525
+ ),
526
+ )
527
+
528
+ optimizer.zero_grad(set_to_none=True)
529
+
530
+ with torch.no_grad():
531
+ if (
532
+ inputs_in_gpu_document_piece_batch_start
533
+ != document_piece_batch_start
534
+ ):
535
+ # Release the previous GPU batch before allocating the next one.
536
+ document_piece_batch_inputs = None
537
+ document_piece_batch_truths = None
538
+
539
+ if (
540
+ document_piece_batch_start
541
+ in document_piece_batch_starts_to_mmaps
542
+ ):
543
+ document_piece_batch_inputs_cpu = (
544
+ document_piece_batch_starts_to_mmaps[
545
+ document_piece_batch_start
546
+ ]
547
+ )
548
+ else:
549
+ document_piece_batch_filepath = (
550
+ inputs_temp_dir_path
551
+ / f"batch-{document_piece_batch_start:012d}.pt"
552
+ )
553
+
554
+ document_piece_batch_activation_store = mbas.read(
555
+ document_piece_batch_start,
556
+ document_piece_batch_end,
557
+ )
558
+ document_piece_batch_inputs_cpu = (
559
+ this_batch_probe.build_input(
560
+ document_piece_batch_activation_store,
561
+ label_model_training_data.train.index_tuples_list[
562
+ document_piece_batch_start:document_piece_batch_end
563
+ ],
564
+ )
565
+ .detach()
566
+ .cpu()
567
+ )
568
+ del document_piece_batch_activation_store # release handle on temporary file
569
+
570
+ incomplete_filepath = (
571
+ document_piece_batch_filepath.with_suffix(
572
+ ".pt.incomplete"
573
+ )
574
+ )
575
+ torch.save(
576
+ document_piece_batch_inputs_cpu,
577
+ incomplete_filepath,
578
+ )
579
+ os.replace(
580
+ incomplete_filepath,
581
+ document_piece_batch_filepath,
582
+ )
583
+
584
+ del document_piece_batch_inputs_cpu
585
+
586
+ document_piece_batch_inputs_cpu = torch.load(
587
+ document_piece_batch_filepath,
588
+ map_location="cpu",
589
+ weights_only=True,
590
+ mmap=True,
591
+ )
592
+ document_piece_batch_starts_to_mmaps[
593
+ document_piece_batch_start
594
+ ] = document_piece_batch_inputs_cpu
595
+
596
+ num_heads = batch_end_head - batch_start_head
597
+
598
+ if document_piece_batch_inputs_cpu.ndim != 3:
599
+ raise RuntimeError(
600
+ f"Expected inputs with shape [heads, index tuples, features], "
601
+ f"but got {tuple(document_piece_batch_inputs_cpu.shape)}"
602
+ )
603
+
604
+ if (
605
+ document_piece_batch_inputs_cpu.shape[0]
606
+ != num_heads
607
+ ):
608
+ raise RuntimeError(
609
+ f"Expected {num_heads} input heads, "
610
+ f"but got {document_piece_batch_inputs_cpu.shape[0]}"
611
+ )
612
+
613
+ document_piece_batch_truths_cpu = torch.cat(
614
+ label_model_training_data.train.truths_list[
615
+ document_piece_batch_start:document_piece_batch_end
616
+ ],
617
+ dim=0,
618
+ )
619
+
620
+ if document_piece_batch_truths_cpu.numel() == 0:
621
+ document_piece_batch_start = (
622
+ document_piece_batch_end
623
+ )
624
+ continue
625
+
626
+ document_piece_batch_inputs = (
627
+ document_piece_batch_inputs_cpu.to(
628
+ self.device, dtype=torch.float32
629
+ )
630
+ )
631
+ # Probe optimisation is intentionally performed in float32 even when
632
+ # LM activations were produced at lower precision, because logistic
633
+ # regression and simple feed-forward networks train poorly with
634
+ # lower precisions.
635
+ del document_piece_batch_inputs_cpu
636
+ inputs_in_gpu_document_piece_batch_start = (
637
+ document_piece_batch_start
638
+ )
639
+ document_piece_batch_truths = (
640
+ document_piece_batch_truths_cpu.to(
641
+ self.device, dtype=torch.float32
642
+ )
643
+ .unsqueeze(0)
644
+ .expand(batch_end_head - batch_start_head, -1)
645
+ )
646
+
647
+ if (
648
+ document_piece_batch_inputs.shape[1]
649
+ != document_piece_batch_truths.shape[1]
650
+ ):
651
+ raise RuntimeError(
652
+ f"Inputs contain {document_piece_batch_inputs.shape[1]} index tuples, "
653
+ f"but the truths describe {document_piece_batch_truths.shape[1]}"
654
+ )
655
+
656
+ assert document_piece_batch_inputs is not None
657
+ assert document_piece_batch_truths is not None
658
+
659
+ document_piece_batch_logits = this_batch_probe(
660
+ document_piece_batch_inputs
661
+ )
662
+
663
+ if (
664
+ document_piece_batch_logits.shape
665
+ != document_piece_batch_truths.shape
666
+ ):
667
+ raise RuntimeError(
668
+ f"Logits and truths have different shapes: "
669
+ f"logits={tuple(document_piece_batch_logits.shape)}, "
670
+ f"truths={tuple(document_piece_batch_truths.shape)}"
671
+ )
672
+
673
+ element_losses = F.binary_cross_entropy_with_logits(
674
+ document_piece_batch_logits,
675
+ document_piece_batch_truths,
676
+ reduction="none",
677
+ )
678
+ # Mean over pairs independently for each head; then combine the
679
+ # independent head objectives without averaging across heads.
680
+ loss = element_losses.mean(dim=1).sum()
681
+
682
+ epoch_loss_sum += element_losses.detach().sum().item()
683
+ epoch_loss_element_count += element_losses.numel()
684
+
685
+ loss.backward() # type: ignore[no-untyped-call]
686
+ optimizer.step()
687
+
688
+ del (
689
+ document_piece_batch_logits,
690
+ element_losses,
691
+ loss,
692
+ )
693
+ document_piece_batch_start = document_piece_batch_end
694
+
695
+ if epoch_loss_element_count == 0:
696
+ raise RuntimeError("No training pairs were processed")
697
+ epoch_loss = epoch_loss_sum / epoch_loss_element_count
698
+ if (
699
+ epoch != 0
700
+ and epoch % self.training_config.evaluate_every_n_epochs == 0
701
+ ) or epoch == self.training_config.max_epochs - 1:
702
+ document_piece_batch_inputs = None
703
+ document_piece_batch_truths = None
704
+ inputs_in_gpu_document_piece_batch_start = None
705
+ with torch.inference_mode():
706
+ weights = cast(Tensor, this_batch_probe.weights).detach()
707
+ head_evaluations = self.label_evaluator.evaluate_heads(
708
+ batch_start_head,
709
+ weights,
710
+ mbas,
711
+ len(label_model_training_data.train.pieces),
712
+ len(label_model_training_data.dev.pieces),
713
+ label_model_training_data.dev.index_tuples_list,
714
+ label_model_training_data.dev.truths_list,
715
+ batch_size,
716
+ False,
717
+ )
718
+ for evaluation in head_evaluations:
719
+ evaluation.epoch = epoch
720
+ self.scorer.score_label_evaluation(evaluation)
721
+ if len(head_model_data_wrappers) == 0:
722
+ head_model_data_wrappers = [
723
+ HeadModelDataWrapper(
724
+ evaluation, 0, weights[idx].cpu().clone()
725
+ )
726
+ for idx, evaluation in enumerate(head_evaluations)
727
+ ]
728
+ else:
729
+ self._track_improvements(
730
+ head_evaluations,
731
+ weights,
732
+ head_model_data_wrappers,
733
+ )
734
+ if (
735
+ min(
736
+ hmdw.evaluations_without_improvement
737
+ for hmdw in head_model_data_wrappers
738
+ )
739
+ >= self.training_config.max_evaluations_without_improvement
740
+ ):
741
+ logger.info(
742
+ f"No significant improvement at any head after {self.training_config.max_evaluations_without_improvement} "
743
+ f"consecutive evaluations, stopping training at epoch {epoch}"
744
+ )
745
+ break
746
+ best_head_model_data_wrapper = max(
747
+ head_model_data_wrappers,
748
+ key=lambda hmdw: hmdw.evaluation.score,
749
+ )
750
+ eval_repr = (
751
+ best_head_model_data_wrapper.evaluation.get_short_repr()
752
+ )
753
+ min_unimproved_evals = min(
754
+ hmdw.evaluations_without_improvement
755
+ for hmdw in head_model_data_wrappers
756
+ )
757
+ epoch_iter.set_postfix(
758
+ loss=f"{epoch_loss:.6f}",
759
+ best_eval=eval_repr,
760
+ min_unimproved_evals=min_unimproved_evals,
761
+ )
762
+ else:
763
+ logger.warning(
764
+ f"Reached max_epochs={self.training_config.max_epochs} before all "
765
+ "heads met the early-stopping criterion; using the best dev "
766
+ "checkpoint observed for each head."
767
+ )
768
+ finally:
769
+ document_piece_batch_inputs = None
770
+ document_piece_batch_truths = None
771
+ document_piece_batch_starts_to_mmaps.clear()
772
+
773
+ best_head_model_data_wrapper = max(
774
+ head_model_data_wrappers, key=lambda hmdw: hmdw.evaluation.score
775
+ )
776
+ logger.info("Per-head evaluations (best is starred):")
777
+ for hmdw in head_model_data_wrappers:
778
+ evaluation = hmdw.evaluation
779
+ logger.info(
780
+ f"{'*' if hmdw is best_head_model_data_wrapper else ''}"
781
+ f"{describe_head_index(evaluation.head_num, self.head_infos)}: "
782
+ f"({evaluation.get_short_repr()}), "
783
+ f"best checkpoint at epoch {evaluation.epoch}"
784
+ )
785
+ return head_model_data_wrappers
786
+
787
+ def _get_sorted_labels_and_orders(
788
+ self, training_dataset_group: TrainingDatasetGroup
789
+ ) -> list[tuple[str, tuple[int, ...]]]:
790
+ labels_and_orders = sorted(
791
+ training_dataset_group.train.assigned_training_labels_and_orders,
792
+ key=lambda item: (item[0], item[1]),
793
+ )
794
+ if "_subword" in self.training_dataset_source_config.labels:
795
+ labels_and_orders.append(("_subword", (0, 1)))
796
+ return labels_and_orders
797
+
798
+ def _track_improvements(
799
+ self,
800
+ head_evaluations: list[PolyprobeLabelEvaluation],
801
+ weights: Tensor,
802
+ head_model_data_wrappers: list[HeadModelDataWrapper],
803
+ ) -> None:
804
+ for idx, head_evaluation in enumerate(head_evaluations):
805
+ head_model_data_wrapper = head_model_data_wrappers[idx]
806
+ if (
807
+ head_model_data_wrapper.evaluations_without_improvement
808
+ >= self.training_config.max_evaluations_without_improvement
809
+ ):
810
+ continue
811
+ new_score = head_evaluation.score
812
+ if (
813
+ new_score
814
+ > head_model_data_wrapper.evaluation.score
815
+ + self.training_config.min_evaluation_delta
816
+ ):
817
+ head_model_data_wrapper.evaluations_without_improvement = 0
818
+ else:
819
+ head_model_data_wrapper.evaluations_without_improvement += 1
820
+
821
+ if new_score > head_model_data_wrapper.evaluation.score:
822
+ head_model_data_wrapper.evaluation = head_evaluation
823
+ head_model_data_wrapper.weights = weights[idx].cpu().clone()
824
+ logger.debug(
825
+ f"Score for head {describe_head_index(head_evaluation.head_num, self.head_infos)} increased to {head_evaluation.score}"
826
+ )
827
+
828
+ def _get_example_activation_store(
829
+ self, training_dataset_group: TrainingDatasetGroup
830
+ ) -> ActivationStore:
831
+ example_document_piece = training_dataset_group.train.pieces[0]
832
+ return self.lm_encoder.encode(
833
+ [example_document_piece],
834
+ self.required_activation_types,
835
+ self.end_layer,
836
+ None,
837
+ )
838
+
839
+ def _log_head_evaluation(
840
+ self, head_evaluations_list: list[PolyprobeLabelEvaluation]
841
+ ) -> None:
842
+ log_lines: list[str] = [""]
843
+ log_lines.append("Highest scoring heads:")
844
+ for head_position in range(
845
+ min(
846
+ self.training_config.num_heads_to_log,
847
+ len(head_evaluations_list),
848
+ )
849
+ ):
850
+ this_head_evaluation = head_evaluations_list[head_position]
851
+ log_lines.append(
852
+ f"Pos {head_position}: head {describe_head_index(this_head_evaluation.head_num, self.head_infos)}, stopped at epoch {this_head_evaluation.epoch}:"
853
+ )
854
+ log_lines.extend(
855
+ this_head_evaluation.get_overall_stats_log_lines(
856
+ self.run_config.log_recall_percent_stats
857
+ )
858
+ )
859
+ log_lines.append("")
860
+ log_lines.append("Lowest scoring head:")
861
+ this_head_evaluation = head_evaluations_list[-1]
862
+ log_lines.append(
863
+ f"Head {describe_head_index(this_head_evaluation.head_num, self.head_infos)}, stopped at epoch {this_head_evaluation.epoch}:"
864
+ )
865
+ log_lines.extend(
866
+ this_head_evaluation.get_overall_stats_log_lines(
867
+ self.run_config.log_recall_percent_stats
868
+ )
869
+ )
870
+ log_lines.append("")
871
+ all_scores = [e.score for e in head_evaluations_list]
872
+
873
+ score_label = self.scorer.get_score_label()
874
+ if len(all_scores) >= 2:
875
+ average = self.scorer.format_score(mean(all_scores))
876
+ sd = self.scorer.format_score(stdev(all_scores))
877
+ log_lines.append(
878
+ f"Mean {score_label} score across all heads: {average}; standard deviation: {sd}"
879
+ )
880
+ else:
881
+ log_lines.append("Not reporting averages as there is only one score.")
882
+ log_lines.append("")
883
+ for log_line in log_lines:
884
+ logger.info(log_line)
885
+
886
+ def _evaluate_pooling_and_add_results_to_label_model(
887
+ self,
888
+ label_model: PolyprobeLabelModel,
889
+ label_model_training_data: LabelModelTrainingData,
890
+ mbas: MemoryBackedActivationStore,
891
+ ) -> None:
892
+ mbas_start_piece_idx = 0
893
+ usage: DatasetSourceUsage
894
+ usages_to_pooled_evaluations: dict[
895
+ DatasetSourceUsage, list[PolyprobeLabelEvaluation]
896
+ ] = {}
897
+ for usage in ("train", "dev", "test"):
898
+ dataset = getattr(label_model_training_data, usage)
899
+ unpooled_evaluations, pooled_evaluations = (
900
+ self.label_evaluator.evaluate_label_model_across_pooling_prefixes(
901
+ label_model,
902
+ self.scorer,
903
+ dataset.pieces,
904
+ dataset.index_tuples_list,
905
+ dataset.truths_list,
906
+ self.run_config.show_progress,
907
+ f"Evaluating {usage} data",
908
+ mbas,
909
+ mbas_start_piece_idx,
910
+ )
911
+ )
912
+ usages_to_pooled_evaluations[usage] = pooled_evaluations
913
+ label_model.unpooled_evaluation_scores[usage] = [
914
+ e.score for e in unpooled_evaluations
915
+ ]
916
+ label_model.pooled_evaluation_scores[usage] = [
917
+ e.score for e in pooled_evaluations
918
+ ]
919
+ label_model.num_positive_index_tuples[usage] = pooled_evaluations[
920
+ 0
921
+ ].num_positive_index_tuples
922
+ label_model.positive_prevalences[usage] = pooled_evaluations[
923
+ 0
924
+ ].positive_prevalence
925
+ if usage == "dev":
926
+ label_model.num_head_results_to_pool = max(
927
+ range(1, len(pooled_evaluations) + 1),
928
+ key=lambda i: pooled_evaluations[i - 1].score,
929
+ )
930
+ elif usage == "test":
931
+ label_model.test_evaluation = pooled_evaluations[
932
+ label_model.num_head_results_to_pool - 1
933
+ ]
934
+ mbas_start_piece_idx += len(dataset.pieces)
935
+ log_lines: list[str] = []
936
+ log_lines.extend(
937
+ get_label_model_description_log_lines(label_model, self.head_infos)
938
+ )
939
+ for usage in ("train", "dev", "test"):
940
+ log_lines.append(f"Evaluation for {usage} document pieces:")
941
+ evaluation = usages_to_pooled_evaluations[usage][
942
+ label_model.num_head_results_to_pool - 1
943
+ ]
944
+ log_lines.extend(
945
+ self.label_evaluator.get_label_model_evaluation_log_lines(
946
+ evaluation,
947
+ )
948
+ )
949
+ log_lines.append("")
950
+ for log_line in log_lines:
951
+ logger.info(log_line)