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/inspect.py ADDED
@@ -0,0 +1,906 @@
1
+ """The inspection verbs: ``reads``, ``symbols``, ``symbol``, ``circuit``, ``compare`` and
2
+ ``seek``.
3
+
4
+ They replace the A6 slots of ``builtin`` (``register(..., replace=True)``). Import is
5
+ torch-free; each op imports the analysis layer when it runs.
6
+
7
+ - ``reads SOURCE``: the attention reads of a source row (``t2``, ``t2.L0.v``,
8
+ ``cache.L1.v[row=2]``) at the cursor's row (``rows=`` for later rows), with mass, exact
9
+ contribution and a native causal verdict (``analysis.measure.reads``).
10
+ - ``symbols``: the symbol table at the cursor (``analysis.symbols.table``); ``symbol NAME =
11
+ ADDR[,ADDR...]`` declares a user symbol over cache rows; ``symbol NAME = whatif`` (or
12
+ ``compare.a|b``, ``EACH:ITEM``) a named symbol from a transplant result (``ops.named``),
13
+ listed under ``named`` by ``symbols``, shown by ``symbol show NAME``.
14
+ - ``circuit CONSUMER [top=K] [depth=D]`` builds a circuit record; ``circuit test ID ref=NAME``
15
+ patches it natively from a reference run (``ref=set:NAME``: a prompt set's per-component
16
+ mean) and seals a ``circuit-test`` record; ``circuit show ID`` prints it as a walk
17
+ (``analysis.circuits.build``, ``analysis.circuits.test``).
18
+ - ``compare A B [consumer=C]``: base, A, B and A+B measured natively, effects and the
19
+ interaction (``analysis.measure.compare``). A side is an edit ``ADDR=VALUE [op]`` or a checkpoint
20
+ name (in memory, else durable).
21
+ - ``seek ADDR``: move the session to an occurrence, forward (``until``), backward
22
+ (``reverse-step``) or, with a project, by replaying a stored recipe (``ORIGIN:ADDR`` with a
23
+ checkpoint name or session id as origin, or an occurrence pointer as JSON).
24
+
25
+ With a project attached, ``symbols`` and ``circuit`` index their sealed records in it.
26
+ Declared symbols belong to the debugger: they are bound again on the run the session moves to
27
+ (``start``, a recipe ``seek``) once their rows are computed, and listed ``unresolved`` until
28
+ then; the circuit ledger moves with a recipe ``seek``.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import re
35
+ import weakref
36
+ from collections import Counter
37
+ from typing import Any
38
+
39
+ from . import named
40
+ from .builtin import GLOBALS, moved, project_of
41
+ from .errors import BadArgs, Refused
42
+ from .predict import build_edit, parse_assignment, parse_consumer, record_view, session_digest
43
+ from .registry import Arg, Op, register
44
+
45
+ _ROW = re.compile(r"t(?P<row>\d+)\.")
46
+ _OPS = ("replace", "add", "scale", "mix")
47
+ _SYMBOLS: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
48
+
49
+
50
+ def _refusal():
51
+ from mdb.analysis.predict.consumers import Refusal
52
+
53
+ return Refusal
54
+
55
+
56
+ def _declared_consumer(ctx, text: str | None):
57
+ return None if text is None else parse_consumer(ctx, text)
58
+
59
+
60
+ def _session_id(ctx) -> str | None:
61
+ project = project_of(ctx)
62
+ return None if project is None or project.read_only else ctx.debugger.session_id
63
+
64
+
65
+ def _store(ctx, records: list[dict[str, Any]]) -> list[str]:
66
+ """Index sealed records in the attached project; the ids stored."""
67
+ if _session_id(ctx) is None:
68
+ return []
69
+ from mdb.core import index
70
+
71
+ return [index.put_record(ctx.debugger.project, record) for record in records]
72
+
73
+
74
+ def _unchanged(ctx, before: str, verb: str) -> None:
75
+ if session_digest(ctx) != before:
76
+ raise RuntimeError(f"{verb} changed the debugger session")
77
+
78
+
79
+ # --------------------------------------------------------------------------- reads
80
+
81
+
82
+ def _reads(ctx, source, rows, consumer, top, causal, min_effect):
83
+ from mdb.analysis.measure import reads as reads_mod
84
+
85
+ before = session_digest(ctx)
86
+ try:
87
+ result = reads_mod.reads(ctx.run, source, rows=rows,
88
+ consumer=_declared_consumer(ctx, consumer), top=top,
89
+ causal=causal, min_effect=float(min_effect))
90
+ except _refusal() as error:
91
+ raise Refused(str(error)) from None
92
+ _unchanged(ctx, before, "reads")
93
+ report = result.report
94
+ tokenizer = ctx.tokenizer
95
+ if tokenizer is not None and "token" in report["source"]:
96
+ report["source"]["text"] = tokenizer.decode([report["source"]["token"]])
97
+ return {**report, "where": ctx.run.where}
98
+
99
+
100
+ # --------------------------------------------------------------------------- symbols
101
+
102
+
103
+ def _symbol_store(ctx) -> dict[str, list[str]]:
104
+ """The symbols declared through this debugger (name -> addresses), whatever its run."""
105
+ if ctx.debugger not in _SYMBOLS:
106
+ _SYMBOLS[ctx.debugger] = {}
107
+ return _SYMBOLS[ctx.debugger]
108
+
109
+
110
+ def _bind_declared(ctx) -> dict[str, dict[str, Any]]:
111
+ """Declare on the current run every symbol of the debugger it does not hold yet; those that
112
+ cannot be bound (rows not computed) are returned with the reason."""
113
+ from mdb.analysis.symbols import binding as _binding
114
+ from mdb.analysis.symbols import table as symbols
115
+
116
+ held = symbols.declared(ctx.run)
117
+ pending = {}
118
+ for name, addresses in _symbol_store(ctx).items():
119
+ if name in held and held[name].addresses == addresses:
120
+ continue
121
+ try:
122
+ _binding.declare(ctx.run, name, addresses)
123
+ except _refusal() as error:
124
+ pending[name] = {"addresses": addresses, "reason": str(error)}
125
+ return pending
126
+
127
+
128
+ _CANDIDATES: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
129
+
130
+
131
+ def candidate_store(ctx) -> dict[str, Any]:
132
+ """The candidate sets declared through this debugger (name -> ``CandidateSet``)."""
133
+ if ctx.debugger not in _CANDIDATES:
134
+ _CANDIDATES[ctx.debugger] = {}
135
+ return _CANDIDATES[ctx.debugger]
136
+
137
+
138
+ def _pairs(text: str | None, what: str) -> list[tuple[str, str]]:
139
+ """``a:b,c:d`` -> ``[(a, b), (c, d)]``."""
140
+ out = []
141
+ for part in (p.strip() for p in (text or "").split(",")):
142
+ if not part:
143
+ continue
144
+ key, colon, value = part.partition(":")
145
+ if not colon or not key or not value:
146
+ raise BadArgs(f"{what} is NAME:VALUE[,NAME:VALUE...], not {part!r}")
147
+ out.append((key.strip(), value.strip()))
148
+ return out
149
+
150
+
151
+ def _table_options(ctx, sets, truth, content_layers, hops, sink, co, lexical_null, switch,
152
+ labels, derive, foreign, causal, min_effect) -> dict[str, Any]:
153
+ """The ``symbols`` op line's options as ``symbols.table`` arguments."""
154
+ from mdb.analysis.symbols import candidates as cands
155
+
156
+ out: dict[str, Any] = {}
157
+ store = candidate_store(ctx)
158
+ truths = dict(_pairs(truth, "truth"))
159
+ if sets:
160
+ chosen = []
161
+ for name in (n.strip() for n in sets.split(",") if n.strip()):
162
+ if name not in store:
163
+ known = ", ".join(sorted(store)) or "none; candidates NAME = W1,W2,..."
164
+ raise Refused(f"no candidate set {name!r} (sets: {known})")
165
+ chosen.append(store[name])
166
+ chosen = cands.cross(chosen)
167
+ built = []
168
+ for c in chosen:
169
+ value = truths.get(c.name)
170
+ if value is not None and re.fullmatch(r"\d+", value):
171
+ value = int(value)
172
+ try:
173
+ built.append(c.candidates(value))
174
+ except _refusal() as error:
175
+ raise Refused(str(error)) from None
176
+ out["sets"] = built
177
+ out["content_layers"] = bool(content_layers)
178
+ elif truth or content_layers or co or switch or lexical_null:
179
+ raise BadArgs("truth=, content_layers=, co=, switch= and lexical_null= need sets=")
180
+ if hops:
181
+ found = {}
182
+ for part in hops.split(","):
183
+ fields = part.strip().split(":")
184
+ if len(fields) != 3:
185
+ raise BadArgs("hops is NAME:NATIVE:DIRECT[,...] (the measured native delta and "
186
+ "the direct-path delta of a replacement of NAME)")
187
+ try:
188
+ found[fields[0]] = {"native_delta": float(fields[1]),
189
+ "direct_delta": float(fields[2]),
190
+ "replacement": "supplied on the op line"}
191
+ except ValueError:
192
+ raise BadArgs(f"hops {part!r}: NATIVE and DIRECT are numbers") from None
193
+ out["hops"] = found
194
+ if sink is not None:
195
+ text = str(sink).strip()
196
+ if text in ("none", "off", ""):
197
+ out["sink"] = ()
198
+ else:
199
+ try:
200
+ out["sink"] = tuple(int(r.strip().lstrip("t")) for r in text.split(","))
201
+ except ValueError:
202
+ raise BadArgs(f"sink is R[,R...] or none, not {text!r}") from None
203
+ if co:
204
+ specs = []
205
+ for part in (p.strip() for p in co.split(",") if p.strip()):
206
+ target, slash, rest = part.partition("/")
207
+ if not slash:
208
+ raise BadArgs("co is TARGET/PROJECT_OUT[:K][,...] (read TARGET with the span "
209
+ "of PROJECT_OUT removed)")
210
+ other, colon, k = rest.partition(":")
211
+ specs.append(cands.CoReadout(target, other, k=int(k) if colon else None))
212
+ out["co"] = specs
213
+ if lexical_null:
214
+ out["lexical_null"] = True
215
+ if switch:
216
+ out["switch"] = dict(_pairs(switch, "switch"))
217
+ if labels:
218
+ parsed = {}
219
+ for key, value in _pairs(labels, "labels"):
220
+ try:
221
+ parsed[key] = int(value) if re.fullmatch(r"-?\d+", value) else float(value) \
222
+ if re.fullmatch(r"-?\d*\.\d+", value) else value
223
+ except ValueError:
224
+ parsed[key] = value
225
+ out["labels"] = parsed
226
+ if derive:
227
+ out["derive"] = dict(_pairs(derive, "derive"))
228
+ if foreign:
229
+ out["foreign"] = True
230
+ if causal not in (None, False, "false", "off"):
231
+ out["causal"] = True if causal in (True, "true", "on") else str(causal)
232
+ out["min_effect"] = float(min_effect or 0.0)
233
+ return out
234
+
235
+
236
+ def _symbols(ctx, consumer, rows, min_mass, readers, offset, limit, sets=None, truth=None,
237
+ content_layers=False, hops=None, sink=None, co=None, lexical_null=False,
238
+ switch=None, labels=None, derive=None, foreign=False, causal=None,
239
+ min_effect=0.0):
240
+ from mdb.analysis.symbols import table as symbols
241
+
242
+ pending = _bind_declared(ctx)
243
+ options = _table_options(ctx, sets, truth, content_layers, hops, sink, co, lexical_null,
244
+ switch, labels, derive, foreign, causal, min_effect)
245
+ try:
246
+ found = symbols.table(ctx.run, consumer=_declared_consumer(ctx, consumer), rows=rows,
247
+ min_mass=float(min_mass), readers=readers, offset=offset,
248
+ limit=limit, session_id=_session_id(ctx),
249
+ tokenizer=ctx.tokenizer, pending=pending,
250
+ store=_page_store(ctx), **options)
251
+ except _refusal() as error:
252
+ raise Refused(str(error)) from None
253
+ stored = _store(ctx, found.records)
254
+ report = dict(found.report)
255
+ if stored:
256
+ report["stored"] = stored
257
+ listed = named.listing(ctx)
258
+ if listed:
259
+ report["named"] = listed # transplant symbols; not part of the table record
260
+ return report
261
+
262
+
263
+ def _candidates(ctx, name, source=None, action="declare", rule="first", paired=None):
264
+ """``candidates NAME = FILE|W1,W2,...|#ID,#ID [rule=first|single] [paired=SET]`` declares a
265
+ candidate set (``analysis.symbols.candidates``); ``candidates show|delete NAME``; ``candidates
266
+ list``. The truth is given per table (``symbols sets=NAME truth=NAME:$var``), never here."""
267
+ from mdb.analysis.symbols import candidates as cands
268
+
269
+ store = candidate_store(ctx)
270
+ if action == "list":
271
+ return {"action": "list", "sets": [c.describe() for _, c in sorted(store.items())][:64]}
272
+ if not name:
273
+ raise BadArgs("candidates needs a name")
274
+ if action in ("show", "delete"):
275
+ if name not in store:
276
+ raise Refused(f"no candidate set {name!r}")
277
+ found = store.pop(name) if action == "delete" else store[name]
278
+ out = {"action": action, **found.describe()}
279
+ if action == "show":
280
+ out["words"] = [{"word": w, "pieces": list(p)} for w, p in
281
+ zip(found.words[:64], found.pieces[:64])]
282
+ return out
283
+ if not source:
284
+ raise BadArgs("write candidates NAME = FILE|W1,W2,...|#ID,#ID")
285
+ text = source.strip()
286
+ try:
287
+ if "," not in text and ("/" in text or text.endswith((".json", ".txt", ".jsonl"))):
288
+ found = cands.load(text, name, ctx.tokenizer, rule=rule)
289
+ else:
290
+ parts = [p.strip() for p in text.split(",") if p.strip()]
291
+ if all(re.fullmatch(r"#?\d+", p) for p in parts):
292
+ found = cands.from_tokens(name, [int(p.lstrip("#")) for p in parts])
293
+ else:
294
+ found = cands.build(name, parts, ctx.tokenizer, rule=rule)
295
+ if paired:
296
+ if paired not in store:
297
+ raise Refused(f"paired= names no candidate set {paired!r}")
298
+ found = cands.pair(found, store[paired])
299
+ except OSError as error:
300
+ raise BadArgs(f"cannot read {text}: {error.strerror or type(error).__name__}") from None
301
+ except _refusal() as error:
302
+ raise Refused(str(error)) from None
303
+ store[name] = found
304
+ others = cands.cross(list(store.values()))
305
+ store.update({c.name: c for c in others})
306
+ return {"action": "declare", **store[name].describe(),
307
+ "declared": sorted(store)}
308
+
309
+
310
+ def _symbol(ctx, name, addresses=None, result=None, action="declare", role=None, readers=6,
311
+ causal=True):
312
+ from mdb.analysis.symbols import binding as _binding
313
+
314
+ if action == "show":
315
+ return named.show(ctx, name)
316
+ if action == "delete":
317
+ return named.delete(ctx, name)
318
+ if (addresses is None) == (result is None):
319
+ raise BadArgs("write symbol NAME = ADDR[,ADDR...] (cache cells) or symbol NAME = "
320
+ "whatif|compare.a|compare.b|EACH:ITEM (a transplant result)")
321
+ if ctx.run is None and result is None:
322
+ raise Refused("symbol needs a live run; start one with `start`")
323
+ if result is not None:
324
+ return named.declare(ctx, name, result, role=role, readers=readers, causal=causal)
325
+ if name in named.store(ctx.debugger):
326
+ raise Refused(f"{name} is a named symbol (symbol show {name}); delete it or choose "
327
+ "another name")
328
+ parts = [part.strip() for part in addresses.split(",") if part.strip()]
329
+ _bind_declared(ctx)
330
+ try:
331
+ binding = _binding.declare(ctx.run, name, parts)
332
+ except _refusal() as error:
333
+ raise Refused(str(error)) from None
334
+ _symbol_store(ctx)[name] = binding.addresses
335
+ return {"symbol": binding.name, "definitions": binding.addresses,
336
+ "rows": sorted({cell.row for cell in binding.cells}),
337
+ "declared": sorted(_symbol_store(ctx))}
338
+
339
+
340
+ # --------------------------------------------------------------------------- circuit
341
+
342
+
343
+ CIRCUIT_TEST_NEEDS_REF = (
344
+ "circuit test needs a reference: circuit test ID ref=NAME, where NAME is another run of "
345
+ "this debugger (e.g. the opposite-answer prompt: `run name=NAME \"...\"` then `until "
346
+ "logits`), or ref=set:NAME for the per-component mean over a prompt set. Zero-ablation is "
347
+ "not offered: zeroing components is off-distribution, and on Qwen2.5-1.5B zeroing the "
348
+ "complement moved the margin by 27.75 against a circuit effect of 1.81, so it said nothing "
349
+ "(issue M4)")
350
+
351
+
352
+ def _page_store(ctx, write: bool = True):
353
+ """The project store a circuit's child pages go to (``write``) or are read from, or None
354
+ (a read-only project is still read)."""
355
+ project = getattr(ctx.debugger, "project", None)
356
+ if project is None or (write and project.read_only):
357
+ return None
358
+ return project.store
359
+
360
+
361
+ def _reference(ctx, ref: str):
362
+ """``(run, name, prompts)`` for ``ref=``: a named run of the debugger, or ``set:NAME`` (the
363
+ set's items as ``(item, token ids)``)."""
364
+ debugger = ctx.debugger
365
+ if debugger is None:
366
+ raise Refused("circuit test ref= names a run of the debugger; there is none here")
367
+ if ref.startswith("set:"):
368
+ from . import sets
369
+
370
+ name = ref[4:]
371
+ found = sets.sets_of(debugger).get(name)
372
+ if found is None:
373
+ raise Refused(f"no prompt set {name!r} (have: "
374
+ f"{', '.join(sets.sets_of(debugger)) or 'none'}; promptset load NAME "
375
+ "FILE)")
376
+ prompts = []
377
+ for item in found.items:
378
+ try:
379
+ prompts.append((item.name, debugger.tokens(item.prompt)))
380
+ except Refused as error:
381
+ raise Refused(f"set {name} item {item.name}: {error}") from None
382
+ return None, name, prompts
383
+ runs = getattr(debugger, "runs", None) or {}
384
+ if ref not in runs:
385
+ raise Refused(f"no run {ref!r} to take reference values from (runs: "
386
+ f"{', '.join(runs) or 'none'}; or ref=set:NAME)")
387
+ if runs[ref] is ctx.run:
388
+ raise Refused(f"ref={ref} is the current run: name another run (info runs)")
389
+ return runs[ref], ref, None
390
+
391
+
392
+ def _circuit(ctx, target, id, top, depth, ref=None, node=None): # noqa: A002 - the wire name
393
+ from mdb.analysis.circuits import build as circuits
394
+
395
+ run = ctx.run
396
+ ledger = circuits.ledger(run)
397
+ if target in ("test", "show"):
398
+ if id is None:
399
+ raise BadArgs(f"write circuit {target} ID")
400
+ if id not in ledger:
401
+ raise Refused(f"no circuit {id} (have: {', '.join(map(str, ledger)) or 'none'})")
402
+ circuit = ledger[id]
403
+ if target == "show" and node is not None:
404
+ try:
405
+ found = circuits.page(circuit, node, store=_page_store(ctx, False))
406
+ except _refusal() as error:
407
+ raise Refused(str(error)) from None
408
+ out = {"action": "show", "id": id, "node": node, "page": found,
409
+ "record": {"id": circuit.record["id"]}}
410
+ if getattr(ctx.debugger, "carried_circuits", {}).get(id) is circuit:
411
+ out["from_previous_run"] = True
412
+ else:
413
+ texts = _source_texts(ctx, found["node"])
414
+ if texts:
415
+ out["token_text"] = texts
416
+ return out
417
+ if node is not None:
418
+ raise BadArgs("node= belongs to circuit show ID")
419
+ if ref is not None and target == "show":
420
+ raise BadArgs("ref= belongs to circuit test ID")
421
+ if target == "show":
422
+ out = {"action": "show", "id": id, "record": record_view(circuit.record),
423
+ "tests": circuit.tests[-1:]}
424
+ if circuit.tests:
425
+ nodes = circuit.tests[-1].get("nodes", {})
426
+ # patched from the reference: the circuit's nodes in the knock-out, the
427
+ # `+N more` groups in the keep-only
428
+ out["ablated"] = {"retained": nodes.get("circuit", {}).get("refs", []),
429
+ "complement": nodes.get("group", {}).get("refs", [])}
430
+ if getattr(ctx.debugger, "carried_circuits", {}).get(id) is circuit:
431
+ out["from_previous_run"] = True # built by an earlier run: its tokens are not
432
+ return out # this run's, so no token text is attached
433
+ texts = _source_texts(ctx, circuit.record["body"]["root"])
434
+ if texts:
435
+ out["token_text"] = texts
436
+ return out
437
+ if ref is None:
438
+ raise Refused(CIRCUIT_TEST_NEEDS_REF)
439
+ if getattr(ctx.debugger, "carried_circuits", {}).get(id) is circuit:
440
+ raise Refused(f"circuit {id} was built by an earlier run: its nodes are that run's "
441
+ "rows; build it again on this run to test it")
442
+ other, name, prompts = _reference(ctx, ref)
443
+ before = session_digest(ctx)
444
+ try:
445
+ found = circuits.test(run, circuit, other, name=name, prompts=prompts,
446
+ session_id=_session_id(ctx), store=_page_store(ctx))
447
+ except _refusal() as error:
448
+ raise Refused(str(error)) from None
449
+ _unchanged(ctx, before, "circuit test")
450
+ out = {"action": "test", "id": id, "test": found["result"], "where": run.where}
451
+ stored = _store(ctx, [found["record"]])
452
+ if stored:
453
+ out["stored"] = stored
454
+ return out
455
+ if ref is not None:
456
+ raise BadArgs("ref= belongs to circuit test ID")
457
+ if id is not None:
458
+ raise BadArgs("circuit CONSUMER takes top= and depth=, not an id")
459
+ try:
460
+ circuit = circuits.build(run, parse_consumer(ctx, target), top=top, depth=depth,
461
+ session_id=_session_id(ctx), store=_page_store(ctx))
462
+ except _refusal() as error:
463
+ raise Refused(str(error)) from None
464
+ out = {"action": "build", "id": circuit.id, "record": record_view(circuit.record)}
465
+ stored = _store(ctx, [circuit.record])
466
+ if stored:
467
+ out["stored"] = stored
468
+ return out
469
+
470
+
471
+ def _source_texts(ctx, root: dict[str, Any]) -> dict[str, str]:
472
+ """Token text of each source-row leaf (node id -> text), when a tokenizer is attached."""
473
+ tokenizer, tokens = ctx.tokenizer, ctx.run.tokens
474
+ if tokenizer is None:
475
+ return {}
476
+ out = {}
477
+ stack = [root]
478
+ while stack and len(out) < 64:
479
+ node = stack.pop()
480
+ stack += node.get("children", [])
481
+ if node["kind"] == "source":
482
+ row = int(node["name"][1:])
483
+ if row < len(tokens):
484
+ out[node["id"]] = tokenizer.decode([int(tokens[row])])
485
+ return out
486
+
487
+
488
+ # --------------------------------------------------------------------------- compare
489
+
490
+
491
+ def _side(ctx, text: str):
492
+ """An edit ``ADDR=VALUE [op]`` (``predict.parse_assignment``: also ``ADDR += X`` and the
493
+ other sugar, ``mix DOSE``, a state cell target and an ``ORIGIN:ADDR`` value) or a checkpoint
494
+ name (in memory first, then durable)."""
495
+ from mdb.analysis.measure.compare import Side
496
+
497
+ words = text.split()
498
+ if _assigns(text):
499
+ usage = "ADDR=VALUE [replace|add|scale|mix DOSE] or ADDR += X"
500
+ address, value, op, dose = parse_assignment(text, usage=usage)
501
+ if (op or "replace") not in _OPS:
502
+ raise BadArgs(f"an edit side is {usage}, not {text!r}")
503
+ return Side(text, edits=[build_edit(ctx, address, value, op or "replace", dose)])
504
+ if len(words) != 1:
505
+ raise BadArgs(f"a side is an edit ADDR=VALUE [op] or a checkpoint name, not {text!r}")
506
+ name = words[0]
507
+ if name in ctx.checkpoints:
508
+ return Side(name, checkpoint=ctx.checkpoints[name])
509
+ project = project_of(ctx)
510
+ if project is not None:
511
+ from mdb.core import recipe as recipes
512
+
513
+ found = recipes.find_checkpoint(project, name, session_id=ctx.debugger.session_id)
514
+ if found is not None:
515
+ try:
516
+ other = ctx.debugger.replay(recipes.load(project, found["body"]["recipe"]))
517
+ except (recipes.RecipeError, ValueError) as error:
518
+ raise Refused(f"checkpoint {name!r} cannot be replayed here: {error}") from None
519
+ return Side(f"{name} (durable)", run=other)
520
+ known = ", ".join(ctx.checkpoints) or "none"
521
+ raise Refused(f"no checkpoint {name!r} (have: {known}) and it is not an edit ADDR=VALUE")
522
+
523
+
524
+ def _assigns(text: str) -> bool:
525
+ """Whether a compare side is an assignment: an ``=`` outside brackets."""
526
+ depth = 0
527
+ for char in text:
528
+ depth += char == "["
529
+ depth -= char == "]"
530
+ if char == "=" and depth == 0:
531
+ return True
532
+ return False
533
+
534
+
535
+ def _compare(ctx, a, b, consumer, path=False):
536
+ from mdb.analysis.measure import compare
537
+
538
+ run = ctx.run
539
+ if consumer is None:
540
+ consumer = f"t{_ROW.match(run.where)['row']}.logits"
541
+ chosen = parse_consumer(ctx, consumer)
542
+ before = session_digest(ctx)
543
+ try:
544
+ sides = {"A": _side(ctx, a), "B": _side(ctx, b)}
545
+ result = compare.compare(run, sides["A"], sides["B"], chosen)
546
+ paths = _compare_paths(run, sides, result["report"], chosen) if path else None
547
+ except _refusal() as error:
548
+ raise Refused(str(error)) from None
549
+ after = session_digest(ctx)
550
+ if after != before:
551
+ raise RuntimeError("compare changed the debugger session")
552
+ report = result["report"]
553
+ report["session"] = {**report["session"], "debugger_before": before,
554
+ "debugger_after": after}
555
+ if paths is not None:
556
+ report["path"] = paths
557
+ return {**report, "consumer": getattr(chosen, "text", chosen), "where": run.where}
558
+
559
+
560
+ _COUNTS = ("moved", "ties", "selections", "heads")
561
+
562
+
563
+ def _compare_paths(run, sides, report, consumer) -> dict[str, Any]:
564
+ """``paths.paired`` for each edit side (and A+B when it was measured): path-diverged with
565
+ the total and frozen-selection effects."""
566
+ from mdb.analysis.measure.paths import paired
567
+
568
+ if not hasattr(consumer, "row"):
569
+ raise Refused("path=true takes a margin M[a,b] or a logit consumer")
570
+ sets = {name: side.edits for name, side in sides.items() if side.edits is not None}
571
+ if "A+B" in report["effects"] and "value" in report["effects"]["A+B"]:
572
+ sets["A+B"] = [*sides["A"].edits, *sides["B"].edits]
573
+ out: dict[str, Any] = {}
574
+ for name in ("A", "B", "A+B"):
575
+ if name not in sets:
576
+ if name in sides:
577
+ out[name] = {"state": "absent", "reason": "a checkpoint side is a session state, "
578
+ "not an edit"}
579
+ continue
580
+ if any(e.cell is not None for e in sets[name]):
581
+ out[name] = {"state": "absent", "reason": "path=true takes port edits, not state "
582
+ "cells"}
583
+ continue
584
+ found = paired(run, [(e.address, e.value, e.op, e.mask) for e in sets[name]], consumer)
585
+ moved = {k: ({"value": v, "authority": "measured"} if k in _COUNTS else v)
586
+ for k, v in found["path"].items()}
587
+ out[name] = {"verdict": found["verdict"], "path": moved,
588
+ "total": found["total"]["dM"], "frozen": found["frozen"]["dM"],
589
+ "holds": found["frozen"]["holds"]}
590
+ return out
591
+
592
+
593
+ # --------------------------------------------------------------------------- seek
594
+
595
+
596
+ def _seek_within(run, address: str) -> list[str]:
597
+ """Move ``run`` to ``address``: forward with ``until``, backward by layer boundaries. All
598
+ or nothing: a target before the run's first stepped row is refused before any move, and a
599
+ failure part way restores the starting cursor."""
600
+ moves = []
601
+ key = run.parse(address)
602
+ root = run.parse(run.root)
603
+ if key < root:
604
+ if key[0] < run.prefill:
605
+ raise ValueError(run.prefilled_reason(key[0]))
606
+ raise ValueError(f"{address} is before this run's root {run.root}")
607
+ start = run.checkpoint()
608
+ try:
609
+ if key < run.parse(run.where):
610
+ while run.parse(run.where) > key:
611
+ run.reverse_step("layer")
612
+ moves.append(f"reverse-step layer to {run.where}")
613
+ if key > run.parse(run.where):
614
+ run.until(address)
615
+ moves.append(f"until {address}")
616
+ except BaseException:
617
+ from mdb.analysis.measure.compare import restore_exactly
618
+
619
+ restore_exactly(run, start)
620
+ raise
621
+ return moves
622
+
623
+
624
+ def _edit_list(run) -> dict[str, list[str]]:
625
+ """The run's committed and staged edits as text (``t<r>.L<l>.<port> <op> <value>``)."""
626
+ def text(row, entry):
627
+ value = entry["value"]
628
+ shown = value.get("value") if value.get("kind") == "scalar" else value.get("sha256",
629
+ "")[:12]
630
+ sel = f"[{entry['selection']}]" if entry.get("selection") else ""
631
+ return f"t{row}.L{entry['layer']}.{entry['port']}{sel} {entry['op']} {shown}"
632
+
633
+ row = int(_ROW.match(run.where)["row"])
634
+ return {"committed": [text(e["row"], e) for e in run.committed_edits()],
635
+ "staged": [text(row, e) for e in run.staged_info()]}
636
+
637
+
638
+ def _dropped(before: dict[str, list[str]], after: dict[str, list[str]]) -> dict[str, Any]:
639
+ """The edits a move dropped and the committed edits it turned back into staged ones."""
640
+ now = Counter(after["committed"]) + Counter(after["staged"])
641
+ dropped = list((Counter(before["committed"]) + Counter(before["staged"]) - now).elements())
642
+ restaged = list((Counter(before["committed"]) & Counter(after["staged"])).elements())
643
+ return {"dropped_edits": dropped[:16], "restaged_edits": restaged[:16]}
644
+
645
+
646
+ def _replayed(ctx, recipe_id: str):
647
+ from mdb.core import recipe as recipes
648
+
649
+ try:
650
+ return ctx.debugger.replay(recipes.load(ctx.debugger.project, recipe_id))
651
+ except (recipes.RecipeError, ValueError) as error:
652
+ raise Refused(f"the stored recipe {recipe_id[:12]} cannot be replayed here: "
653
+ f"{error}") from None
654
+
655
+
656
+ def _origin_recipe(ctx, branch: str, address: str) -> str:
657
+ """The recipe standing for origin ``branch``: a durable checkpoint of that name, or the
658
+ recipe the occurrence index (or the session cursor) of session ``branch`` holds."""
659
+ from mdb.core import index
660
+ from mdb.core import recipe as recipes
661
+
662
+ project = ctx.debugger.project
663
+ named = recipes.find_checkpoint(project, branch, session_id=ctx.debugger.session_id)
664
+ if named is not None:
665
+ return named["body"]["recipe"]
666
+ if branch in {r["session_id"] for r in project.sessions()}:
667
+ # exported occurrences are indexed under their origin-qualified address
668
+ row = index.find_occurrence(project, branch, f"{branch}:{address}",
669
+ layers=ctx.run.adapter.layers,
670
+ ports=ctx.run.program.names, global_ports=GLOBALS)
671
+ if row is not None and row["recipe_id"]:
672
+ return row["recipe_id"]
673
+ cursor = index.get_cursor(project, branch)
674
+ if cursor is not None:
675
+ return index.get_record(project, branch, cursor)["body"]["recipe"]
676
+ known = ", ".join(getattr(ctx.debugger, "runs", None) or ()) or "none"
677
+ raise Refused(f"origin {branch}: names no run (have: {known}), no durable checkpoint and no "
678
+ "session with a stored recipe in this project")
679
+
680
+
681
+ def _seek_named(ctx, name: str, plain: str):
682
+ """``seek NAME:ADDR``: make the run named ``NAME`` current (as ``frame NAME:``), then move it
683
+ to ``plain``. All or nothing: a failed move puts the previous run back as the current one."""
684
+ from .builtin import _switch
685
+
686
+ previous, target = ctx.run, ctx.debugger.runs[name]
687
+ if target is not previous:
688
+ _switch(ctx, target)
689
+ before = _edit_list(target)
690
+ try:
691
+ moves = _seek_within(target, plain)
692
+ except ValueError as error:
693
+ if target is not previous:
694
+ _switch(ctx, previous)
695
+ raise Refused(f"cannot reach {name}:{plain}: {error}") from None
696
+ return moved(ctx, {"target": plain, "moves": moves, "via": "run", "run": name,
697
+ **_dropped(before, _edit_list(target))})
698
+
699
+
700
+ def _seek(ctx, target):
701
+ from mdb.core import address as addresses
702
+ from mdb.core.pointers import RecordError, validate_occurrence_pointer
703
+
704
+ run = ctx.run
705
+ text = target.strip()
706
+ moves: list[str] = []
707
+ origin = None
708
+ if text.startswith("{"):
709
+ try:
710
+ pointer = validate_occurrence_pointer(json.loads(text), ports=run.program.names,
711
+ global_ports=GLOBALS)
712
+ except (ValueError, RecordError) as error:
713
+ raise BadArgs(f"not an occurrence pointer: {error}") from None
714
+ parsed = addresses.from_json(pointer["address"], ports=run.program.names,
715
+ global_ports=GLOBALS)
716
+ recipe_id = pointer["recipe"]
717
+ origin = "pointer"
718
+ else:
719
+ head = text.partition("[")[0]
720
+ relative = (":" not in head and not head.startswith(("@", "cache."))
721
+ and not _ROW.match(head))
722
+ # `L20.p` and `logits` mean the cursor's row, as they do for `until` and `print`
723
+ full = f"t{_ROW.match(run.where)['row']}.{text}" if relative else text
724
+ try:
725
+ parsed = addresses.parse(full, ports=run.program.names, global_ports=GLOBALS)
726
+ except addresses.AddressError as error:
727
+ raise BadArgs(f"bad address {text!r}: {error}") from None
728
+ recipe_id = None
729
+ if parsed.origin is not None:
730
+ origin = parsed.origin.branch or "@cut"
731
+ if not isinstance(parsed, addresses.Occurrence) or parsed.selector != addresses.Selector():
732
+ raise Refused("seek moves to an occurrence t<row>.<stop> (no selector, no cache cell)")
733
+ plain = addresses.format_address(addresses.Occurrence(parsed.token, parsed.port,
734
+ parsed.layer))
735
+ runs = getattr(ctx.debugger, "runs", None) or {}
736
+ named = origin if origin in runs else None # a run started with name=NAME: switch to it
737
+ if named is not None:
738
+ return _seek_named(ctx, named, plain)
739
+ own = origin is None or origin == getattr(ctx.debugger, "session_id", None)
740
+ before = _edit_list(run)
741
+ if own and recipe_id is None:
742
+ try:
743
+ moves = _seek_within(run, plain)
744
+ except ValueError as error:
745
+ if project_of(ctx) is None:
746
+ raise Refused(f"cannot reach {plain}: {error}; an occurrence outside this run "
747
+ "is reachable only through a stored recipe (attach with project= "
748
+ "and checkpoint)") from None
749
+ recipe_id = _origin_recipe(ctx, ctx.debugger.session_id, plain)
750
+ else:
751
+ return moved(ctx, {"target": plain, "moves": moves, "via": "run",
752
+ **_dropped(before, _edit_list(run))})
753
+ if project_of(ctx) is None:
754
+ raise Refused(f"{text}: no run named {origin!r} (have: {', '.join(runs) or 'none'}); "
755
+ "reaching another origin needs a stored recipe; attach with project=")
756
+ if origin == "@cut":
757
+ raise Refused("an @cut origin names no recipe; use a checkpoint name or a pointer")
758
+ if recipe_id is None:
759
+ recipe_id = _origin_recipe(ctx, origin, plain)
760
+ replayed = _replayed(ctx, recipe_id)
761
+ moves.append(f"replay recipe {recipe_id[:12]} to {replayed.where}")
762
+ try:
763
+ moves += _seek_within(replayed, plain)
764
+ except ValueError as error:
765
+ raise Refused(f"the stored recipe reaches {replayed.where}, but not {plain}: "
766
+ f"{error}") from None
767
+ from mdb.analysis.circuits import build as circuits
768
+
769
+ circuits.ledger(replayed).update(circuits.ledger(run))
770
+ ctx.set_run(replayed)
771
+ ctx.debugger.live = replayed
772
+ _bind_declared(ctx)
773
+ return moved(ctx, {"target": plain, "moves": moves, "via": "recipe",
774
+ "recipe": recipe_id, **_dropped(before, _edit_list(replayed))})
775
+
776
+
777
+ # --------------------------------------------------------------------------- registration
778
+
779
+ _CONSUMER = Arg("consumer", "str", positional=False,
780
+ help="M[a,b], logits[i] or a residual port / o address")
781
+ register(Op("reads", "Who reads a value: attention reads of a source row with mass, exact "
782
+ "contribution and a native causal verdict",
783
+ (Arg("source", "str", required=True,
784
+ help="t<r>, t<r>.L<l>.k|v or cache.L<l>.k|v[row=<r>]"),
785
+ Arg("rows", "str", positional=False, help="reader rows: R, A:B or all"),
786
+ _CONSUMER,
787
+ Arg("top", "int", default=8, minimum=1, maximum=32, positional=False,
788
+ help="reads listed with a verdict; the rest are summed"),
789
+ Arg("causal", "bool", default=True, positional=False,
790
+ help="measure each listed read's verdict natively"),
791
+ Arg("min_effect", "number", default=0.0, positional=False,
792
+ help="a measured change above this is causal")),
793
+ "navigate", True, _reads,
794
+ usage="reads SOURCE [rows=R|A:B|all] [consumer=C] [top=K] [causal=false]"),
795
+ replace=True)
796
+ register(Op("symbols", "Symbol table at the cursor: bindings with definition sites, lifetimes, "
797
+ "readers, status and an Unbound row (stored as records with a project)",
798
+ (_CONSUMER, Arg("rows", "str", positional=False, help="reader rows: R, A:B or all"),
799
+ Arg("min_mass", "number", default=0.1, positional=False,
800
+ help="a read above this mass marks the lifetime"),
801
+ Arg("readers", "int", default=3, minimum=1, maximum=8, positional=False),
802
+ Arg("offset", "int", default=0, minimum=0, positional=False),
803
+ Arg("limit", "int", default=16, minimum=1, maximum=16, positional=False),
804
+ Arg("sets", "str", positional=False,
805
+ help="candidate sets for content readouts: NAME[,NAME...] (candidates op)"),
806
+ Arg("truth", "str", positional=False,
807
+ help="SET:TOKEN|WORD[,...]: each set's true token ($var in each)"),
808
+ Arg("content_layers", "bool", default=False, positional=False,
809
+ help="a per-layer content strip per set"),
810
+ Arg("hops", "str", positional=False,
811
+ help="NAME:NATIVE:DIRECT[,...]: measured hop deltas -> indirect share"),
812
+ Arg("sink", "str", positional=False,
813
+ help="sink rows for mass_nonsink: R[,R...] or none (default 0)"),
814
+ Arg("co", "str", positional=False,
815
+ help="TARGET/OTHER[:K][,...]: read TARGET with OTHER's whole span removed"),
816
+ Arg("lexical_null", "bool", default=False, positional=False,
817
+ help="the truth token's own readout per set"),
818
+ Arg("switch", "str", positional=False,
819
+ help="TARGET:ON[,...]: TARGET's truth = the word paired with ON's decoded "
820
+ "word"),
821
+ Arg("labels", "str", positional=False, help="KEY:VALUE[,...] item labels"),
822
+ Arg("derive", "str", positional=False,
823
+ help="KEY:PATH[,...] derived labels (e.g. dec:content.countries.best)"),
824
+ Arg("foreign", "bool", default=False, positional=False,
825
+ help="TransformerLens / nnsight / pyvene names per binding and read"),
826
+ Arg("causal", "str", positional=False,
827
+ help="true|mask|zero: measure each listed binding's causal liveness"),
828
+ Arg("min_effect", "number", default=0.0, positional=False,
829
+ help="causal: a change above this (and the floor) is an effect")),
830
+ "mutate", True, _symbols,
831
+ usage="symbols [consumer=C] [rows=R|A:B|all] [min_mass=X] [offset=N] [limit=N] "
832
+ "[sets=A,B truth=A:$x content_layers=true lexical_null=true co=B/A[:K] "
833
+ "switch=B:A] [hops=N:NAT:DIR] [sink=0|none] [labels=K:V derive=K:PATH] "
834
+ "[foreign=true] [causal=true|mask|zero min_effect=X]"),
835
+ replace=True)
836
+ register(Op("candidates", "Declare a candidate set for content readouts (candidates NAME = "
837
+ "FILE|W1,W2,...|#ID,... [rule=first|single] [paired=SET]): token pieces, "
838
+ "first-subword and collision flags, sha256 provenance; candidates show|delete NAME, "
839
+ "candidates list",
840
+ (Arg("name", "str"),
841
+ Arg("source", "str", positional=False,
842
+ help="a file (JSON words / {words, pairs} / one per line), words, or #ids"),
843
+ Arg("action", "choice", default="declare",
844
+ choices=("declare", "show", "delete", "list"), positional=False),
845
+ Arg("rule", "choice", default="first", choices=("first", "single"),
846
+ positional=False, help="first: rank the first piece; single: refuse "
847
+ "multi-piece words"),
848
+ Arg("paired", "str", positional=False,
849
+ help="a declared set whose words pair with these (parallel lists), for "
850
+ "switch=")),
851
+ "mutate", False, _candidates,
852
+ usage="candidates NAME = FILE|W1,W2,...|#ID,... [rule=first|single] [paired=SET] | "
853
+ "candidates show|delete NAME | candidates list"))
854
+ register(Op("symbol", "Declare a user symbol over cache rows (symbol NAME = ADDR[,ADDR...]), or a "
855
+ "named symbol from a transplant result (symbol NAME = whatif|compare.a|compare.b|"
856
+ "EACH:ITEM): its role, source row, readers and measured effect, usable as an "
857
+ "address; symbol show|delete NAME",
858
+ (Arg("name", "str", required=True),
859
+ Arg("addresses", "str", positional=False, help="cache cells: ADDR[,ADDR...]"),
860
+ Arg("result", "str", positional=False,
861
+ help="whatif, compare.a, compare.b (the last of this session) or EACH:ITEM "
862
+ "(an each result's item)"),
863
+ Arg("action", "choice", default="declare", choices=("declare", "show", "delete"),
864
+ positional=False),
865
+ Arg("role", "str", positional=False,
866
+ help="the source row's role when several (or none) name it"),
867
+ Arg("readers", "int", default=6, minimum=1, maximum=named.MAX_READERS,
868
+ positional=False, help="readers listed from reads (top K)"),
869
+ Arg("causal", "bool", default=True, positional=False,
870
+ help="measure each listed reader's causal verdict natively")),
871
+ "mutate", False, _symbol,
872
+ usage="symbol NAME = ADDR[,ADDR...] | symbol NAME = whatif|compare.a|compare.b|"
873
+ "EACH:ITEM [role=R] [readers=K] [causal=false] | symbol show|delete NAME"),
874
+ replace=True)
875
+ register(Op("circuit", "Circuit records: build from the exact decomposition (nodes, edges, "
876
+ "remainder), test by native patching from a reference run, show as a walk",
877
+ (Arg("target", "str", required=True, help="a consumer, or test / show"),
878
+ Arg("id", "int", minimum=1),
879
+ Arg("top", "int", default=4, minimum=1, maximum=8, positional=False),
880
+ Arg("depth", "int", default=2, minimum=1, maximum=3, positional=False),
881
+ Arg("node", "str", positional=False,
882
+ help="circuit show ID: the node whose page to read (n12), for a group "
883
+ "the record stores as a child page"),
884
+ Arg("ref", "str", positional=False,
885
+ help="circuit test ID: the reference run whose values are patched in (a run "
886
+ "name, or set:NAME for a prompt set's per-component mean)")),
887
+ "mutate", True, _circuit,
888
+ usage="circuit CONSUMER [top=K] [depth=D] | circuit test ID ref=NAME|set:NAME | "
889
+ "circuit show ID [node=NODEID]"),
890
+ replace=True)
891
+ register(Op("compare", "Compare branches: base, A, B and A+B measured natively, effects and "
892
+ "the interaction",
893
+ (Arg("a", "str", required=True, help="ADDR=VALUE [op] or a checkpoint name"),
894
+ Arg("b", "str", required=True, help="ADDR=VALUE [op] or a checkpoint name"),
895
+ _CONSUMER,
896
+ Arg("path", "bool", default=False, positional=False,
897
+ help="also run each edit side free and with downstream p held at the base "
898
+ "(paths.paired): path-diverged, total and frozen-selection effects")),
899
+ "navigate", True, _compare,
900
+ usage="compare A B [consumer=C] [path=true] (A, B: ADDR=VALUE [op] or a checkpoint "
901
+ "name)"),
902
+ replace=True)
903
+ register(Op("seek", "Move the session to an occurrence: forward, backward, or by replaying a "
904
+ "stored recipe (ORIGIN:ADDR or an occurrence pointer)",
905
+ (Arg("target", "str", required=True),), "navigate", True, _seek,
906
+ usage="seek ADDR | seek ORIGIN:ADDR | seek POINTER-JSON"), replace=True)