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
mdb/ops/errors.py ADDED
@@ -0,0 +1,8 @@
1
+ """Typed operation errors that every front end renders the same way (re-exported from
2
+ ``mdb.core.errors``, which is stdlib only)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from mdb.core.errors import BadArgs, OpError, Refused, UnknownOp, internal
7
+
8
+ __all__ = ["BadArgs", "OpError", "Refused", "UnknownOp", "internal"]
mdb/ops/features.py ADDED
@@ -0,0 +1,513 @@
1
+ """SAE verbs: ``sae`` (load / list feature bases) and ``features`` (active features at a residual
2
+ port with the error row, their direct effects on a consumer with exact closure, or a per-layer
3
+ profile of what the SAE drops). Feature edits ride the ordinary edit path: ``set``, ``whatif``
4
+ and ``compare`` take a feature expression as the value (``builtin.value_source``):
5
+
6
+ set L14.h_out += feature[123]*2 # add 2 d_123
7
+ whatif L20.h_out += feature[77,coef]*-1 --consumer M[a,b] # remove a_77 d_77 (ablate f77)
8
+ whatif L20.h_out += error*-1 --consumer M[a,b] # splice the SAE reconstruction
9
+ set L20.h_out = recon # replace the port by the reconstruction
10
+
11
+ Import is torch-free; the analysis layer is imported when an op runs.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Any
17
+
18
+ from mdb.core.records import num
19
+
20
+ from .builtin import Target, resolve_target
21
+ from .errors import BadArgs, Refused
22
+ from .registry import Arg, Op, register
23
+
24
+ _EXACT, _MEASURED, _LOCAL = "derived-exact", "measured", "derived-local"
25
+
26
+
27
+ def _sets(ctx) -> dict[str, Any]:
28
+ """The loaded SAE sets: held by the debugger (they belong to the model), else the context."""
29
+ owner = ctx.debugger if ctx.debugger is not None else ctx
30
+ found = getattr(owner, "_sae_sets", None)
31
+ if found is None:
32
+ found = {}
33
+ owner._sae_sets = found
34
+ return found
35
+
36
+
37
+ def _sae_error():
38
+ from mdb.analysis.features.basis import SaeError
39
+
40
+ return SaeError
41
+
42
+
43
+ def _pick(ctx, name: str | None, layer: int, port: str):
44
+ """``(set, basis)`` covering ``L<layer>.<port>``."""
45
+ sets = _sets(ctx)
46
+ if not sets:
47
+ raise Refused("no SAE loaded: sae load NAME PATH [layers=...]")
48
+ chosen = [sets[name]] if name else list(sets.values())
49
+ if name and name not in sets:
50
+ raise Refused(f"no SAE named {name} (have: {', '.join(sets)})")
51
+ hits = []
52
+ for found in chosen:
53
+ try:
54
+ basis = found.for_site(layer, port)
55
+ except _sae_error() as error:
56
+ raise Refused(str(error)) from None
57
+ if basis is not None:
58
+ hits.append((found, basis))
59
+ if not hits:
60
+ raise Refused(f"no loaded SAE covers L{layer}.{port} (sites: "
61
+ + "; ".join(f"{s.name}: L<{','.join(map(str, s.layers))}>.{s.port}"
62
+ for s in chosen) + ")")
63
+ if len(hits) > 1:
64
+ raise Refused(f"several SAEs cover L{layer}.{port}: name one with sae=NAME")
65
+ return hits[0]
66
+
67
+
68
+ def _text(ctx, token: int) -> str | None:
69
+ tokenizer = ctx.tokenizer
70
+ if tokenizer is None:
71
+ return None
72
+ try:
73
+ return tokenizer.decode([int(token)])
74
+ except Exception: # noqa: BLE001 - a label only
75
+ return None
76
+
77
+
78
+ def _promotes(ctx, run, basis, feature: int, lens: int) -> dict[str, Any]:
79
+ from mdb.analysis.measure.readout import logit_lens
80
+
81
+ ids = logit_lens(run, basis.direction(feature), lens)
82
+ return {"authority": _LOCAL, "value": None, "meaning": "top tokens of W_U (gamma . d_f), "
83
+ "float32 ranking: what the direction promotes, not a label",
84
+ "ids": ids, "texts": [_text(ctx, i) for i in ids]}
85
+
86
+
87
+ # --------------------------------------------------------------------------- feature values
88
+
89
+
90
+ def is_feature_expression(value: Any) -> bool:
91
+ from mdb.analysis.features.sae import is_expression
92
+
93
+ return is_expression(value)
94
+
95
+
96
+ def feature_value(ctx, target: Target, value: str):
97
+ """The float64 tensor (port shape) of a feature expression at the edited site, and its
98
+ source text. ``feature[ID]`` needs nothing from the run; ``coef``, ``error`` and ``recon``
99
+ read the site's current value (it must be computed)."""
100
+ import torch
101
+
102
+ from mdb.analysis.features.sae import edit_vector, parse_terms
103
+
104
+ if target.layer_port is None:
105
+ raise Refused(f"feature values apply to residual ports, not {target.text}")
106
+ layer, port = target.layer_port
107
+ try:
108
+ terms = parse_terms(value)
109
+ except _sae_error() as error:
110
+ raise BadArgs(str(error)) from None
111
+ found, basis = _pick(ctx, None, layer, port)
112
+ values: dict[Any, Any] = {}
113
+ for kind, _, coef, _, origin in terms:
114
+ if not (kind in ("error", "recon") or coef) or origin in values:
115
+ continue
116
+ if origin is None:
117
+ source_run, label = ctx.run, ""
118
+ else:
119
+ runs = getattr(ctx.debugger, "runs", {}) or {}
120
+ if origin not in runs:
121
+ raise Refused(f"no run named {origin} (info runs)")
122
+ source_run, label = runs[origin], f"{origin}:"
123
+ try:
124
+ values[origin] = source_run.read(target.run_target)
125
+ except Exception as error: # noqa: BLE001 - not computed yet
126
+ raise Refused(f"{value} needs the value at {label}{target.run_target}, which is not "
127
+ f"readable there ({error}); run past it (frame NAME: / until), or use "
128
+ "whatif from a later stop") from None
129
+ try:
130
+ vector = edit_vector(basis, terms, values)
131
+ except _sae_error() as error:
132
+ raise Refused(str(error)) from None
133
+ shape = tuple(ctx.run.port_shape(port))
134
+ if int(torch.tensor(shape).prod()) != vector.numel():
135
+ raise Refused(f"{target.text} has shape {list(shape)}, the SAE direction "
136
+ f"{vector.numel()} values")
137
+ return vector.reshape(shape), f"{value} (SAE {found.name} L{basis.layer})"
138
+
139
+
140
+ # --------------------------------------------------------------------------- sae
141
+
142
+
143
+ def _layers(text: str | None) -> list[int] | None:
144
+ if text in (None, "", "all"):
145
+ return None
146
+ out: list[int] = []
147
+ for part in text.split(","):
148
+ if ":" in part:
149
+ a, b = part.split(":", 1)
150
+ out += list(range(int(a), int(b)))
151
+ else:
152
+ out.append(int(part))
153
+ return out
154
+
155
+
156
+ def _sae(ctx, action, name, path, layers, k, port, cache, verify, layer):
157
+ from mdb.analysis.features.basis import open_set
158
+
159
+ sets = _sets(ctx)
160
+ if action == "list":
161
+ return {"saes": [s.describe() for s in sets.values()], "count": len(sets)}
162
+ if action == "drop":
163
+ if name not in sets:
164
+ raise Refused(f"no SAE named {name}")
165
+ sets.pop(name)
166
+ return {"dropped": name, "count": len(sets)}
167
+ if action != "load":
168
+ raise BadArgs("write sae load NAME PATH [layers=A:B|i,j|all] [k=K] [port=h_out|h] "
169
+ "[cache=N] [verify=true] | sae list | sae drop NAME")
170
+ if name and not path: # a named source from the config ([sae] sources)
171
+ from mdb.core import settings
172
+
173
+ named = settings.current().get("sae.sources").get(name)
174
+ if named is None:
175
+ known = ", ".join(sorted(settings.current().get("sae.sources"))) or "none"
176
+ raise BadArgs(f"write sae load NAME PATH, or name a configured SAE source "
177
+ f"([sae] sources: {known})")
178
+ path = named["path"]
179
+ layers = layers if layers is not None else named.get("layers")
180
+ k = k if k is not None else named.get("k")
181
+ port = port if port is not None else named.get("port")
182
+ layer = layer if layer is not None else named.get("layer")
183
+ verify = verify if verify is not None else named.get("verify")
184
+ cache = cache if cache is not None else named.get("cache")
185
+ if not name or not path:
186
+ raise BadArgs("write sae load NAME PATH")
187
+ cache = 4 if cache is None else cache
188
+ try:
189
+ found = open_set(name, path, layers=_layers(layers), k=k, port=port, cache=cache,
190
+ verify=bool(verify), layer=layer)
191
+ except _sae_error() as error:
192
+ raise Refused(str(error)) from None
193
+ except ValueError as error:
194
+ raise BadArgs(str(error)) from None
195
+ d = int(ctx.run.adapter.model.config.hidden_size) if ctx.run is not None else None
196
+ if d is not None:
197
+ basis = found.get(found.layers[0])
198
+ if basis.d_model != d:
199
+ raise Refused(f"SAE {name} has d_model {basis.d_model}, the model {d}")
200
+ sets[name] = found
201
+ return {"loaded": found.describe(), "count": len(sets)}
202
+
203
+
204
+ # --------------------------------------------------------------------------- features
205
+
206
+
207
+ def _feature_rows(ctx, run, basis, split, dec, top, lens, by_effect):
208
+ acts = dict(zip(dec.ids, dec.acts.tolist()))
209
+ norms = dec.D.norm(dim=0).tolist()
210
+ norm_of = dict(zip(dec.ids, norms))
211
+ effects = {i: e for i, _, e in split["features"]} if split else {}
212
+ order = sorted(dec.ids, key=(lambda i: -abs(effects[i])) if by_effect else
213
+ (lambda i: -acts[i]))
214
+ rows = []
215
+ for rank, feature in enumerate(order[:top]):
216
+ row = {"feature": int(feature), "activation": num(acts[feature], _EXACT),
217
+ "decoder_norm": num(norm_of[feature], _EXACT)}
218
+ if split:
219
+ row["effect"] = num(effects[feature], _EXACT, proof="P19")
220
+ if lens and rank < 8:
221
+ row["promotes"] = _promotes(ctx, run, basis, feature, lens)
222
+ rows.append(row)
223
+ rest = order[top:]
224
+ more = {"count": len(rest), "activation_sum": num(sum(acts[i] for i in rest), _EXACT)}
225
+ if split:
226
+ more["effect_sum"] = num(sum(effects[i] for i in rest), _EXACT, proof="P19")
227
+ return rows, more
228
+
229
+
230
+ def _consumer(ctx, text):
231
+ from mdb.analysis.measure.readout import readout
232
+
233
+ from .predict import parse_consumer
234
+
235
+ target = parse_consumer(ctx, text)
236
+ try:
237
+ reader = readout(ctx.run, target)
238
+ except Exception as error: # noqa: BLE001 - Refusal
239
+ raise Refused(str(error)) from None
240
+ if not reader.scalar:
241
+ raise Refused("features consumer= takes a margin M[a,b] or a logit logits[i]")
242
+ if reader.native is None:
243
+ raise Refused(f"{reader.text} is not computed at {ctx.run.where}")
244
+ return reader
245
+
246
+
247
+ def _split_json(split, reader):
248
+ direct = split["direct"]
249
+ parts = [abs(e) for _, _, e in split["features"]] + [abs(split["bias"]), abs(split["error"])]
250
+ total_abs = sum(parts) or 1.0
251
+ later = sum(v for _, _, v in split["downstream"])
252
+ closure = split["native"] - (split["bias"] + split["error"]
253
+ + sum(e for _, _, e in split["features"])
254
+ + later + split["head_bias"] + split["remainder"])
255
+ return {
256
+ "consumer": reader.text, "native": num(split["native"], _MEASURED, proof="P19"),
257
+ "direct": num(direct, _EXACT, proof="P19"),
258
+ "direct_meaning": "rho c.x: the site's residual on the skip path to the readout",
259
+ "features_sum": num(sum(e for _, _, e in split["features"]), _EXACT, proof="P19"),
260
+ "bias": num(split["bias"], _EXACT, proof="P19"),
261
+ "error": num(split["error"], _EXACT, proof="P19"),
262
+ "error_share_of_direct": (num(split["error"] / direct, _EXACT) if direct else
263
+ {"state": "unresolved", "reason": "direct effect is 0"}),
264
+ "error_share_of_abs": num(abs(split["error"]) / total_abs, _EXACT),
265
+ "later_layers": num(later, _EXACT, proof="P19"),
266
+ "head_bias": num(split["head_bias"], _EXACT, proof="P19"),
267
+ "remainder": num(split["remainder"], _MEASURED, proof="P19"),
268
+ "closure": num(closure, _EXACT, proof="P19"),
269
+ "identity_gap": num(split["identity_gap"], _EXACT),
270
+ "closure_meaning": "native - (features + bias + error + later layers + head bias + "
271
+ "remainder), float64 summation only",
272
+ }
273
+
274
+
275
+ def _profile(ctx, target_text, name, reader, shift=0):
276
+ from mdb.analysis.features.sae import margin_split
277
+
278
+ run = ctx.run
279
+ port = target_text.rsplit(".", 1)[1]
280
+ sets = _sets(ctx)
281
+ chosen = [sets[name]] if name else list(sets.values())
282
+ if not chosen:
283
+ raise Refused("no SAE loaded: sae load NAME PATH")
284
+ if len(chosen) > 1:
285
+ raise Refused("several SAEs are loaded: name one with sae=NAME")
286
+ found = chosen[0]
287
+ rows = []
288
+ for own in found.layers:
289
+ layer = own if port == found.port else (own + 1 if port == "h" else own - 1)
290
+ layer += shift
291
+ if not 0 <= layer < run.adapter.layers:
292
+ continue
293
+ basis = found.get(own)
294
+ split = margin_split(run, reader, basis, layer, port)
295
+ stats = split["decomposition"].stats()
296
+ entry = {"layer": layer, "site": f"L{layer}.{port}", "sae_layer": own,
297
+ **_split_json(split, reader),
298
+ "error_fraction_of_norm": stats["error_fraction_of_norm"],
299
+ "active": stats["active"]}
300
+ for key in ("consumer", "native", "direct_meaning", "closure_meaning"):
301
+ entry.pop(key)
302
+ rows.append(entry)
303
+ return {"mode": "profile", "sae": found.name, "consumer": reader.text, "shift": shift,
304
+ "shift_meaning": "the layer-L SAE applied at L+shift (0 = its own site); a "
305
+ "misaligned site still closes, only the error fraction shows it",
306
+ "native": num(float(reader.native), _MEASURED, proof="P19"),
307
+ "layers": rows, "count": len(rows), "where": run.where}
308
+
309
+
310
+ def _match(ctx, run, target, basis, text, top, lens, dec):
311
+ from mdb.analysis.features.sae import match_unit, unit_vector
312
+
313
+ try:
314
+ vector, meaning = unit_vector(run, target.row, text)
315
+ found = match_unit(basis, vector, top)
316
+ except _sae_error() as error:
317
+ raise Refused(str(error)) from None
318
+ except ValueError as error:
319
+ raise Refused(str(error)) from None
320
+ acts = dict(zip(dec.ids, dec.acts.tolist())) if dec is not None else {}
321
+ rows = []
322
+ for rank, (feature, cos, coef) in enumerate(zip(found["ids"], found["cos"], found["coef"])):
323
+ row = {"feature": feature, "cos": num(cos, _EXACT), "coef": num(coef, _EXACT),
324
+ "active_here": feature in acts}
325
+ if feature in acts:
326
+ row["activation"] = num(acts[feature], _EXACT)
327
+ if lens and rank < 8:
328
+ row["promotes"] = _promotes(ctx, run, basis, feature, lens)
329
+ rows.append(row)
330
+ return {"unit": text, "meaning": meaning, "norm": num(found["norm"], _EXACT),
331
+ "features": rows,
332
+ "outside_fraction": num(found["outside_fraction"], _EXACT),
333
+ "outside_meaning": "||v - D c|| / ||v||, c the least-squares fit on the listed "
334
+ "decoder directions: the part of the unit's write no listed "
335
+ "feature spans",
336
+ "ranking": "float32 cosine over all decoder directions (derived-local), the listed "
337
+ "cosines recomputed in float64"}
338
+
339
+
340
+ def _features(ctx, address, top, sae, consumer, lens, circuit, match=None, shift=0):
341
+ from mdb.analysis.features.sae import margin_split
342
+
343
+ run = ctx.run
344
+ if run is None:
345
+ raise Refused("no run: start one first")
346
+ reader = _consumer(ctx, consumer) if consumer else None
347
+ text = (address or "").strip()
348
+ if "*" in text:
349
+ if reader is None:
350
+ raise BadArgs("a layer pattern (L*.h_out) needs consumer=M[a,b]")
351
+ if not text.lstrip("t0123456789.").startswith("L*."):
352
+ raise BadArgs("write features L*.h_out|L*.h consumer=M[a,b]")
353
+ return _profile(ctx, text, sae, reader, int(shift or 0))
354
+ found_target = resolve_target(ctx, text)
355
+ if found_target.layer_port is None or found_target.selector:
356
+ raise Refused(f"features reads a whole residual port (L<i>.h_out or L<i>.h), not "
357
+ f"{found_target.text}")
358
+ layer, port = found_target.layer_port
359
+ sae_set, basis = _pick(ctx, sae, layer, port)
360
+ try:
361
+ x = run.read(found_target.run_target)
362
+ except Exception as error: # noqa: BLE001 - not computed
363
+ raise Refused(f"{found_target.run_target} has not been computed at {run.where}: "
364
+ f"{error}") \
365
+ from None
366
+ info = run.read_info(found_target.run_target)
367
+ if reader is not None:
368
+ if reader.row != found_target.row:
369
+ raise Refused(f"{reader.text} is on row t{reader.row}, the port on "
370
+ f"t{found_target.row}")
371
+ split = margin_split(run, reader, basis, layer, port)
372
+ dec = split["decomposition"]
373
+ else:
374
+ split, dec = None, basis.decompose(x)
375
+ stats = dec.stats()
376
+ rows, more = _feature_rows(ctx, run, basis, split, dec, top, lens, reader is not None)
377
+ error_row = {"norm": stats["error_norm"],
378
+ "fraction_of_norm": stats["error_fraction_of_norm"],
379
+ "fraction_of_energy": stats["error_fraction_of_energy"],
380
+ "meaning": "native minus reconstruction (b_dec + sum a_f d_f)"}
381
+ out: dict[str, Any] = {
382
+ "mode": "port", "target": found_target.run_target, "sae": basis.describe(),
383
+ "value": {"norm": stats["x_norm"], "authority_note": info.get("authority")},
384
+ "features": rows, "more": more, "error": error_row,
385
+ "bias": {"norm": stats["bias_norm"]}, "reconstruction": {"norm": stats["recon_norm"]},
386
+ "active": stats["active"], "identity_closure": stats["identity_closure"],
387
+ "where": run.where}
388
+ if found_target.row == 0:
389
+ from mdb.analysis.symbols.components import FIRST_ROW_CAVEAT
390
+
391
+ out["caveat"] = FIRST_ROW_CAVEAT
392
+ if match:
393
+ out["match"] = _match(ctx, run, found_target, basis, match, top, lens, dec)
394
+ if info.get("upstream_edits"):
395
+ out["under_edits"] = [f"t{e['row']}.L{e['layer']}.{e['port']}"
396
+ for e in info["upstream_edits"]]
397
+ if split is not None:
398
+ accounting = _split_json(split, reader)
399
+ out["accounting"] = accounting
400
+ error_row["effect"] = accounting["error"]
401
+ out["bias"]["effect"] = accounting["bias"]
402
+ if circuit:
403
+ from mdb.analysis.features.sae import circuit as build
404
+
405
+ from .inspect import _session_id, _store
406
+ from .predict import record_view
407
+
408
+ try:
409
+ built = build(run, reader, split, basis, top=min(top, 8),
410
+ session_id=_session_id(ctx))
411
+ except Exception as error: # noqa: BLE001 - Refusal
412
+ raise Refused(str(error)) from None
413
+ out["circuit"] = {"id": built.id, "record": record_view(built.record)["id"]}
414
+ stored = _store(ctx, [built.record])
415
+ if stored:
416
+ out["circuit"]["stored"] = stored
417
+ return out
418
+
419
+
420
+ register(Op("sae", "Load, list or drop SAE feature bases (per-layer residual SAEs)",
421
+ (Arg("action", "choice", default="list", choices=("load", "list", "drop")),
422
+ Arg("name", "str"), Arg("path", "str"),
423
+ Arg("layers", "str", positional=False, help="A:B, i,j or all (default all)"),
424
+ Arg("k", "int", positional=False, minimum=1, help="top-k when config.json lacks it"),
425
+ Arg("port", "choice", positional=False, choices=("h_out", "h"),
426
+ help="site when config.json has no hook_point"),
427
+ Arg("cache", "int", minimum=1, maximum=64, positional=False,
428
+ help="layers kept loaded, least recently used dropped (default 4)"),
429
+ Arg("verify", "bool", positional=False,
430
+ help="hash each file on load (sha256; default false)"),
431
+ Arg("layer", "int", positional=False, minimum=0, help="layer of a single file")),
432
+ "mutate", False, _sae,
433
+ usage="sae load NAME [PATH] [layers=A:B] [k=K] [cache=N] [verify=true] | sae list | "
434
+ "sae drop NAME (no PATH: the [sae] sources entry NAME of the config)"))
435
+ register(Op("features", "SAE features at a residual port with the error row; with a consumer, "
436
+ "each feature's, the bias's and the error's exact direct effect and the closure "
437
+ "(L*.h_out: per-layer profile of what the SAE drops)",
438
+ (Arg("address", "str", required=True),
439
+ Arg("top", "int", default=8, minimum=1, maximum=64, positional=False),
440
+ Arg("sae", "str", positional=False),
441
+ Arg("consumer", "str", positional=False, help="M[a,b] or logits[i]"),
442
+ Arg("lens", "int", default=0, minimum=0, maximum=8, positional=False,
443
+ help="top tokens each listed feature's direction promotes (logit lens)"),
444
+ Arg("circuit", "bool", default=False, positional=False,
445
+ help="store a circuit record with the SAE expansion (needs consumer)"),
446
+ Arg("match", "str", positional=False,
447
+ help="name an mdb unit: L<l>.f[i=N], L<l>.A[hH] or L<l>.A[hH,src=S]; lists "
448
+ "the decoder directions closest to its write"),
449
+ Arg("shift", "int", default=0, minimum=-4, maximum=4, positional=False,
450
+ help="profile only: apply each layer's SAE this many layers off its site "
451
+ "(site-alignment check)")),
452
+ "navigate", True, _features,
453
+ usage="features ADDR [top=K] [sae=NAME] [consumer=M[a,b]] [lens=N] [circuit=true] "
454
+ "[match=UNIT] "
455
+ "| features L*.h_out consumer=M[a,b]"))
456
+
457
+
458
+ def _feature(ctx, feature, layer, sae, top):
459
+ from mdb.analysis.features.sae import trace_feature
460
+
461
+ run = ctx.run
462
+ if run is None:
463
+ raise Refused("no run: start one first")
464
+ row = int(run.where.split(".", 1)[0][1:])
465
+ stop = run.where.split(".", 1)[1]
466
+ if stop not in ("logits", "sample"):
467
+ raise Refused(f"t{row}.logits has not been computed at {run.where}: feature traces the "
468
+ f"whole row, run `until t{row}.logits` first")
469
+ sets = _sets(ctx)
470
+ found = sets.get(sae) if sae else (next(iter(sets.values())) if len(sets) == 1 else None)
471
+ if found is None:
472
+ raise Refused("no SAE chosen: load one (sae load) or name it with sae=NAME (sae list)")
473
+ try:
474
+ basis = found.get(int(layer))
475
+ out = trace_feature(run, basis, int(feature), row, top=top)
476
+ except _sae_error() as error:
477
+ raise Refused(str(error)) from None
478
+ probe = [{"layer": p["layer"], **{k: num(p[k], _EXACT) for k in ("h", "r", "h_out")}}
479
+ for p in out["probe"]]
480
+ writers = [{"layer": w["layer"], "attn": num(w["attn"], _EXACT),
481
+ "mlp": num(w["mlp"], _EXACT)} for w in out["writers"]]
482
+ first, last = out["first_above"], out["last_above"]
483
+ return {
484
+ "feature": out["feature"], "site": f"t{row}.{out['site']}", "sae": found.name,
485
+ "active_at_site": out["active"], "cutoff": num(out["cutoff"], _EXACT),
486
+ "cutoff_meaning": "smallest active float32 pre-activation at the site (top-k "
487
+ "threshold); the probe above it at the site means active",
488
+ "enc_bias": num(out["enc_bias"], "supplied"),
489
+ "probe": probe, "writers": writers,
490
+ "first_above": f"t{row}.L{first[0]}.{first[1]}" if first else None,
491
+ "last_above": f"t{row}.L{last[0]}.{last[1]}" if last else None,
492
+ "heads": {"layer": out["attn_layer"],
493
+ "items": [{"index": h, "share": num(v, _EXACT, proof="P07")}
494
+ for h, v in out["heads"]]},
495
+ "neurons": {"layer": out["mlp_layer"],
496
+ "items": [{"index": i, "share": num(v, _EXACT, proof="P15")}
497
+ for i, v in out["neurons"]]},
498
+ "meaning": "probe = W_enc[f].x + b_enc[f] at every residual port; writers = W_enc[f]."
499
+ "o_l and W_enc[f].m_l (exact linear shares of the probe's change); heads "
500
+ "and neurons of the strongest writers",
501
+ "where": run.where}
502
+
503
+
504
+ register(Op("feature", "Life of one SAE feature along the cursor's row: its encoder probe at "
505
+ "every residual port (h, r, h_out), where it first crosses the site's top-k "
506
+ "threshold, and which attention/MLP (heads, neurons) write it",
507
+ (Arg("feature", "int", required=True, minimum=0),
508
+ Arg("layer", "int", required=True, minimum=0, positional=False,
509
+ help="the SAE layer the feature belongs to"),
510
+ Arg("sae", "str", positional=False),
511
+ Arg("top", "int", default=4, minimum=1, maximum=16, positional=False)),
512
+ "read", True, _feature,
513
+ usage="feature ID layer=L [sae=NAME] [top=K]"))
mdb/ops/graph.py ADDED
@@ -0,0 +1,58 @@
1
+ """Producer/consumer edges of a port program, read from ``PortSpec.inputs`` (no text parsing).
2
+
3
+ ``PortSpec.inputs`` names the earlier ports a port reads, plus two pseudo-nodes: ``"cache"``
4
+ (the key/value cache rows of earlier tokens) and ``"prev_layer"`` (the previous layer's
5
+ committed output; ``emb`` for layer 0). ``producers``/``consumers`` hold real ports only;
6
+ ``pseudo`` lists a port's pseudo-node reads, which ``backtrace`` shows as named frames.
7
+
8
+ Across layers: ``L<i>.h`` is produced by ``L<i-1>.h_out`` (``emb`` for layer 0), ``emb`` by
9
+ ``start``, ``fn`` by the last layer's ``h_out``, ``logits`` by ``fn``, ``sample`` by
10
+ ``logits``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any
16
+
17
+ PSEUDO = ("cache", "prev_layer")
18
+
19
+
20
+ def producers(program: Any) -> dict[str, tuple[str, ...]]:
21
+ names = set(program.names)
22
+ return {spec.name: tuple(i for i in spec.inputs if i in names) for spec in program.ports}
23
+
24
+
25
+ def pseudo(program: Any) -> dict[str, tuple[str, ...]]:
26
+ return {spec.name: tuple(i for i in spec.inputs if i in PSEUDO) for spec in program.ports}
27
+
28
+
29
+ def consumers(program: Any) -> dict[str, tuple[str, ...]]:
30
+ edges = producers(program)
31
+ return {
32
+ name: tuple(other for other in program.names if name in edges[other])
33
+ for name in program.names
34
+ }
35
+
36
+
37
+ def layering(program: Any, focus: str, *, root: str = "h") -> list[list[str]]:
38
+ """Ancestors of ``focus`` back to ``root``, by longest distance from ``focus``.
39
+
40
+ Level 0 is ``[focus]``; a port shared by two paths sits at its deepest level, so the
41
+ layer input ``h`` comes last.
42
+ """
43
+ edges = producers(program)
44
+ order = {name: i for i, name in enumerate(program.names)}
45
+ depth = {focus: 0}
46
+ for name in sorted(order, key=order.get, reverse=True):
47
+ if name not in depth or name == root:
48
+ continue
49
+ for item in edges[name]:
50
+ depth[item] = max(depth.get(item, 0), depth[name] + 1)
51
+ levels: dict[int, list[str]] = {}
52
+ for name, level in depth.items():
53
+ levels.setdefault(level, []).append(name)
54
+ return [sorted(levels[i], key=order.get) for i in sorted(levels)]
55
+
56
+
57
+ def chain_text(levels: list[list[str]]) -> str:
58
+ return " <- ".join(",".join(level) for level in levels)