interprelens 0.3.0__tar.gz

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 (65) hide show
  1. interprelens-0.3.0/.env.example +5 -0
  2. interprelens-0.3.0/.gitignore +45 -0
  3. interprelens-0.3.0/LICENSE +21 -0
  4. interprelens-0.3.0/PKG-INFO +59 -0
  5. interprelens-0.3.0/README.md +28 -0
  6. interprelens-0.3.0/pyproject.toml +132 -0
  7. interprelens-0.3.0/src/interprelens/__init__.py +63 -0
  8. interprelens-0.3.0/src/interprelens/api.py +297 -0
  9. interprelens-0.3.0/src/interprelens/core/__init__.py +29 -0
  10. interprelens-0.3.0/src/interprelens/core/hooks.py +360 -0
  11. interprelens-0.3.0/src/interprelens/core/interventions.py +112 -0
  12. interprelens-0.3.0/src/interprelens/core/logits.py +64 -0
  13. interprelens-0.3.0/src/interprelens/core/residuals.py +24 -0
  14. interprelens-0.3.0/src/interprelens/core/sites.py +98 -0
  15. interprelens-0.3.0/src/interprelens/core/tracer.py +301 -0
  16. interprelens-0.3.0/src/interprelens/core/types.py +76 -0
  17. interprelens-0.3.0/src/interprelens/heads/__init__.py +6 -0
  18. interprelens-0.3.0/src/interprelens/heads/data.py +213 -0
  19. interprelens-0.3.0/src/interprelens/heads/gates.py +153 -0
  20. interprelens-0.3.0/src/interprelens/heads/headmap.py +233 -0
  21. interprelens-0.3.0/src/interprelens/heads/metrics.py +65 -0
  22. interprelens-0.3.0/src/interprelens/models/__init__.py +28 -0
  23. interprelens-0.3.0/src/interprelens/models/adapters.py +408 -0
  24. interprelens-0.3.0/src/interprelens/plugins/__init__.py +0 -0
  25. interprelens-0.3.0/src/interprelens/plugins/position/__init__.py +115 -0
  26. interprelens-0.3.0/src/interprelens/plugins/position/behavior.py +72 -0
  27. interprelens-0.3.0/src/interprelens/plugins/position/data.py +184 -0
  28. interprelens-0.3.0/src/interprelens/plugins/position/decomposition.py +75 -0
  29. interprelens-0.3.0/src/interprelens/plugins/position/plots.py +48 -0
  30. interprelens-0.3.0/src/interprelens/plugins/position/profiles.py +253 -0
  31. interprelens-0.3.0/src/interprelens/plugins/position/scores.py +36 -0
  32. interprelens-0.3.0/src/interprelens/plugins/position/validation.py +126 -0
  33. interprelens-0.3.0/src/interprelens/scorers/__init__.py +4 -0
  34. interprelens-0.3.0/src/interprelens/scorers/ablation.py +80 -0
  35. interprelens-0.3.0/src/interprelens/scorers/attribution_patching.py +69 -0
  36. interprelens-0.3.0/src/interprelens/scorers/base.py +25 -0
  37. interprelens-0.3.0/src/interprelens/scorers/chg/__init__.py +116 -0
  38. interprelens-0.3.0/src/interprelens/scorers/chg/chg.py +331 -0
  39. interprelens-0.3.0/src/interprelens/scorers/chg/taxonomy.py +72 -0
  40. interprelens-0.3.0/src/interprelens/scorers/chg/trainer.py +425 -0
  41. interprelens-0.3.0/src/interprelens/scorers/registry.py +109 -0
  42. interprelens-0.3.0/src/interprelens/utils/__init__.py +11 -0
  43. interprelens-0.3.0/src/interprelens/utils/helpers.py +230 -0
  44. interprelens-0.3.0/src/interprelens/utils/tensor_dict.py +374 -0
  45. interprelens-0.3.0/src/interprelens/utils/tokenisation.py +165 -0
  46. interprelens-0.3.0/src/interprelens/viz/__init__.py +3 -0
  47. interprelens-0.3.0/src/interprelens/viz/plot.py +129 -0
  48. interprelens-0.3.0/tests/conftest.py +165 -0
  49. interprelens-0.3.0/tests/fixtures/chg_baseline.pt +0 -0
  50. interprelens-0.3.0/tests/fixtures/chg_baseline_spec.py +12 -0
  51. interprelens-0.3.0/tests/test_chg.py +38 -0
  52. interprelens-0.3.0/tests/test_chg_scorer.py +78 -0
  53. interprelens-0.3.0/tests/test_e2e_llama.py +73 -0
  54. interprelens-0.3.0/tests/test_gates.py +96 -0
  55. interprelens-0.3.0/tests/test_head_data.py +33 -0
  56. interprelens-0.3.0/tests/test_headmap.py +73 -0
  57. interprelens-0.3.0/tests/test_hooks.py +164 -0
  58. interprelens-0.3.0/tests/test_plot.py +36 -0
  59. interprelens-0.3.0/tests/test_position.py +146 -0
  60. interprelens-0.3.0/tests/test_prompt_tokenizer.py +27 -0
  61. interprelens-0.3.0/tests/test_quantization.py +37 -0
  62. interprelens-0.3.0/tests/test_release_smoke.py +26 -0
  63. interprelens-0.3.0/tests/test_scorers.py +96 -0
  64. interprelens-0.3.0/tests/test_tensor_dict.py +55 -0
  65. interprelens-0.3.0/tests/test_tracer.py +101 -0
