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,218 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ import warnings
7
+ from typing import Any, cast
8
+
9
+ import torch
10
+ import transformers
11
+ from torch import Tensor
12
+ from tqdm.auto import tqdm as Tqdm
13
+ from transformer_lens.model_bridge import TransformerBridge
14
+ from transformer_lens.utilities.components_utils import get_act_name
15
+ from transformers import AutoTokenizer
16
+
17
+ from polyprobe.activations import ACTIVATION_TYPES, ActivationStore, ActivationType
18
+ from polyprobe.document import DocumentPiece
19
+ from polyprobe.registry import PolyprobeRegistry
20
+
21
+ logger = logging.getLogger(__name__)
22
+ ARCHITECTURES_TO_ARCHITECTURE_ENCODER_NAMES = {
23
+ "OPTForCausalLM": "OPTArchitectureEncoder",
24
+ "Qwen3ForCausalLM": "GQAAttentionArchitectureEncoder",
25
+ "Qwen3_5ForCausalLM": "Qwen3_5ArchitectureEncoder",
26
+ # note that for Cohere2, rot_q and rot_k are normalized but not in fact rotated in NoPE layers.
27
+ "Cohere2ForCausalLM": "GQAAttentionArchitectureEncoder",
28
+ }
29
+
30
+
31
+ class LMEncoder:
32
+ """Encodes documents with a transformer language model and adds the observed vectors
33
+ to their representations.
34
+
35
+ Chooses the most appropriate floating-point data type based on the hardware architecture.
36
+
37
+ lm_name: the Hugging Face name of the LM, e.g. "Qwen/Qwen3-4B".
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ registry: PolyprobeRegistry,
43
+ lm_name: str,
44
+ device: torch.device,
45
+ architectures_to_architecture_encoder_names: dict[str, str] | None,
46
+ ):
47
+ self.registry = registry
48
+ self.lm_name = lm_name
49
+ self.device = device
50
+ self.tokenizer = AutoTokenizer.from_pretrained(
51
+ lm_name, use_fast=True, trust_remote_code=False
52
+ )
53
+ if not self.tokenizer.is_fast:
54
+ raise ValueError("Need a fast tokenizer for offset mapping alignment.")
55
+ if device.type == "cuda" and torch.cuda.is_bf16_supported(
56
+ including_emulation=False
57
+ ):
58
+ dtype = torch.bfloat16
59
+ elif device.type == "cpu":
60
+ dtype = torch.float32
61
+ else:
62
+ dtype = torch.float16
63
+
64
+ model_type = transformers.AutoConfig.from_pretrained(
65
+ lm_name,
66
+ trust_remote_code=False,
67
+ ).model_type
68
+ with warnings.catch_warnings():
69
+ warnings.filterwarnings(
70
+ "ignore",
71
+ message=r"Hook alias .* did not resolve.*",
72
+ category=UserWarning,
73
+ module=r"transformer_lens",
74
+ )
75
+ if model_type in {"qwen3_5", "qwen3_5_text"}:
76
+ # necessary to stop the vision model from being loaded
77
+ text_config = transformers.Qwen3_5TextConfig.from_pretrained(lm_name)
78
+ hf_model = transformers.Qwen3_5ForCausalLM.from_pretrained(
79
+ lm_name,
80
+ config=text_config,
81
+ torch_dtype=dtype,
82
+ attn_implementation="eager",
83
+ )
84
+ cast(torch.nn.Module, hf_model).to(device=device, dtype=dtype)
85
+ self.bridge = TransformerBridge.boot_transformers(
86
+ lm_name,
87
+ hf_model=hf_model,
88
+ device=device,
89
+ dtype=dtype,
90
+ trust_remote_code=False,
91
+ )
92
+ else:
93
+ self.bridge = TransformerBridge.boot_transformers(
94
+ lm_name,
95
+ device=device,
96
+ dtype=dtype,
97
+ trust_remote_code=False,
98
+ )
99
+ self.bridge.eval()
100
+ self.architecture = self.bridge.cfg.architecture
101
+ if architectures_to_architecture_encoder_names is None:
102
+ architectures_to_architecture_encoder_names = (
103
+ ARCHITECTURES_TO_ARCHITECTURE_ENCODER_NAMES
104
+ )
105
+ if self.architecture not in architectures_to_architecture_encoder_names:
106
+ raise ValueError(f"LM Architecture {self.architecture} is not supported.")
107
+ architecture_encoder_type = registry.get_architecture_encoder_type(
108
+ architectures_to_architecture_encoder_names[self.architecture]
109
+ )
110
+ self.architecture_encoder = architecture_encoder_type(self.bridge)
111
+ self.heads_per_layer = self.bridge.cfg.n_heads
112
+ self.head_infos = self.architecture_encoder.get_head_infos()
113
+ self.parameters: dict[str, Any] = {}
114
+
115
+ def create_document_piece(self, text: str, identifier: str) -> DocumentPiece:
116
+ tokenized = self.tokenizer(
117
+ text,
118
+ return_offsets_mapping=True,
119
+ add_special_tokens=True,
120
+ return_tensors="pt",
121
+ truncation=True,
122
+ )
123
+ input_ids = tokenized["input_ids"]
124
+ lm_offsets = [
125
+ (lo[0], lo[1]) for lo in tokenized["offset_mapping"].squeeze(0).tolist()
126
+ ]
127
+
128
+ return DocumentPiece(
129
+ text=text,
130
+ input_ids=input_ids,
131
+ lm_offsets=lm_offsets,
132
+ identifier=identifier,
133
+ )
134
+
135
+ def encode(
136
+ self,
137
+ pieces: list[DocumentPiece],
138
+ activation_types: set[ActivationType],
139
+ stop_at_layer: int | None,
140
+ progress: Tqdm | None, # type: ignore[type-arg]
141
+ ) -> ActivationStore:
142
+ """
143
+ Encodes the document pieces with the LM and gathers and returns
144
+ the required activation generated within all heads up to the specified layer.
145
+
146
+ pieces: the document pieces to encode.
147
+ activation_types: the activation types required by the probe.
148
+ stop_at_layer: the number of layers to encode.
149
+ progress_bar: an existing progress bar, or *None* if none is being displayed.
150
+ """
151
+ if not pieces:
152
+ raise ValueError("Cannot encode an empty list of document pieces.")
153
+ for activation_type in activation_types:
154
+ if activation_type not in ACTIVATION_TYPES:
155
+ raise ValueError(
156
+ f"Activation type {activation_type} is not supported by Polyprobe."
157
+ )
158
+ if not self.architecture_encoder.is_activation_type_supported(
159
+ activation_type
160
+ ):
161
+ raise ValueError(
162
+ f"Activation type {activation_type} is not supported by architecture encoder {type(self.architecture_encoder).__name__}."
163
+ )
164
+ if stop_at_layer is None:
165
+ stop_at_layer = self.head_infos[-1][0] + 1
166
+
167
+ wanted_hook_names = [
168
+ get_act_name(act, layer)
169
+ for layer in range(stop_at_layer)
170
+ for act in activation_types
171
+ ]
172
+
173
+ activation_types_to_activation_lists: dict[ActivationType, list[Tensor]] = {
174
+ activation_type: [] for activation_type in activation_types
175
+ }
176
+ piece_offsets: list[int] = [0]
177
+ with torch.inference_mode(), warnings.catch_warnings():
178
+ warnings.filterwarnings(
179
+ "ignore",
180
+ message=r"Hook alias .* did not resolve.*",
181
+ category=UserWarning,
182
+ module=r"transformer_lens",
183
+ )
184
+ for piece in pieces:
185
+ _, cache = self.bridge.run_with_cache(
186
+ piece.input_ids.to(self.device),
187
+ stop_at_layer=stop_at_layer,
188
+ return_type=None,
189
+ names_filter=wanted_hook_names,
190
+ )
191
+ piece_offsets.append(piece_offsets[-1] + len(piece.input_ids[0]))
192
+ for activation_type in activation_types:
193
+ if activation_type in ("attn_scores", "pattern"):
194
+ activation = self.architecture_encoder.stack_attention_matrix(
195
+ cache,
196
+ activation_type,
197
+ stop_at_layer,
198
+ )
199
+ else:
200
+ activation = self.architecture_encoder.stack_heads(
201
+ cache,
202
+ activation_type,
203
+ stop_at_layer,
204
+ )
205
+ activation = activation.to(torch.device("cpu"), dtype=torch.float32)
206
+ activation_types_to_activation_lists[activation_type].append(
207
+ activation
208
+ )
209
+ if progress is not None:
210
+ progress.update(1)
211
+
212
+ return ActivationStore(
213
+ activations={
214
+ activation_type: torch.cat(activation_list, dim=1)
215
+ for activation_type, activation_list in activation_types_to_activation_lists.items()
216
+ },
217
+ piece_offsets=piece_offsets,
218
+ )
@@ -0,0 +1,82 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from collections.abc import Generator
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+ from typing import TextIO
10
+
11
+ from tqdm import tqdm
12
+
13
+
14
+ class TqdmLoggingHandler(logging.StreamHandler[TextIO]):
15
+ def emit(self, record: logging.LogRecord) -> None:
16
+ try:
17
+ msg = self.format(record)
18
+ tqdm.write(msg)
19
+ self.flush()
20
+ except Exception:
21
+ self.handleError(record)
22
+
23
+
24
+ def setup_console_logging(*, level: int) -> None:
25
+ """
26
+ Set up console logging for normal library/app usage.
27
+ Safe to call multiple times.
28
+ """
29
+
30
+ logger = logging.getLogger("polyprobe")
31
+ logger.setLevel(level)
32
+
33
+ logger.propagate = False
34
+
35
+ # Avoid adding duplicate console handlers.
36
+ if any(getattr(h, "_is_console_handler", False) for h in logger.handlers):
37
+ return
38
+
39
+ console_handler = TqdmLoggingHandler()
40
+ console_handler._is_console_handler = True # type: ignore[attr-defined]
41
+ console_handler.setLevel(level)
42
+ console_handler.setFormatter(
43
+ logging.Formatter(
44
+ "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
45
+ datefmt="%Y-%m-%d %H:%M:%S",
46
+ )
47
+ )
48
+
49
+ logger.addHandler(console_handler)
50
+
51
+
52
+ @contextmanager
53
+ def logging_to_file(
54
+ log_file: Path | str,
55
+ *,
56
+ level: int = logging.INFO,
57
+ ) -> Generator[None, None, None]:
58
+ """
59
+ Temporarily add a dated file handler for one training/generation run.
60
+ Remove it again when the run finishes.
61
+ """
62
+
63
+ file_handler = logging.FileHandler(log_file, encoding="utf-8")
64
+ file_handler.setLevel(level)
65
+ file_handler.setFormatter(
66
+ logging.Formatter(
67
+ "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
68
+ datefmt="%Y-%m-%d %H:%M:%S",
69
+ )
70
+ )
71
+
72
+ logger = logging.getLogger("polyprobe")
73
+ logger.addHandler(file_handler)
74
+
75
+ try:
76
+ yield
77
+ except Exception:
78
+ logger.exception("Run failed.")
79
+ raise
80
+ finally:
81
+ logger.removeHandler(file_handler)
82
+ file_handler.close()