interprelens 0.3.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.
Files changed (46) hide show
  1. interprelens/__init__.py +63 -0
  2. interprelens/api.py +297 -0
  3. interprelens/core/__init__.py +29 -0
  4. interprelens/core/hooks.py +360 -0
  5. interprelens/core/interventions.py +112 -0
  6. interprelens/core/logits.py +64 -0
  7. interprelens/core/residuals.py +24 -0
  8. interprelens/core/sites.py +98 -0
  9. interprelens/core/tracer.py +301 -0
  10. interprelens/core/types.py +76 -0
  11. interprelens/heads/__init__.py +6 -0
  12. interprelens/heads/data.py +213 -0
  13. interprelens/heads/gates.py +153 -0
  14. interprelens/heads/headmap.py +233 -0
  15. interprelens/heads/metrics.py +65 -0
  16. interprelens/models/__init__.py +28 -0
  17. interprelens/models/adapters.py +408 -0
  18. interprelens/plugins/__init__.py +0 -0
  19. interprelens/plugins/position/__init__.py +115 -0
  20. interprelens/plugins/position/behavior.py +72 -0
  21. interprelens/plugins/position/data.py +184 -0
  22. interprelens/plugins/position/decomposition.py +75 -0
  23. interprelens/plugins/position/plots.py +48 -0
  24. interprelens/plugins/position/profiles.py +253 -0
  25. interprelens/plugins/position/scores.py +36 -0
  26. interprelens/plugins/position/validation.py +126 -0
  27. interprelens/scorers/__init__.py +4 -0
  28. interprelens/scorers/ablation.py +80 -0
  29. interprelens/scorers/attribution_patching.py +69 -0
  30. interprelens/scorers/base.py +25 -0
  31. interprelens/scorers/chg/__init__.py +116 -0
  32. interprelens/scorers/chg/chg.py +331 -0
  33. interprelens/scorers/chg/taxonomy.py +72 -0
  34. interprelens/scorers/chg/trainer.py +425 -0
  35. interprelens/scorers/registry.py +109 -0
  36. interprelens/utils/__init__.py +11 -0
  37. interprelens/utils/helpers.py +230 -0
  38. interprelens/utils/tensor_dict.py +374 -0
  39. interprelens/utils/tokenisation.py +165 -0
  40. interprelens/viz/__init__.py +3 -0
  41. interprelens/viz/plot.py +129 -0
  42. interprelens-0.3.0.dist-info/METADATA +59 -0
  43. interprelens-0.3.0.dist-info/RECORD +46 -0
  44. interprelens-0.3.0.dist-info/WHEEL +4 -0
  45. interprelens-0.3.0.dist-info/entry_points.txt +2 -0
  46. interprelens-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,63 @@