@@ -0,0 +1,5 @@
1
+ # Hugging Face token used for gated model downloads in development-only tests.
2
+ HF_TOKEN=your_huggingface_token_here
3
+
4
+ # Default real-model integration target for CHG/core smoke tests.
5
+ CHG_DEFAULT_MODEL=meta-llama/Llama-3.2-1B
@@ -0,0 +1,45 @@
1
+ # Local secrets
2
+ .env
3
+ .env.*
4
+ !.env.example
5
+
6
+ # Virtual environments
7
+ .venv/
8
+ venv/
9
+ .python-version
10
+
11
+ # Python caches
12
+ __pycache__/
13
+ *.py[cod]
14
+ *.pyo
15
+
16
+ # Test and tool caches
17
+ .pytest_cache/
18
+ .ruff_cache/
19
+ .mypy_cache/
20
+ .hypothesis/
21
+ .tox/
22
+ .nox/
23
+ .coverage
24
+ .coverage.*
25
+ htmlcov/
26
+
27
+ # Build artifacts
28
+ build/
29
+ dist/
30
+ *.egg-info/
31
+ pip-wheel-metadata/
32
+
33
+ # Notebook and editor clutter
34
+ .ipynb_checkpoints/
35
+ .vscode/
36
+ .idea/
37
+ .DS_Store
38
+
39
+ # Local logs
40
+ *.log
41
+ .claude/
42
+ CLAUDE.md
43
+ output/
44
+ process/
45
+ benchmarks/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bowen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.5
2
+ Name: interprelens
3
+ Version: 0.3.0
4
+ Summary: InterpreLens: find, compare and act on the attention heads behind any LLM behaviour.
5
+ Project-URL: Homepage, https://github.com/Aisuko/interprelens
6
+ Project-URL: Repository, https://github.com/Aisuko/interprelens
7
+ Author: Bowen
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: huggingface-hub>=0.20.0
12
+ Requires-Dist: numpy>=1.24.0
13
+ Requires-Dist: safetensors>=0.4.0
14
+ Requires-Dist: torch>=2.0.0
15
+ Requires-Dist: transformers>=4.30.0
16
+ Provides-Extra: chg
17
+ Requires-Dist: pandas>=2.0.0; extra == 'chg'
18
+ Requires-Dist: tqdm>=4.65.0; extra == 'chg'
19
+ Provides-Extra: datasets
20
+ Requires-Dist: datasets>=2.14.0; extra == 'datasets'
21
+ Requires-Dist: pyarrow>=12.0.0; extra == 'datasets'
22
+ Provides-Extra: position
23
+ Requires-Dist: matplotlib>=3.7.0; extra == 'position'
24
+ Provides-Extra: quant
25
+ Requires-Dist: accelerate>=0.26.0; extra == 'quant'
26
+ Requires-Dist: bitsandbytes>=0.45.0; extra == 'quant'
27
+ Provides-Extra: viz
28
+ Requires-Dist: matplotlib>=3.7.0; extra == 'viz'
29
+ Requires-Dist: pandas>=2.0.0; extra == 'viz'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # interprelens
33
+
34
+ **Find, compare and act on the attention heads behind any LLM behaviour.**
35
+
36
+ `interprelens` scores attention heads (ablation, attribution patching, Causal Head Gating,
37
+ positional bias) and returns one common `HeadMap` you can save, compare and plot.
38
+ A paper is not the end: we turn our published research into a tool others can use.
39
+
40
+ **Used in 2 papers:** [CoCHI](https://aisuko.github.io/confix/) (NeurIPS 2026) and
41
+ [CPS](https://aisuko.github.io/cps/) (WSDM '27). Reproduce both with `inteprelens==0.2.1`.
42
+
43
+ ## Install
44
+ Not on PyPI yet. From source:
45
+ ```bash
46
+ git clone https://github.com/Aisuko/interprelens && cd interprelens && uv sync
47
+ ```
48
+
49
+ ## Examples
50
+
51
+ [`examples/`](examples/README.md): [head scoring](examples/head_scoring.md),
52
+ [positional bias](examples/position_bias.md), [tracing and hooks](examples/tracing_and_hooks.md),
53
+ [installation and extras](examples/installation.md).
54
+
55
+ ## Acknowledgements
56
+ Builds on [Causal Head Gating](https://github.com/jonhanke/nam_causal-head-gating) (Nam et al., NeurIPS 2025).
57
+
58
+ ## License
59
+ MIT, see [LICENSE](LICENSE). Contributing: run `make hooks` once; commits need a DCO sign-off (`git commit -s`).
@@ -0,0 +1,28 @@
1
+ # interprelens
2
+
3
+ **Find, compare and act on the attention heads behind any LLM behaviour.**
4
+
5
+ `interprelens` scores attention heads (ablation, attribution patching, Causal Head Gating,
6
+ positional bias) and returns one common `HeadMap` you can save, compare and plot.
7
+ A paper is not the end: we turn our published research into a tool others can use.
8
+
9
+ **Used in 2 papers:** [CoCHI](https://aisuko.github.io/confix/) (NeurIPS 2026) and
10
+ [CPS](https://aisuko.github.io/cps/) (WSDM '27). Reproduce both with `inteprelens==0.2.1`.
11
+
12
+ ## Install
13
+ Not on PyPI yet. From source:
14
+ ```bash
15
+ git clone https://github.com/Aisuko/interprelens && cd interprelens && uv sync
16
+ ```
17
+
18
+ ## Examples
19
+
20
+ [`examples/`](examples/README.md): [head scoring](examples/head_scoring.md),
21
+ [positional bias](examples/position_bias.md), [tracing and hooks](examples/tracing_and_hooks.md),
22
+ [installation and extras](examples/installation.md).
23
+
24
+ ## Acknowledgements
25
+ Builds on [Causal Head Gating](https://github.com/jonhanke/nam_causal-head-gating) (Nam et al., NeurIPS 2025).
26
+
27
+ ## License
28
+ MIT, see [LICENSE](LICENSE). Contributing: run `make hooks` once; commits need a DCO sign-off (`git commit -s`).
@@ -0,0 +1,132 @@
1
+ [project]
2
+ name = "interprelens"
3
+ version = "0.3.0"
4
+ description = "InterpreLens: find, compare and act on the attention heads behind any LLM behaviour."
5
+ readme = "README.md"
6
+ license = { text = "MIT" }
7
+ authors = [
8
+ { name = "Bowen" },
9
+ ]
10
+ requires-python = ">=3.10"
11
+ dependencies = [
12
+ "torch>=2.0.0",
13
+ "transformers>=4.30.0",
14
+ "huggingface_hub>=0.20.0",
15
+ "numpy>=1.24.0",
16
+ "safetensors>=0.4.0",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ datasets = [
21
+ "datasets>=2.14.0",
22
+ "pyarrow>=12.0.0",
23
+ ]
24
+
25
+ chg = [
26
+ "tqdm>=4.65.0",
27
+ "pandas>=2.0.0",
28
+ ]
29
+
30
+ viz = [
31
+ "matplotlib>=3.7.0",
32
+ "pandas>=2.0.0",
33
+ ]
34
+
35
+ position = [
36
+ "matplotlib>=3.7.0",
37
+ ]
38
+
39
+ quant = [
40
+ "bitsandbytes>=0.45.0",
41
+ "accelerate>=0.26.0",
42
+ ]
43
+
44
+ [project.entry-points."interprelens.scorers"]
45
+ position = "interprelens.plugins.position:PositionScorer"
46
+
47
+ [project.urls]
48
+ Homepage = "https://github.com/Aisuko/interprelens"
49
+ Repository = "https://github.com/Aisuko/interprelens"
50
+
51
+ [build-system]
52
+ requires = ["hatchling>=1.27.0,<2"]
53
+ build-backend = "hatchling.build"
54
+
55
+ [tool.uv]
56
+ # Single source of truth for the uv version: uv enforces it locally and
57
+ # setup-uv reads it in CI (version-file). Bump it here only.
58
+ required-version = "==0.13.12"
59
+ default-groups = []
60
+
61
+ [dependency-groups]
62
+ dev = [
63
+ "black>=24.0.0",
64
+ "ipykernel>=6.0.0",
65
+ "mypy>=1.10.0",
66
+ "pre-commit>=3.7.0",
67
+ "pytest>=9.0.2",
68
+ "pytest-cov>=5.0.0",
69
+ "python-dotenv>=1.0.1",
70
+ "ruff>=0.6.0",
71
+ ]
72
+ publish = [
73
+ "build>=1.2.2",
74
+ "check-wheel-contents>=0.6.0",
75
+ "hatchling>=1.27.0,<2",
76
+ "twine>=7.0.0",
77
+ ]
78
+
79
+ [tool.hatch.build.targets.wheel]
80
+ packages = ["src/interprelens"]
81
+
82
+ [tool.hatch.build.targets.sdist]
83
+ include = [
84
+ "/src",
85
+ "/tests",
86
+ "/README.md",
87
+ "/LICENSE",
88
+ "/pyproject.toml",
89
+ "/.env.example",
90
+ ]
91
+
92
+ [tool.black]
93
+ line-length = 100
94
+ target-version = ["py310", "py311", "py312"]
95
+
96
+ [tool.ruff]
97
+ line-length = 100
98
+ target-version = "py310"
99
+
100
+ [tool.ruff.lint]
101
+ select = ["E", "W", "F", "I", "B", "C4", "UP"]
102
+ ignore = ["E501", "B008", "C901"]
103
+
104
+ [tool.ruff.lint.isort]
105
+ known-first-party = ["interprelens"]
106
+
107
+ [tool.mypy]
108
+ python_version = "3.10"
109
+ warn_return_any = true
110
+ warn_unused_configs = true
111
+ disallow_untyped_defs = false
112
+ ignore_missing_imports = true
113
+
114
+ [tool.pytest.ini_options]
115
+ testpaths = ["tests"]
116
+ python_files = ["test_*.py"]
117
+ addopts = "-v --tb=short"
118
+ markers = [
119
+ "gpu: tests that require the local CUDA + Llama test environment",
120
+ ]
121
+
122
+ [tool.coverage.run]
123
+ source = ["src/interprelens"]
124
+ branch = true
125
+
126
+ [tool.coverage.report]
127
+ exclude_lines = [
128
+ "pragma: no cover",
129
+ "def __repr__",
130
+ "raise NotImplementedError",
131
+ "if TYPE_CHECKING:",
132
+ ]
@@ -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
+ ]
@@ -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
+ ]