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/lines.py ADDED
@@ -0,0 +1,496 @@
1
+ """Command lines -> op arguments: the one parser of the REPL's command language.
2
+
3
+ ``parse(name, text)`` turns the text after a verb into the op's JSON args; ``resolve_verb``
4
+ resolves aliases and unique prefixes. It lives in ``mdb.ops`` (moved unchanged from
5
+ ``mdb.repl.shell``, which re-exports it) so an op that runs another op line, ``each``, and the
6
+ embedding API ``Debugger.each`` parse with the same code as the REPL. Nothing here evaluates
7
+ an expression or loads a model library.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+ from typing import Any
15
+
16
+ from .errors import BadArgs, UnknownOp
17
+ from .predict import parse_assignment
18
+ from .registry import registry
19
+
20
+ ALIASES = {
21
+ "s": "step", "n": "next", "c": "continue", "b": "break", "p": "print", "bt": "backtrace",
22
+ "u": "until", "d": "delete", "i": "info", "l": "list", "r": "run", "q": "quit",
23
+ "h": "help", "rs": "reverse-step", "rn": "reverse-next", "rc": "reverse-continue",
24
+ "where": "where", "exit": "quit",
25
+ }
26
+ _INT = re.compile(r"-?\d+")
27
+ _KEYWORD = re.compile(r"(?P<key>[a-z_]+)=(?P<value>.*)", re.S)
28
+
29
+
30
+ # --------------------------------------------------------------------------- tokenizing
31
+
32
+
33
+ def split(text: str) -> list[tuple[str, int, int]]:
34
+ """Whitespace-separated words, keeping ``[...]`` and quoted text together.
35
+
36
+ Returns ``(word, start, end)``; a word that is wholly a quoted string loses its quotes.
37
+ """
38
+ words, i, n = [], 0, len(text)
39
+ while i < n:
40
+ while i < n and text[i].isspace():
41
+ i += 1
42
+ if i >= n:
43
+ break
44
+ start, depth, quote = i, 0, None
45
+ while i < n:
46
+ char = text[i]
47
+ if quote:
48
+ if char == "\\" and i + 1 < n:
49
+ i += 2
50
+ continue
51
+ if char == quote:
52
+ quote = None
53
+ elif char in "\"'":
54
+ quote = char
55
+ elif char == "[":
56
+ depth += 1
57
+ elif char == "]":
58
+ depth = max(0, depth - 1)
59
+ elif char.isspace() and depth == 0:
60
+ break
61
+ i += 1
62
+ if quote:
63
+ raise BadArgs(f"unterminated quote in {text[start:]!r}")
64
+ word = text[start:i]
65
+ if len(word) >= 2 and word[0] == word[-1] and word[0] in "\"'":
66
+ word = json.loads(word) if word[0] == '"' else word[1:-1]
67
+ words.append((word, start, i))
68
+ return words
69
+
70
+
71
+ def _after(text: str, words: list[tuple[str, int, int]], index: int) -> str:
72
+ return text[words[index][1]:].strip() if index < len(words) else ""
73
+
74
+
75
+ def _convert(arg: Any, raw: str) -> Any:
76
+ kind = arg.type
77
+ if kind == "int":
78
+ if not _INT.fullmatch(raw):
79
+ raise BadArgs(f"{arg.name} must be an integer, got {raw!r}")
80
+ return int(raw)
81
+ if kind == "number":
82
+ try:
83
+ return float(raw)
84
+ except ValueError:
85
+ raise BadArgs(f"{arg.name} must be a number, got {raw!r}") from None
86
+ if kind == "bool":
87
+ if raw.lower() not in ("true", "false", "on", "off", "1", "0"):
88
+ raise BadArgs(f"{arg.name} must be true or false")
89
+ return raw.lower() in ("true", "on", "1")
90
+ if kind == "choice":
91
+ found = [c for c in arg.choices if str(c).startswith(raw)]
92
+ exact = [c for c in arg.choices if str(c) == raw]
93
+ if exact:
94
+ return exact[0]
95
+ if len(found) != 1:
96
+ raise BadArgs(f"{arg.name} is one of {', '.join(map(str, arg.choices))}")
97
+ return found[0]
98
+ if kind == "ints":
99
+ items = raw.split()
100
+ if not all(_INT.fullmatch(item) for item in items):
101
+ raise BadArgs(f"{arg.name} takes integers")
102
+ return [int(item) for item in items]
103
+ if kind == "value":
104
+ try:
105
+ return float(raw)
106
+ except ValueError:
107
+ return raw
108
+ return raw
109
+
110
+
111
+ def _generic(op: Any, text: str) -> dict[str, Any]:
112
+ args: dict[str, Any] = {}
113
+ known = {arg.name: arg for arg in op.args}
114
+ positional = [arg for arg in op.args if arg.positional]
115
+ for word, _, _ in split(text):
116
+ match = _KEYWORD.fullmatch(word)
117
+ if match and match["key"] in known:
118
+ args[match["key"]] = _convert(known[match["key"]], match["value"])
119
+ continue
120
+ if positional and positional[0].type == "ints":
121
+ args.setdefault(positional[0].name, []).extend(
122
+ _convert(positional[0], word))
123
+ continue
124
+ # A choice word may land in a later positional slot: "step layer", "step 3 layer".
125
+ slot = None
126
+ for arg in positional:
127
+ if arg.type == "choice" and any(str(c).startswith(word) for c in arg.choices) \
128
+ and not _INT.fullmatch(word):
129
+ slot = arg
130
+ break
131
+ if slot is None:
132
+ if not positional:
133
+ raise BadArgs(f"{op.name} takes no argument {word!r}")
134
+ slot = positional[0]
135
+ positional.remove(slot)
136
+ args[slot.name] = _convert(slot, word)
137
+ return args
138
+
139
+
140
+ def _prompt_args(text: str) -> dict[str, Any]:
141
+ args: dict[str, Any] = {}
142
+ words = split(text)
143
+ rest = []
144
+ for word, _, _ in words:
145
+ match = _KEYWORD.fullmatch(word)
146
+ if match and match["key"] in ("budget", "prefill", "retain_rows"):
147
+ if not _INT.fullmatch(match["value"]):
148
+ raise BadArgs(f"{match['key']} must be an integer, got {match['value']!r}")
149
+ args[match["key"]] = int(match["value"])
150
+ elif match and match["key"] == "lookahead":
151
+ args["lookahead"] = match["value"]
152
+ elif match and match["key"] in ("name", "from") and not rest:
153
+ args[match["key"]] = match["value"]
154
+ elif match and match["key"] == "verify" and "from" in args and not rest:
155
+ if match["value"] not in ("true", "false", "report"):
156
+ raise BadArgs("verify is true, false or report")
157
+ args["verify"] = match["value"]
158
+ else:
159
+ rest.append(word)
160
+ if rest:
161
+ if all(_INT.fullmatch(word) for word in rest):
162
+ args["prompt"] = [int(word) for word in rest]
163
+ else:
164
+ args["prompt"] = " ".join(rest)
165
+ return args
166
+
167
+
168
+ def _break_args(text: str) -> dict[str, Any]:
169
+ words = split(text)
170
+ if not words:
171
+ raise BadArgs("break needs an address pattern, e.g. break L*.p")
172
+ args: dict[str, Any] = {"pattern": words[0][0]}
173
+ if len(words) > 1:
174
+ if words[1][0] != "if":
175
+ raise BadArgs("write break PATTERN [if CONDITION]")
176
+ args["condition"] = _after(text, words, 2)
177
+ return args
178
+
179
+
180
+ def _watch_args(text: str) -> dict[str, Any]:
181
+ words = split(text)
182
+ if not words:
183
+ raise BadArgs("watch needs an address, e.g. watch L0.h[d=3]")
184
+ args: dict[str, Any] = {"address": words[0][0]}
185
+ index = 1
186
+ if index < len(words) and words[index][0] in ("change", "level", "edge"):
187
+ args["mode"] = words[index][0]
188
+ index += 1
189
+ if index < len(words):
190
+ if words[index][0] != "if":
191
+ raise BadArgs("write watch ADDR [change|level|edge] [if PREDICATE]")
192
+ args["predicate"] = _after(text, words, index + 1)
193
+ return args
194
+
195
+
196
+ def _equals_outside_brackets(word: str) -> int:
197
+ """Index of the first ``=`` that is not inside ``[...]`` or quotes, else -1."""
198
+ depth, quote = 0, None
199
+ for i, char in enumerate(word):
200
+ if quote:
201
+ quote = None if char == quote else quote
202
+ elif char in "\"'":
203
+ quote = char
204
+ elif char == "[":
205
+ depth += 1
206
+ elif char == "]":
207
+ depth = max(0, depth - 1)
208
+ elif char == "=" and depth == 0:
209
+ return i
210
+ return -1
211
+
212
+
213
+ _SET_USAGE = "set ADDR = VALUE [replace|add|scale|mix DOSE] (or ADDR += X, -=, *=, /=)"
214
+ _SUGAR = ("+=", "-=", "*=", "/=")
215
+
216
+
217
+ def _set_args(text: str) -> dict[str, Any]:
218
+ """``ADDR = VALUE [OP [DOSE]]``, ``ADDR VALUE [OP]`` or ``ADDR += X`` (``-= *= /=``), via
219
+ ``mdb.ops.predict.parse_assignment`` (parsed, never evaluated)."""
220
+ words = [word for word, _, _ in split(text)]
221
+ if not words:
222
+ raise BadArgs(f"write {_SET_USAGE}")
223
+ joined = " ".join(words)
224
+ if _equals_outside_brackets(joined) < 0:
225
+ joined = " ".join([words[0], "=", *words[1:]])
226
+ target, value, op, dose = parse_assignment(joined, usage=_SET_USAGE)
227
+ args: dict[str, Any] = {"target": target, "value": value}
228
+ if op is not None:
229
+ args["op"] = op
230
+ if dose is not None:
231
+ args["dose"] = dose
232
+ return args
233
+
234
+
235
+ _WHATIF_USAGE = ("write whatif ADDR = VALUE [replace|add|scale|mix DOSE] --consumer "
236
+ "M[a,b]|logits[i]|ADDR [path=true] | whatif ADDR donors=RUN,...|PATTERN "
237
+ "--consumer C [path=true]")
238
+
239
+
240
+ def _whatif_args(text: str) -> dict[str, Any]:
241
+ """``whatif ADDR = VALUE [OP] --consumer C``; ``consumer=C`` is accepted too. ``whatif ADDR
242
+ donors=NAMES --consumer C`` takes each donor run's value at ADDR."""
243
+ words = split(text)
244
+ consumer, kept, i, path, donors = None, [], 0, False, None
245
+ while i < len(words):
246
+ word = words[i][0]
247
+ if word == "--consumer" and i + 1 < len(words):
248
+ consumer, i = words[i + 1][0], i + 2
249
+ elif word.startswith(("consumer=", "--consumer=")):
250
+ consumer, i = word.split("=", 1)[1], i + 1
251
+ elif word.startswith("path="):
252
+ path, i = word.split("=", 1)[1].lower() in ("true", "1", "yes"), i + 1
253
+ elif word.startswith("donors="):
254
+ donors, i = word.split("=", 1)[1], i + 1
255
+ else:
256
+ kept.append(words[i])
257
+ i += 1
258
+ if not consumer or not kept:
259
+ raise BadArgs(_WHATIF_USAGE)
260
+ extra = {"consumer": consumer, **({"path": True} if path else {})}
261
+ if donors is not None:
262
+ if len(kept) != 1 or not donors:
263
+ raise BadArgs(_WHATIF_USAGE)
264
+ return {"target": kept[0][0], "donors": donors, **extra}
265
+ try:
266
+ args = _set_args(" ".join(text[start:end] for _, start, end in kept))
267
+ except BadArgs:
268
+ raise BadArgs(_WHATIF_USAGE) from None
269
+ return {**args, **extra}
270
+
271
+
272
+ def _up_args(text: str) -> dict[str, Any]:
273
+ args: dict[str, Any] = {}
274
+ for word, _, _ in split(text):
275
+ if _INT.fullmatch(word):
276
+ args["n"] = int(word)
277
+ elif "port" not in args:
278
+ args["port"] = word
279
+ else:
280
+ raise BadArgs("write up [N] [PORT]")
281
+ return args
282
+
283
+
284
+ def _condition_args(text: str) -> dict[str, Any]:
285
+ words = split(text)
286
+ if not words or not _INT.fullmatch(words[0][0]):
287
+ raise BadArgs("write condition N [EXPR] (no EXPR removes the condition)")
288
+ args: dict[str, Any] = {"id": int(words[0][0])}
289
+ expr = _after(text, words, 1)
290
+ if expr:
291
+ args["expr"] = expr
292
+ return args
293
+
294
+
295
+ def _consumer_option(text: str) -> tuple[str | None, str]:
296
+ """Take ``consumer=C`` (or ``--consumer C``, ``--consumer=C``) out of a command line."""
297
+ words = split(text)
298
+ consumer, kept, i = None, [], 0
299
+ while i < len(words):
300
+ word = words[i][0]
301
+ if word == "--consumer" and i + 1 < len(words):
302
+ consumer, i = words[i + 1][0], i + 2
303
+ elif word.startswith(("consumer=", "--consumer=")):
304
+ consumer, i = word.split("=", 1)[1], i + 1
305
+ else:
306
+ kept.append(words[i])
307
+ i += 1
308
+ return consumer, " ".join(text[start:end] for _, start, end in kept)
309
+
310
+
311
+ def _with_consumer(name: str):
312
+ """The generic parser of ``name`` that also takes ``--consumer C``."""
313
+ def parse_args(text: str) -> dict[str, Any]:
314
+ consumer, rest = _consumer_option(text)
315
+ args = _generic(registry()[name], rest)
316
+ if consumer is not None:
317
+ args["consumer"] = consumer
318
+ return args
319
+
320
+ return parse_args
321
+
322
+
323
+ _COMPARE_USAGE = ("write compare A B [consumer=C] [path=true]; a side is ADDR=VALUE [op] (ADDR += X ...) "
324
+ "or a checkpoint")
325
+ _OP_WORDS = ("replace", "add", "scale", "mix")
326
+
327
+
328
+ def _compare_args(text: str) -> dict[str, Any]:
329
+ """``compare A B [consumer=C]`` (or ``--consumer C``): a side is ``ADDR=VALUE
330
+ [replace|add|scale|mix DOSE]`` (spaces around ``=`` allowed; ``ADDR += X`` and the other
331
+ sugar too) or a checkpoint name."""
332
+ consumer, rest = _consumer_option(text)
333
+ args: dict[str, Any] = {}
334
+ words = []
335
+ for word, _, _ in split(rest):
336
+ if word.startswith("path="):
337
+ args["path"] = word.split("=", 1)[1].lower() in ("true", "1", "yes")
338
+ else:
339
+ words.append(word)
340
+ sides: list[list[str]] = []
341
+ i = 0
342
+ while i < len(words):
343
+ word = words[i]
344
+ if i + 2 < len(words) and words[i + 1] in ("=", *_SUGAR):
345
+ word, i = f"{word}{words[i + 1]}{words[i + 2]}", i + 2
346
+ elif word.endswith(("=", *_SUGAR)) and _equals_outside_brackets(word) == len(word) - 1 \
347
+ and i + 1 < len(words):
348
+ word, i = f"{word}{words[i + 1]}", i + 1
349
+ last = sides[-1] if sides else None
350
+ if last and _equals_outside_brackets(last[0]) > 0 and word in _OP_WORDS \
351
+ and len(last) == 1:
352
+ last.append(word)
353
+ if word == "mix" and i + 1 < len(words):
354
+ last.append(words[i + 1])
355
+ i += 1
356
+ else:
357
+ sides.append([word])
358
+ i += 1
359
+ if len(sides) != 2:
360
+ raise BadArgs(_COMPARE_USAGE)
361
+ args.update(a=" ".join(sides[0]), b=" ".join(sides[1]))
362
+ if consumer is not None:
363
+ args["consumer"] = consumer
364
+ return args
365
+
366
+
367
+ def _symbol_args(text: str) -> dict[str, Any]:
368
+ """``symbol NAME = ADDR[,ADDR...]``; ``symbol NAME = whatif|compare.a|compare.b|EACH:ITEM
369
+ [role=R] [readers=K] [causal=false]`` (a named symbol from a transplant result);
370
+ ``symbol show|delete NAME``."""
371
+ from . import named
372
+
373
+ words = text.split()
374
+ if len(words) == 2 and words[0] in ("show", "delete"):
375
+ return {"action": words[0], "name": words[1]}
376
+ name, equals, addresses = text.partition("=")
377
+ if not equals or not name.strip() or not addresses.strip():
378
+ raise BadArgs("write symbol NAME = ADDR[,ADDR...], symbol NAME = whatif|compare.a|"
379
+ "compare.b|EACH:ITEM, or symbol show|delete NAME")
380
+ first, _, rest = addresses.strip().partition(" ")
381
+ if named.is_reference(first):
382
+ return {"name": name.strip(), "result": first, **named.parse_args(rest)}
383
+ return {"name": name.strip(), "addresses": addresses.strip()}
384
+
385
+
386
+ def _candidates_args(text: str) -> dict[str, Any]:
387
+ """``candidates NAME = SOURCE [rule=R] [paired=SET]``; ``candidates show|delete NAME``;
388
+ ``candidates list``."""
389
+ words = text.split()
390
+ if words == ["list"]:
391
+ return {"action": "list"}
392
+ if len(words) == 2 and words[0] in ("show", "delete"):
393
+ return {"action": words[0], "name": words[1]}
394
+ name, equals, rest = text.partition("=")
395
+ if not equals or not name.strip() or not rest.strip():
396
+ raise BadArgs("write candidates NAME = FILE|W1,W2,...|#ID,... [rule=first|single] "
397
+ "[paired=SET], candidates show|delete NAME or candidates list")
398
+ parts = rest.split()
399
+ options = {}
400
+ while parts and re.fullmatch(r"(rule|paired)=\S+", parts[-1]):
401
+ key, _, value = parts.pop().partition("=")
402
+ options[key] = value
403
+ return {"name": name.strip(), "source": " ".join(parts), **options}
404
+
405
+
406
+ SPECIAL = {
407
+ "start": _prompt_args,
408
+ "run": _prompt_args,
409
+ "break": _break_args,
410
+ "tbreak": _break_args,
411
+ "watch": _watch_args,
412
+ "set": _set_args,
413
+ "whatif": _whatif_args,
414
+ "up": _up_args,
415
+ "condition": _condition_args,
416
+ "reads": _with_consumer("reads"),
417
+ "symbols": _with_consumer("symbols"),
418
+ "circuit": _with_consumer("circuit"),
419
+ "features": _with_consumer("features"),
420
+ "compare": _compare_args,
421
+ "symbol": _symbol_args,
422
+ "candidates": _candidates_args,
423
+ }
424
+
425
+
426
+ def parse(name: str, text: str) -> dict[str, Any]:
427
+ """Command-line text -> the op's JSON args."""
428
+ if name in SPECIAL:
429
+ return SPECIAL[name](text)
430
+ found = registry()[name]
431
+ if found.extra.get("accepts_any"):
432
+ return {}
433
+ return _generic(found, text)
434
+
435
+
436
+ WHY = ("there is no `why` verb; to ask why an output came out as it did: `explain M[a,b]` "
437
+ "(at the logits) splits the margin exactly into its contributions, `backtrace` lists the "
438
+ "producer chain of the focus port, `reads SOURCE --consumer C` finds the attention reads "
439
+ "that carry a row into a consumer, `circuit C` builds the circuit behind it")
440
+
441
+
442
+ def resolve_verb(word: str, local: tuple[str, ...] = ()) -> str:
443
+ """A verb as typed -> its op name: exact, alias, or unique prefix (``local`` adds the
444
+ REPL's own commands to the candidates)."""
445
+ ops = registry()
446
+ if word in ops or word in local:
447
+ return word
448
+ if word in ALIASES:
449
+ return ALIASES[word]
450
+ names = sorted(set(ops) | set(local))
451
+ found = [name for name in names if name.startswith(word)]
452
+ if len(found) == 1:
453
+ return found[0]
454
+ if not found:
455
+ raise UnknownOp(f'undefined command "{word}"; ' + (WHY if word == "why" else 'try "help"'))
456
+ raise UnknownOp(f'ambiguous command "{word}": {", ".join(found)}')
457
+
458
+
459
+ def route(name: str, rest: str) -> tuple[str, str]:
460
+ """``set load NAME FILE``, ``set define NAME JSON`` and ``set show NAME`` are the
461
+ ``promptset`` op (no address is named ``load``, ``define`` or ``show``); every other line
462
+ keeps its verb."""
463
+ words = rest.split(None, 1)
464
+ if name == "set" and words and words[0] in ("load", "define", "show"):
465
+ return "promptset", rest
466
+ return name, rest
467
+
468
+
469
+ _EACH_USAGE = ("write each SET [at=ADDR] [prefill=K|@ROLE] [shard=K/N] [keep]: OP LINE "
470
+ "[; OP LINE ...]")
471
+
472
+
473
+ def _each_args(text: str) -> dict[str, Any]:
474
+ """``each SET [at=ADDR] [prefill=K|@ROLE] [keep]: LINE``: the set and options before the
475
+ first ``:``, the op line(s) after it, kept as text (the op parses them once, as a
476
+ template)."""
477
+ head, colon, line = text.partition(":")
478
+ words = head.split()
479
+ if not colon or not words or not line.strip():
480
+ raise BadArgs(_EACH_USAGE)
481
+ args: dict[str, Any] = {"set": words[0], "line": line.strip()}
482
+ for word in words[1:]:
483
+ if word == "keep":
484
+ args["keep"] = True
485
+ elif word.startswith("at="):
486
+ args["at"] = word[3:]
487
+ elif word.startswith("prefill=") and len(word) > 8:
488
+ args["prefill"] = word[8:]
489
+ elif word.startswith("shard=") and len(word) > 6:
490
+ args["shard"] = word[6:]
491
+ else:
492
+ raise BadArgs(_EACH_USAGE)
493
+ return args
494
+
495
+
496
+ SPECIAL["each"] = _each_args