1
+ """
2
+ interprelens: find, compare and act on the attention heads behind any LLM behaviour.
3
+
4
+ Every method scores attention heads and returns the same :class:`HeadMap`
5
+ (``[n_layers, n_heads]``, higher = more important), which can be saved, compared and plotted.
6
+
7
+ Original CHG code: https://github.com/jonhanke/nam_causal-head-gating (Nam et al., NeurIPS 2025).
8
+
9
+ Quick start:
10
+ >>> from interprelens import HeadDataset, LensAPI
11
+ >>> lens = LensAPI.from_pretrained("meta-llama/Llama-3.2-1B")
12
+ >>> data = HeadDataset.from_pattern_task("aba", lens.tokenizer, num_samples=64, seed=0)
13
+ >>> heads = lens.score_heads("ablation", data)
14
+ >>> heads.plot("heads.png")
15
+ """
16
+
17
+ from .api import LensAPI
18
+ from .core.hooks import (
19
+ autograd_node_hook,
20
+ capture_backward_pre,
21
+ capture_gradients,
22
+ capture_kwargs_hook,
23
+ tensor_grad_hook,
24
+ )
25
+ from .core.interventions import InterventionSpec, apply_interventions
26
+ from .core.sites import ALL_SITES, GLOBAL_SITES, LAYER_SITES, SITE_SPECS
27
+ from .core.tracer import TransformerTracer
28
+ from .core.types import LayerSiteKey, SiteRequest, TraceResult
29
+ from .heads.data import HeadDataset
30
+ from .heads.gates import head_gates, mean_head_outputs
31
+ from .heads.headmap import HeadMap
32
+ from .scorers.base import HeadScorer
33
+ from .scorers.registry import get_scorer, list_scorers, register_scorer, scorer_info
34
+
35
+ __version__ = "0.3.0"
36
+ __author__ = "Bowen"
37
+ __all__ = [
38
+ "LensAPI",
39
+ "HeadMap",
40
+ "HeadDataset",
41
+ "HeadScorer",
42
+ "head_gates",
43
+ "mean_head_outputs",
44
+ "get_scorer",
45
+ "list_scorers",
46
+ "register_scorer",
47
+ "scorer_info",
48
+ "TransformerTracer",
49
+ "TraceResult",
50
+ "SiteRequest",
51
+ "LayerSiteKey",
52
+ "ALL_SITES",
53
+ "LAYER_SITES",
54
+ "GLOBAL_SITES",
55
+ "SITE_SPECS",
56
+ "InterventionSpec",
57
+ "apply_interventions",
58
+ "autograd_node_hook",
59
+ "capture_backward_pre",
60
+ "capture_gradients",
61
+ "capture_kwargs_hook",
62
+ "tensor_grad_hook",
63
+ ]
interprelens/api.py ADDED
@@ -0,0 +1,297 @@
1
+ """
2
+ Original from: https://github.com/jonhanke/nam_causal-head-gating
3
+ Adapted and extended for Causal Summer project by:
4
+ - Bowen
5
+ - 2026-03-09
6
+
7
+ High-level API for `interprelens`.
8
+
9
+ This module provides LensAPI, a user-friendly interface for transformer
10
+ architecture analysis with minimal boilerplate.
11
+ """
12
+
13
+ from collections.abc import Iterable
14
+ from typing import Any, Literal
15
+
16
+ import torch
17
+ from torch import Tensor
18
+
19
+ from .core.sites import SiteName
20
+ from .core.tracer import TransformerTracer
21
+ from .core.types import TraceResult
22
+ from .heads.data import HeadDataset
23
+ from .heads.headmap import HeadMap
24
+ from .models.adapters import ModelAdapter, get_adapter
25
+ from .scorers.registry import get_scorer
26
+
27
+
28
+ class LensAPI:
29
+ """
30
+ High-level interface: load a model, score its attention heads, trace its activations.
31
+
32
+ Attributes:
33
+ model: The transformer model being analyzed.
34
+ tokenizer: The tokenizer for the model.
35
+ adapter: Model adapter for architecture-specific access.
36
+
37
+ Example:
38
+ >>> from interprelens import HeadDataset, LensAPI
39
+ >>> lens = LensAPI.from_pretrained("meta-llama/Llama-3.2-1B")
40
+ >>> data = HeadDataset.from_pattern_task("aba", lens.tokenizer, num_samples=64, seed=0)
41
+ >>> heads = lens.score_heads("ablation", data)
42
+ >>> heads.top_k(5)
43
+ >>> heads.plot("heads.png")
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ model: Any,
49
+ tokenizer: Any,
50
+ adapter: ModelAdapter | None = None,
51
+ device: str | None = None,
52
+ quantization: str | None = None,
53
+ ):
54
+ """
55
+ Initialize LensAPI with a model and tokenizer.
56
+
57
+ Args:
58
+ model: A HuggingFace transformer model (should be in eval mode
59
+ with frozen parameters).
60
+ tokenizer: The corresponding tokenizer.
61
+ adapter: Optional model adapter. Auto-detected if not provided.
62
+ device: Device to use. Auto-detected if not provided.
63
+
64
+ Note:
65
+ Use LensAPI.from_pretrained() for easier initialization.
66
+ """
67
+ self.model = model
68
+ self.tokenizer = tokenizer
69
+ self.adapter = adapter if adapter is not None else get_adapter(model)
70
+
71
+ # Ensure model is ready for analysis
72
+ self.model.eval()
73
+ for param in self.model.parameters():
74
+ param.requires_grad = False
75
+
76
+ self._device = self._resolve_device(device)
77
+ self.quantization = quantization
78
+
79
+ @staticmethod
80
+ def _resolve_device(device: str | None) -> str:
81
+ """Determine the device to use."""
82
+ if device is not None:
83
+ return device
84
+ if torch.cuda.is_available():
85
+ return "cuda"
86
+ elif torch.backends.mps.is_available():
87
+ return "mps"
88
+ return "cpu"
89
+
90
+ @classmethod
91
+ def from_pretrained(
92
+ cls,
93
+ model_name_or_path: str,
94
+ device: str | None = None,
95
+ dtype: Any | None = None,
96
+ trust_remote_code: bool = False,
97
+ quantization: Literal["4bit", "8bit"] | None = None,
98
+ **model_kwargs: Any,
99
+ ) -> "LensAPI":
100
+ """
101
+ Create a LensAPI from a pretrained model.
102
+
103
+ Args:
104
+ model_name_or_path: HuggingFace model identifier or local path.
105
+ device: Device to load model on ('cuda', 'mps', 'cpu', or None for auto).
106
+ dtype: Data type for model weights (e.g., torch.float16). Defaults to
107
+ bfloat16 on CUDA when supported, float16 on other GPUs/MPS, float32 on CPU.
108
+ trust_remote_code: Whether to trust remote code for custom models.
109
+ quantization: "4bit" (NF4) or "8bit" via bitsandbytes (CUDA only; install
110
+ with ``pip install interprelens[quant]``). Weights stay quantized in memory.
111
+ **model_kwargs: Additional arguments passed to from_pretrained().
112
+
113
+ Returns:
114
+ Initialized LensAPI.
115
+
116
+ Example::
117
+
118
+ lens = LensAPI.from_pretrained("meta-llama/Llama-3.2-1B")
119
+ """
120
+ from transformers import AutoModelForCausalLM, AutoTokenizer
121
+
122
+ # Determine device
123
+ device = LensAPI._resolve_device(device)
124
+
125
+ # Deprecated alias kept for backward compatibility
126
+ legacy_dtype = model_kwargs.pop("torch_dtype", None)
127
+ if dtype is None:
128
+ dtype = legacy_dtype
129
+
130
+ # Set default dtype if not specified
131
+ # Note: mps does not support bfloat16
132
+ if dtype is None and device in ("cuda", "mps"):
133
+ if device == "cuda" and torch.cuda.is_bf16_supported():
134
+ dtype = torch.bfloat16
135
+ else:
136
+ dtype = torch.float16
137
+
138
+ if quantization is not None:
139
+ if quantization not in ("4bit", "8bit"):
140
+ raise ValueError(f"quantization must be '4bit', '8bit' or None, got {quantization!r}")
141
+ if device != "cuda":
142
+ raise ValueError("quantization requires a CUDA device.")
143
+ try:
144
+ import bitsandbytes # noqa: F401
145
+ from transformers import BitsAndBytesConfig
146
+ except ImportError as e:
147
+ raise ImportError(
148
+ "quantization requires bitsandbytes: pip install 'interprelens[quant]'"
149
+ ) from e
150
+ if quantization == "4bit":
151
+ model_kwargs["quantization_config"] = BitsAndBytesConfig(
152
+ load_in_4bit=True,
153
+ bnb_4bit_quant_type="nf4",
154
+ bnb_4bit_compute_dtype=torch.bfloat16,
155
+ )
156
+ else:
157
+ model_kwargs["quantization_config"] = BitsAndBytesConfig(load_in_8bit=True)
158
+ model_kwargs.setdefault("device_map", {"": 0})
159
+
160
+ # Load tokenizer
161
+ tokenizer = AutoTokenizer.from_pretrained(
162
+ model_name_or_path,
163
+ trust_remote_code=trust_remote_code,
164
+ )
165
+
166
+ # Ensure tokenizer has pad token
167
+ if tokenizer.pad_token is None:
168
+ tokenizer.pad_token = tokenizer.eos_token
169
+
170
+ explicit_device_map = model_kwargs.get("device_map")
171
+
172
+ # Load model
173
+ model = AutoModelForCausalLM.from_pretrained(
174
+ model_name_or_path,
175
+ dtype=dtype,
176
+ trust_remote_code=trust_remote_code,
177
+ **model_kwargs,
178
+ )
179
+
180
+ # Quantized / device-mapped models are already placed; .to() fails on bnb models
181
+ if explicit_device_map is None and quantization is None:
182
+ model.to(device)
183
+
184
+ return cls(model, tokenizer, device=device, quantization=quantization)
185
+
186
+ def score_heads(
187
+ self,
188
+ method: str,
189
+ data: HeadDataset | tuple[list[str], list[str]],
190
+ **cfg: Any,
191
+ ) -> HeadMap | dict[str, HeadMap]:
192
+ """
193
+ Score every attention head with ``method`` on ``data``. Higher = more important.
194
+
195
+ Args:
196
+ method: a registered scorer (see :func:`interprelens.list_scorers`), e.g.
197
+ ``"ablation"``, ``"attribution_patching"``, ``"chg"``.
198
+ data: a :class:`~interprelens.HeadDataset`, or ``(prompts, targets)`` texts.
199
+ **cfg: scorer arguments (``mode="mean"``, ``num_updates=...``, ``seed=...``).
200
+
201
+ Returns:
202
+ A :class:`~interprelens.HeadMap`, or a dict of them (``"chg"``).
203
+ """
204
+ scorer = get_scorer(method)
205
+ if isinstance(data, tuple):
206
+ data = HeadDataset.from_texts(data[0], data[1], self.tokenizer)
207
+ return scorer.score(self, data, **cfg)
208
+
209
+ def model_info(self) -> dict[str, Any]:
210
+ """``{"name", "n_layers", "n_heads", "n_kv_heads", "head_dim"}`` of the loaded model."""
211
+ cfg = getattr(self.model, "config", None)
212
+ n_heads = self.adapter.num_heads
213
+ return {
214
+ "name": getattr(cfg, "_name_or_path", None) or self.model.__class__.__name__,
215
+ "n_layers": self.adapter.num_layers,
216
+ "n_heads": n_heads,
217
+ "n_kv_heads": getattr(cfg, "num_key_value_heads", None) or n_heads,
218
+ "head_dim": self.adapter.head_dim,
219
+ }
220
+
221
+ @property
222
+ def device(self) -> str:
223
+ return self._device
224
+
225
+ def _prepare_inputs(
226
+ self,
227
+ *,
228
+ texts: str | list[str] | None = None,
229
+ input_ids: Tensor | None = None,
230
+ attention_mask: Tensor | None = None,
231
+ ) -> tuple[Tensor, Tensor | None]:
232
+ """Normalize text or tensor inputs onto the API device."""
233
+
234
+ if input_ids is None:
235
+ if texts is None:
236
+ raise ValueError("Either `texts` or `input_ids` must be provided.")
237
+ if isinstance(texts, str):
238
+ texts = [texts]
239
+ batch = self.tokenizer(
240
+ texts,
241
+ return_tensors="pt",
242
+ padding=True,
243
+ )
244
+ input_ids = batch["input_ids"].to(self._device)
245
+ if attention_mask is None and "attention_mask" in batch:
246
+ attention_mask = batch["attention_mask"].to(self._device)
247
+ else:
248
+ input_ids = input_ids.to(self._device)
249
+ if attention_mask is not None:
250
+ attention_mask = attention_mask.to(self._device)
251
+
252
+ return input_ids, attention_mask
253
+
254
+ def trace(
255
+ self,
256
+ *,
257
+ texts: str | list[str] | None = None,
258
+ input_ids: Tensor | None = None,
259
+ attention_mask: Tensor | None = None,
260
+ layers: Iterable[int] | None = None,
261
+ sites: Iterable[SiteName] | None = None,
262
+ detach: bool = True,
263
+ clone: bool = True,
264
+ **model_kwargs: Any,
265
+ ) -> TraceResult:
266
+ """
267
+ Trace named transformer sites for a batch of inputs.
268
+
269
+ Either `texts` or `input_ids` must be provided. When `texts` are used,
270
+ the tokenizer is applied with padding and tensors are moved to the API device.
271
+ """
272
+ input_ids, attention_mask = self._prepare_inputs(
273
+ texts=texts,
274
+ input_ids=input_ids,
275
+ attention_mask=attention_mask,
276
+ )
277
+
278
+ tracer = TransformerTracer(self.model, adapter=self.adapter)
279
+ return tracer.trace(
280
+ input_ids=input_ids,
281
+ attention_mask=attention_mask,
282
+ layers=layers,
283
+ sites=sites,
284
+ detach=detach,
285
+ clone=clone,
286
+ **model_kwargs,
287
+ )
288
+
289
+ @property
290
+ def num_layers(self) -> int:
291
+ """Number of transformer layers in the model."""
292
+ return self.adapter.num_layers
293
+
294
+ @property
295
+ def num_heads(self) -> int:
296
+ """Number of attention heads per layer."""
297
+ return self.adapter.num_heads
@@ -0,0 +1,29 @@
1
+ from .hooks import (
2
+ autograd_node_hook,
3
+ capture_backward_pre,
4
+ capture_gradients,
5
+ capture_kwargs_hook,
6
+ tensor_grad_hook,
7
+ )
8
+ from .interventions import InterventionSpec, apply_interventions
9
+ from .sites import ALL_SITES, GLOBAL_SITES, LAYER_SITES, SITE_SPECS
10
+ from .tracer import TransformerTracer
11
+ from .types import LayerSiteKey, SiteRequest, TraceResult
12
+
13
+ __all__ = [
14
+ "ALL_SITES",
15
+ "GLOBAL_SITES",
16
+ "InterventionSpec",
17
+ "LAYER_SITES",
18
+ "LayerSiteKey",
19
+ "SITE_SPECS",
20
+ "SiteRequest",
21
+ "TraceResult",
22
+ "TransformerTracer",
23
+ "apply_interventions",
24
+ "autograd_node_hook",
25
+ "capture_backward_pre",
26
+ "capture_gradients",
27
+ "capture_kwargs_hook",
28
+ "tensor_grad_hook",
29
+ ]