model-debugger 0.4.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 (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,685 @@
1
+ """Feature bases: SAE and transcoder dictionaries as exact bases at one site.
2
+
3
+ ``FeatureBasis`` (an SAE: encoder, decoder, bias) and ``TranscoderBasis``/``TranscoderSet``
4
+ (transcoders, one per layer) load from local files (sha256-pinned) or from SAELens releases
5
+ (``saelens_ref``, ``saelens_from_local``); ``SaeSet``/``open_set`` hold a lazily loaded set of
6
+ layers. ``Decomposition`` is ``x = b_dec + sum_f a_f d_f + e`` at one row.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import math
14
+ import os
15
+ import re
16
+ from collections import OrderedDict
17
+ from collections.abc import Sequence
18
+ from dataclasses import dataclass, field
19
+ from typing import Any
20
+
21
+ from ..numerics.labels import EXACT, MEASURED, f64
22
+
23
+ SITE_PORTS = ("h_out", "h")
24
+ _HOOKS = {"resid_post": "h_out", "hook_resid_post": "h_out", "h_out": "h_out",
25
+ "resid_pre": "h", "hook_resid_pre": "h", "h": "h"}
26
+
27
+
28
+ def _torch():
29
+ import torch
30
+
31
+ return torch
32
+
33
+
34
+ class SaeError(ValueError):
35
+ """A basis that cannot be loaded or applied (shape, site, file): a refusal, not a crash."""
36
+
37
+
38
+ def _sha256(path: str) -> str:
39
+ digest = hashlib.sha256()
40
+ with open(path, "rb") as handle:
41
+ for chunk in iter(lambda: handle.read(1 << 22), b""):
42
+ digest.update(chunk)
43
+ return digest.hexdigest()
44
+
45
+
46
+ def _manifest(directory: str) -> dict[str, str]:
47
+ """``name -> sha256`` from a ``manifest.txt`` (``NAME SHA256 SIZE`` lines) beside the files,
48
+ written by the transfer that verified them."""
49
+ path = os.path.join(directory, "manifest.txt")
50
+ out: dict[str, str] = {}
51
+ if os.path.isfile(path):
52
+ for line in open(path, encoding="utf-8"):
53
+ parts = line.split()
54
+ if len(parts) >= 2 and re.fullmatch(r"[0-9a-f]{64}", parts[1]):
55
+ out[parts[0]] = parts[1]
56
+ return out
57
+
58
+
59
+ @dataclass
60
+ class FeatureBasis:
61
+ """One SAE at one site. Tensors are the stored ones (float32 on the host):
62
+ ``W_enc (d_sae, d)``, ``b_enc (d_sae,)``, ``W_dec (d, d_sae)``, ``b_dec (d,)``."""
63
+
64
+ name: str
65
+ layer: int
66
+ port: str
67
+ k: int
68
+ W_enc: Any
69
+ b_enc: Any
70
+ W_dec: Any
71
+ b_dec: Any
72
+ source: dict[str, Any] = field(default_factory=dict)
73
+
74
+ def __post_init__(self) -> None:
75
+ if self.port not in SITE_PORTS:
76
+ raise SaeError(f"an SAE site is one of {', '.join(SITE_PORTS)}, not {self.port}")
77
+ d_sae, d = (int(x) for x in self.W_enc.shape)
78
+ if tuple(self.W_dec.shape) == (d_sae, d): # stored (d_sae, d): transpose view
79
+ self.W_dec = self.W_dec.T
80
+ if (tuple(self.W_dec.shape) != (d, d_sae) or tuple(self.b_enc.shape) != (d_sae,)
81
+ or tuple(self.b_dec.shape) != (d,)):
82
+ raise SaeError(f"SAE {self.name} L{self.layer}: shapes W_enc {tuple(self.W_enc.shape)}"
83
+ f" W_dec {tuple(self.W_dec.shape)} b_enc {tuple(self.b_enc.shape)} "
84
+ f"b_dec {tuple(self.b_dec.shape)} do not form one basis")
85
+ if not 1 <= self.k <= d_sae:
86
+ raise SaeError(f"k = {self.k} is outside 1..{d_sae}")
87
+
88
+ @property
89
+ def d_model(self) -> int:
90
+ return int(self.W_enc.shape[1])
91
+
92
+ @property
93
+ def d_sae(self) -> int:
94
+ return int(self.W_enc.shape[0])
95
+
96
+ @property
97
+ def site(self) -> str:
98
+ return f"L{self.layer}.{self.port}"
99
+
100
+ def covers(self, layer: int, port: str) -> bool:
101
+ """True when ``L<layer>.<port>`` holds the value this basis was trained on."""
102
+ if self.port == "h_out":
103
+ return (layer, port) in ((self.layer, "h_out"), (self.layer + 1, "h"))
104
+ return (layer, port) in ((self.layer, "h"), (self.layer - 1, "h_out"))
105
+
106
+ # --- the identity ---------------------------------------------------------------------
107
+
108
+ def _vector(self, x: Any) -> Any:
109
+ torch = _torch()
110
+ flat = x.detach().reshape(-1)
111
+ if flat.numel() != self.d_model:
112
+ raise SaeError(f"SAE {self.name} expects {self.d_model} values, got {flat.numel()}")
113
+ if not flat.is_floating_point():
114
+ raise SaeError("SAE input must be floating point")
115
+ return flat.to("cpu"), torch
116
+
117
+ def select(self, x: Any) -> tuple[list[int], Any]:
118
+ """The active set by the published rule: ``topk(relu(W_enc x + b_enc), k)`` in float32
119
+ (``x`` widened to float32 exactly from bf16/fp16); entries whose float32 value is 0 are
120
+ not active. Returns ``(ids, pre32 of those ids)`` in descending order."""
121
+ flat, torch = self._vector(x)
122
+ pre = torch.addmv(self.b_enc.float(), self.W_enc.float(), flat.float())
123
+ values, ids = torch.topk(torch.relu(pre), self.k)
124
+ keep = values > 0
125
+ return [int(i) for i in ids[keep].tolist()], values[keep]
126
+
127
+ def encode(self, x: Any) -> dict[str, Any]:
128
+ """``{ids, acts}``: the active set and its float64 activations
129
+ ``relu(W_enc[ids] x + b_enc[ids])`` (rows sliced, then cast; ``x`` cast once)."""
130
+ torch = _torch()
131
+ flat, _ = self._vector(x)
132
+ ids, _ = self.select(flat)
133
+ x64 = flat.to(torch.float64)
134
+ index = torch.tensor(ids, dtype=torch.long)
135
+ rows = self.W_enc.index_select(0, index).to(torch.float64)
136
+ acts = torch.relu(rows @ x64 + self.b_enc.index_select(0, index).to(torch.float64))
137
+ return {"ids": ids, "acts": acts}
138
+
139
+ def direction(self, feature: int) -> Any:
140
+ """``d_f`` in float64 (one column sliced, then cast)."""
141
+ torch = _torch()
142
+ if not 0 <= int(feature) < self.d_sae:
143
+ raise SaeError(f"feature {feature} is outside 0..{self.d_sae - 1}")
144
+ return self.W_dec[:, int(feature)].to(torch.float64)
145
+
146
+ def directions(self, ids: Sequence[int]) -> Any:
147
+ torch = _torch()
148
+ index = torch.tensor(list(ids), dtype=torch.long)
149
+ return self.W_dec.index_select(1, index).to(torch.float64) # (d, n)
150
+
151
+ def bias(self) -> Any:
152
+ return self.b_dec.to(_torch().float64)
153
+
154
+ def decompose(self, x: Any) -> Decomposition:
155
+ """The exact identity ``x = b_dec + D a + e`` at a native value ``x``."""
156
+ torch = _torch()
157
+ flat, _ = self._vector(x)
158
+ x64 = flat.to(torch.float64)
159
+ enc = self.encode(flat)
160
+ D = self.directions(enc["ids"])
161
+ parts = D * enc["acts"] # (d, n): a_f d_f per column
162
+ bias = self.bias()
163
+ recon = bias + parts.sum(dim=1)
164
+ error = x64 - recon
165
+ return Decomposition(self, x64, enc["ids"], enc["acts"], D, parts, bias, recon, error)
166
+
167
+ def describe(self) -> dict[str, Any]:
168
+ return {"name": self.name, "layer": self.layer, "site": self.site, "k": self.k,
169
+ "d_model": self.d_model, "d_sae": self.d_sae, "source": dict(self.source),
170
+ "saelens": {**saelens_ref(self.source.get("repo"), self.layer, self.port),
171
+ **self.source.get("saelens", {})}}
172
+
173
+ def to_saelens(self, device: str = "cpu") -> Any:
174
+ """The same dictionary as a SAELens ``TopKSAE`` (``sae_lens`` 6.x), built the way SAELens's
175
+ own ``qwen_scope`` loader builds it (``architecture topk``, no input normalisation,
176
+ ``apply_b_dec_to_input`` False, ``W_enc``/``W_dec`` transposed to SAELens's
177
+ ``(d_in, d_sae)``/``(d_sae, d_in)``), with ``hook_name`` metadata and a strict
178
+ state-dict load (a missing or misnamed key is an error, not silent random weights).
179
+ Use it for SAELens's ecosystem (``SAETransformerBridge``, ``use_error_term``, evals,
180
+ Neuronpedia ids); mdb's own numbers stay the float64 identity above."""
181
+ from sae_lens import SAE
182
+
183
+ ref = saelens_ref(self.source.get("repo"), self.layer, self.port)
184
+ cfg = {"architecture": "topk", "d_in": self.d_model, "d_sae": self.d_sae, "k": self.k,
185
+ "dtype": "float32", "device": device, "apply_b_dec_to_input": False,
186
+ "normalize_activations": "none",
187
+ "metadata": {"hook_name": ref["hook_name"], "model_name": ref.get("model"),
188
+ "prepend_bos": False, "sae_lens_training_version": None}}
189
+ sae = SAE.from_dict(cfg)
190
+ sae.load_state_dict({"W_enc": self.W_enc.T.contiguous(),
191
+ "W_dec": self.W_dec.T.contiguous(),
192
+ "b_enc": self.b_enc, "b_dec": self.b_dec}, strict=True)
193
+ return sae.to(device).eval()
194
+
195
+
196
+ @dataclass
197
+ class TranscoderBasis:
198
+ """A transcoder: a dictionary that READS the MLP input ``L<l>.n`` and WRITES
199
+ the MLP output ``L<l>.m``. mwhanna layout (SAELens ``mwhanna_transcoder`` loader, verified
200
+ against the library): ``acts = relu(W_enc n + b_enc)`` (every positive pre-activation is
201
+ active, no top-k), no ``b_dec`` subtracted from the input, and the write
202
+
203
+ m = b_dec + sum_{f active} a_f d_f + e
204
+
205
+ with ``d_f`` the rows of the stored ``W_dec (d_sae, d)`` (held as a ``(d, d_sae)`` view, as
206
+ ``FeatureBasis``) and ``e = m - b_dec - sum a_f d_f`` the error against the NATIVE ``m``
207
+ (defined as the remainder, so the identity closes to float64 roundoff; never dropped). The
208
+ active set is chosen in float32 (``x`` widened exactly), the activations recomputed in float64
209
+ from the native bits (rows sliced, then cast), as experiment scripts did by hand. Same interface
210
+ as ``FeatureBasis`` (``encode``, ``direction(s)``, ``bias``, ``describe``) plus ``decompose(n,
211
+ m)``; ``components.transcoder_binding`` makes it a ``ComponentBinding`` of the MLP write."""
212
+
213
+ name: str
214
+ layer: int
215
+ W_enc: Any
216
+ b_enc: Any
217
+ W_dec: Any
218
+ b_dec: Any
219
+ source: dict[str, Any] = field(default_factory=dict)
220
+ read_port: str = "n"
221
+ write_port: str = "m"
222
+ kind: str = "transcoder"
223
+
224
+ def __post_init__(self) -> None:
225
+ d_sae, d = (int(x) for x in self.W_enc.shape)
226
+ if tuple(self.W_dec.shape) == (d_sae, d):
227
+ self.W_dec = self.W_dec.T
228
+ if (tuple(self.W_dec.shape) != (d, d_sae) or tuple(self.b_enc.shape) != (d_sae,)
229
+ or tuple(self.b_dec.shape) != (d,)):
230
+ raise SaeError(f"transcoder {self.name} L{self.layer}: shapes W_enc "
231
+ f"{tuple(self.W_enc.shape)} W_dec {tuple(self.W_dec.shape)} b_enc "
232
+ f"{tuple(self.b_enc.shape)} b_dec {tuple(self.b_dec.shape)} do not "
233
+ "form one dictionary")
234
+
235
+ port = property(lambda self: self.read_port)
236
+ d_model = property(lambda self: int(self.W_enc.shape[1]))
237
+ d_sae = property(lambda self: int(self.W_enc.shape[0]))
238
+
239
+ @property
240
+ def site(self) -> str:
241
+ return f"L{self.layer}.{self.read_port}->L{self.layer}.{self.write_port}"
242
+
243
+ def covers(self, layer: int, port: str) -> bool:
244
+ """True for the read site ``L<layer>.n`` (the value it encodes)."""
245
+ return (layer, port) == (self.layer, self.read_port)
246
+
247
+ _vector = FeatureBasis._vector
248
+ direction = FeatureBasis.direction
249
+ directions = FeatureBasis.directions
250
+ bias = FeatureBasis.bias
251
+
252
+ def select(self, x: Any) -> tuple[list[int], Any]:
253
+ """Every feature whose float32 pre-activation ``W_enc x + b_enc`` is positive, by
254
+ descending value (``W_enc``, ``b_enc`` and ``x`` widened exactly to float32, so a bf16
255
+ file's rounding is not in the active set)."""
256
+ flat, torch = self._vector(x)
257
+ pre = torch.addmv(self.b_enc.float(), self.W_enc.float(), flat.float())
258
+ ids = (pre > 0).nonzero().reshape(-1)
259
+ values = pre.index_select(0, ids)
260
+ order = values.argsort(descending=True)
261
+ return [int(i) for i in ids[order].tolist()], values[order]
262
+
263
+ def encode(self, x: Any) -> dict[str, Any]:
264
+ """``{ids, acts}``: active set and float64 ``relu(W_enc[ids] x + b_enc[ids])`` (a feature
265
+ whose float64 activation is 0 is dropped)."""
266
+ torch = _torch()
267
+ flat, _ = self._vector(x)
268
+ ids, _ = self.select(flat)
269
+ index = torch.tensor(ids, dtype=torch.long)
270
+ rows = self.W_enc.index_select(0, index).to(torch.float64)
271
+ acts = torch.relu(rows @ flat.to(torch.float64)
272
+ + self.b_enc.index_select(0, index).to(torch.float64))
273
+ keep = acts > 0
274
+ return {"ids": [i for i, k in zip(ids, keep.tolist()) if k], "acts": acts[keep]}
275
+
276
+ def decompose(self, x: Any, native: Any = None) -> Decomposition:
277
+ """``m = b_dec + D a + e`` for MLP input ``x`` (``n``) and native output ``native``
278
+ (``m``; without it the error is not defined and is returned as zeros, ``x`` keeps the
279
+ reconstruction)."""
280
+ torch = _torch()
281
+ enc = self.encode(x)
282
+ D = self.directions(enc["ids"])
283
+ parts = D * enc["acts"]
284
+ bias = self.bias()
285
+ recon = bias + parts.sum(dim=1)
286
+ if native is None:
287
+ m64, error = recon, torch.zeros_like(recon)
288
+ else:
289
+ m64 = f64(native).reshape(-1).cpu()
290
+ if m64.numel() != recon.numel():
291
+ raise SaeError(f"native MLP write has {m64.numel()} values, the transcoder "
292
+ f"writes {recon.numel()}")
293
+ error = m64 - recon
294
+ return Decomposition(self, m64, enc["ids"], enc["acts"], D, parts, bias, recon, error)
295
+
296
+ def describe(self) -> dict[str, Any]:
297
+ return {"name": self.name, "kind": "transcoder", "layer": self.layer, "site": self.site,
298
+ "reads": f"L{self.layer}.{self.read_port}",
299
+ "writes": f"L{self.layer}.{self.write_port}", "activation": "relu",
300
+ "d_model": self.d_model, "d_sae": self.d_sae, "source": dict(self.source),
301
+ "saelens": {**self.source.get("saelens", {}),
302
+ "hook_name": f"blocks.{self.layer}.mlp.hook_in",
303
+ "hook_name_out": f"blocks.{self.layer}.hook_mlp_out",
304
+ "architecture": "transcoder (mwhanna layout)",
305
+ "apply_b_dec_to_input": False},
306
+ "circuit_tracer": {"node_id": f"{self.layer}_<feature>_<pos>",
307
+ "error_node_id": f"0_{self.layer}_<pos>"}}
308
+
309
+ def to_saelens(self, device: str = "cpu") -> Any:
310
+ """The same dictionary as a SAELens ``Transcoder`` (``sae_lens`` 6.x), configured as the
311
+ ``mwhanna_transcoder`` loader configures it (relu, no input normalisation,
312
+ ``apply_b_dec_to_input`` False, ``hook_name``/``hook_name_out``), strict state-dict load
313
+ with ``W_enc`` transposed to SAELens's ``(d_in, d_sae)`` as that loader does."""
314
+ from sae_lens import SAE
315
+
316
+ cfg = {"architecture": "transcoder", "d_in": self.d_model, "d_out": self.d_model,
317
+ "d_sae": self.d_sae, "dtype": "float32", "device": device,
318
+ "activation_fn": "relu", "normalize_activations": "none",
319
+ "apply_b_dec_to_input": False,
320
+ "metadata": {"hook_name": f"blocks.{self.layer}.mlp.hook_in",
321
+ "hook_name_out": f"blocks.{self.layer}.hook_mlp_out"}}
322
+ sae = SAE.from_dict(cfg)
323
+ sae.load_state_dict({"W_enc": self.W_enc.T.contiguous().float(),
324
+ "W_dec": self.W_dec.T.contiguous().float(),
325
+ "b_enc": self.b_enc.float(), "b_dec": self.b_dec.float()},
326
+ strict=True)
327
+ return sae.to(device).eval()
328
+
329
+ def node(self, row: int, feature: int) -> dict[str, Any]:
330
+ """The circuit-tracer node of ``feature`` at ``row`` (``foreign_names.ct_node``)."""
331
+ from mdb.core.foreign_names import ct_node
332
+
333
+ return ct_node(self.layer, row, feature)
334
+
335
+
336
+ @dataclass
337
+ class TranscoderSet:
338
+ """Per-layer transcoders from a directory (mwhanna layout: ``layer_<L>.safetensors`` with
339
+ ``W_enc W_dec b_enc b_dec``; ``layer<L>.*.pt`` with the same keys also read), loaded on first
340
+ use, at most ``cache`` layers kept."""
341
+
342
+ name: str
343
+ path: str
344
+ files: dict[int, str]
345
+ cache: int = 4
346
+ config: dict[str, Any] = field(default_factory=dict)
347
+ verify: bool = False
348
+ _loaded: OrderedDict = field(default_factory=OrderedDict, repr=False)
349
+ hashes: dict[int, dict[str, Any]] = field(default_factory=dict)
350
+ port = "n"
351
+
352
+ @property
353
+ def layers(self) -> tuple[int, ...]:
354
+ return tuple(sorted(self.files))
355
+
356
+ def describe(self) -> dict[str, Any]:
357
+ return {"name": self.name, "kind": "transcoder", "path": self.path,
358
+ "layers": list(self.layers), "reads": "L<l>.n", "writes": "L<l>.m",
359
+ "model": self.config.get("model_name"), "loaded": list(self._loaded),
360
+ "files": {str(k): v for k, v in sorted(self.hashes.items())}}
361
+
362
+ def for_site(self, layer: int, port: str) -> TranscoderBasis | None:
363
+ return self.get(layer) if port == "n" and layer in self.files else None
364
+
365
+ def get(self, layer: int) -> TranscoderBasis:
366
+ torch = _torch()
367
+ if layer not in self.files:
368
+ raise SaeError(f"transcoder set {self.name} has no layer {layer} (has "
369
+ f"{', '.join(map(str, self.layers))})")
370
+ if layer in self._loaded:
371
+ self._loaded.move_to_end(layer)
372
+ return self._loaded[layer]
373
+ path = self.files[layer]
374
+ try:
375
+ if path.endswith(".safetensors"):
376
+ from safetensors.torch import load_file
377
+
378
+ state = load_file(path, device="cpu")
379
+ else:
380
+ state = torch.load(path, map_location="cpu", weights_only=True)
381
+ except Exception as error: # noqa: BLE001 - reported as a refusal
382
+ raise SaeError(f"cannot load {path}: {type(error).__name__}: {error}") from None
383
+ missing = [key for key in ("W_enc", "W_dec", "b_enc", "b_dec") if key not in state]
384
+ if missing:
385
+ raise SaeError(f"{path} lacks {', '.join(missing)}")
386
+ unsupported = [key for key in state if key == "W_skip" or "threshold" in key]
387
+ if unsupported:
388
+ raise SaeError(f"{path} has {', '.join(sorted(unsupported))}: a skip connection or a "
389
+ "JumpReLU threshold is not modelled here (ReLU, no skip), so its "
390
+ "features and error would be wrong; refused")
391
+ info: dict[str, Any] = {"file": os.path.basename(path), "bytes": os.path.getsize(path),
392
+ "keys": sorted(state)}
393
+ if self.verify:
394
+ info["sha256"] = _sha256(path)
395
+ self.hashes[layer] = info
396
+ basis = TranscoderBasis(self.name, layer, state["W_enc"], state["b_enc"], state["W_dec"],
397
+ state["b_dec"], {"set": self.name, "path": path, **info,
398
+ **_link_metadata(self.config, layer)})
399
+ self._loaded[layer] = basis
400
+ while len(self._loaded) > max(1, self.cache):
401
+ self._loaded.popitem(last=False)
402
+ return basis
403
+
404
+
405
+ def open_transcoders(name: str, path: str, *, layers: Sequence[int] | None = None,
406
+ cache: int = 4, verify: bool = False) -> TranscoderSet:
407
+ """A ``TranscoderSet`` over a directory (``layer_<L>.safetensors`` or ``layer<L>*.pt``;
408
+ ``config.json`` read when present). Nothing is loaded until a layer is used."""
409
+ path = os.path.abspath(os.path.expanduser(path))
410
+ if not os.path.isdir(path):
411
+ raise SaeError(f"no transcoder directory at {path}")
412
+ files: dict[int, str] = {}
413
+ for entry in os.listdir(path):
414
+ match = re.fullmatch(r"layer_?(\d+)(?:\.[\w-]+)*\.(safetensors|pt)", entry)
415
+ if match:
416
+ files[int(match[1])] = os.path.join(path, entry)
417
+ if not files:
418
+ raise SaeError(f"{path} holds no layer_<L>.safetensors / layer<L>.pt files")
419
+ if layers is not None:
420
+ wanted = {int(x) for x in layers}
421
+ absent = sorted(wanted - set(files))
422
+ if absent:
423
+ raise SaeError(f"{path} has no layer(s) {', '.join(map(str, absent))}")
424
+ files = {k: v for k, v in files.items() if k in wanted}
425
+ config: dict[str, Any] = {}
426
+ cfg = os.path.join(path, "config.json")
427
+ yml = [os.path.join(path, n) for n in ("config.yaml", "config.yml")
428
+ if os.path.isfile(os.path.join(path, n))]
429
+ if os.path.isfile(cfg):
430
+ config = json.load(open(cfg, encoding="utf-8"))
431
+ elif yml:
432
+ try:
433
+ import yaml
434
+
435
+ config = yaml.safe_load(open(yml[0], encoding="utf-8")) or {}
436
+ except ImportError:
437
+ config = {"unparsed_config": yml[0]}
438
+ if not isinstance(config, dict):
439
+ raise SaeError(f"{yml[0]} is not a mapping")
440
+ return TranscoderSet(name, path, files, cache=int(cache), config=config, verify=verify)
441
+
442
+
443
+ # SAELens 6.55.5 ``pretrained_saes.yaml`` releases of the Qwen-Scope residual suites
444
+ # (``conversion_func: qwen_scope``; sae ids ``layer<L>``; hook ``blocks.<L>.hook_resid_post``).
445
+ _SAELENS_RELEASES = {
446
+ "Qwen/SAE-Res-Qwen3-1.7B-Base-W32K-L0_50": ("qwen-scope-3-1.7b-base-w32k-l50",
447
+ "Qwen/Qwen3-1.7B-Base"),
448
+ "Qwen/SAE-Res-Qwen3-1.7B-Base-W32K-L0_100": ("qwen-scope-3-1.7b-base-w32k-l100",
449
+ "Qwen/Qwen3-1.7B-Base"),
450
+ "Qwen/SAE-Res-Qwen3-8B-Base-W64K-L0_50": ("qwen-scope-3-8b-base-w64k-l50",
451
+ "Qwen/Qwen3-8B-Base"),
452
+ "Qwen/SAE-Res-Qwen3-8B-Base-W64K-L0_100": ("qwen-scope-3-8b-base-w64k-l100",
453
+ "Qwen/Qwen3-8B-Base"),
454
+ }
455
+
456
+
457
+ def _link_metadata(config: dict[str, Any], layer: int) -> dict[str, Any]:
458
+ """Local config metadata: per-layer identities, plus a declared SAELens release."""
459
+ out: dict[str, Any] = {}
460
+ ids = config.get("neuronpedia_ids", {})
461
+ identity = ids.get(f"layer{layer}") if isinstance(ids, dict) else None
462
+ if identity is not None:
463
+ out["neuronpedia_id"] = identity
464
+ # Use the standard SAELens field for a single, explicitly layer-bound dictionary.
465
+ metadata = config.get("metadata", {})
466
+ if isinstance(metadata, dict) and metadata.get("hook_layer") == layer:
467
+ if metadata.get("neuronpedia_id") is not None:
468
+ out.setdefault("neuronpedia_id", metadata["neuronpedia_id"])
469
+ release = config.get("saelens_release")
470
+ sae_ids = config.get("saelens_ids", {})
471
+ if release and isinstance(sae_ids, dict) and f"layer{layer}" in sae_ids:
472
+ out["saelens"] = {"release": release, "sae_id": sae_ids[f"layer{layer}"]}
473
+ return out
474
+
475
+
476
+ def saelens_ref(repo: str | None, layer: int, port: str) -> dict[str, Any]:
477
+ """The SAELens / TransformerLens names of the SAE at ``L<layer>.<port>``: ``hook_name``
478
+ (``h_out`` = ``blocks.L.hook_resid_post``, ``h`` = ``blocks.L.hook_resid_pre``) and, for a
479
+ Qwen-Scope repo SAELens lists, its ``release`` and ``sae_id`` (for
480
+ ``SAE.from_pretrained(release, sae_id)``)."""
481
+ hook = {"h_out": "hook_resid_post", "h": "hook_resid_pre"}[port]
482
+ out: dict[str, Any] = {"hook_name": f"blocks.{layer}.{hook}"}
483
+ if repo in _SAELENS_RELEASES:
484
+ release, model = _SAELENS_RELEASES[repo]
485
+ out.update(release=release, sae_id=f"layer{layer}", model=model)
486
+ return out
487
+
488
+
489
+ def saelens_from_local(release: str, sae_id: str, local_dir: str, *, device: str = "cpu",
490
+ cfg_overrides: dict[str, Any] | None = None) -> Any:
491
+ """``SAE.from_pretrained(release, sae_id)`` with SAELens's OWN registered converter, reading
492
+ the checkpoint from ``local_dir`` instead of the Hugging Face hub (offline / non-cache layout).
493
+
494
+ SAELens resolves a release through ``pretrained_saes.yaml`` and the converter named there; for
495
+ the Qwen-Scope suites that is ``qwen_scope`` = ``sae_lens.loading.pretrained_sae_loaders.
496
+ qwen_scope_sae_huggingface_loader``, which fetches the file with the module-global
497
+ ``hf_hub_download(repo_id, filename=folder_name)``. This passes that converter, unchanged, as
498
+ ``from_pretrained(..., converter=...)`` while that one name is rebound (for the duration of
499
+ the call) to return ``local_dir/<filename>`` (``local_dir`` may also be the single file).
500
+ Nothing of mdb's ``to_saelens`` is used, so SAELens's loader and a ``FeatureBasis`` over the
501
+ same file can be compared. ``cfg_overrides`` (e.g. a tiny ``d_in``/``d_sae``/``activation_fn_
502
+ kwargs``) are merged last into the converter's config, exactly as SAELens's own overrides are."""
503
+ from sae_lens import SAE
504
+ from sae_lens.loading import pretrained_sae_loaders as loaders
505
+
506
+ converter = loaders.NAMED_PRETRAINED_SAE_LOADERS["qwen_scope"]
507
+ local = os.path.abspath(os.path.expanduser(local_dir))
508
+
509
+ def fetch(repo_id: str, filename: str | None = None, **_kw: Any) -> str:
510
+ path = local if os.path.isfile(local) else os.path.join(local, os.path.basename(filename or ""))
511
+ if not os.path.isfile(path):
512
+ raise SaeError(f"{path} does not exist (SAELens asked for {repo_id}/{filename})")
513
+ return path
514
+
515
+ def convert(**kw: Any) -> Any:
516
+ kw["cfg_overrides"] = {**(kw.get("cfg_overrides") or {}), **(cfg_overrides or {})}
517
+ return converter(**kw)
518
+
519
+ saved = loaders.hf_hub_download
520
+ loaders.hf_hub_download = fetch
521
+ try:
522
+ return SAE.from_pretrained(release, sae_id, device=device, converter=convert).eval()
523
+ finally:
524
+ loaders.hf_hub_download = saved
525
+
526
+
527
+ @dataclass
528
+ class Decomposition:
529
+ basis: FeatureBasis
530
+ x: Any
531
+ ids: list[int]
532
+ acts: Any
533
+ D: Any
534
+ parts: Any
535
+ bias: Any
536
+ recon: Any
537
+ error: Any
538
+
539
+ def stats(self) -> dict[str, Any]:
540
+ """Norm accounting of the identity (``derived-exact`` except the native norm)."""
541
+ x2 = float(self.x.pow(2).sum())
542
+ e2 = float(self.error.pow(2).sum())
543
+ closure = float((self.bias + self.parts.sum(dim=1) + self.error - self.x).abs().max())
544
+ return {"x_norm": _n(math.sqrt(x2), MEASURED), "error_norm": _n(math.sqrt(e2), EXACT),
545
+ "recon_norm": _n(float(self.recon.norm()), EXACT),
546
+ "bias_norm": _n(float(self.bias.norm()), EXACT),
547
+ "error_fraction_of_norm": _n(math.sqrt(e2 / x2) if x2 else 0.0, EXACT),
548
+ "error_fraction_of_energy": _n(e2 / x2 if x2 else 0.0, EXACT),
549
+ "active": len(self.ids),
550
+ "identity_closure": _n(closure, EXACT)}
551
+
552
+
553
+ def _n(value: float, authority: str, proof: str | None = None) -> dict[str, Any]:
554
+ from mdb.core.records import num
555
+
556
+ return num(float(value), authority, proof=proof)
557
+
558
+
559
+ # --------------------------------------------------------------------------- sets of layers
560
+
561
+
562
+ @dataclass
563
+ class SaeSet:
564
+ """A named family of per-layer SAEs read from a directory (Qwen-Scope layout:
565
+ ``config.json`` + ``layer{L}.sae.pt``) or from one file bound to one layer."""
566
+
567
+ name: str
568
+ path: str
569
+ port: str
570
+ k: int
571
+ layers: tuple[int, ...]
572
+ files: dict[int, str]
573
+ cache: int = 4
574
+ config: dict[str, Any] = field(default_factory=dict)
575
+ revision: str | None = None
576
+ verify: bool = False
577
+ _loaded: OrderedDict = field(default_factory=OrderedDict, repr=False)
578
+ hashes: dict[int, dict[str, Any]] = field(default_factory=dict)
579
+
580
+ def describe(self) -> dict[str, Any]:
581
+ return {"name": self.name, "path": self.path, "site_port": self.port, "k": self.k,
582
+ "layers": list(self.layers), "cache": self.cache,
583
+ "loaded": list(self._loaded), "revision": self.revision,
584
+ "hook_point": self.config.get("hook_point"),
585
+ "repo": self.config.get("hf_repo_id"),
586
+ "files": {str(layer): self.hashes.get(layer, {"file": os.path.basename(p)})
587
+ for layer, p in sorted(self.files.items())
588
+ if layer in self._loaded or layer in self.hashes}}
589
+
590
+ def site_of(self, layer: int) -> str:
591
+ return f"L{layer}.{self.port}"
592
+
593
+ def for_site(self, layer: int, port: str) -> FeatureBasis | None:
594
+ """The basis whose site holds ``L<layer>.<port>``, or None."""
595
+ candidates = [layer] if port == self.port else (
596
+ [layer - 1] if (self.port, port) == ("h_out", "h") else
597
+ [layer + 1] if (self.port, port) == ("h", "h_out") else [])
598
+ for own in candidates:
599
+ if own in self.files:
600
+ return self.get(own)
601
+ return None
602
+
603
+ def get(self, layer: int) -> FeatureBasis:
604
+ torch = _torch()
605
+ if layer not in self.files:
606
+ raise SaeError(f"SAE {self.name} has no layer {layer} (has "
607
+ f"{', '.join(map(str, sorted(self.files)))})")
608
+ if layer in self._loaded:
609
+ self._loaded.move_to_end(layer)
610
+ return self._loaded[layer]
611
+ path = self.files[layer]
612
+ try:
613
+ state = torch.load(path, map_location="cpu", weights_only=True)
614
+ except Exception as error: # noqa: BLE001 - reported as a refusal
615
+ raise SaeError(f"cannot load {path}: {type(error).__name__}: {error}") from None
616
+ missing = [key for key in ("W_enc", "W_dec", "b_enc", "b_dec") if key not in state]
617
+ if missing:
618
+ raise SaeError(f"{path} lacks {', '.join(missing)}")
619
+ info: dict[str, Any] = {"file": os.path.basename(path), "bytes": os.path.getsize(path)}
620
+ listed = _manifest(os.path.dirname(path)).get(os.path.basename(path))
621
+ if listed:
622
+ info["sha256_manifest"] = listed
623
+ if self.verify:
624
+ info["sha256"] = _sha256(path)
625
+ if listed:
626
+ info["manifest_match"] = info["sha256"] == listed
627
+ self.hashes[layer] = info
628
+ source = {"set": self.name, "path": path, "revision": self.revision,
629
+ "repo": self.config.get("hf_repo_id"), **info,
630
+ **_link_metadata(self.config, layer)}
631
+ basis = FeatureBasis(self.name, layer, self.port, self.k, state["W_enc"],
632
+ state["b_enc"], state["W_dec"], state["b_dec"], source)
633
+ self._loaded[layer] = basis
634
+ while len(self._loaded) > max(1, self.cache):
635
+ self._loaded.popitem(last=False)
636
+ return basis
637
+
638
+
639
+ def open_set(name: str, path: str, *, layers: Sequence[int] | None = None, k: int | None = None,
640
+ port: str | None = None, cache: int = 4, verify: bool = False,
641
+ layer: int | None = None) -> SaeSet:
642
+ """An ``SaeSet`` over a directory (``config.json`` gives ``k``, ``hook_point`` and the
643
+ layers; files ``layer{L}.sae.pt``) or one ``.pt`` file (``layer`` and ``k`` required).
644
+ Nothing is loaded until a layer is used."""
645
+ path = os.path.abspath(os.path.expanduser(path))
646
+ config: dict[str, Any] = {}
647
+ files: dict[int, str] = {}
648
+ revision = None
649
+ if os.path.isdir(path):
650
+ cfg = os.path.join(path, "config.json")
651
+ if os.path.isfile(cfg):
652
+ config = json.load(open(cfg, encoding="utf-8"))
653
+ rev = os.path.join(path, "REVISION")
654
+ if os.path.isfile(rev):
655
+ revision = open(rev, encoding="utf-8").read().strip() or None
656
+ for entry in os.listdir(path):
657
+ match = re.fullmatch(r"layer(\d+)\.sae\.pt", entry)
658
+ if match:
659
+ files[int(match[1])] = os.path.join(path, entry)
660
+ if not files:
661
+ raise SaeError(f"{path} holds no layer<L>.sae.pt files")
662
+ elif os.path.isfile(path):
663
+ if layer is None:
664
+ raise SaeError("a single SAE file needs layer=L")
665
+ files[int(layer)] = path
666
+ else:
667
+ raise SaeError(f"no SAE at {path}")
668
+ if layers is not None:
669
+ wanted = set(int(x) for x in layers)
670
+ absent = sorted(wanted - set(files))
671
+ if absent:
672
+ raise SaeError(f"{path} has no layer(s) {', '.join(map(str, absent))}")
673
+ files = {key: value for key, value in files.items() if key in wanted}
674
+ hook = port or _HOOKS.get(str(config.get("hook_point", "")), None)
675
+ if hook is None:
676
+ raise SaeError(f"unknown hook point {config.get('hook_point')!r}: give port=h_out|h")
677
+ k = int(k if k is not None else config.get("k", 0) or 0)
678
+ if k < 1:
679
+ raise SaeError("the SAE's k (top-k) is not in config.json: give k=K")
680
+ return SaeSet(name, path, hook, k, tuple(sorted(files)), files, cache=int(cache),
681
+ config=config, revision=revision, verify=verify)
682
+
683
+
684
+ __all__ = ["Decomposition", "FeatureBasis", "TranscoderBasis", "TranscoderSet", "open_transcoders",
685
+ "saelens_ref", "SaeError", "SaeSet", "open_set"]