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,253 @@
1
+ """circuit-tracer attribution graphs as mdb edges, and mdb's exact direct effects to check them.
2
+
3
+ A circuit-tracer 0.5.0 ``Graph`` is a dense adjacency over nodes in the order ``[active
4
+ features, error nodes (layer-major, then position), token embeddings, logits]`` (rows: targets,
5
+ columns: sources); an entry is the direct effect of the source on the target in circuit-tracer's
6
+ local replacement model: attention patterns and RMSNorm scales frozen at the native forward,
7
+ each MLP replaced by its transcoder's features plus a fixed error, a target feature measured at
8
+ its pre-activation, a logit node as the demeaned unembedding row ``W_U[tok] - mean(W_U)`` read
9
+ through the frozen final norm.
10
+
11
+ ``graph_edges`` turns a graph into mdb edges: each node named by ``core.foreign_names``
12
+ (``ct_node``, ``ct_error_node``, ``ct_token_node``, ``ct_logit_node``: the mdb address the
13
+ node reads or writes), each edge a ``circuit_map.Edge`` kind (``read`` when the source and
14
+ target rows differ: the path crosses attention; ``compose`` within a row; ``consume`` into a
15
+ logit) with its weight (``supplied``: circuit-tracer's number). ``direct_effects`` recomputes the
16
+ same matrix in float64 from an mdb run (``derived-exact`` on the run's captured attention
17
+ weights ``p``, residuals ``h``/``r`` for the frozen norm scales, and ``n``/``m`` for the error
18
+ nodes): the frozen system is linear, so a source's write propagated through the frozen
19
+ attention value paths and the residual stream is the edge. ``compare`` reports the agreement.
20
+
21
+ Running circuit-tracer itself needs its declared pins (transformers <= 4.57.3, huggingface-hub
22
+ < 1.0), nnsight with ``nnsight.intervention.tracing.tracer.Barrier`` (0.6.x / 0.7.x; moved in
23
+ 0.8) and, for its TransformerLens backend, TransformerLens < 4 (``HookedTransformer``): it does
24
+ not run in the mdb library environment (transformers 5.13.1, nnsight 0.8.2, TL 4.4). The graph
25
+ is a plain tensor file, so mdb reads one made elsewhere without importing circuit-tracer.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from typing import Any
31
+
32
+ from mdb.core.foreign_names import ct_error_node, ct_logit_node, ct_node, ct_token_node
33
+
34
+ KEYS = ("adjacency_matrix", "active_features", "input_tokens")
35
+
36
+
37
+ def read_graph(source: Any) -> dict[str, Any]:
38
+ """A graph as a plain dict: a circuit-tracer ``Graph`` (duck-typed), a dict with its fields,
39
+ or a path to either (``Graph.to_pt`` needs circuit-tracer importable to unpickle; a dict of
40
+ tensors does not). ``n_layers`` comes from the dict or ``Graph.cfg.n_layers``."""
41
+ import torch
42
+
43
+ if isinstance(source, (str, bytes)) or hasattr(source, "__fspath__"):
44
+ try:
45
+ source = torch.load(source, map_location="cpu", weights_only=True)
46
+ except Exception: # noqa: BLE001 - a pickled Graph dict holds circuit-tracer objects
47
+ source = torch.load(source, map_location="cpu", weights_only=False)
48
+ if not isinstance(source, dict):
49
+ source = {"adjacency_matrix": source.adjacency_matrix,
50
+ "active_features": source.active_features,
51
+ "input_tokens": source.input_tokens, "cfg": source.cfg,
52
+ "activation_values": source.activation_values,
53
+ "logit_token_ids": source.logit_token_ids}
54
+ out = dict(source)
55
+ missing = [k for k in KEYS if k not in out]
56
+ if missing:
57
+ raise ValueError(f"not a circuit-tracer graph: missing {missing}")
58
+ if "n_layers" not in out:
59
+ out["n_layers"] = int(out["cfg"].n_layers)
60
+ if "logit_token_ids" not in out:
61
+ targets = out["logit_targets"]
62
+ out["logit_token_ids"] = torch.tensor([int(getattr(t, "vocab_idx", t)) for t in targets])
63
+ return out
64
+
65
+
66
+ def nodes(graph: dict[str, Any]) -> list[dict[str, Any]]:
67
+ """The graph's nodes in adjacency order, each an mdb foreign name with its ``kind``."""
68
+ layers = int(graph["n_layers"])
69
+ tokens = [int(t) for t in graph["input_tokens"].reshape(-1)]
70
+ out = [{"kind": "feature", **ct_node(int(l), int(p), int(f))}
71
+ for l, p, f in graph["active_features"].tolist()]
72
+ out += [{"kind": "error", **ct_error_node(l, p)}
73
+ for l in range(layers) for p in range(len(tokens))]
74
+ out += [{"kind": "token", **ct_token_node(p, t)} for p, t in enumerate(tokens)]
75
+ last = len(tokens) - 1
76
+ out += [{"kind": "logit", **ct_logit_node(last, int(t), layers)}
77
+ for t in graph["logit_token_ids"].reshape(-1)]
78
+ if len(out) != graph["adjacency_matrix"].shape[0]:
79
+ raise ValueError(f"{len(out)} nodes for a {tuple(graph['adjacency_matrix'].shape)} "
80
+ "adjacency (pruned or max_feature_nodes graphs are not supported)")
81
+ return out
82
+
83
+
84
+ def edge_kind(src: dict[str, Any], dst: dict[str, Any]) -> str:
85
+ if dst["kind"] == "logit":
86
+ return "consume"
87
+ return "read" if src["position"] != dst["position"] else "compose"
88
+
89
+
90
+ def graph_edges(source: Any, *, min_abs: float = 0.0) -> list[dict[str, Any]]:
91
+ """Every nonzero edge (``|weight| > min_abs``) as ``{src, dst, weight, edge}``: the
92
+ endpoints as foreign names, the weight ``supplied`` by circuit-tracer, ``edge`` the
93
+ ``circuit_map.Edge`` over the node ids."""
94
+ from mdb.analysis.numerics.labels import SUPPLIED, num
95
+ from mdb.analysis.symbols.circuit_map import Edge
96
+
97
+ graph = read_graph(source)
98
+ named = nodes(graph)
99
+ matrix = graph["adjacency_matrix"].double()
100
+ out = []
101
+ for dst_i, src_i in (matrix.abs() > min_abs).nonzero().tolist():
102
+ src, dst = named[src_i], named[dst_i]
103
+ out.append({"src": src, "dst": dst,
104
+ "weight": num(float(matrix[dst_i, src_i]), SUPPLIED),
105
+ "edge": Edge(src["id"], dst["id"], edge_kind(src, dst))})
106
+ return out
107
+
108
+
109
+ # --------------------------------------------------------------------------- exact check
110
+
111
+
112
+ def _frozen(run: Any, rows: int) -> dict[str, Any]:
113
+ """The frozen operands from the run (cursor at or past the last row's logits): per layer the
114
+ attention weights ``p`` (rows, H, rows) and the norm scales of ``h`` and ``r``; the final
115
+ norm scale; ``n`` and ``m`` for the error nodes. float64."""
116
+ import torch
117
+
118
+ from mdb.analysis.numerics.labels import f64
119
+
120
+ model = run.adapter.model
121
+ eps = float(model.config.rms_norm_eps)
122
+ layers = run.adapter.layers
123
+
124
+ def rho(x: Any) -> Any:
125
+ return 1.0 / torch.sqrt(x.pow(2).mean(-1) + eps)
126
+
127
+ def port(name: str) -> Any:
128
+ return torch.stack([f64(run.read(f"t{r}.{name}")).reshape(-1) for r in range(rows)])
129
+
130
+ out: dict[str, Any] = {"p": [], "rho_in": [], "rho_post": [], "n": [], "m": []}
131
+ for layer in range(layers):
132
+ p = torch.zeros(rows, run.adapter.num_heads, rows, dtype=torch.float64)
133
+ for r in range(rows):
134
+ p[r, :, : r + 1] = f64(run.read(f"t{r}.L{layer}.p")).reshape(run.adapter.num_heads, -1)
135
+ out["p"].append(p)
136
+ out["rho_in"].append(rho(port(f"L{layer}.h")))
137
+ out["rho_post"].append(rho(port(f"L{layer}.r")))
138
+ out["n"].append(port(f"L{layer}.n"))
139
+ out["m"].append(port(f"L{layer}.m"))
140
+ out["rho_final"] = rho(port(f"L{layers - 1}.h_out"))
141
+ return out
142
+
143
+
144
+ def direct_effects(run: Any, graph: Any, transcoders: dict[str, list[Any]], *,
145
+ zero_rows: int = 1) -> Any:
146
+ """The graph's adjacency recomputed by mdb in float64 (``derived-exact`` on the run's
147
+ captured operands): every source's write (feature: activation x decoder row; error: native
148
+ ``m`` minus the transcoder's reconstruction; token: its embedding row) carried through the
149
+ frozen system (attention patterns and norm scales fixed, MLPs blocked) to every target
150
+ (feature: encoder row . the change of ``n``; logit: demeaned unembedding row . the change
151
+ of the final norm output). ``transcoders``: ``W_enc``, ``W_dec``, ``b_enc``, ``b_dec`` per
152
+ layer (circuit-tracer's ``(d_transcoder, d_model)`` layout, ReLU). The first ``zero_rows``
153
+ rows' error nodes are zero (circuit-tracer's ``zero_positions``, row 0; its graph holds no
154
+ feature there). With ``zero_rows=0`` and ``b_dec`` = 0 every MLP write is a node, so the
155
+ edges into a logit sum to its demeaned native value. Qwen2/Qwen3/Llama layout."""
156
+ import torch
157
+
158
+ from mdb.analysis.numerics.labels import f64
159
+
160
+ graph = read_graph(graph)
161
+ named = nodes(graph)
162
+ tokens = [int(t) for t in graph["input_tokens"].reshape(-1)]
163
+ rows = len(tokens)
164
+ hf = run.adapter.model
165
+ body = hf.model
166
+ layers = run.adapter.layers
167
+ heads, kv, dh = run.adapter.num_heads, run.adapter.num_kv_heads, run.adapter.head_dim
168
+ group = heads // kv
169
+ frozen = _frozen(run, rows)
170
+ enc = [f64(w) for w in transcoders["W_enc"]]
171
+ dec = [f64(w) for w in transcoders["W_dec"]]
172
+ b_enc = [f64(b) for b in transcoders["b_enc"]]
173
+ b_dec = [f64(b) for b in transcoders["b_dec"]]
174
+ lm = f64(hf.lm_head.weight)
175
+ unembed = lm - lm.mean(0, keepdim=True)
176
+ weights = []
177
+ for layer in range(layers):
178
+ block = body.layers[layer]
179
+ weights.append((f64(block.input_layernorm.weight), f64(block.self_attn.v_proj.weight),
180
+ f64(block.self_attn.o_proj.weight),
181
+ f64(block.post_attention_layernorm.weight)))
182
+ gamma_final = f64(body.norm.weight)
183
+
184
+ def carry(start: int, position: int, vector: Any) -> tuple[list[Any], Any]:
185
+ """The change of ``n`` at every layer after ``start`` and of the final norm output."""
186
+ dx = torch.zeros(rows, vector.shape[0], dtype=torch.float64)
187
+ dx[position] = vector
188
+ dn: list[Any] = [None] * layers
189
+ for layer in range(start + 1, layers):
190
+ g_in, w_v, w_o, g_post = weights[layer]
191
+ a = g_in * frozen["rho_in"][layer][:, None] * dx
192
+ v = (a @ w_v.T).reshape(rows, kv, dh)
193
+ v = v.repeat_interleave(group, dim=1) # (rows, H, dh)
194
+ attended = torch.einsum("ths,shd->thd", frozen["p"][layer], v)
195
+ dr = dx + attended.reshape(rows, heads * dh) @ w_o.T
196
+ dn[layer] = g_post * frozen["rho_post"][layer][:, None] * dr
197
+ dx = dr
198
+ return dn, gamma_final * frozen["rho_final"][-1] * dx[-1]
199
+
200
+ size = len(named)
201
+ out = torch.zeros(size, size, dtype=torch.float64)
202
+ targets = [(i, n) for i, n in enumerate(named) if n["kind"] in ("feature", "logit")]
203
+ for j, src in enumerate(named):
204
+ if src["kind"] == "feature":
205
+ layer, position = src["layer"], src["position"]
206
+ act = torch.relu(enc[layer][src["feature"]] @ frozen["n"][layer][position]
207
+ + b_enc[layer][src["feature"]])
208
+ start, vector = layer, act * dec[layer][src["feature"]]
209
+ elif src["kind"] == "error":
210
+ layer, position = src["layer"], src["position"]
211
+ if position < zero_rows:
212
+ continue
213
+ pre = torch.relu(frozen["n"][layer][position] @ enc[layer].T + b_enc[layer])
214
+ start = layer
215
+ vector = frozen["m"][layer][position] - (pre @ dec[layer] + b_dec[layer])
216
+ elif src["kind"] == "token":
217
+ start, position = -1, src["position"]
218
+ vector = f64(body.embed_tokens.weight[src["token"]])
219
+ else:
220
+ continue
221
+ dn, dfinal = carry(start, position, vector)
222
+ for i, dst in targets:
223
+ if dst["kind"] == "feature":
224
+ if dst["layer"] <= start or dn[dst["layer"]] is None:
225
+ continue
226
+ out[i, j] = enc[dst["layer"]][dst["feature"]] @ dn[dst["layer"]][dst["position"]]
227
+ else:
228
+ out[i, j] = unembed[dst["token"]] @ dfinal
229
+ return out
230
+
231
+
232
+ def compare(supplied: Any, exact: Any, *, floor: float = 0.0) -> dict[str, Any]:
233
+ """Agreement of circuit-tracer's adjacency with mdb's exact one over the entries either
234
+ makes nonzero (``|.| > floor``): count, largest absolute and relative gap, Pearson r, sign
235
+ agreement, and the ratio of their Frobenius norms (all ``measured``)."""
236
+ import torch
237
+
238
+ from mdb.analysis.numerics.labels import MEASURED, num
239
+
240
+ a, b = supplied.double().reshape(-1), exact.double().reshape(-1)
241
+ keep = (a.abs() > floor) | (b.abs() > floor)
242
+ a, b = a[keep], b[keep]
243
+ gap = (a - b).abs()
244
+ scale = b.abs().max().clamp(min=1e-300)
245
+ r = torch.corrcoef(torch.stack([a, b]))[0, 1] if a.numel() > 1 else torch.tensor(1.0)
246
+ return {"edges": int(keep.sum()), "max_abs_gap": num(float(gap.max()), MEASURED),
247
+ "max_gap_over_max_edge": num(float(gap.max() / scale), MEASURED),
248
+ "pearson_r": num(float(r), MEASURED),
249
+ "sign_agree": int(((a > 0) == (b > 0)).sum()),
250
+ "norm_ratio": num(float(a.norm() / b.norm().clamp(min=1e-300)), MEASURED)}
251
+
252
+
253
+ __all__ = ["compare", "direct_effects", "edge_kind", "graph_edges", "nodes", "read_graph"]
@@ -0,0 +1,44 @@
1
+ """circuit-tracer interop: an import shim and the correspondence of its graph nodes to mdb
2
+ addresses (``core.foreign_names.ct_*``).
3
+
4
+ circuit-tracer 0.5.0 declares ``huggingface-hub<1.0``; under hub 1.x its package import fails
5
+ on ``HF_HUB_ENABLE_HF_TRANSFER``.
6
+ ``import_circuit_tracer`` sets that constant to False before importing. Attribution itself does
7
+ not run under transformers 5.x / nnsight 0.8 / TransformerLens 4 (``ReplacementModel`` import
8
+ errors; ``circuit_tracer_graph`` and docs/INTEROP.md give the pins that run it); the node ids
9
+ and the module locations of circuit-tracer's Qwen3 mapping are checked
10
+ (``tests/test_interop_symtab.py``).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any
16
+
17
+ # circuit-tracer's Qwen3 ``feature_hook_mapping`` key -> the mdb port at that location
18
+ HOOK_PORTS = {"mlp.hook_in": "n", "mlp.hook_out": "m"}
19
+
20
+
21
+ def import_circuit_tracer() -> Any:
22
+ """``circuit_tracer`` imported under huggingface_hub 1.x (the constant shim)."""
23
+ import huggingface_hub.constants as constants
24
+
25
+ if not hasattr(constants, "HF_HUB_ENABLE_HF_TRANSFER"):
26
+ constants.HF_HUB_ENABLE_HF_TRANSFER = False
27
+ import circuit_tracer
28
+
29
+ return circuit_tracer
30
+
31
+
32
+ def qwen3_locations(layer: int) -> dict[str, tuple[str, str]]:
33
+ """mdb port -> (nnsight envoy path, input|output) from circuit-tracer's own Qwen3 mapping."""
34
+ import_circuit_tracer()
35
+ from circuit_tracer.utils.tl_nnsight_mapping import get_mapping
36
+
37
+ mapping = get_mapping("Qwen3ForCausalLM")
38
+ out = {HOOK_PORTS[k]: (path.format(layer=layer), side)
39
+ for k, (path, side) in mapping.feature_hook_mapping.items() if k in HOOK_PORTS}
40
+ out["emb"] = (mapping.embed_location, "output")
41
+ return out
42
+
43
+
44
+ __all__ = ["HOOK_PORTS", "import_circuit_tracer", "qwen3_locations"]
mdb/interop/clone.py ADDED
@@ -0,0 +1,22 @@
1
+ """A module tree over the same tensors, for tools that rewrite the tree they are handed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ def shared_clone(model: Any) -> Any:
9
+ """A new module tree over the SAME parameter and buffer tensors (no weight copy).
10
+
11
+ Two tools rewrite the module tree they are given, measured on tiny Qwen2 (tests):
12
+ ``TransformerBridge.boot_transformers(hf_model=...)`` replaces modules in place (33 -> 155
13
+ modules; layers become ``BlockBridge``, attention a ``PositionEmbeddingsAttentionBridge``),
14
+ and nnsight's ``.source`` replaces an attention module's ``forward`` with an instrumented
15
+ copy that binds ``eager_attention_forward`` at rewrite time. After either, mdb's eager
16
+ interceptor no longer sees that layer's attention. Handing the tool a shared clone leaves
17
+ mdb's tree untouched while both read one copy of the weights.
18
+ """
19
+ import copy
20
+
21
+ memo = {id(t): t for t in list(model.parameters()) + list(model.buffers())}
22
+ return copy.deepcopy(model, memo)
mdb/interop/names.py ADDED
@@ -0,0 +1,295 @@
1
+ """One name table: mdb ports <-> TransformerLens (TransformerBridge, v4) hook names <-> nnsight
2
+ module paths, and the layout conversions between them.
3
+
4
+ Measured on tiny Qwen2/Qwen3 (``tests/test_interop.py``): every mapped value is bitwise equal
5
+ across mdb ``trace``, an unprocessed ``TransformerBridge`` wrapping the same module, and nnsight
6
+ on the same module. Weight-processed TransformerLens (``enable_compatibility_mode()``) lives in
7
+ another basis; see ``docs/INTEROP.md`` for what changes.
8
+
9
+ Layouts (one sequence position ``r`` of a full forward over ``T`` tokens):
10
+
11
+ - ``seq``: tool ``(batch, pos, X)`` <-> mdb ``(batch, 1, X)``
12
+ - ``heads_flat``: TL ``(batch, pos, head, head_dim)`` <-> mdb ``(batch, 1, head*head_dim)``
13
+ - ``heads``: nnsight ``(batch, pos, head, head_dim)`` <-> mdb ``(batch, 1, head, head_dim)``
14
+ - ``heads_t``: TL q_norm/k_norm ``(batch, head, pos, head_dim)`` <-> mdb ``(batch, 1, head, head_dim)``
15
+ - ``rot_q``: TL ``(batch, pos, head, head_dim)`` <-> mdb ``(batch, head, 1, head_dim)``
16
+ - ``rot_k``: TL ``(batch, pos, kv, head_dim)`` <-> mdb ``(batch, kv, r+1, head_dim)`` (mdb's ``kr``
17
+ holds the cached rows too)
18
+ - ``scores``: ``(batch, head, query, key)`` <-> mdb ``(batch, head, 1, r+1)``
19
+
20
+ This module imports no torch at import time.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import re
26
+ from dataclasses import dataclass
27
+ from typing import Any
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Name:
32
+ port: str
33
+ tl: str | None # bridge-native hook name (``{l}`` = layer)
34
+ tl_aliases: tuple[str, ...] # other TL names of the same value (legacy / component names)
35
+ tl_layout: str | None
36
+ nn: str | None # nnsight path relative to ``model.model.layers[l]``
37
+ nn_layout: str | None
38
+ note: str = ""
39
+
40
+
41
+ _A = "blocks.{l}.attn."
42
+ NAMES: tuple[Name, ...] = (
43
+ Name("h", "blocks.{l}.hook_resid_pre", ("blocks.{l}.hook_in", "blocks.{l}.ln1.hook_in"),
44
+ "seq", ".input", "seq"),
45
+ Name("a", "blocks.{l}.ln1.hook_out", ("blocks.{l}.attn.hook_in",), "seq",
46
+ ".input_layernorm.output", "seq",
47
+ "ln1.hook_normalized is RMSNorm without w_in; equal to a only with fold_ln"),
48
+ Name("q", _A + "q.hook_out", (_A + "hook_q",), "heads_flat", ".self_attn.q_proj.output", "seq"),
49
+ Name("qn", _A + "q_norm.hook_out", (), "heads_t", ".self_attn.q_norm.output", "heads"),
50
+ Name("k", _A + "k.hook_out", (_A + "hook_k",), "heads_flat", ".self_attn.k_proj.output", "seq"),
51
+ Name("kn", _A + "k_norm.hook_out", (), "heads_t", ".self_attn.k_norm.output", "heads"),
52
+ Name("v", _A + "v.hook_out", (_A + "hook_v",), "heads_flat", ".self_attn.v_proj.output", "seq"),
53
+ Name("qr", _A + "hook_rot_q", (), "rot_q", ".self_attn.source.attention_interface_1.inputs[0][1]",
54
+ "bh"),
55
+ Name("kr", _A + "hook_rot_k", (), "rot_k", ".self_attn.source.attention_interface_1.inputs[0][2]",
56
+ "bh_k"),
57
+ Name("s", _A + "hook_attn_scores", (), "scores", None, None,
58
+ "mdb s is a replica (scaling*qr kr^T + mask); nnsight has no module output for it"),
59
+ Name("p", _A + "hook_pattern", (), "scores", ".self_attn.output[1]", "scores"),
60
+ Name("A", _A + "hook_z", (_A + "o.hook_in",), "heads_flat", ".self_attn.o_proj.input", "seq"),
61
+ Name("o", "blocks.{l}.hook_attn_out", (_A + "hook_out", _A + "o.hook_out"), "seq",
62
+ ".self_attn.o_proj.output", "seq"),
63
+ Name("r", "blocks.{l}.hook_resid_mid", ("blocks.{l}.ln2.hook_in",), "seq",
64
+ ".post_attention_layernorm.input", "seq"),
65
+ Name("n", "blocks.{l}.ln2.hook_out", ("blocks.{l}.mlp.hook_in", "blocks.{l}.mlp.gate.hook_in",
66
+ "blocks.{l}.mlp.in.hook_in"), "seq",
67
+ ".mlp.input", "seq", "ln2.hook_normalized is RMSNorm without w_post"),
68
+ Name("g", "blocks.{l}.mlp.gate.hook_out", ("blocks.{l}.mlp.hook_pre",), "seq",
69
+ ".mlp.gate_proj.output", "seq"),
70
+ Name("sg", None, (), None, ".mlp.act_fn.output", "seq",
71
+ "TransformerLens has no hook on silu(g); read g and apply silu"),
72
+ Name("u", "blocks.{l}.mlp.in.hook_out", ("blocks.{l}.mlp.hook_pre_linear",), "seq",
73
+ ".mlp.up_proj.output", "seq"),
74
+ Name("f", "blocks.{l}.mlp.hook_post", ("blocks.{l}.mlp.out.hook_in",), "seq",
75
+ ".mlp.down_proj.input", "seq"),
76
+ Name("m", "blocks.{l}.hook_mlp_out", ("blocks.{l}.mlp.hook_out", "blocks.{l}.mlp.out.hook_out"),
77
+ "seq", ".mlp.down_proj.output", "seq"),
78
+ Name("h_out", "blocks.{l}.hook_resid_post", ("blocks.{l}.hook_out",), "seq", ".output", "seq"),
79
+ )
80
+ GLOBAL_NAMES = {
81
+ "emb": ("hook_embed", ("embed.hook_out",), "model.model.embed_tokens.output"),
82
+ "fn": ("ln_final.hook_out", ("unembed.hook_in",), "model.model.norm.output"),
83
+ "logits": ("unembed.hook_out", ("hook_unembed",), "model.lm_head.output"),
84
+ }
85
+ BY_PORT = {name.port: name for name in NAMES}
86
+ _LAYER = re.compile(r"^L(?P<l>\d+)\.(?P<port>\w+)$")
87
+
88
+
89
+ class NoName(KeyError):
90
+ """The address or tool name has no exact counterpart (the reason is the message)."""
91
+
92
+ def __str__(self) -> str:
93
+ return str(self.args[0]) if self.args else "no counterpart"
94
+
95
+
96
+ def _split(address: str) -> tuple[int | None, str]:
97
+ match = _LAYER.fullmatch(address.strip())
98
+ if match:
99
+ return int(match["l"]), match["port"]
100
+ if address.strip() in GLOBAL_NAMES:
101
+ return None, address.strip()
102
+ raise NoName(f"{address!r} is not L<l>.<port> or one of {', '.join(GLOBAL_NAMES)}")
103
+
104
+
105
+ def to_tl(address: str) -> str:
106
+ """``L22.A`` -> ``blocks.22.attn.hook_z`` (bridge-native name)."""
107
+ layer, port = _split(address)
108
+ if layer is None:
109
+ return GLOBAL_NAMES[port][0]
110
+ name = BY_PORT.get(port)
111
+ if name is None:
112
+ raise NoName(f"mdb has no port {port!r}")
113
+ if name.tl is None:
114
+ raise NoName(f"{address}: {name.note}")
115
+ return name.tl.format(l=layer)
116
+
117
+
118
+ def to_nnsight(address: str) -> str:
119
+ """``L22.A`` -> ``model.model.layers[22].self_attn.o_proj.input``."""
120
+ layer, port = _split(address)
121
+ if layer is None:
122
+ return GLOBAL_NAMES[port][2]
123
+ name = BY_PORT.get(port)
124
+ if name is None or name.nn is None:
125
+ raise NoName(f"{address}: " + (name.note if name else f"mdb has no port {port!r}"))
126
+ return f"model.model.layers[{layer}]{name.nn}"
127
+
128
+
129
+ def _reverse_tl() -> list[tuple[re.Pattern[str], str]]:
130
+ out = []
131
+ for name in NAMES:
132
+ for hook in ((name.tl,) if name.tl else ()) + name.tl_aliases:
133
+ out.append((re.compile("^" + re.escape(hook).replace(r"\{l\}", r"(\d+)") + "$"),
134
+ name.port))
135
+ return out
136
+
137
+
138
+ _TL_REVERSE = _reverse_tl()
139
+
140
+
141
+ def from_tl(hook: str) -> str:
142
+ """``blocks.22.attn.hook_z`` (or an alias) -> ``L22.A``."""
143
+ for glob, (native, aliases, _) in GLOBAL_NAMES.items():
144
+ if hook == native or hook in aliases:
145
+ return glob
146
+ for pattern, port in _TL_REVERSE:
147
+ match = pattern.fullmatch(hook)
148
+ if match:
149
+ return f"L{match.group(1)}.{port}"
150
+ raise NoName(f"TransformerLens hook {hook!r} has no mdb port (e.g. ln*.hook_scale, "
151
+ "ln*.hook_normalized, hook_cos/hook_sin, *.hook_in of q/k/v projections)")
152
+
153
+
154
+ _NN = re.compile(r"^(?:model\.)?model\.layers\[(\d+)\](.*)$")
155
+
156
+
157
+ def from_nnsight(path: str) -> str:
158
+ """``model.model.layers[22].self_attn.o_proj.input`` -> ``L22.A``."""
159
+ for glob, (_, _, nn) in GLOBAL_NAMES.items():
160
+ if path in (nn, nn.removeprefix("model.")):
161
+ return glob
162
+ match = _NN.fullmatch(path.strip())
163
+ if match:
164
+ for name in NAMES:
165
+ if name.nn == match.group(2):
166
+ return f"L{match.group(1)}.{name.port}"
167
+ raise NoName(f"nnsight path {path!r} has no mdb port")
168
+
169
+
170
+ def table(ports: tuple[str, ...] | None = None) -> list[dict[str, Any]]:
171
+ """The name table as rows (for docs and the REPL)."""
172
+ return [{"port": n.port, "transformer_lens": n.tl, "aliases": list(n.tl_aliases),
173
+ "nnsight": None if n.nn is None else f"model.model.layers[l]{n.nn}",
174
+ "note": n.note} for n in NAMES if ports is None or n.port in ports]
175
+
176
+
177
+ # --- layouts ---------------------------------------------------------------------------------
178
+
179
+
180
+ def to_mdb(layout: str, value: Any, row: int, *, heads: int | None = None) -> Any:
181
+ """One row ``row`` of a tool's full-sequence tensor, in mdb's layout for that port."""
182
+ if layout == "seq":
183
+ return value[:, row:row + 1]
184
+ if layout == "heads_flat":
185
+ piece = value[:, row:row + 1]
186
+ return piece.reshape(*piece.shape[:2], -1)
187
+ if layout == "heads":
188
+ return value[:, row:row + 1]
189
+ if layout == "heads_t": # TL q_norm/k_norm hooks: (batch, head, pos, head_dim)
190
+ return value[:, :, row:row + 1].transpose(1, 2)
191
+ if layout == "rot_q":
192
+ return value[:, row:row + 1].transpose(1, 2)
193
+ if layout == "rot_k":
194
+ return value[:, :row + 1].transpose(1, 2)
195
+ if layout == "scores":
196
+ return value[:, :, row:row + 1, :row + 1]
197
+ if layout == "bh": # nnsight eager argument (batch, head, pos, head_dim)
198
+ return value[:, :, row:row + 1]
199
+ if layout == "bh_k":
200
+ return value[:, :, :row + 1]
201
+ raise ValueError(f"unknown layout {layout!r}")
202
+
203
+
204
+ def to_tool(layout: str, value: Any, *, head_dim: int) -> Any:
205
+ """A full-sequence mdb ``trace`` value (``(batch, pos, ...)``, as ``mdb.trace`` keeps the
206
+ native layout) in the TransformerLens layout of the mapped hook."""
207
+ if layout in ("seq", "heads", "scores"):
208
+ return value
209
+ if layout == "heads_flat":
210
+ return value.reshape(*value.shape[:2], -1, head_dim)
211
+ if layout in ("rot_q", "rot_k", "heads_t"): # (batch, pos, head, d) <-> (batch, head, pos, d)
212
+ return value.transpose(1, 2)
213
+ raise ValueError(f"unknown layout {layout!r}")
214
+
215
+
216
+ _TL_RANK = {"seq": 3, "heads_flat": 4, "heads": 4, "heads_t": 4, "rot_q": 4, "rot_k": 4,
217
+ "scores": 4}
218
+
219
+
220
+ def tl_hook(port: str, fn: Any) -> Any:
221
+ """A TransformerLens hook function that hands ``fn`` the value in MDB's layout.
222
+
223
+ ``port`` is ``L<l>.<port>`` or a bare port (``A``, ``v``, ``q`` ...); the layout comes from the
224
+ name table (``tl_layout``). TL 4.4 bridge ``hook_z``/``hook_v``/``hook_q``/``hook_k`` are
225
+ ``(batch, pos, head, head_dim)`` while mdb keeps ``(batch, pos, head*head_dim)`` (layout
226
+ ``heads_flat``): indexing the TL tensor as mdb-flat patches the wrong slice silently. The
227
+ returned ``hook(x, hook)`` refuses an ``x`` whose rank is not the TL layout's (a wrong-rank
228
+ tensor means the wrong hook or a processed/fused one), converts ``x`` to mdb layout, calls
229
+ ``fn(mdb_tensor, hook)``, and converts the result back; a ``None`` return keeps ``x`` (TL's
230
+ convention; an in-place edit of the mdb tensor is an edit of ``x``, which is a view of it).
231
+ ``fn`` must return the same mdb shape it was given (a refusal otherwise)."""
232
+ address = port if _LAYER.fullmatch(port.strip()) else f"L0.{port}"
233
+ _, bare = _split(address)
234
+ name = BY_PORT.get(bare)
235
+ if name is None or name.tl is None or name.tl_layout is None:
236
+ raise NoName(f"{port!r} has no TransformerLens hook layout"
237
+ + (f": {name.note}" if name else ""))
238
+ layout = name.tl_layout
239
+ rank = _TL_RANK[layout]
240
+
241
+ def hook_fn(x: Any, hook: Any = None) -> Any:
242
+ if x.ndim != rank:
243
+ raise ValueError(f"{port}: TL layout {layout} is {rank}-D, got shape "
244
+ f"{tuple(x.shape)} (wrong hook, or a fused/processed bridge)")
245
+ head_dim = int(x.shape[-1])
246
+ mdb = to_tool(layout, x, head_dim=head_dim) if layout != "heads_flat" else \
247
+ x.reshape(*x.shape[:2], -1)
248
+ out = fn(mdb, hook)
249
+ if out is None:
250
+ return None
251
+ if tuple(out.shape) != tuple(mdb.shape):
252
+ raise ValueError(f"{port}: fn returned shape {tuple(out.shape)}, expected the mdb "
253
+ f"layout shape {tuple(mdb.shape)}")
254
+ return to_tool(layout, out, head_dim=head_dim)
255
+
256
+ return hook_fn
257
+
258
+
259
+ # --- foreign names of cells, rows and reads: ``mdb.core.foreign_names`` (re-exported here;
260
+ # analysis attaches them to symbol-table rows and may not import this layer) ---
261
+ from mdb.core.foreign_names import ( # noqa: E402,F401
262
+ MEASURED_MAP,
263
+ SUPPLIED_MAP,
264
+ UNVERIFIED_MAP,
265
+ binding_names,
266
+ cell_names,
267
+ ct_error_node,
268
+ ct_logit_node,
269
+ ct_node,
270
+ ct_token_node,
271
+ neuronpedia_url,
272
+ read_names,
273
+ row_names,
274
+ )
275
+
276
+
277
+ def residual_names(layer: int, port: str = "h_out", *, repo: str | None = None,
278
+ row: int | None = None) -> dict[str, Any]:
279
+ """Foreign names of a residual site ``L<layer>.<port>`` (``h`` or ``h_out``): TL hook,
280
+ nnsight path and, for a Qwen-Scope repo SAELens lists, its ``release``/``sae_id``."""
281
+ from mdb.analysis.features.basis import saelens_ref
282
+
283
+ index = "" if row is None else f"[:, {row}]"
284
+ return {"address": f"L{layer}.{port}" if row is None else f"t{row}.L{layer}.{port}",
285
+ "tl": {"hook": to_tl(f"L{layer}.{port}") + index, "verified": MEASURED_MAP},
286
+ "nnsight": {"path": to_nnsight(f"L{layer}.{port}") + index,
287
+ "verified": MEASURED_MAP},
288
+ "pyvene": ({"layer": layer, "component": f"model.layers[{layer}].output",
289
+ "unit": "pos", "verified": MEASURED_MAP} if port == "h_out" else
290
+ {"layer": layer, "component": "block_input", "unit": "pos",
291
+ "verified": MEASURED_MAP}),
292
+ "saelens": {**saelens_ref(repo, layer, port),
293
+ "verified": MEASURED_MAP if repo else UNVERIFIED_MAP}}
294
+
295
+