polyprobe 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of polyprobe might be problematic. Click here for more details.

Files changed (48) hide show
  1. polyprobe/__init__.py +8 -0
  2. polyprobe/activations.py +353 -0
  3. polyprobe/architecture_encoders/architecture_encoder.py +71 -0
  4. polyprobe/architecture_encoders/gqa.py +77 -0
  5. polyprobe/architecture_encoders/opt.py +51 -0
  6. polyprobe/architecture_encoders/qwen3_5.py +100 -0
  7. polyprobe/batching.py +133 -0
  8. polyprobe/config.py +101 -0
  9. polyprobe/document.py +138 -0
  10. polyprobe/evaluation.py +945 -0
  11. polyprobe/index_tuple_selectors/causal_combinatorial.py +49 -0
  12. polyprobe/index_tuple_selectors/index_tuple_selector.py +23 -0
  13. polyprobe/inferrer.py +480 -0
  14. polyprobe/lm_encoder.py +218 -0
  15. polyprobe/logging_utils.py +82 -0
  16. polyprobe/manager.py +607 -0
  17. polyprobe/model.py +342 -0
  18. polyprobe/poolers/max.py +23 -0
  19. polyprobe/poolers/mean.py +34 -0
  20. polyprobe/poolers/passthrough.py +21 -0
  21. polyprobe/poolers/pooler.py +88 -0
  22. polyprobe/probe_components/index_pair.py +368 -0
  23. polyprobe/probe_components/probe_component.py +92 -0
  24. polyprobe/probes/linear.py +46 -0
  25. polyprobe/probes/neural.py +220 -0
  26. polyprobe/probes/probe.py +164 -0
  27. polyprobe/py.typed +0 -0
  28. polyprobe/registry.py +248 -0
  29. polyprobe/scorers/average_precision.py +27 -0
  30. polyprobe/scorers/f1.py +24 -0
  31. polyprobe/scorers/roc-auc.py +28 -0
  32. polyprobe/scorers/scorer.py +43 -0
  33. polyprobe/training/config.py +127 -0
  34. polyprobe/training/dataset_sources/dataset_source.py +142 -0
  35. polyprobe/training/dataset_sources/ud_dependency_dataset_source.py +517 -0
  36. polyprobe/training/runner.py +951 -0
  37. polyprobe/training/training_data.py +180 -0
  38. polyprobe/training/truthers/direct.py +206 -0
  39. polyprobe/training/truthers/random.py +63 -0
  40. polyprobe/training/truthers/subword.py +49 -0
  41. polyprobe/training/truthers/truther.py +96 -0
  42. polyprobe/util.py +599 -0
  43. polyprobe-1.0.0.dist-info/METADATA +63 -0
  44. polyprobe-1.0.0.dist-info/RECORD +48 -0
  45. polyprobe-1.0.0.dist-info/WHEEL +5 -0
  46. polyprobe-1.0.0.dist-info/licenses/LICENSE +73 -0
  47. polyprobe-1.0.0.dist-info/licenses/LICENSE-CC-BY-4.0 +395 -0
  48. polyprobe-1.0.0.dist-info/top_level.txt +1 -0
polyprobe/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .logging_utils import logging_to_file as logging_to_file
6
+ from .manager import PolyprobeManager as PolyprobeManager
7
+ from .model import PolyprobeModel as PolyprobeModel
8
+ from .registry import PolyprobeRegistry as PolyprobeRegistry
@@ -0,0 +1,353 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ import shutil
7
+ import tempfile
8
+ from dataclasses import dataclass
9
+ from itertools import accumulate
10
+ from pathlib import Path
11
+ from types import TracebackType
12
+ from typing import Literal, Self, get_args
13
+
14
+ import torch
15
+ from torch import Tensor
16
+
17
+ from polyprobe.document import DocumentPiece
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ ActivationType = Literal["k", "q", "rot_k", "rot_q", "v", "z", "attn_scores", "pattern"]
22
+
23
+ ACTIVATION_TYPES = frozenset(get_args(ActivationType))
24
+
25
+
26
+ @dataclass
27
+ class ActivationStore:
28
+ """
29
+ Captures the relevant activations gathered from heads while a document piece is being encoded by an LM.
30
+
31
+ activations: a dictionary from activation types to tensors with shape (heads, tokens, dim) or (heads, attending tokens * attended tokens).
32
+ piece_offsets: the offsets demarcating information about different document pieces in dimension 1 of the tensors in *activations*.
33
+ """
34
+
35
+ activations: dict[ActivationType, Tensor]
36
+ piece_offsets: list[int]
37
+
38
+
39
+ class MemoryBackedActivationStore:
40
+ """
41
+ Allows a large amount of activation information to be written to a temporary file directory and mapped into memory as required.
42
+ Used in the training runner where the same activations are required over and over again for train and eval. This object is
43
+ a context manager, e.g.:
44
+
45
+ ```
46
+ with MemoryBackedActivationStore(example_activation_store, pieces) as mbas:
47
+ ...
48
+ ```
49
+
50
+ Note that reading from this store yields a view on the temporary file which must be deallocated using *del* after use and before
51
+ leaving the context manager, otherwise issues with temporary file management may arise on some platforms.
52
+
53
+ example_activation_store: an activation store encoded for typically a single short document piece for reference on which tensors
54
+ the probe requires and what their shapes are.
55
+ pieces: the document pieces whose activations will be written and mapped by this store. Writing and reading must respect the order
56
+ in which they are presented to this __init__() method.
57
+ temp_dir: the path under which to create and use the temporary directory, or *None* to use the operating-system standard.
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ example_activation_store: ActivationStore,
63
+ pieces: list[DocumentPiece],
64
+ temp_dir: Path | None = None,
65
+ ) -> None:
66
+ if not pieces:
67
+ raise ValueError("pieces must not be empty")
68
+
69
+ self._activation_shapes = {
70
+ activation_type: tuple(activation.shape)
71
+ for activation_type, activation in example_activation_store.activations.items()
72
+ }
73
+
74
+ head_tensors = [
75
+ act
76
+ for act in example_activation_store.activations.values()
77
+ if len(act.shape) == 3
78
+ ]
79
+ self._head_dtype = head_tensors[0].dtype if head_tensors else None
80
+
81
+ matrix_tensors = [
82
+ act
83
+ for act in example_activation_store.activations.values()
84
+ if len(act.shape) == 2
85
+ ]
86
+ self._matrix_dtype = matrix_tensors[0].dtype if matrix_tensors else None
87
+
88
+ piece_lengths = [len(piece.input_ids[0]) for piece in pieces]
89
+ squared_piece_lengths = [length * length for length in piece_lengths]
90
+
91
+ self._head_boundaries = list(accumulate(piece_lengths, initial=0))
92
+ self._matrix_boundaries = list(accumulate(squared_piece_lengths, initial=0))
93
+
94
+ self._temp_parent_dir = temp_dir
95
+ self._temp_dir: tempfile.TemporaryDirectory[str] | None = None
96
+ self._activations: dict[ActivationType, Tensor] = {}
97
+
98
+ def __enter__(self) -> Self:
99
+
100
+ if self._temp_dir is not None:
101
+ raise RuntimeError("Activation store is already open")
102
+
103
+ self._temp_dir = tempfile.TemporaryDirectory(
104
+ prefix="polyprobe-mbas-",
105
+ dir=self._temp_parent_dir,
106
+ )
107
+
108
+ try:
109
+ temp_dir_path = Path(self._temp_dir.name)
110
+
111
+ total_tokens = self._head_boundaries[-1]
112
+ total_matrix_elements = self._matrix_boundaries[-1]
113
+
114
+ usage = shutil.disk_usage(temp_dir_path)
115
+
116
+ required_bytes = 0
117
+
118
+ for activation_type, shape in self._activation_shapes.items():
119
+ if len(shape) == 3:
120
+ num_elements = shape[0] * total_tokens * shape[2]
121
+ dtype = self._head_dtype
122
+ elif len(shape) == 2:
123
+ num_elements = shape[0] * total_matrix_elements
124
+ dtype = self._matrix_dtype
125
+ else:
126
+ raise ValueError(
127
+ f"Activation {activation_type!r} has unsupported shape "
128
+ f"{shape}; expected 2D or 3D"
129
+ )
130
+
131
+ element_size = torch.empty(0, dtype=dtype).element_size()
132
+ required_bytes += num_elements * element_size
133
+
134
+ safety_margin = 5 * 1024**3
135
+
136
+ if required_bytes + safety_margin > usage.free:
137
+ raise RuntimeError(
138
+ f"Activation cache requires approximately "
139
+ f"{required_bytes / 1024**3:.1f} GiB, but only "
140
+ f"{usage.free / 1024**3:.1f} GiB is free in {self._temp_dir.name}"
141
+ )
142
+
143
+ for activation_type, shape in self._activation_shapes.items():
144
+ path = temp_dir_path / f"{activation_type}.bin"
145
+
146
+ if len(shape) == 3:
147
+ num_heads, _, dimension = shape
148
+
149
+ storage = torch.from_file(
150
+ str(path),
151
+ shared=True,
152
+ size=num_heads * total_tokens * dimension,
153
+ dtype=self._head_dtype,
154
+ )
155
+
156
+ self._activations[activation_type] = storage.view(
157
+ total_tokens,
158
+ num_heads,
159
+ dimension,
160
+ )
161
+
162
+ elif len(shape) == 2:
163
+ num_heads, _ = shape
164
+
165
+ storage = torch.from_file(
166
+ str(path),
167
+ shared=True,
168
+ size=num_heads * total_matrix_elements,
169
+ dtype=self._matrix_dtype,
170
+ )
171
+
172
+ self._activations[activation_type] = storage.view(
173
+ total_matrix_elements,
174
+ num_heads,
175
+ )
176
+
177
+ else:
178
+ raise ValueError(
179
+ f"Activation {activation_type!r} has unsupported shape "
180
+ f"{shape}; expected 2D or 3D"
181
+ )
182
+
183
+ return self
184
+ except BaseException:
185
+ self._cleanup()
186
+ raise
187
+
188
+ def write(
189
+ self,
190
+ activation_store: ActivationStore,
191
+ start_piece_idx: int,
192
+ end_piece_idx: int,
193
+ ) -> None:
194
+ """Writes an *ActivationStore* to the specified position on disk.
195
+
196
+ activation_store: the in-memory activation store.
197
+ start_piece_idx, end_piece_idx: the indices of the pieces for which to store the activations.
198
+ """
199
+ self._require_open()
200
+ self._validate_piece_range(start_piece_idx, end_piece_idx)
201
+ expected_types = set(self._activations)
202
+ received_types = set(activation_store.activations)
203
+
204
+ if received_types != expected_types:
205
+ raise ValueError(
206
+ f"Activation types do not match; "
207
+ f"received={sorted(received_types)}, expected={sorted(expected_types)}"
208
+ )
209
+
210
+ for activation_type, source in activation_store.activations.items():
211
+ try:
212
+ destination = self._activations[activation_type]
213
+ except KeyError as error:
214
+ raise KeyError(
215
+ f"No file-backed storage was allocated for " f"{activation_type!r}"
216
+ ) from error
217
+
218
+ source = source.detach()
219
+
220
+ if destination.ndim == 3:
221
+ start_offset = self._head_boundaries[start_piece_idx]
222
+ end_offset = self._head_boundaries[end_piece_idx]
223
+
224
+ expected_shape: tuple[int, ...] = (
225
+ destination.shape[1],
226
+ end_offset - start_offset,
227
+ destination.shape[2],
228
+ )
229
+
230
+ if tuple(source.shape) != expected_shape:
231
+ raise ValueError(
232
+ f"For activation {activation_type!r}, pieces "
233
+ f"[{start_piece_idx}, {end_piece_idx}] require shape "
234
+ f"{expected_shape}, but received {tuple(source.shape)}"
235
+ )
236
+
237
+ destination[
238
+ start_offset:end_offset,
239
+ :,
240
+ :,
241
+ ].copy_(source.permute(1, 0, 2))
242
+
243
+ elif destination.ndim == 2:
244
+ start_offset = self._matrix_boundaries[start_piece_idx]
245
+ end_offset = self._matrix_boundaries[end_piece_idx]
246
+
247
+ expected_shape = (
248
+ destination.shape[1],
249
+ end_offset - start_offset,
250
+ )
251
+
252
+ if tuple(source.shape) != expected_shape:
253
+ raise ValueError(
254
+ f"For activation {activation_type!r}, pieces "
255
+ f"[{start_piece_idx}, {end_piece_idx}] require shape "
256
+ f"{expected_shape}, but received {tuple(source.shape)}"
257
+ )
258
+
259
+ destination[
260
+ start_offset:end_offset,
261
+ :,
262
+ ].copy_(source.permute(1, 0))
263
+
264
+ else:
265
+ raise AssertionError("Stored activation must be 2D or 3D")
266
+
267
+ def __exit__(
268
+ self,
269
+ exc_type: type[BaseException] | None,
270
+ exc_value: BaseException | None,
271
+ traceback: TracebackType | None,
272
+ ) -> Literal[False]:
273
+ self._cleanup()
274
+ # Do not suppress exceptions raised inside the with block.
275
+ return False
276
+
277
+ def read(
278
+ self,
279
+ start_piece_idx: int,
280
+ end_piece_idx: int,
281
+ ) -> ActivationStore:
282
+ """Returns a view over the specified activation tensors, packages as an *ActivationStore* object.
283
+
284
+ start_piece_idx, end_piece_idx: the indices of the pieces for which to return the activations.
285
+ """
286
+ self._require_open()
287
+ self._validate_piece_range(start_piece_idx, end_piece_idx)
288
+
289
+ return_activations: dict[ActivationType, Tensor] = {}
290
+
291
+ for activation_type, activation in self._activations.items():
292
+ if activation.ndim == 3:
293
+ start_offset = self._head_boundaries[start_piece_idx]
294
+ end_offset = self._head_boundaries[end_piece_idx]
295
+
296
+ return_activations[activation_type] = activation[
297
+ start_offset:end_offset,
298
+ :,
299
+ :,
300
+ ].permute(1, 0, 2)
301
+
302
+ elif activation.ndim == 2:
303
+ start_offset = self._matrix_boundaries[start_piece_idx]
304
+ end_offset = self._matrix_boundaries[end_piece_idx]
305
+
306
+ return_activations[activation_type] = activation[
307
+ start_offset:end_offset,
308
+ :,
309
+ ].permute(1, 0)
310
+
311
+ else:
312
+ raise AssertionError("Stored activation must be 2D or 3D")
313
+
314
+ chunk_start = self._head_boundaries[start_piece_idx]
315
+
316
+ piece_offsets = [
317
+ offset - chunk_start
318
+ for offset in self._head_boundaries[start_piece_idx : end_piece_idx + 1]
319
+ ]
320
+
321
+ return ActivationStore(
322
+ activations=return_activations,
323
+ piece_offsets=piece_offsets,
324
+ )
325
+
326
+ def _validate_piece_range(
327
+ self,
328
+ start_piece_idx: int,
329
+ end_piece_idx: int,
330
+ ) -> None:
331
+ num_pieces = len(self._head_boundaries) - 1
332
+ if not (0 <= start_piece_idx < end_piece_idx <= num_pieces):
333
+ raise IndexError(
334
+ "Expected a non-empty half-open piece range satisfying "
335
+ f"0 <= start < end <= {num_pieces}, but got "
336
+ f"[{start_piece_idx}, {end_piece_idx})"
337
+ )
338
+
339
+ def _require_open(self) -> None:
340
+ if self._temp_dir is None:
341
+ raise RuntimeError(
342
+ "MemoryBackedActivationStore is not open; "
343
+ "use it inside a with statement"
344
+ )
345
+
346
+ def _cleanup(self) -> None:
347
+ # Remove this class's references to the mappings before attempting to
348
+ # delete their backing files.
349
+ self._activations.clear()
350
+
351
+ if self._temp_dir is not None:
352
+ self._temp_dir.cleanup()
353
+ self._temp_dir = None
@@ -0,0 +1,71 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+ from abc import ABC, abstractmethod
7
+
8
+ import torch
9
+ from transformer_lens import ActivationCache
10
+ from transformer_lens.model_bridge import TransformerBridge
11
+
12
+ from polyprobe.activations import ActivationType
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class ArchitectureEncoder(ABC):
18
+ """
19
+ Instances are responsible for LM encoding.
20
+ Each instance maps to one or more architectures under
21
+ https://github.com/TransformerLensOrg/TransformerLens/tree/main/transformer_lens/model_bridge/supported_architectures.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ bridge: TransformerBridge,
27
+ ):
28
+ self.bridge = bridge
29
+ self.n_heads = self.bridge.cfg.n_heads
30
+ self.d_head = self.bridge.cfg.d_head
31
+
32
+ @classmethod
33
+ def is_activation_type_supported(cls, actiivation_type: ActivationType) -> bool:
34
+ """
35
+ An implementation should subclass this method and return *False* for activation types
36
+ that it does not support.
37
+ """
38
+ return True
39
+
40
+ @abstractmethod
41
+ def stack_heads(
42
+ self,
43
+ cache: ActivationCache,
44
+ activation_type: ActivationType,
45
+ stop_at_layer: int,
46
+ ) -> torch.Tensor:
47
+ """
48
+ Returns a tensor of shape (heads, tokens, dim) containing the activations of the specified type for a document piece.
49
+
50
+ activation_type: one of 'k', 'q', 'v', 'rot_k', 'rot_q', or 'z' specifying the activations to stack.
51
+ """
52
+
53
+ @abstractmethod
54
+ def stack_attention_matrix(
55
+ self,
56
+ cache: ActivationCache,
57
+ activation_type: ActivationType,
58
+ stop_at_layer: int,
59
+ ) -> torch.Tensor:
60
+ """Returns a tensor of shape (heads, attending tokens * attended tokens) containing the activations of the specified type for a document piece.
61
+
62
+ activation_type: one of 'attn_scores', 'pattern' specifying the activations to stack.
63
+ """
64
+
65
+ @abstractmethod
66
+ def get_head_infos(self) -> list[tuple[int, int]]:
67
+ """Returns a list of tuples of the form (<layer num>, <head num>) describing
68
+ the attention heads encoded by the LM. Note that in some architectures not all layers
69
+ are attention layers, in which case the assigned layer numbers are not
70
+ contiguous.
71
+ """
@@ -0,0 +1,77 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import torch
6
+ from torch import Tensor
7
+ from transformer_lens import ActivationCache
8
+ from transformer_lens.model_bridge import TransformerBridge
9
+
10
+ from polyprobe.activations import ActivationType
11
+
12
+ from .architecture_encoder import ArchitectureEncoder
13
+
14
+
15
+ class GQAAttentionArchitectureEncoder(ArchitectureEncoder):
16
+ """Encoder for standard full attention and grouped-query attention (GQA) architectures.
17
+
18
+ Assumes:
19
+ - Attention hooks use TransformerLens's standard tensor layouts.
20
+ - All transformer layers contain conventional attention.
21
+ - K/V heads can be expanded to query heads using GQA.
22
+
23
+ Note that this architecture encoder is used for the Cohere2 architecture, where
24
+ rot_k and rot_q tensors are output at all heads but are only actually rotated
25
+ as well as normalised on RoPE layers; there are also NoPE layers, where the tensors
26
+ are normalised but not rotated.
27
+
28
+ """
29
+
30
+ @classmethod
31
+ def is_activation_type_supported(cls, activation_type: ActivationType) -> bool:
32
+ return True # supports all attention types supported by Polyprobe
33
+
34
+ def __init__(
35
+ self,
36
+ bridge: TransformerBridge,
37
+ ):
38
+ super().__init__(bridge)
39
+ n_query_heads = bridge.cfg.n_heads
40
+ n_kv_heads = bridge.cfg.n_key_value_heads or n_query_heads
41
+ self.queries_per_kv_head = n_query_heads // n_kv_heads
42
+
43
+ def stack_heads(
44
+ self, cache: ActivationCache, activation_type: str, stop_at_layer: int
45
+ ) -> torch.Tensor:
46
+ all_tensors: list[Tensor] = []
47
+ for layer in range(stop_at_layer):
48
+ this_layer_tensors = cache[f"blocks.{layer}.attn.hook_{activation_type}"]
49
+ all_tensors.append(this_layer_tensors)
50
+ if len(all_tensors) == 0:
51
+ raise ValueError(
52
+ f"No activations of type {activation_type} were recovered."
53
+ )
54
+ encoding = (
55
+ torch.cat(all_tensors, dim=0).permute(0, 2, 1, 3).flatten(0, 1).float()
56
+ )
57
+ if activation_type in ("k", "rot_k", "v"):
58
+ encoding = encoding.repeat_interleave(self.queries_per_kv_head, dim=0)
59
+ return encoding
60
+
61
+ def stack_attention_matrix(
62
+ self,
63
+ cache: ActivationCache,
64
+ activation_type: ActivationType,
65
+ stop_at_layer: int,
66
+ ) -> torch.Tensor:
67
+ all_tensors: list[Tensor] = []
68
+ for layer in range(stop_at_layer):
69
+ this_layer_tensors = cache[f"blocks.{layer}.attn.hook_{activation_type}"]
70
+ all_tensors.append(this_layer_tensors)
71
+ return torch.cat(all_tensors, dim=0).flatten(0, 1).flatten(1, 2).float()
72
+
73
+ def get_head_infos(self) -> list[tuple[int, int]]:
74
+ head_infos: list[tuple[int, int]] = []
75
+ for layer in range(self.bridge.cfg.n_layers):
76
+ head_infos.extend([(layer, head_num) for head_num in range(self.n_heads)])
77
+ return head_infos
@@ -0,0 +1,51 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import torch
6
+ from torch import Tensor
7
+ from transformer_lens import ActivationCache
8
+
9
+ from polyprobe.activations import ActivationType
10
+
11
+ from .architecture_encoder import ArchitectureEncoder
12
+
13
+
14
+ class OPTArchitectureEncoder(ArchitectureEncoder):
15
+ """For e.g. facebook/opt-125m. This is a good test for a model whose tokenizer adds a BOS token
16
+ at the beginning of the stream as well as for one that does not use RoPE."""
17
+
18
+ @classmethod
19
+ def is_activation_type_supported(cls, activation_type: ActivationType) -> bool:
20
+ return activation_type not in ("rot_q", "rot_k")
21
+
22
+ def stack_heads(
23
+ self, cache: ActivationCache, activation_type: str, stop_at_layer: int
24
+ ) -> torch.Tensor:
25
+ all_tensors: list[Tensor] = []
26
+ for layer in range(stop_at_layer):
27
+ this_layer_tensors = cache[f"blocks.{layer}.attn.hook_{activation_type}"]
28
+ all_tensors.append(this_layer_tensors)
29
+ if len(all_tensors) == 0:
30
+ raise ValueError(
31
+ f"No activations of type {activation_type} were recovered."
32
+ )
33
+ return torch.cat(all_tensors, dim=0).permute(0, 2, 1, 3).flatten(0, 1).float()
34
+
35
+ def stack_attention_matrix(
36
+ self,
37
+ cache: ActivationCache,
38
+ activation_type: ActivationType,
39
+ stop_at_layer: int,
40
+ ) -> torch.Tensor:
41
+ all_tensors: list[Tensor] = []
42
+ for layer in range(stop_at_layer):
43
+ this_layer_tensors = cache[f"blocks.{layer}.attn.hook_{activation_type}"]
44
+ all_tensors.append(this_layer_tensors)
45
+ return torch.cat(all_tensors, dim=0).flatten(0, 1).flatten(1, 2).float()
46
+
47
+ def get_head_infos(self) -> list[tuple[int, int]]:
48
+ head_infos: list[tuple[int, int]] = []
49
+ for layer in range(self.bridge.cfg.n_layers):
50
+ head_infos.extend([(layer, head_num) for head_num in range(self.n_heads)])
51
+ return head_infos
@@ -0,0 +1,100 @@
1
+ # SPDX-FileCopyrightText: 2026 Richard Paul Hudson
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import logging
6
+
7
+ import torch
8
+ from torch import Tensor, tensor
9
+ from transformer_lens import ActivationCache
10
+ from transformer_lens.utilities.components_utils import get_act_name
11
+
12
+ from polyprobe.activations import ActivationType
13
+
14
+ from .gqa import GQAAttentionArchitectureEncoder
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class Qwen3_5ArchitectureEncoder(GQAAttentionArchitectureEncoder):
20
+ """The Qwen3.5 architecture combines Gated DeltaNet linear attention
21
+ with standard gated softmax attention in a 3:1 ratio, meaning that
22
+ only every fourth layer is accessible to analysis by Polyprobe.
23
+ """
24
+
25
+ def stack_heads(
26
+ self, cache: ActivationCache, activation_type: str, stop_at_layer: int
27
+ ) -> torch.Tensor:
28
+ all_tensors: list[Tensor] = []
29
+ for layer in range(stop_at_layer):
30
+ act_name = f"blocks.{layer}.attn.hook_{activation_type}"
31
+ if act_name in cache:
32
+ this_layer_tensors = cache[act_name]
33
+ if activation_type == "q":
34
+ this_layer_tensors, _ = self._preprocess_gated_q_proj(
35
+ this_layer_tensors
36
+ )
37
+ all_tensors.append(this_layer_tensors)
38
+ if len(all_tensors) == 0:
39
+ raise ValueError(
40
+ f"No activations of type {activation_type} were recovered."
41
+ )
42
+ activation = (
43
+ torch.cat(all_tensors, dim=0).permute(0, 2, 1, 3).flatten(0, 1).float()
44
+ )
45
+ if activation_type in ("k", "rot_k", "v"):
46
+ activation = activation.repeat_interleave(self.queries_per_kv_head, dim=0)
47
+ return activation
48
+
49
+ def stack_attention_matrix(
50
+ self,
51
+ cache: ActivationCache,
52
+ activation_type: ActivationType,
53
+ stop_at_layer: int,
54
+ ) -> torch.Tensor:
55
+ all_tensors: list[Tensor] = []
56
+ for layer in range(stop_at_layer):
57
+ act_name = f"blocks.{layer}.attn.hook_{activation_type}"
58
+ if act_name in cache:
59
+ this_layer_tensors = cache[act_name]
60
+ all_tensors.append(this_layer_tensors)
61
+ if len(all_tensors) == 0:
62
+ raise ValueError(
63
+ f"No activations of type {activation_type} were recovered."
64
+ )
65
+ return torch.cat(all_tensors, dim=0).flatten(0, 1).flatten(1, 2).float()
66
+
67
+ def _preprocess_gated_q_proj(self, gated: Tensor) -> tuple[Tensor, Tensor]:
68
+
69
+ if gated.ndim == 4: # from TL 4
70
+ if gated.shape[2:] != (
71
+ self.n_heads * 2,
72
+ self.d_head,
73
+ ):
74
+ raise ValueError(f"Unexpected gated Q shape: {gated.shape}")
75
+ gated = gated.flatten(start_dim=2)
76
+
77
+ else:
78
+ if gated.ndim != 3 or gated.shape[-1] != self.n_heads * self.d_head * 2:
79
+ raise ValueError(f"Unexpected gated Q shape: {gated.shape}")
80
+
81
+ gated = gated.reshape(*gated.shape[:2], self.n_heads, self.d_head * 2)
82
+ return gated[..., : self.d_head], gated[..., self.d_head :]
83
+
84
+ def get_head_infos(self) -> list[tuple[int, int]]:
85
+ wanted_hook_names = [
86
+ get_act_name("k", layer) for layer in range(self.bridge.cfg.n_layers)
87
+ ]
88
+ _, cache = self.bridge.run_with_cache(
89
+ tensor([[5834]]).to(self.bridge.device), # hardcoded 'hi'
90
+ stop_at_layer=self.bridge.cfg.n_layers,
91
+ return_type=None,
92
+ names_filter=wanted_hook_names,
93
+ )
94
+ head_infos: list[tuple[int, int]] = []
95
+ for layer in range(self.bridge.cfg.n_layers):
96
+ if f"blocks.{layer}.attn.hook_k" in cache:
97
+ head_infos.extend(
98
+ [(layer, head_num) for head_num in range(self.n_heads)]
99
+ )
100
+ return head_infos