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/builtin.py ADDED
@@ -0,0 +1,1977 @@
1
+ """The built-in ops over ``mdb.engine.Run``. Import is torch-free; each op imports the engine
2
+ when it runs.
3
+
4
+ Addresses accepted by ops (``ADDR``): a canonical occurrence ``t3.L0.p[h0,src=2]``, the same
5
+ without the row (the cursor's row), a bare port of the focus/cursor layer (``p[h0]``), a
6
+ global (``emb fn logits sample start``), or a cache cell ``cache.L0.v[kv0,row=2]`` read at the
7
+ current clock. A target with an origin (``boiling:...``, ``@cut+edit:...``) and ``~program`` are
8
+ refused; a run is switched to with ``frame NAME:``.
9
+
10
+ State cells: ``set cache.L1.v[kv0,row=2] = VALUE [replace|add|scale|mix DOSE]`` stages a cell
11
+ edit (``Run.set_cell``). VALUE is a number, an address of this run, or ``ORIGIN:ADDR`` (a cache
12
+ cell or a ``v``/``kr`` occurrence of another named run, project session or checkpoint;
13
+ ``Debugger.cell_value``).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import math
20
+ import re
21
+ from dataclasses import dataclass, replace
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from mdb.core import address as addresses
26
+ from mdb.core.records import num
27
+
28
+ from . import graph
29
+ from .errors import BadArgs, Refused
30
+ from .registry import Arg, op, slot
31
+
32
+ GLOBALS = (*addresses.DEFAULT_GLOBALS, "start")
33
+ _ROW = re.compile(r"t(?P<row>\d+)\.(?P<rest>.+)")
34
+ _LAYER_PORT = re.compile(r"L(?P<layer>\d+)\.(?P<port>\w+)")
35
+ STATS = ("norm", "min", "max", "mean", "abs_max")
36
+ MAX_DISPLAYS = 8
37
+ MAX_CHECKPOINTS = 4096
38
+ MAX_CHECKPOINT_NAME = 64 # characters
39
+ STEP_CAP = 4096 # most units one step/next/reverse-step may take
40
+ PAGE = 32 # default page size of every list; 64 is the most one result may hold
41
+ GLOBAL_OPERATORS = {
42
+ "start": "tokens of the context so far (before the pending row is embedded)",
43
+ "emb": "emb = embed(token)",
44
+ "fn": "fn = final_norm(h_out of the last layer)",
45
+ "logits": "logits = lm_head(fn)",
46
+ "sample": "sample = argmax(logits) (greedy)",
47
+ }
48
+
49
+
50
+ def _bp():
51
+ from mdb.engine import breakpoints
52
+
53
+ return breakpoints
54
+
55
+
56
+ def _num(value: Any, authority: str = "measured") -> dict[str, Any]:
57
+ """A labelled number; a NaN/Inf has no honest numeric claim, so it is an unresolved field
58
+ that says which non-finite value it was."""
59
+ if isinstance(value, float) and not math.isfinite(value):
60
+ return _unresolved(f"non-finite value ({'nan' if value != value else str(value)})")
61
+ return num(value, authority)
62
+
63
+
64
+ # Run.read_info says "derived" for a replica recomputed from a supplied value; the record
65
+ # vocabulary (mdb.core.pointers.AUTHORITIES) has no bare "derived".
66
+ _AUTHORITY = {"measured": "measured", "supplied": "supplied", "derived": "derived-exact",
67
+ "derived-exact": "derived-exact", "derived-local": "derived-local",
68
+ "bound": "bound"}
69
+
70
+
71
+ def _unresolved(reason: str) -> dict[str, str]:
72
+ """A field that was requested but could not be computed (never silently dropped)."""
73
+ return {"state": "unresolved", "reason": reason}
74
+
75
+
76
+ def _page(items: list, offset: int, limit: int) -> tuple[list, dict[str, int]]:
77
+ """One page of a list: the slice and ``total``/``offset``/``limit`` (never a refusal for
78
+ length; an ``offset`` past the end is an empty page)."""
79
+ return items[offset:offset + limit], {"total": len(items), "offset": offset, "limit": limit}
80
+
81
+
82
+ _OFFSET = Arg("offset", "int", default=0, minimum=0, positional=False, help="first item of the page")
83
+ _LIMIT = Arg("limit", "int", default=PAGE, minimum=1, maximum=64, positional=False,
84
+ help="items per page (default 32, at most 64)", configurable=True)
85
+
86
+
87
+ def _labelled(key: str, value: Any) -> Any:
88
+ """Plain JSON with every number labelled (measured) unless it is a structural integer."""
89
+ from .registry import INTEGER_KEYS
90
+
91
+ if isinstance(value, bool) or value is None or isinstance(value, str):
92
+ return value
93
+ if isinstance(value, int) and key in INTEGER_KEYS:
94
+ return value
95
+ if isinstance(value, (int, float)):
96
+ return _num(value)
97
+ if isinstance(value, dict):
98
+ return {k: _labelled(k, v) for k, v in value.items()}
99
+ if isinstance(value, (list, tuple)):
100
+ return [_labelled(key, v) for v in value]
101
+ return str(value)
102
+
103
+
104
+ # --------------------------------------------------------------------------- addresses
105
+
106
+
107
+ @dataclass
108
+ class Target:
109
+ text: str
110
+ run_target: str | None
111
+ row: int | None
112
+ label: str | None
113
+ selector: addresses.Selector
114
+ cell: addresses.StateCell | None = None
115
+
116
+ @property
117
+ def layer_port(self) -> tuple[int, str] | None:
118
+ if self.label is None:
119
+ return None
120
+ match = _LAYER_PORT.fullmatch(self.label)
121
+ return None if match is None else (int(match["layer"]), match["port"])
122
+
123
+
124
+ def _program(ctx):
125
+ if ctx.run is not None:
126
+ return ctx.run.program
127
+ if ctx.debugger is None:
128
+ raise Refused("no model attached")
129
+ return ctx.debugger.program
130
+
131
+
132
+ def _split(where: str) -> tuple[int, str]:
133
+ match = _ROW.fullmatch(where)
134
+ return int(match["row"]), match["rest"]
135
+
136
+
137
+ def _current_layer(ctx) -> int | None:
138
+ for text in (ctx.focus, ctx.run.where):
139
+ if text:
140
+ match = _LAYER_PORT.search(text)
141
+ if match is not None:
142
+ return int(match["layer"])
143
+ return ctx.run.pending_layer
144
+
145
+
146
+ def resolve_target(ctx, text: str | None) -> Target:
147
+ run = ctx.run
148
+ program = run.program
149
+ text = (text or "").strip() or ctx.focus or run.where
150
+ if "~" in text:
151
+ raise Refused("a ~program pointer is not a value this verb can read; read the stop itself "
152
+ "(print ADDR)")
153
+ base, bracket, tail = text.partition("[")
154
+ if ":" in base or base.startswith("@"):
155
+ raise Refused("an address in another run or cut (NAME:ADDR, @cut+edit:ADDR) cannot be "
156
+ "read with this verb; use it as an edit value (set ADDR = NAME:ADDR), or "
157
+ "move to that run with `frame NAME:`")
158
+ if base.startswith("cache."):
159
+ try:
160
+ cell = addresses.parse(text, ports=program.names, global_ports=GLOBALS)
161
+ except addresses.AddressError as error:
162
+ raise BadArgs(f"bad address {text!r}: {error}") from None
163
+ if cell.layer >= run.adapter.layers:
164
+ raise BadArgs(f"no layer {cell.layer} in a {run.adapter.layers}-layer model")
165
+ return Target(addresses.format_address(cell), None, None, None, cell.selector, cell)
166
+ match = _ROW.fullmatch(base)
167
+ row = int(match["row"]) if match else _split(run.where)[0]
168
+ rest = match["rest"] if match else base
169
+ if rest in program.names:
170
+ layer = _current_layer(ctx)
171
+ if layer is None:
172
+ raise Refused(f"bare port {rest!r} needs a layer here; write L<i>.{rest}")
173
+ label = f"L{layer}.{rest}"
174
+ elif rest in GLOBALS or _LAYER_PORT.fullmatch(rest):
175
+ label = rest
176
+ else:
177
+ raise BadArgs(
178
+ f"bad address {text!r}: expected t<row>.L<i>.<port>, L<i>.<port>, a port "
179
+ f"({', '.join(program.names)}), a global ({', '.join(GLOBALS)}) or cache.L<i>.k|v"
180
+ )
181
+ try:
182
+ parsed = addresses.parse(
183
+ f"t{row}.{label}{bracket}{tail}", ports=program.names, global_ports=GLOBALS
184
+ )
185
+ except addresses.AddressError as error:
186
+ raise BadArgs(f"bad address {text!r}: {error}") from None
187
+ if parsed.port == "M":
188
+ raise Refused("M[a,b] is a derived value, not a stop or a port: read it with print, x or "
189
+ "display, analyse it with explain, forecast, whatif or compare")
190
+ layer_port = _LAYER_PORT.fullmatch(label)
191
+ if layer_port is not None and int(layer_port["layer"]) >= run.adapter.layers:
192
+ raise BadArgs(f"no layer {layer_port['layer']} in a {run.adapter.layers}-layer model")
193
+ return Target(
194
+ addresses.format_address(parsed), f"t{row}.{label}", row, label, parsed.selector
195
+ )
196
+
197
+
198
+ def _prov_json(raw: dict[str, Any]) -> dict[str, Any]:
199
+ """``breakpoints.provenance`` as JSON: the label of the shown value and why."""
200
+ authority = raw.get("authority", "measured")
201
+ state = raw.get("state", "resolved")
202
+ if authority is None and state != "resolved":
203
+ # the engine declined to label the value (a replica whose check failed or never ran):
204
+ # no authority is claimed, so no number about it is either
205
+ out: dict[str, Any] = {"state": state, "reason": str(raw.get("reason") or state),
206
+ "edited": bool(raw.get("edited"))}
207
+ elif authority not in _AUTHORITY:
208
+ raise Refused(f"engine reported an unknown authority {authority!r}")
209
+ else:
210
+ out = {"authority": _AUTHORITY[authority], "edited": bool(raw.get("edited"))}
211
+ if raw.get("by"):
212
+ by = raw["by"]
213
+ out["by"] = by if isinstance(by, str) else ",".join(map(str, by))
214
+ kind = raw.get("kind")
215
+ if kind and kind != "native":
216
+ out["edit_kind"] = str(kind)
217
+ if raw.get("under_edits_total"):
218
+ out["under_edits"] = [dict(item) for item in raw["under_edits"]]
219
+ out["under_edits_total"] = int(raw["under_edits_total"])
220
+ if raw.get("mixed"):
221
+ out["mixed"] = {k: int(v) for k, v in raw["mixed"].items()}
222
+ if raw.get("same_port_edit"):
223
+ out["same_port_edit"] = dict(raw["same_port_edit"])
224
+ if raw.get("from_checkpoint"):
225
+ out["from_checkpoint"] = dict(raw["from_checkpoint"])
226
+ for key in ("realisation_exact", "realisation_max_abs_error"):
227
+ if raw.get(key) is not None:
228
+ out[key] = raw[key] if key == "realisation_exact" else _num(raw[key], "measured")
229
+ if raw.get("replica_equal") is None:
230
+ # None is "not applicable" or "not reached". A replica derived from captured operands
231
+ # is labelled derived-exact either way; when its comparison with native has not run
232
+ # the output says so.
233
+ if raw.get("replica_checked") is False:
234
+ out["replica_checked"] = False
235
+ if raw.get("port") in ("s", "p"):
236
+ out["replica_check_at"] = "p"
237
+ elif raw.get("port") in ("s", "A") and kind == "replica":
238
+ reason = "replica check not reached"
239
+ out["replica_equal"] = _unresolved(reason)
240
+ out["replica_max_abs_diff"] = _unresolved(reason)
241
+ else:
242
+ out["replica_equal"] = bool(raw["replica_equal"])
243
+ out["replica_checked"] = True
244
+ if raw.get("max_abs_diff") is not None:
245
+ out["replica_max_abs_diff"] = _num(raw["max_abs_diff"])
246
+ return out
247
+
248
+
249
+ def selector_mask(axes: tuple[str, ...], shape: tuple[int, ...], selector: Any, *, head_dim: int,
250
+ row: int | None = None, tokenizer: Any = None, text: str = "value"
251
+ ) -> tuple[Any, tuple[Any, ...], tuple[int, ...]]:
252
+ """A selector over a value of ``shape`` (axis names ``axes``) as ``(mask, index, chosen)``:
253
+ the bool mask of the picked elements, the advanced index of the picked block and its shape.
254
+ A selection out of range is ``Refused``, one that does not apply ``BadArgs`` (``text`` names
255
+ the address in both)."""
256
+ import torch
257
+
258
+ bp = _bp()
259
+ try:
260
+ picks = bp.plan(axes, list(shape), selector, head_dim=head_dim, row=row,
261
+ tokenizer=tokenizer)
262
+ except bp.SelectionRange as error:
263
+ raise Refused(f"{text}: {error}") from None
264
+ except bp.SelectionError as error:
265
+ raise BadArgs(f"{text}: {error}") from None
266
+ index = tuple(
267
+ torch.tensor(list(range(shape[axis]) if pick is None else pick), dtype=torch.long).view(
268
+ [-1 if a == axis else 1 for a in range(len(shape))])
269
+ for axis, pick in enumerate(picks)
270
+ )
271
+ mask = torch.zeros(shape, dtype=torch.bool)
272
+ mask[index] = True
273
+ chosen = tuple(shape[a] if pick is None else len(pick) for a, pick in enumerate(picks))
274
+ return mask, index, chosen
275
+
276
+
277
+ def _read_info(ctx, target: Target, selection=None) -> dict[str, Any]:
278
+ """Provenance of a value, from ``Run.read_info`` / ``Run.edit_mask`` (never a default)."""
279
+ bp = _bp()
280
+ if target.cell is not None:
281
+ return _prov_json(bp.cell_provenance(ctx.run, target.cell.layer, selection,
282
+ target.cell.tensor))
283
+ raw = bp.provenance(ctx.run, target.run_target, selection)
284
+ raw["port"] = target.layer_port[1] if target.layer_port else None
285
+ return _prov_json(raw)
286
+
287
+
288
+ def _read(ctx, target: Target):
289
+ run = ctx.run
290
+ if target.cell is not None:
291
+ # The committed boundary state (the cursor's cut): rows written so far, not the row
292
+ # the pending layer is about to write.
293
+ return run.read_cache(target.cell.layer, target.cell.tensor)
294
+ return run.read(target.run_target)
295
+
296
+
297
+ def _axes(ctx, target: Target) -> tuple[str, ...]:
298
+ bp = _bp()
299
+ if target.cell is not None:
300
+ return bp.CELL_AXES
301
+ return bp.stop_axes(ctx.run.program, target.label)
302
+
303
+
304
+ def _select(ctx, target: Target, value):
305
+ bp = _bp()
306
+ axes = _axes(ctx, target)
307
+ row = target.row if target.label not in (None, "start") and "row" in axes else None
308
+ try:
309
+ return bp.select(value, axes, target.selector, head_dim=ctx.run.adapter.head_dim,
310
+ row=row, tokenizer=ctx.tokenizer)
311
+ except bp.SelectionRange as error:
312
+ raise Refused(f"{target.text}: {error}") from None
313
+ except bp.SelectionError as error:
314
+ raise BadArgs(f"{target.text}: {error}") from None
315
+
316
+
317
+ def _check_selector(ctx, target: Target) -> None:
318
+ """Bound-check a target's selector against the axis sizes that are knowable without a
319
+ value (a refusal naming the axis and its size, before anything is stored)."""
320
+ if not target.selector.keys and not target.selector.tokens:
321
+ return
322
+ bp = _bp()
323
+ axes = _axes(ctx, target)
324
+ try:
325
+ bp.plan(axes, bp.axis_sizes(ctx.run.adapter, axes), target.selector,
326
+ head_dim=ctx.run.adapter.head_dim, row=None, tokenizer=_NoTokenizer())
327
+ except bp.SelectionRange as error:
328
+ raise Refused(f"{target.text}: {error}") from None
329
+ except bp.SelectionError as error:
330
+ raise BadArgs(f"{target.text}: {error}") from None
331
+
332
+
333
+ class _NoTokenizer:
334
+ """Token-text selectors are resolved when the value is read, not when it is stored."""
335
+
336
+ def encode(self, text: str, add_special_tokens: bool = False) -> list[int]:
337
+ return [0]
338
+
339
+
340
+ def _text(ctx, token_id: int) -> str | None:
341
+ tokenizer = ctx.tokenizer
342
+ if tokenizer is None:
343
+ return None
344
+ return tokenizer.decode([int(token_id)])
345
+
346
+
347
+ def _token(ctx, token_id: int) -> dict[str, Any]:
348
+ out: dict[str, Any] = {"id": int(token_id)}
349
+ text = _text(ctx, token_id)
350
+ if text is not None:
351
+ out["text"] = text
352
+ return out
353
+
354
+
355
+ def _tokens(ctx, ids: list[int], keep: int = 16) -> dict[str, Any]:
356
+ return {"tokens": [_token(ctx, i) for i in ids[-keep:]], "tokens_total": len(ids)}
357
+
358
+
359
+ def _edited(ctx) -> bool:
360
+ return ctx.run.edited
361
+
362
+
363
+ def _edited_origin(ctx, target: Target) -> tuple[Any, str | None, int, str]:
364
+ """``(origin, recipe id, event, cut)`` of a value read under edits: ``@cut+ref...`` (the
365
+ boundary cut it is computed from and the reference of each edit applied in that transition,
366
+ ``mdb.core.recipe.edit_ref``) and, with a writable project, the stored recipe of the cursor
367
+ (edit values and masks as blobs) that reproduces it. Raises ``Refused`` when the recipe
368
+ cannot be stored (an edit tensor not held, an over-large recipe)."""
369
+ from mdb.core import recipe as recipes
370
+ from mdb.core.pointers import RecordError
371
+
372
+ run = ctx.run
373
+ origin = run.origin_of(target.run_target)
374
+ edits = tuple(recipes.edit_ref(m) for m in origin["edits"])
375
+ project = project_of(ctx)
376
+ recipe = None
377
+ if project is not None and not project.read_only:
378
+ try:
379
+ sealed = recipes.from_checkpoint(run.checkpoint(pin=False), tokens=run.tokens,
380
+ layers=run.adapter.layers,
381
+ tensors=run.edit_tensors(), store=project.store)
382
+ recipe = recipes.save(project, ctx.debugger.session_id, sealed)
383
+ except RecordError as error:
384
+ raise Refused(f"the edits do not fit one replay recipe: {error}") from error
385
+ return (addresses.Origin(cut=origin["cut"], edits=edits), recipe, origin["transitions"],
386
+ origin["cut"])
387
+
388
+
389
+ def _pointer(ctx, target: Target, value) -> tuple[dict | None, str | None]:
390
+ from mdb.core.pointers import RecordError, occurrence_pointer
391
+ from mdb.engine.ports import tensor_digest
392
+
393
+ if target.cell is not None:
394
+ return None, "cache cells are read at the current clock; no occurrence pointer"
395
+ if target.label == "start":
396
+ return None, "start is the token list, not a port occurrence"
397
+ run = ctx.run
398
+ cut = recipe = event = None
399
+ address = addresses.parse(target.run_target, ports=run.program.names,
400
+ global_ports=GLOBALS)
401
+ authority, reason = _claim(_read_info(ctx, target))
402
+ if authority is None:
403
+ return None, f"no occurrence pointer: the value's label was refused ({reason})"
404
+ if _edited(ctx):
405
+ # an edited value is addressed by its cut and the edits applied after it; with a
406
+ # writable project the recipe (and every edit tensor, as a blob) is stored so
407
+ # mdb.resolve and seek can reproduce it bitwise; without one it resolves to a refusal.
408
+ try:
409
+ origin, recipe, event, cut = _edited_origin(ctx, target)
410
+ except (Refused, ValueError) as error:
411
+ return None, f"no occurrence pointer: {error}"
412
+ address = replace(address, origin=origin)
413
+ else:
414
+ layer_port = target.layer_port
415
+ if layer_port is not None and run.pending_layer == layer_port[0] and (
416
+ _split(run.where)[0] == target.row
417
+ ):
418
+ cut = run.checkpoint(pin=False)["cut"]
419
+ try:
420
+ pointer = occurrence_pointer(
421
+ address,
422
+ program="stepped",
423
+ shape=list(value.shape),
424
+ dtype=str(value.dtype).removeprefix("torch."),
425
+ sha256=tensor_digest(value.contiguous()),
426
+ recipe=recipe,
427
+ event=event,
428
+ cut=cut,
429
+ authority=authority,
430
+ ports=run.program.names,
431
+ global_ports=addresses.DEFAULT_GLOBALS,
432
+ )
433
+ except RecordError as error:
434
+ return None, f"no occurrence pointer: {error}"
435
+ return pointer, None
436
+
437
+
438
+ def _claim(provenance: dict[str, Any]) -> tuple[str | None, str | None]:
439
+ """``(authority, reason)`` of a value's provenance; no authority means its numbers are
440
+ withheld (``{state: "unresolved", reason}``) with the reason the engine gave."""
441
+ return provenance.get("authority"), provenance.get("reason")
442
+
443
+
444
+ def _stats(raw: dict[str, Any], authority: str | None = "measured",
445
+ reason: str | None = None) -> dict[str, Any]:
446
+ """Labelled statistics. With NaN/Inf elements they run over the finite ones
447
+ (``over: "finite"``) beside integer ``nonfinite`` counts; with no finite element every
448
+ statistic is ``{state: "unresolved", reason}``; so is every statistic of a value whose label
449
+ the engine refused."""
450
+ out: dict[str, Any] = {}
451
+ if authority is None:
452
+ for name in (*STATS, "argmax_index"):
453
+ out[name] = _unresolved(reason or "no authority label")
454
+ out["argmax_index"] = list(raw["argmax_index"]) if "argmax_index" in raw else []
455
+ elif "unresolved" in raw:
456
+ for name in (*STATS, "argmax_index"):
457
+ out[name] = _unresolved(raw["unresolved"])
458
+ else:
459
+ out = {name: _num(raw[name], authority) for name in STATS}
460
+ out["argmax_index"] = list(raw["argmax_index"])
461
+ out["numel"] = int(raw["numel"])
462
+ if "nonfinite" in raw:
463
+ out["over"] = "finite"
464
+ out["nonfinite"] = {k: int(v) for k, v in raw["nonfinite"].items()}
465
+ return out
466
+
467
+
468
+ def _json_values(part) -> tuple[list, dict[str, int] | None]:
469
+ """A flat tensor slice as JSON numbers; NaN/Inf become the strings ``"nan"``, ``"inf"``,
470
+ ``"-inf"`` (JSON has none), with their counts."""
471
+ import torch
472
+
473
+ if not part.is_floating_point():
474
+ return [int(v) for v in part.tolist()], None
475
+ values = part.to(torch.float64).tolist()
476
+ counts = _bp().nonfinite(part)
477
+ if not any(counts.values()):
478
+ return values, None
479
+ named = {float("inf"): "inf", float("-inf"): "-inf"}
480
+ return [("nan" if v != v else named[v]) if (v != v or v in named) else v
481
+ for v in values], counts
482
+
483
+
484
+ def _reduction(ctx, target: Target, *, k: int = 5, slice_count: int = 0,
485
+ pointer: bool = True) -> dict[str, Any]:
486
+ bp = _bp()
487
+ value = _read(ctx, target)
488
+ selection = _select(ctx, target, value)
489
+ provenance = _read_info(ctx, target, selection)
490
+ authority, reason = _claim(provenance)
491
+ out: dict[str, Any] = {
492
+ "address": target.text,
493
+ "shape": list(value.shape),
494
+ "dtype": str(value.dtype).removeprefix("torch."),
495
+ "axes": list(selection.axes),
496
+ "provenance": provenance,
497
+ }
498
+ if list(selection.value.shape) != list(value.shape):
499
+ out["selected_shape"] = list(selection.value.shape)
500
+ if not value.is_floating_point():
501
+ ids = [int(i) for i in selection.value.reshape(-1).tolist()]
502
+ out.update(_tokens(ctx, ids, keep=32))
503
+ else:
504
+ if selection.value.numel() == 0:
505
+ raise BadArgs(f"{target.text}: the selection is empty")
506
+ out["stats"] = _stats(bp.reduce(selection), authority, reason)
507
+ vocab = "vocab" in selection.axes # logits: the largest, not the largest |v|
508
+ entries = []
509
+ for index, item in bp.top(selection, k, signed=vocab):
510
+ entry: dict[str, Any] = {
511
+ "index": index,
512
+ "value": _num(item, authority) if authority else _unresolved(reason or "refused"),
513
+ }
514
+ if vocab and ctx.tokenizer is not None:
515
+ entry["text"] = _text(ctx, index[-1])
516
+ entries.append(entry)
517
+ out["k"] = k
518
+ out["top"] = entries
519
+ out["rank"] = "value" if vocab else "magnitude"
520
+ if slice_count:
521
+ flat, counts = _json_values(selection.value.reshape(-1)[:slice_count])
522
+ out["slice"] = ({"offset": 0, "values": flat, "authority": authority} if authority
523
+ else {"offset": 0, "values": _unresolved(reason or "refused")})
524
+ if counts:
525
+ out["slice"]["nonfinite"] = counts
526
+ if pointer:
527
+ found, reason = _pointer(ctx, target, value)
528
+ if found is not None:
529
+ out["pointer"] = found
530
+ else:
531
+ out["pointer_omitted"] = reason
532
+ return out
533
+
534
+
535
+ def _margin_reading(ctx, address: str | None) -> dict[str, Any] | None:
536
+ """``print``/``x``/``display`` of a declared margin ``M[a,b]`` (token ids or quoted texts, as
537
+ ``explain``/``forecast``/``whatif`` read them): the difference of the row's two logits at
538
+ the cursor, ``measured`` (the label of the logits stop's provenance), or ``Refused`` when
539
+ that row's logits are not computed yet. None when ``address`` is not a margin."""
540
+ from .predict import _margin
541
+
542
+ if address is None or ctx.run is None:
543
+ return None
544
+ margin = _margin(ctx, address)
545
+ if margin is None:
546
+ return None
547
+ run = ctx.run
548
+ stop = f"t{margin.row}.logits"
549
+ try:
550
+ logits = run.read(stop)
551
+ except ValueError:
552
+ raise Refused(f"M[{margin.a},{margin.b}] is the difference of two logits of row "
553
+ f"t{margin.row}, not computed at {run.where}: run `until {stop}` first"
554
+ ) from None
555
+ flat = logits.reshape(-1)
556
+ high, low = flat[margin.a].double(), flat[margin.b].double() # slice, then one widening
557
+ provenance = _prov_json({**_bp().provenance(run, stop, None), "port": None})
558
+ authority, reason = _claim(provenance)
559
+ text = f"t{margin.row}.M[{margin.a},{margin.b}]"
560
+ number = (lambda v: _num(float(v), authority) if authority else _unresolved(reason or "refused"))
561
+ return {
562
+ "address": text, "shape": [], "dtype": "float64", "axes": [], "provenance": provenance,
563
+ "margin": {"a": _token(ctx, margin.a), "b": _token(ctx, margin.b),
564
+ "logit_a": number(high), "logit_b": number(low), "value": number(high - low),
565
+ "rule": f"logits[a] - logits[b] of {stop}; the exact float64 difference of "
566
+ "the two stored logits"},
567
+ }
568
+
569
+
570
+ # --------------------------------------------------------------------------- stops
571
+
572
+
573
+ def _stop(ctx, where: str | None = None) -> dict[str, Any]:
574
+ run = ctx.run
575
+ row, label = _split(where or run.where)
576
+ info: dict[str, Any] = {"address": f"t{row}.{label}", "row": row}
577
+ match = _LAYER_PORT.fullmatch(label)
578
+ if match is not None:
579
+ spec = run.program.spec(match["port"])
580
+ info.update(
581
+ layer=int(match["layer"]),
582
+ port=spec.name,
583
+ sublayer=spec.sublayer,
584
+ operator=spec.operator,
585
+ proofs=list(spec.proofs),
586
+ )
587
+ else:
588
+ info.update(port=label, operator=GLOBAL_OPERATORS.get(label, label), proofs=[])
589
+ return info
590
+
591
+
592
+ def _displays(ctx) -> list[dict[str, Any]]:
593
+ from .errors import OpError
594
+
595
+ out = []
596
+ for number, text in sorted(ctx.displays.items())[:MAX_DISPLAYS]:
597
+ try:
598
+ item = _margin_reading(ctx, text) or _reduction(
599
+ ctx, resolve_target(ctx, text), k=3, pointer=False)
600
+ item.pop("axes", None)
601
+ out.append({"id": number, **item})
602
+ except (OpError, ValueError) as error:
603
+ out.append({"id": number, "address": text, "unavailable": str(error)})
604
+ return out
605
+
606
+
607
+ def moved(ctx, extra: dict[str, Any] | None = None) -> dict[str, Any]:
608
+ ctx.focus, ctx.focus_stack = None, []
609
+ out: dict[str, Any] = {"where": ctx.run.where, "stop": _stop(ctx)}
610
+ if extra:
611
+ out.update(extra)
612
+ if ctx.displays:
613
+ out["displays"] = _displays(ctx)
614
+ return out
615
+
616
+
617
+ def _hits(hits: list[dict[str, Any]]) -> list[dict[str, Any]]:
618
+ out = []
619
+ for hit in hits:
620
+ item = {key: hit[key] for key in ("id", "kind", "pattern", "mode") if key in hit}
621
+ for key in ("old", "new"):
622
+ if key in hit:
623
+ prov = hit.get(f"{key}_provenance") or {"authority": "measured"}
624
+ item[f"{key}_provenance"] = _prov_json(prov)
625
+ item[key] = _stats(hit[key], *_claim(item[f"{key}_provenance"]))
626
+ out.append(item)
627
+ return out
628
+
629
+
630
+ # --------------------------------------------------------------------------- run / start
631
+
632
+
633
+ def _switch(ctx, run) -> None:
634
+ """Make ``run`` the context's run, keeping each named run's in-memory checkpoints with it
635
+ (``Debugger.run_checkpoints``) so switching back finds them."""
636
+ debugger = ctx.debugger
637
+ keep = getattr(debugger, "run_checkpoints", None)
638
+ if keep is None:
639
+ keep = debugger.run_checkpoints = {}
640
+ old = getattr(ctx.run, "name", None)
641
+ if old is not None and debugger.runs.get(old) is ctx.run:
642
+ keep[old] = dict(ctx.checkpoints)
643
+ ctx.set_run(run)
644
+ ctx.checkpoints.update(keep.pop(run.name, {}) if run.name is not None else {})
645
+ debugger.live = run
646
+
647
+
648
+ def _start(ctx, prompt, name: str | None = None, prefill: int | None = None,
649
+ lookahead: str | None = None, retain_rows: int | None = None) -> None:
650
+ if ctx.debugger is None:
651
+ raise Refused("no model attached; use mdb.attach(model) or --tiny")
652
+ if prompt is None:
653
+ if ctx.run is None:
654
+ raise BadArgs("start needs a prompt (text or token ids)")
655
+ prompt = list(ctx.run.tokens)
656
+ if prefill is not None:
657
+ count = len(ctx.debugger.tokens(prompt))
658
+ if prefill > count - 1:
659
+ raise Refused(f"prefill={prefill} is past the prompt: it has {count} tokens, so "
660
+ f"prefill is 0..{count - 1} (the row after the prefilled ones is the "
661
+ "first stepped row)")
662
+ # the one start: cursor at t<first stepped row>.L0.h; the prompt rows from `prefill` on are
663
+ # stepped one row at a time, tokens forced (one session, built under that split)
664
+ options = {key: value for key, value in (("prefill", prefill), ("lookahead", lookahead),
665
+ ("retain_rows", retain_rows)) if value is not None}
666
+ run = ctx.debugger.run(prompt, name=name, **options)
667
+ getattr(ctx.debugger, "run_checkpoints", {}).pop(run.name, None) # a new run of that name
668
+ _switch(ctx, run)
669
+
670
+
671
+ _PROMPT = Arg("prompt", "prompt", help="prompt text (needs a tokenizer) or token ids; "
672
+ "omitted = the current run's prompt")
673
+ _NAME = Arg("name", "str", positional=False,
674
+ help="name of the run (default main): other runs take values from it as NAME:ADDR")
675
+ _PREFILL = Arg("prefill", "int", minimum=0, positional=False,
676
+ help="prompt rows computed in one batched call (default all but the last); the "
677
+ "rest are stepped one row at a time with their tokens forced, so their "
678
+ "ports are stops (0 steps every row)")
679
+
680
+
681
+ # engine.run.LOOKAHEADS, spelled out: this module imports no torch (a test compares the two)
682
+ LOOKAHEADS = ("none", "layer", "auto")
683
+ _LOOKAHEAD = Arg("lookahead", "choice", choices=LOOKAHEADS, positional=False,
684
+ help="what a move inside a layer computes: none (default; stops at the port), "
685
+ "layer (one full-layer call), auto")
686
+ _RETAIN = Arg("retain_rows", "int", minimum=0, positional=False,
687
+ help="keep boundary cuts of only the last N rows (memory bound; older rows cannot "
688
+ "be rewound to)")
689
+
690
+
691
+ def procedure_json(run) -> dict[str, Any]:
692
+ """The run's prefill split as op JSON: ``rows`` (prompt rows batched), ``text`` and
693
+ ``default`` (all prompt rows but the last batched, the procedure of ``start`` without
694
+ ``prefill=``)."""
695
+ procedure = run.procedure
696
+ return {"rows": procedure["prefill"], "text": procedure["text"],
697
+ "default": procedure["prefill"] == procedure["prompt_rows"] - 1}
698
+
699
+
700
+ def _started(ctx) -> dict[str, Any]:
701
+ return {"prompt_tokens": len(ctx.run.tokens), "run": ctx.run.name,
702
+ "prefill": procedure_json(ctx.run)}
703
+
704
+
705
+ _FROM = Arg("from", "str", positional=False,
706
+ help="a checkpoint to start from instead of a prompt: a file path, or a record id "
707
+ "(prefix) or checkpoint name of the project (`checkpoints` lists both); "
708
+ "rehydrated at its cursor with no prefix recompute, "
709
+ "its values labelled `from checkpoint ID, path unverified`")
710
+ _VERIFY = Arg("verify", "choice", choices=("false", "true", "report"), positional=False,
711
+ help="with from=: replay the checkpoint's recipe from its root first (true: "
712
+ "refuse unless it reaches the checkpoint, and label the run path verified; "
713
+ "report: show the result)")
714
+
715
+
716
+ @op("start", "Prefill a prompt and stop at the first stepped row's first port (L0.h), or "
717
+ "start from a checkpoint (from=ID|NAME|PATH) at its cursor",
718
+ _PROMPT, _NAME, _PREFILL, _LOOKAHEAD, _RETAIN, _FROM, _VERIFY, effect="native",
719
+ needs_live=False,
720
+ usage="start [name=NAME] [prefill=K] [lookahead=none|layer|auto] [retain_rows=N] "
721
+ "[TEXT | ID ID ...] | start from=ID|NAME|PATH [name=NAME] [verify=true|report] "
722
+ "[lookahead=MODE]")
723
+ def _op_start(ctx, prompt, name, prefill, lookahead, retain_rows, **given):
724
+ source = given.get("from")
725
+ verify = given.get("verify") or "false"
726
+ if source is None:
727
+ if verify != "false":
728
+ raise BadArgs("verify= applies to start from=CHECKPOINT")
729
+ _start(ctx, prompt, name, prefill, lookahead, retain_rows)
730
+ return moved(ctx, _started(ctx))
731
+ if ctx.debugger is None:
732
+ raise Refused("no model attached; use mdb.attach(model) or --tiny")
733
+ if prompt is not None or prefill is not None or retain_rows is not None:
734
+ raise BadArgs("start from=CHECKPOINT takes its prompt and split from the checkpoint: "
735
+ "give no prompt, prefill or retain_rows")
736
+ run = ctx.debugger.run_from(source, name=name, lookahead=lookahead,
737
+ verify={"false": False, "true": True}.get(verify, verify))
738
+ getattr(ctx.debugger, "run_checkpoints", {}).pop(run.name, None)
739
+ _switch(ctx, run)
740
+ core = run.core
741
+ out = {**_started(ctx), "from_checkpoint": dict(run.from_checkpoint),
742
+ "checkpoint": {"record": core["record"], "where": core["where"],
743
+ "history": core["history"], "exact": bool(core["exact"]),
744
+ "load_seconds": _num(core.get("load_seconds") or 0.0)}}
745
+ if core.get("verified") is not None:
746
+ found = core["verified"]
747
+ out["verified"] = {"ok": bool(found["ok"]), "state": found["state"],
748
+ "reason": found.get("reason")}
749
+ return moved(ctx, out)
750
+
751
+
752
+ @op("run", "Like start, then continue to the first armed breakpoint or watch", _PROMPT,
753
+ Arg("budget", "int", default=8, minimum=0, maximum=STEP_CAP, positional=False,
754
+ help="token rows continue may enter (minimum 1, at most 4096)"),
755
+ _NAME, _PREFILL, _LOOKAHEAD, _RETAIN,
756
+ effect="native", needs_live=False,
757
+ usage="run [name=NAME] [prefill=K] [lookahead=MODE] [retain_rows=N] [TEXT | ID ID ...] "
758
+ "[budget=N]")
759
+ def _op_run(ctx, prompt, budget, name, prefill, lookahead, retain_rows):
760
+ _start(ctx, prompt, name, prefill, lookahead, retain_rows)
761
+ if not ctx.table.armed():
762
+ return moved(ctx, {**_started(ctx), "reason": "no-breakpoints"})
763
+ return _continue(ctx, budget=budget, extra=None, more=_started(ctx))
764
+
765
+
766
+ # --------------------------------------------------------------------------- cursor
767
+
768
+
769
+ @op("where", "Show the cursor, its operator and the context tokens", effect="read")
770
+ def _op_where(ctx):
771
+ run = ctx.run
772
+ out = {"where": run.where, "stop": _stop(ctx), "staged": len(run.edits),
773
+ "lookahead": getattr(run, "lookahead", None), "prefill": procedure_json(run)}
774
+ if getattr(run, "cells", None):
775
+ out["staged_cells"] = len(run.cells)
776
+ if getattr(run, "name", None) is not None:
777
+ out["run"] = run.name
778
+ if ctx.focus:
779
+ out["focus"] = ctx.focus
780
+ past = run.status().get("computed_past_cursor") or []
781
+ if past: # computed by the native call but not held: say so rather than hide it
782
+ out["computed_past_cursor"] = list(past)
783
+ out.update(_tokens(ctx, [int(t) for t in run.session.read("tokens")[0].tolist()]))
784
+ return out
785
+
786
+
787
+ @op("frame", "Show or set the focus address (print/list/backtrace default to it); NAME: "
788
+ "switches to the named run",
789
+ Arg("address", "address", help="an address, 'cursor' to follow the cursor again, or NAME: "
790
+ "(a run started with name=NAME)"),
791
+ effect="navigate", usage="frame [ADDR | cursor | NAME:]")
792
+ def _op_frame(ctx, address):
793
+ if address is not None and address.endswith(":") and "[" not in address:
794
+ name = address[:-1]
795
+ runs = getattr(ctx.debugger, "runs", {})
796
+ if name not in runs:
797
+ raise Refused(f"no run named {name!r} (have: {', '.join(runs) or 'none'})")
798
+ if runs[name] is not ctx.run:
799
+ _switch(ctx, runs[name])
800
+ return {"focus": ctx.run.where, "cursor": ctx.run.where, "run": name,
801
+ "where": ctx.run.where, "stop": _stop(ctx)}
802
+ if address == "cursor":
803
+ ctx.focus, ctx.focus_stack = None, []
804
+ elif address is not None:
805
+ target = resolve_target(ctx, address)
806
+ ctx.focus, ctx.focus_stack = target.text, []
807
+ focus = ctx.focus or ctx.run.where
808
+ out: dict[str, Any] = {"focus": focus, "cursor": ctx.run.where}
809
+ target = resolve_target(ctx, focus)
810
+ if target.label is not None:
811
+ out["frame"] = _stop(ctx, target.run_target)
812
+ return out
813
+
814
+
815
+ _N = Arg("n", "int", default=1, minimum=1, maximum=STEP_CAP, help="repeat count (at most 4096)")
816
+ _BUDGET = Arg("budget", "int", default=8, minimum=0, maximum=STEP_CAP, positional=False,
817
+ help="token rows that may be entered before stopping (minimum 1, at most 4096)")
818
+ _ENGINE_UNITS = {
819
+ "port": lambda label: True,
820
+ "sublayer": lambda label: label in addresses.DEFAULT_GLOBALS or label == "start"
821
+ or label.endswith((".r", ".h_out")),
822
+ "layer": lambda label: label in addresses.DEFAULT_GLOBALS or label == "start"
823
+ or label.endswith(".h_out"),
824
+ "token": lambda label: label == "start",
825
+ }
826
+
827
+
828
+ def _walk(run, unit: str, n: int, *, reverse: bool) -> tuple[int, int]:
829
+ """Where ``n`` unit steps end, computed from the stop order alone (nothing moves)."""
830
+ accept = _ENGINE_UNITS[unit]
831
+ stops = run.stops()
832
+ size = len(stops)
833
+ key = run.parse(run.where)
834
+ root = run.parse(run.root)
835
+ for _ in range(n):
836
+ while True:
837
+ row, index = key
838
+ if reverse:
839
+ key = (row, index - 1) if index else (row - 1, size - 1)
840
+ else:
841
+ key = (row, index + 1) if index + 1 < size else (row + 1, 0)
842
+ if reverse and key < root:
843
+ raise Refused(f"cannot reverse before the run root t{root[0]}.{stops[root[1]]}; "
844
+ "nothing moved")
845
+ if accept(stops[key[1]]):
846
+ break
847
+ return key
848
+
849
+
850
+ def _capped(ctx, unit: str, n: int, budget: int, *, reverse: bool) -> None:
851
+ """Refuse, before anything moves, a unit step that would enter more token rows than
852
+ ``budget`` (layer and token units; port and sublayer are bounded by ``n`` <= 4096)."""
853
+ run = ctx.run
854
+ target = _walk(run, unit, n, reverse=reverse)
855
+ here = run.parse(run.where)
856
+ entered = abs(target[0] - here[0])
857
+ limit = max(1, budget)
858
+ if unit in ("layer", "token") and entered > limit:
859
+ raise Refused(
860
+ f"{'reverse-' if reverse else ''}step {n} {unit} would enter {entered} token rows "
861
+ f"(budget {limit}); pass budget=N (at most {STEP_CAP}). Nothing moved.")
862
+
863
+
864
+ def _step_forward(ctx, n: int, unit: str, budget: int) -> dict[str, Any]:
865
+ _capped(ctx, unit, n, budget, reverse=False)
866
+ for _ in range(n):
867
+ try:
868
+ ctx.run.step(unit, 1)
869
+ except ValueError as error:
870
+ if "capacity" not in str(error):
871
+ raise
872
+ return moved(ctx, {"reason": "end-of-context"})
873
+ return moved(ctx)
874
+
875
+
876
+ def _step_back(ctx, n: int, unit: str, budget: int) -> dict[str, Any]:
877
+ _capped(ctx, unit, n, budget, reverse=True)
878
+ ctx.run.reverse_step(unit, n)
879
+ return moved(ctx)
880
+
881
+
882
+ @op("step", "Step one port (or N units; layer/token units enter at most `budget` rows)", _N,
883
+ Arg("unit", "choice", default="port", choices=("port", "sublayer", "layer", "token")),
884
+ _BUDGET, effect="navigate", motion=True,
885
+ usage="step [N] [port|sublayer|layer|token] [budget=ROWS]")
886
+ def _op_step(ctx, n, unit, budget):
887
+ return _step_forward(ctx, n, unit, budget)
888
+
889
+
890
+ @op("next", "Step to the last port of the sublayer (r, then h_out)", _N,
891
+ effect="navigate", motion=True, usage="next [N]")
892
+ def _op_next(ctx, n):
893
+ return _step_forward(ctx, n, "sublayer", 1)
894
+
895
+
896
+ @op("finish", "From a port inside a layer: run to that layer's h_out. From h_out or a "
897
+ "token-level stop: run to this row's sample", effect="navigate", motion=True)
898
+ def _op_finish(ctx):
899
+ run = ctx.run
900
+ row, label = _split(run.where)
901
+ found = _LAYER_PORT.fullmatch(label)
902
+ if found is not None and found["port"] != "h_out":
903
+ run.until(f"t{row}.L{found['layer']}.h_out")
904
+ elif label == "sample":
905
+ raise Refused(f"already at t{row}.sample, the end of the row; use `step token`")
906
+ else:
907
+ run.until(f"t{row}.sample")
908
+ return moved(ctx)
909
+
910
+
911
+ def _run_to(ctx, target: str, budget: int, *, name: str) -> dict[str, Any]:
912
+ """Run to an address, stopping earlier at an armed breakpoint or watch."""
913
+ bp = _bp()
914
+ run = ctx.run
915
+ found = resolve_target(ctx, target)
916
+ if found.cell is not None:
917
+ raise BadArgs(f"{name} takes a port occurrence, not a cache cell")
918
+ if name == "advance" and found.selector:
919
+ raise BadArgs("advance takes a port occurrence without selectors")
920
+ key, here = run.parse(found.run_target), run.parse(run.where)
921
+ if key == here and name == "until":
922
+ return moved(ctx)
923
+ if key[0] < getattr(run, "first_row", 0):
924
+ raise Refused(f"{found.run_target}: {run.prefilled_reason(key[0])}")
925
+ if key <= here:
926
+ raise Refused(f"{found.run_target} is "
927
+ + ("behind the cursor " if name == "until" else "not ahead of the cursor ")
928
+ + f"{run.where}; use reverse-step or restart")
929
+ if key[0] > run.adapter.max_positions - 1:
930
+ raise Refused(f"{found.run_target} is past the model's context limit "
931
+ f"({run.adapter.max_positions} positions)")
932
+ pattern = bp.parse_pattern(found.run_target, run.program)
933
+ item = bp.Breakpoint(0, found.run_target, pattern, kind="advance")
934
+ budget = max(budget, key[0] - here[0] + 1)
935
+ out = _continue(ctx, budget=budget, extra=[item])
936
+ if name == "until" and out["reason"] == "advance":
937
+ out.update(reason="reached", hits=[], hits_total=0)
938
+ out.pop("omitted", None)
939
+ return out
940
+
941
+
942
+ @op("until", "Run to an address, stopping earlier at an armed breakpoint or watch",
943
+ Arg("target", "address", required=True), _BUDGET, effect="navigate", motion=True,
944
+ usage="until ADDR [budget=ROWS]")
945
+ def _op_until(ctx, target, budget):
946
+ return _run_to(ctx, target, budget, name="until")
947
+
948
+
949
+ @op("advance", "Run to an address, stopping earlier at an armed breakpoint or watch",
950
+ Arg("target", "address", required=True), _BUDGET, effect="navigate", motion=True,
951
+ usage="advance ADDR [budget=ROWS]")
952
+ def _op_advance(ctx, target, budget):
953
+ return _run_to(ctx, target, budget, name="advance")
954
+
955
+
956
+ @op("feed", "Forced tokens: run each row to sample with the given id supplied in place of "
957
+ "the greedy argmax, commit it, and stop at the next row's start (native in every port)",
958
+ Arg("ids", "ints", required=True), effect="navigate", motion=True, usage="feed ID [ID ...]")
959
+ def _op_feed(ctx, ids):
960
+ run = ctx.run
961
+ if len(ids) > STEP_CAP:
962
+ raise Refused(f"feed takes at most {STEP_CAP} tokens; nothing moved")
963
+ if run.parse(run.where)[0] + len(ids) > run.adapter.max_positions - 1:
964
+ raise Refused(f"feeding {len(ids)} tokens passes the model's context limit "
965
+ f"({run.adapter.max_positions} positions); nothing moved")
966
+ try:
967
+ run.feed(ids)
968
+ except ValueError as error:
969
+ raise Refused(str(error)) from None
970
+ supplied = sorted(run.supplied_tokens().items())
971
+ return moved(ctx, {"supplied": [f"t{r}.sample={t}" for r, t in supplied[-len(ids):]]})
972
+
973
+
974
+ def _selection_of(hits: list[dict[str, Any]]) -> str | None:
975
+ """The selector of the first hit's pattern (``[h0]``), which ``print`` then shows."""
976
+ for hit in hits:
977
+ pattern = hit.get("pattern", "")
978
+ if "[" in pattern:
979
+ return pattern[pattern.index("["):]
980
+ return None
981
+
982
+
983
+ def _continue(ctx, *, budget, extra, more=None) -> dict[str, Any]:
984
+ bp = _bp()
985
+ run = ctx.run
986
+ result = bp.run_forward(run, ctx.table, budget=budget, extra=extra,
987
+ tokenizer=ctx.tokenizer, max_positions=run.adapter.max_positions)
988
+ return _stopped(ctx, result, {"budget": max(1, budget), **(more or {})})
989
+
990
+
991
+ def _stopped(ctx, result: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:
992
+ """The result of a forward/reverse run-to-hit: the first 32 hits (``hits_total`` and
993
+ ``omitted`` say how many there were), an ``error`` when a condition failed to evaluate,
994
+ and the cursor, always."""
995
+ hits = result["hits"]
996
+ payload.update(reason=result["reason"], hits=_hits(hits[:PAGE]), hits_total=len(hits))
997
+ if len(hits) > PAGE:
998
+ payload["omitted"] = len(hits) - PAGE
999
+ if "error" in result:
1000
+ payload["error"] = dict(result["error"])
1001
+ out = moved(ctx, payload)
1002
+ selection = _selection_of(hits)
1003
+ if selection is not None:
1004
+ ctx.focus = f"{ctx.run.where}{selection}"
1005
+ out["focus"] = ctx.focus
1006
+ return out
1007
+
1008
+
1009
+ @op("continue", "Run to the next armed breakpoint or watch hit (N: ignore the breakpoint "
1010
+ "stopped at N-1 more times, as gdb)", Arg("n", "int", default=1, minimum=1),
1011
+ _BUDGET, effect="navigate", motion=True, usage="continue [N] [budget=ROWS]")
1012
+ def _op_continue(ctx, n, budget):
1013
+ more = {}
1014
+ if n > 1:
1015
+ stop = ctx.table.last_stop if ctx._table is not None else None
1016
+ ids = [i for i in (stop["ids"] if stop else []) if i in ctx.table.items]
1017
+ if stop is not None and stop["where"] == ctx.run.where and ids:
1018
+ for number in ids:
1019
+ ctx.table.items[number].ignore = n - 1
1020
+ more["ignored"] = {"ids": ids, "count": n - 1}
1021
+ else:
1022
+ more["note"] = "not stopped at a breakpoint; the count is ignored"
1023
+ return _continue(ctx, budget=budget, extra=None, more=more)
1024
+
1025
+
1026
+ # --------------------------------------------------------------------------- breakpoints
1027
+
1028
+
1029
+ _COND = Arg("condition", "condition", positional=False,
1030
+ help="e.g. norm > 3 and argmax == 2; reductions: norm min max mean abs_max argmax "
1031
+ "numel; v[...] indexes")
1032
+
1033
+
1034
+ def _adapter(ctx):
1035
+ return ctx.run.adapter if ctx.run is not None else getattr(ctx.debugger, "adapter", None)
1036
+
1037
+
1038
+ def _table_error(error: Exception):
1039
+ """Table/selector failures as typed errors: out-of-range is a refusal naming the axis and
1040
+ its size, anything malformed is bad arguments."""
1041
+ bp = _bp()
1042
+ if isinstance(error, bp.SelectionRange):
1043
+ return Refused(str(error))
1044
+ return BadArgs(str(error))
1045
+
1046
+
1047
+ def _add_break(ctx, pattern, condition, temporary):
1048
+ bp = _bp()
1049
+ try:
1050
+ item = ctx.table.add_break(pattern, _program(ctx), condition=condition,
1051
+ temporary=temporary, adapter=_adapter(ctx))
1052
+ except (addresses.AddressError, bp.ConditionError, bp.SelectionError) as error:
1053
+ raise _table_error(error) from None
1054
+ return {"breakpoint": item.describe()}
1055
+
1056
+
1057
+ @op("break", "Set a breakpoint on an address pattern (L*.p, t5.L1.o, logits, cache.L0.v[row=2]); cache cells are evaluated at boundary stops only",
1058
+ Arg("pattern", "pattern", required=True), _COND, effect="mutate", needs_live=False,
1059
+ usage="break PATTERN [if CONDITION]")
1060
+ def _op_break(ctx, pattern, condition):
1061
+ return _add_break(ctx, pattern, condition, False)
1062
+
1063
+
1064
+ @op("tbreak", "Set a breakpoint that deletes itself after its first hit",
1065
+ Arg("pattern", "pattern", required=True), _COND, effect="mutate", needs_live=False,
1066
+ usage="tbreak PATTERN [if CONDITION]")
1067
+ def _op_tbreak(ctx, pattern, condition):
1068
+ return _add_break(ctx, pattern, condition, True)
1069
+
1070
+
1071
+ def _ids(found: list[int]) -> dict[str, Any]:
1072
+ """Ids affected by an op, the first 32 of them (``total`` and ``omitted`` say the rest)."""
1073
+ out: dict[str, Any] = {"ids": found[:PAGE], "total": len(found)}
1074
+ if len(found) > PAGE:
1075
+ out["omitted"] = len(found) - PAGE
1076
+ return out
1077
+
1078
+
1079
+ @op("delete", "Delete breakpoints and watches (all when no ids are given)",
1080
+ Arg("ids", "ints"), effect="mutate", needs_live=False, usage="delete [ID ...]")
1081
+ def _op_delete(ctx, ids):
1082
+ gone = ctx.table.delete(ids)
1083
+ out: dict[str, Any] = {"deleted": gone[:PAGE], "deleted_total": len(gone)}
1084
+ if len(gone) > PAGE:
1085
+ out["omitted"] = len(gone) - PAGE
1086
+ return out
1087
+
1088
+
1089
+ @op("enable", "Enable breakpoints and watches (all when no ids are given)",
1090
+ Arg("ids", "ints"), effect="mutate", needs_live=False, usage="enable [ID ...]")
1091
+ def _op_enable(ctx, ids):
1092
+ return {"enabled": True, **_ids(ctx.table.set_enabled(ids, True))}
1093
+
1094
+
1095
+ @op("disable", "Disable breakpoints and watches without deleting them (all when no ids)",
1096
+ Arg("ids", "ints"), effect="mutate", needs_live=False, usage="disable [ID ...]")
1097
+ def _op_disable(ctx, ids):
1098
+ return {"enabled": False, **_ids(ctx.table.set_enabled(ids, False))}
1099
+
1100
+
1101
+ @op("condition", "Set the condition of breakpoint N (a watch's predicate); no expression "
1102
+ "removes it", Arg("id", "int", required=True, minimum=1),
1103
+ Arg("expr", "condition", positional=False), effect="mutate", needs_live=False,
1104
+ usage="condition N [EXPR]")
1105
+ def _op_condition(ctx, id, expr): # noqa: A002 - the arg name is the wire name
1106
+ bp = _bp()
1107
+ try:
1108
+ item = ctx.table.set_condition(id, expr, _program(ctx), _adapter(ctx))
1109
+ except (addresses.AddressError, bp.ConditionError, bp.SelectionError) as error:
1110
+ raise _table_error(error) from None
1111
+ return {"watch" if item.kind == "watch" else "breakpoint": item.describe(),
1112
+ "removed": expr is None}
1113
+
1114
+
1115
+ @op("ignore", "Ignore the next COUNT hits of breakpoint N (they are counted, not reported)",
1116
+ Arg("id", "int", required=True, minimum=1), Arg("count", "int", required=True, minimum=0),
1117
+ effect="mutate", needs_live=False, usage="ignore N COUNT")
1118
+ def _op_ignore(ctx, id, count): # noqa: A002
1119
+ item = ctx.table.set_ignore(id, count)
1120
+ return {"watch" if item.kind == "watch" else "breakpoint": item.describe(), "ignore": count}
1121
+
1122
+
1123
+ @op("watch", "Watch an address: stop when it changes (or a predicate holds: level/edge); cache cells (cache.L<i>.k|v) are evaluated at boundary stops only",
1124
+ Arg("address", "pattern", required=True),
1125
+ Arg("mode", "choice", default="change", choices=("change", "level", "edge")),
1126
+ Arg("predicate", "condition", positional=False), effect="mutate", needs_live=False,
1127
+ usage="watch ADDR [change|level|edge] [if PREDICATE]")
1128
+ def _op_watch(ctx, address, mode, predicate):
1129
+ bp = _bp()
1130
+ from .predict import _margin
1131
+
1132
+ if ctx.run is not None and _margin(ctx, address) is not None:
1133
+ raise Refused("watch takes a stop, a port or a cache cell, not the derived margin "
1134
+ "M[a,b]; watch logits[a] and logits[b], or `display M[a,b]` to see it "
1135
+ "after every stop")
1136
+ try:
1137
+ item = ctx.table.add_watch(address, _program(ctx), predicate=predicate, mode=mode,
1138
+ adapter=_adapter(ctx))
1139
+ except ValueError as error: # Address/Condition/SelectionError, or a mode without predicate
1140
+ raise _table_error(error) from None
1141
+ out: dict[str, Any] = {"watch": item.describe()}
1142
+ if ctx.run is not None:
1143
+ try:
1144
+ primed = bp.prime(ctx.run, item, tokenizer=ctx.tokenizer)
1145
+ except Exception as error: # noqa: BLE001 - nothing stays armed that cannot be read
1146
+ ctx.table.delete([item.id])
1147
+ if isinstance(error, ValueError):
1148
+ raise _table_error(error) from None
1149
+ raise
1150
+ out["baseline"] = primed
1151
+ return out
1152
+
1153
+
1154
+ @op("display", "Show an address after every stop (no address: list displays)",
1155
+ Arg("address", "address"), effect="mutate", usage="display [ADDR]")
1156
+ def _op_display(ctx, address):
1157
+ if address is not None:
1158
+ if len(ctx.displays) >= MAX_DISPLAYS:
1159
+ raise Refused(f"at most {MAX_DISPLAYS} displays")
1160
+ from .predict import _margin
1161
+
1162
+ if _margin(ctx, address) is not None:
1163
+ text = address.strip()
1164
+ else:
1165
+ target = resolve_target(ctx, address)
1166
+ _check_selector(ctx, target)
1167
+ if target.cell is None and target.label is not None:
1168
+ text = address.strip()
1169
+ else:
1170
+ text = target.text
1171
+ ctx.displays[ctx.next_display_id()] = text
1172
+ return {"displays": _displays(ctx)}
1173
+
1174
+
1175
+ @op("undisplay", "Remove displays (all when no ids are given)", Arg("ids", "ints"),
1176
+ effect="mutate", needs_live=False, usage="undisplay [ID ...]")
1177
+ def _op_undisplay(ctx, ids):
1178
+ if ids is None:
1179
+ gone = sorted(ctx.displays)
1180
+ ctx.displays.clear()
1181
+ else:
1182
+ missing = [i for i in ids if i not in ctx.displays]
1183
+ if missing:
1184
+ raise Refused(f"no display {missing[0]}")
1185
+ gone = sorted(ids)
1186
+ for i in ids:
1187
+ del ctx.displays[i]
1188
+ return {"deleted": gone}
1189
+
1190
+
1191
+ # --------------------------------------------------------------------------- values
1192
+
1193
+
1194
+ @op("print", "Reduce a value: shape, dtype, stats, top-k by |value| (logits: by value), "
1195
+ "pointer",
1196
+ Arg("address", "address"),
1197
+ Arg("top", "int", default=5, minimum=1, maximum=16, positional=False, configurable=True),
1198
+ Arg("slice", "int", default=0, minimum=0, maximum=32, positional=False,
1199
+ help="also show the first N selected values", configurable=True),
1200
+ effect="read", usage="print [ADDR] [top=K] [slice=N]")
1201
+ def _op_print(ctx, address, top, slice): # noqa: A002 - the arg name is the wire name
1202
+ margin = _margin_reading(ctx, address)
1203
+ if margin is not None:
1204
+ return margin
1205
+ return _reduction(ctx, resolve_target(ctx, address), k=top, slice_count=slice)
1206
+
1207
+
1208
+ @op("x", "Examine raw values: a bounded slice of the selected, flattened value",
1209
+ Arg("address", "address"),
1210
+ Arg("count", "int", default=16, minimum=1, maximum=64, configurable=True),
1211
+ Arg("offset", "int", default=0, minimum=0), effect="read",
1212
+ usage="x [ADDR] [COUNT] [OFFSET]")
1213
+ def _op_x(ctx, address, count, offset):
1214
+ margin = _margin_reading(ctx, address)
1215
+ if margin is not None:
1216
+ if offset:
1217
+ raise BadArgs(f"offset {offset} is past the 1 selected value")
1218
+ value = margin["margin"]["value"]
1219
+ values = ({"values": [value["value"]], "authority": value["authority"]}
1220
+ if "authority" in value else value)
1221
+ return {"address": margin["address"], "shape": [], "selected_shape": [],
1222
+ "dtype": "float64", "offset": 0, "count": 1, "numel": 1, "values": values,
1223
+ "provenance": margin["provenance"], "margin": margin["margin"]}
1224
+ target = resolve_target(ctx, address)
1225
+ value = _read(ctx, target)
1226
+ selection = _select(ctx, target, value)
1227
+ provenance = _read_info(ctx, target, selection)
1228
+ flat = selection.value.reshape(-1)
1229
+ if offset >= flat.numel():
1230
+ raise BadArgs(f"offset {offset} is past the {flat.numel()} selected values")
1231
+ part = flat[offset:offset + count]
1232
+ values, counts = _json_values(part)
1233
+ out = {
1234
+ "address": target.text,
1235
+ "shape": list(value.shape),
1236
+ "selected_shape": list(selection.value.shape),
1237
+ "dtype": str(value.dtype).removeprefix("torch."),
1238
+ "offset": offset,
1239
+ "count": len(values),
1240
+ "numel": int(flat.numel()),
1241
+ }
1242
+ if part.is_floating_point():
1243
+ authority, reason = _claim(provenance)
1244
+ out["values"] = ({"values": values, "authority": authority} if authority
1245
+ else _unresolved(reason or "refused"))
1246
+ if counts:
1247
+ out["nonfinite"] = counts
1248
+ out["provenance"] = provenance
1249
+ else:
1250
+ out.update(_tokens(ctx, values, keep=64))
1251
+ return out
1252
+
1253
+
1254
+ def _edit_json(record: dict[str, Any]) -> dict[str, Any]:
1255
+ """A staged or committed edit (``Run.staged_info`` / ``Run.committed_edits`` record): the
1256
+ requested value ``supplied``, the selection and mask fields, and every realisation field
1257
+ (cast and realised errors, ``changed_fraction``, replica fields, ``p`` row sums) kept,
1258
+ numbers labelled ``measured`` except the row-sum tolerance, which is ``supplied``."""
1259
+ value = record["value"]
1260
+ out: dict[str, Any] = {"port": record["port"], "op": record["op"], "kind": value["kind"]}
1261
+ if value["kind"] == "scalar":
1262
+ out["value"] = _num(value["value"], "supplied")
1263
+ else:
1264
+ out.update(sha256=value["sha256"], shape=value["shape"],
1265
+ dtype=value["dtype"].removeprefix("torch."))
1266
+ for key, item in record.items():
1267
+ if key in ("port", "op", "value"):
1268
+ continue
1269
+ if key in ("row_sum_tolerance", "dose"):
1270
+ out[key] = _num(item, "supplied")
1271
+ else:
1272
+ out[key] = _labelled(key, item)
1273
+ return out
1274
+
1275
+
1276
+ def value_source(ctx, value, target: Target | None = None):
1277
+ """A scalar, the tensor at another computed address of the same run, or (with the edited
1278
+ ``target``) an SAE feature expression (``feature[ID]*X``, ``feature[ID,coef]``, ``error``,
1279
+ ``recon``, ``bias``; ``mdb.ops.features.feature_value``)."""
1280
+ if not isinstance(value, str):
1281
+ return value, None
1282
+ if target is not None:
1283
+ from .features import feature_value, is_feature_expression
1284
+
1285
+ if is_feature_expression(value):
1286
+ return feature_value(ctx, target, value)
1287
+ try:
1288
+ return float(value), None
1289
+ except ValueError:
1290
+ pass
1291
+ source = resolve_target(ctx, value)
1292
+ tensor = _read(ctx, source)
1293
+ return _select(ctx, source, tensor).value, source.text
1294
+
1295
+
1296
+ def finite_limit(run, value) -> None:
1297
+ import torch
1298
+
1299
+ dtype = run.adapter.dtype
1300
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and dtype.is_floating_point:
1301
+ limit = float(torch.finfo(dtype).max)
1302
+ if abs(float(value)) > limit:
1303
+ raise Refused(
1304
+ f"{value!r} is outside the finite range of {str(dtype).removeprefix('torch.')} "
1305
+ f"(|x| <= {limit:.6g}); nothing was staged")
1306
+
1307
+
1308
+ def _cell_block(ctx, text: str):
1309
+ """The block ``(1, kv, rows, d)`` an address of this run names, as a cell value."""
1310
+ from .debugger import cell_block
1311
+
1312
+ run = ctx.run
1313
+ found = resolve_target(ctx, text)
1314
+ if found.cell is not None:
1315
+ return cell_block(run, found.cell), found.text
1316
+ if found.layer_port is None:
1317
+ raise Refused(f"a cell value is a cache cell or a v/kr occurrence, not {found.text}")
1318
+ parsed = addresses.parse(found.text, ports=run.program.names, global_ports=GLOBALS)
1319
+ return cell_block(run, parsed), found.text
1320
+
1321
+
1322
+ def cell_request(ctx, found: Target, value: Any, op: str, dose: float | None) -> dict[str, Any]:
1323
+ """A state-cell edit request from op arguments: ``{layer, tensor, rows, kv, d, value, op,
1324
+ dose, selection, source, origin}``. The selector picks kv heads, rows (default: every row
1325
+ written at the cursor) and head-dim offsets; a tensor value must have the picked block's
1326
+ shape ``(1, kv, rows, d)`` exactly."""
1327
+ from mdb.engine.edits import CELL_AXES, CELL_OPS
1328
+
1329
+ run = ctx.run
1330
+ cell = found.cell
1331
+ if op not in CELL_OPS:
1332
+ raise BadArgs(f"a cell op is one of {', '.join(CELL_OPS)}")
1333
+ if (op == "mix") != (dose is not None):
1334
+ raise BadArgs("mix needs a dose (set ADDR = VALUE mix DOSE), and only mix takes one")
1335
+ current = run.read_cache(cell.layer, cell.tensor, staged=False)
1336
+ length = int(current.shape[2])
1337
+ bp = _bp()
1338
+ sizes = [1, int(current.shape[1]), None, int(current.shape[3])]
1339
+ try:
1340
+ picks = bp.plan(CELL_AXES, sizes, cell.selector, head_dim=run.adapter.head_dim)
1341
+ except bp.SelectionRange as error:
1342
+ raise Refused(f"{found.text}: {error}") from None
1343
+ except bp.SelectionError as error:
1344
+ raise BadArgs(f"{found.text}: {error}") from None
1345
+ rows = list(range(length)) if picks[2] is None else list(picks[2])
1346
+ if not rows:
1347
+ raise Refused(f"{found.text} holds no rows yet at {run.where}")
1348
+ kv = None if picks[1] is None else list(picks[1])
1349
+ d = None if picks[3] is None else list(picks[3])
1350
+ source = origin = None
1351
+ if isinstance(value, str):
1352
+ try:
1353
+ value = float(value)
1354
+ except ValueError:
1355
+ source = value.strip()
1356
+ if ":" in source.partition("[")[0]:
1357
+ value, origin = ctx.debugger.cell_value(source, run=run)
1358
+ else:
1359
+ value, source = _cell_block(ctx, source)
1360
+ if isinstance(value, (int, float)):
1361
+ finite_limit(run, value)
1362
+ else:
1363
+ want = (1, len(kv) if kv else int(current.shape[1]), len(rows),
1364
+ len(d) if d else int(current.shape[3]))
1365
+ if tuple(value.shape) != want:
1366
+ differ = ", ".join(f"{axis} {have} vs {need}" for axis, have, need
1367
+ in zip(CELL_AXES, value.shape, want) if have != need)
1368
+ raise Refused(f"{source} selects shape {list(value.shape)}; {found.text} selects "
1369
+ f"{list(want)} ({differ}); select the same block on both sides")
1370
+ selection = found.text.partition("[")[2].rstrip("]") or None
1371
+ return {"layer": cell.layer, "tensor": cell.tensor, "rows": rows, "kv": kv, "d": d,
1372
+ "value": value, "op": op, "dose": dose, "selection": selection, "source": source,
1373
+ "origin": origin}
1374
+
1375
+
1376
+ def _is_origin_value(value: Any) -> bool:
1377
+ """``ORIGIN:ADDR``: a value text with a ``:`` before any selector bracket."""
1378
+ return isinstance(value, str) and ":" in value.partition("[")[0]
1379
+
1380
+
1381
+ def _is_import(ctx, value: str) -> bool:
1382
+ """``IMPORT:t<r>.L<l>.<port>``: values another tool computed (``Debugger.import_values``),
1383
+ taken as a whole port that the edited target's selector masks."""
1384
+ branch = value.partition(":")[0].strip()
1385
+ return branch in getattr(ctx.debugger, "imports", {})
1386
+
1387
+
1388
+ def origin_port_value(ctx, text: str):
1389
+ """``(tensor, pointer)`` of ``ORIGIN:ADDR`` for a port edit: the occurrence ADDR names in
1390
+ the run ORIGIN stands for, with ADDR's selector applied there. ADDR is read with this
1391
+ run's defaults (a missing row is the cursor's row, a bare port the current layer, as for an
1392
+ address of this run) and may name another row or layer than the edited port. The fetch is
1393
+ ``Debugger.origin_value`` (the one cell edits use): the donor's cursor and state are left
1394
+ as they were. The selected block is sliced first and then cast once to this run's dtype."""
1395
+ run = ctx.run
1396
+ branch, _, rest = (part.strip() for part in text.strip().partition(":"))
1397
+ if branch.startswith("@"):
1398
+ raise Refused(f"{text}: an @cut origin is not a run; name a run (info runs), a project "
1399
+ "session id or a durable checkpoint name")
1400
+ if not branch or not rest:
1401
+ raise BadArgs(f"{text}: write ORIGIN:ADDR (a run name, then an address of that run)")
1402
+ if ctx.debugger is None:
1403
+ raise Refused(f"{text}: a value from another run needs the debugger's named runs "
1404
+ "(mdb.attach, then start ... name=NAME)")
1405
+ if rest.startswith("cache."):
1406
+ raise Refused(f"{text}: a port takes a port or stop occurrence of another run, not a "
1407
+ "cache cell; put a cache cell into a cache cell (set cache.L<i>.k|v[...] = "
1408
+ f"{text})")
1409
+ source = resolve_target(ctx, rest)
1410
+ if source.label == "start":
1411
+ raise Refused(f"{text}: start is the token list, not a value")
1412
+ label = f"{branch}:{source.text}"
1413
+
1414
+ def pick(donor):
1415
+ from .debugger import NotHeld
1416
+
1417
+ try:
1418
+ tensor = donor.read(source.run_target)
1419
+ except ValueError as error:
1420
+ if donor.parse(source.run_target) > donor.parse(donor.where):
1421
+ raise NotHeld(f"{branch} has not computed {source.run_target} (it is at "
1422
+ f"{donor.where}): run it there first (frame {branch}: then "
1423
+ f"until {source.run_target})") from None
1424
+ raise NotHeld(f"{label}: {error} (start {branch} with `start name={branch} "
1425
+ "prefill=K ...` to step that row; the keys and values of a prefilled "
1426
+ "row are the cache cells cache.L<i>.k|v[row=N], which a cell edit "
1427
+ "takes)") from None
1428
+ block = _select(ctx, source, tensor).value
1429
+ # one move: the selected block to this run's device and dtype together (a donor of
1430
+ # another device is moved, never mixed with this run's tensors)
1431
+ if block.dtype != run.adapter.dtype or block.device != run.adapter.device:
1432
+ block = block.to(device=run.adapter.device, dtype=run.adapter.dtype)
1433
+ return block.detach().clone()
1434
+
1435
+ return ctx.debugger.origin_value(branch, label, run=run, pick=pick)
1436
+
1437
+
1438
+ def port_request(ctx, found: Target, value: Any) -> dict[str, Any]:
1439
+ """A port edit request from op arguments: ``{value, mask, selection, source, origin}``.
1440
+
1441
+ ``value`` is a number, an address of this run (its value) or ``ORIGIN:ADDR`` (the value of
1442
+ another run, ``origin_port_value``; ``origin`` is then its pointer). A selector on the
1443
+ edited port becomes ONE masked edit (shape known without running anything): the op applies
1444
+ to the selected elements only and the rest stay bit-identical, the same ahead of the cursor
1445
+ as at it. A value of this run broadcasts to the selection; a value of another run must
1446
+ have the selected block's shape exactly (a patch copies a block, it does not broadcast)."""
1447
+ import torch
1448
+
1449
+ run = ctx.run
1450
+ origin = None
1451
+ whole = False # an import's whole port (``Debugger.port_value``): the selector masks it
1452
+ if _is_origin_value(value) and _is_import(ctx, value):
1453
+ source, whole = value.strip(), True
1454
+ value, origin = ctx.debugger.port_value(source, run=run)
1455
+ elif _is_origin_value(value):
1456
+ value, origin = origin_port_value(ctx, value)
1457
+ source = origin["address"]
1458
+ else:
1459
+ value, source = value_source(ctx, value, found)
1460
+ finite_limit(run, value)
1461
+ shape = tuple(run.port_shape(found.layer_port[1]))
1462
+ mask = selection = None
1463
+ if found.selector:
1464
+ axes = _axes(ctx, found)
1465
+ mask, index, chosen = selector_mask(
1466
+ axes, shape, found.selector, head_dim=run.adapter.head_dim,
1467
+ row=found.row if "row" in axes else None, tokenizer=ctx.tokenizer, text=found.text)
1468
+ selection = found.text.partition("[")[2].rstrip("]")
1469
+ else:
1470
+ index, chosen = None, shape
1471
+ if origin is not None and not whole and tuple(value.shape) != tuple(chosen):
1472
+ raise Refused(f"{source} selects shape {list(value.shape)}; {found.text} selects "
1473
+ f"{list(chosen)}; select the same block on both sides (the same port "
1474
+ "kind, heads and row length)")
1475
+ if index is not None and isinstance(value, torch.Tensor) and not whole:
1476
+ if torch.broadcast_shapes(value.shape, chosen) != chosen:
1477
+ raise BadArgs(f"{source} does not broadcast to the selection {list(chosen)}")
1478
+ # the block is built where the value lives (a donor's value is on the model's device;
1479
+ # the host-built index and mask move to it, the selector's tensors are tiny)
1480
+ where = value.device
1481
+ full = torch.zeros(shape, dtype=run.adapter.dtype, device=where)
1482
+ full[tuple(axis.to(where) for axis in index)] = value.to(run.adapter.dtype).expand(chosen)
1483
+ value = full
1484
+ return {"value": value, "mask": mask, "selection": selection, "source": source,
1485
+ "origin": origin}
1486
+
1487
+
1488
+ def _set_cell(ctx, found: Target, value: Any, op: str, dose: float | None) -> dict[str, Any]:
1489
+ from mdb.engine.edits import CELL_BOUNDARY, CELL_READ
1490
+
1491
+ run = ctx.run
1492
+ request = cell_request(ctx, found, value, op, dose)
1493
+ try:
1494
+ run.set_cell(request["layer"], request["tensor"], request["value"], op,
1495
+ rows=request["rows"], kv=request["kv"], d=request["d"], dose=dose,
1496
+ selection=request["selection"], origin=request["origin"])
1497
+ except ValueError as error:
1498
+ raise Refused(f"{found.text}: {error}") from None
1499
+ record = run.staged_cells()[-1]
1500
+ tensor = request["tensor"]
1501
+ out: dict[str, Any] = {
1502
+ "target": found.text, "edits": [_edit_json(record)], "staged": len(run.edits),
1503
+ "staged_cells": len(run.cells), "where": run.where,
1504
+ "cell": {"layer": request["layer"], "tensor": tensor, "rows": request["rows"],
1505
+ "kv": request["kv"], "d": request["d"], "timing": record["cell"]["timing"],
1506
+ "read": f"L{request['layer']}.{CELL_READ[tensor]}",
1507
+ "boundary": f"L{request['layer']}.{CELL_BOUNDARY[tensor]}"},
1508
+ }
1509
+ if request["source"] is not None:
1510
+ out["source"] = request["source"]
1511
+ if request["origin"] is not None:
1512
+ out["origin"] = dict(request["origin"])
1513
+ return out
1514
+
1515
+
1516
+ @op("set", "Stage an edit at a port of the pending layer, or of a state cell "
1517
+ "(cache.L<i>.k|v[kv,row,d]): set ADDR = VALUE [op]",
1518
+ Arg("target", "address", required=True), Arg("value", "value", required=True),
1519
+ Arg("op", "choice", default="replace", choices=("replace", "add", "scale", "mix")),
1520
+ Arg("dose", "number", positional=False, help="mix only: cell + dose * (value - cell)"),
1521
+ effect="mutate", usage="set ADDR = VALUE|ADDR|ORIGIN:ADDR [replace|add|scale|mix DOSE]")
1522
+ def _op_set(ctx, target, value, op, dose=None):
1523
+ run = ctx.run
1524
+ found = resolve_target(ctx, target)
1525
+ if found.cell is not None:
1526
+ return _set_cell(ctx, found, value, op, dose)
1527
+ if found.layer_port is None:
1528
+ raise Refused(f"edits apply to ports of the pending layer, not {found.text}")
1529
+ if op == "mix" or dose is not None:
1530
+ raise Refused("mix DOSE applies to state cells (cache.L<i>.k|v); a port takes "
1531
+ "replace, add or scale")
1532
+ request = port_request(ctx, found, value)
1533
+ # atomic: failure stages nothing (check: an edit the cursor's values see is realised now)
1534
+ manifest = run.set(found.run_target, request["value"], op, mask=request["mask"],
1535
+ selection=request["selection"], origin=request["origin"], check=True)
1536
+ staged = run.staged_info()
1537
+ out = {"target": found.text, "edits": [_edit_json(staged[-1] if staged else manifest)],
1538
+ "staged": len(run.edits), "where": run.where}
1539
+ if request["source"] is not None:
1540
+ out["source"] = request["source"]
1541
+ if request["origin"] is not None:
1542
+ out["origin"] = dict(request["origin"])
1543
+ if found.selector:
1544
+ out["realised_as"] = f"one masked {op} on the selected elements"
1545
+ return out
1546
+
1547
+
1548
+ @op("commit", "Commit the pending layer with its staged edits (cursor to its h_out)",
1549
+ effect="mutate", motion=True)
1550
+ def _op_commit(ctx):
1551
+ committed = len(ctx.run.edits)
1552
+ cells = len(getattr(ctx.run, "cells", ()))
1553
+ try:
1554
+ ctx.run.commit()
1555
+ except ValueError as error:
1556
+ if committed:
1557
+ raise Refused(
1558
+ f"cannot commit: the engine refused the layer state ({error}). Staged edits "
1559
+ "that make a value non-finite (inf/nan) cannot be committed: inspect the "
1560
+ "edited ports with `print`, then run `abort` to drop the staged edits."
1561
+ ) from error
1562
+ raise
1563
+ extra = {"committed": committed}
1564
+ if cells:
1565
+ extra["committed_cells"] = cells
1566
+ return moved(ctx, extra)
1567
+
1568
+
1569
+ @op("abort", "Drop the staged edits of the pending layer (and the staged cell edits)",
1570
+ effect="mutate")
1571
+ def _op_abort(ctx):
1572
+ dropped = len(ctx.run.edits)
1573
+ cells = len(getattr(ctx.run, "cells", ()))
1574
+ ctx.run.abort()
1575
+ extra = {"count": dropped}
1576
+ if cells:
1577
+ extra["staged_cells"] = cells
1578
+ return moved(ctx, extra)
1579
+
1580
+
1581
+ # --------------------------------------------------------------------------- program
1582
+
1583
+
1584
+ def _checks(ctx) -> dict[str, Any]:
1585
+ out = {}
1586
+ for name, check in ctx.run.checks.items():
1587
+ item = {key: value for key, value in check.items() if isinstance(value, bool)}
1588
+ if "max_abs_diff" in check:
1589
+ item["max_abs_diff"] = _num(check["max_abs_diff"])
1590
+ out[name] = item
1591
+ return out
1592
+
1593
+
1594
+ @op("list", "The layer's port program: operator text, proof IDs, cursor marked",
1595
+ Arg("layer", "int", minimum=0), effect="read", usage="list [LAYER]")
1596
+ def _op_list(ctx, layer):
1597
+ run = ctx.run
1598
+ row, label = _split(run.where)
1599
+ focus_port = None
1600
+ if layer is None:
1601
+ layer = _current_layer(ctx)
1602
+ if layer is None:
1603
+ layer = 0 if label in ("start", "emb") else run.adapter.layers - 1
1604
+ if layer >= run.adapter.layers:
1605
+ raise BadArgs(f"no layer {layer} in a {run.adapter.layers}-layer model")
1606
+ match = _LAYER_PORT.fullmatch(label)
1607
+ at = match["port"] if match is not None and int(match["layer"]) == layer else None
1608
+ if ctx.focus:
1609
+ found = _LAYER_PORT.search(ctx.focus)
1610
+ if found is not None and int(found["layer"]) == layer:
1611
+ focus_port = found["port"].split("[")[0]
1612
+ here = run.parse(run.where)
1613
+ rows = []
1614
+ for spec in run.program.ports:
1615
+ key = run.parse(f"t{row}.L{layer}.{spec.name}")
1616
+ rows.append({
1617
+ "port": spec.name,
1618
+ "sublayer": spec.sublayer,
1619
+ "operator": spec.operator,
1620
+ "proofs": list(spec.proofs),
1621
+ "editable": spec.editable,
1622
+ "cursor": spec.name == at,
1623
+ "focus": spec.name == focus_port,
1624
+ "computed": key <= here,
1625
+ })
1626
+ out = {"layer": layer, "row": row, "where": run.where, "ports": rows}
1627
+ if run.pending_layer == layer and ctx.run.checks:
1628
+ out["checks"] = _checks(ctx)
1629
+ return out
1630
+
1631
+
1632
+ def _focus_parts(ctx, address: str | None) -> tuple[int, str]:
1633
+ target = resolve_target(ctx, address)
1634
+ if target.label is None:
1635
+ raise BadArgs("backtrace and up/down follow port occurrences, not cache cells")
1636
+ return target.row, target.label
1637
+
1638
+
1639
+ def _producers(program, layers: int, label: str) -> list[str]:
1640
+ """Every producer frame of a stop, nearest-first (the first is what ``up`` follows)."""
1641
+ match = _LAYER_PORT.fullmatch(label)
1642
+ if match is None:
1643
+ found = {"emb": "start", "fn": f"L{layers - 1}.h_out", "logits": "fn",
1644
+ "sample": "logits"}.get(label)
1645
+ return [] if found is None else [found]
1646
+ layer, port = int(match["layer"]), match["port"]
1647
+ inputs = graph.producers(program)[port]
1648
+ if inputs:
1649
+ return [f"L{layer}.{item}" for item in inputs]
1650
+ return ["emb" if layer == 0 else f"L{layer - 1}.h_out"]
1651
+
1652
+
1653
+ def _producer(program, layers: int, label: str) -> str | None:
1654
+ found = _producers(program, layers, label)
1655
+ return found[0] if found else None
1656
+
1657
+
1658
+ def _consumer(program, layers: int, label: str) -> str | None:
1659
+ match = _LAYER_PORT.fullmatch(label)
1660
+ if match is None:
1661
+ return {"start": "emb", "emb": "L0.h", "fn": "logits", "logits": "sample"}.get(label)
1662
+ layer, port = int(match["layer"]), match["port"]
1663
+ outputs = graph.consumers(program)[port]
1664
+ if outputs:
1665
+ return f"L{layer}.{outputs[0]}"
1666
+ return f"L{layer + 1}.h" if layer + 1 < layers else "fn"
1667
+
1668
+
1669
+ @op("backtrace", "Producer chain from the focus port back to the layer input",
1670
+ Arg("address", "address"), effect="read", usage="backtrace [ADDR]")
1671
+ def _op_backtrace(ctx, address):
1672
+ run = ctx.run
1673
+ row, label = _focus_parts(ctx, address)
1674
+ match = _LAYER_PORT.fullmatch(label)
1675
+ frames = []
1676
+ if match is None:
1677
+ levels, item = [], label
1678
+ while item is not None and _LAYER_PORT.fullmatch(item) is None:
1679
+ levels.append([item])
1680
+ item = _producer(run.program, run.adapter.layers, item)
1681
+ if item is not None:
1682
+ levels.append([item])
1683
+ for level, names in enumerate(levels):
1684
+ for name in names:
1685
+ frames.append({"level": level, **_stop(ctx, f"t{row}.{name}")})
1686
+ chain = graph.chain_text(levels)
1687
+ else:
1688
+ layer = int(match["layer"])
1689
+ levels = graph.layering(run.program, match["port"])
1690
+ edges = graph.producers(run.program)
1691
+ extra = graph.pseudo(run.program)
1692
+ for level, names in enumerate(levels):
1693
+ for name in names:
1694
+ frame = _stop(ctx, f"t{row}.L{layer}.{name}")
1695
+ frame["level"] = level
1696
+ frame["inputs"] = [p for p in edges[name] if any(p in lv for lv in levels)]
1697
+ if extra[name]:
1698
+ frame["reads"] = list(extra[name]) # pseudo-nodes: cache, prev_layer
1699
+ frames.append(frame)
1700
+ chain = graph.chain_text(levels)
1701
+ return {"focus": f"t{row}.{label}", "chain": chain, "frames": frames}
1702
+
1703
+
1704
+ @op("up", "Move the focus to a producer (toward the layer input), N times; `up PORT` picks "
1705
+ "the producer by name, the result lists the alternatives", _N,
1706
+ Arg("port", "str", help="the producer to follow first, e.g. o from r"),
1707
+ effect="navigate", usage="up [N] [PORT]")
1708
+ def _op_up(ctx, n, port):
1709
+ run = ctx.run
1710
+ layers = run.adapter.layers
1711
+ row, label = _focus_parts(ctx, None)
1712
+ stack = list(ctx.focus_stack)
1713
+ here = ctx.focus or run.where
1714
+ options: list[str] = []
1715
+ for step in range(n): # computed on copies: a refusal leaves the focus where it was
1716
+ options = _producers(run.program, layers, label)
1717
+ if not options:
1718
+ raise Refused(f"no frame beyond t{row}.{label}")
1719
+ chosen = options[0]
1720
+ if port is not None and step == 0:
1721
+ named = [o for o in options if o.split(".")[-1] == port or o == port]
1722
+ if not named:
1723
+ raise Refused(f"t{row}.{label} has no producer {port!r}; producers: "
1724
+ + ", ".join(options))
1725
+ chosen = named[0]
1726
+ stack.append(here) # one stack entry per frame, so `down 1` walks back one frame
1727
+ label = chosen
1728
+ here = f"t{row}.{label}"
1729
+ ctx.focus, ctx.focus_stack = here, stack
1730
+ out: dict[str, Any] = {"focus": ctx.focus, "frame": _stop(ctx, ctx.focus),
1731
+ "producers": options, "alternatives": [o for o in options
1732
+ if o != label]}
1733
+ if run.parse(ctx.focus) > run.parse(run.where):
1734
+ out["computed"] = False
1735
+ return out
1736
+
1737
+
1738
+ @op("down", "Move the focus back toward its consumer, N times", _N, effect="navigate",
1739
+ usage="down [N]")
1740
+ def _op_down(ctx, n):
1741
+ run = ctx.run
1742
+ focus, stack = ctx.focus, list(ctx.focus_stack)
1743
+ for _ in range(n):
1744
+ if stack:
1745
+ focus = stack.pop()
1746
+ continue
1747
+ row, label = _focus_parts(ctx, focus)
1748
+ nxt = _consumer(run.program, run.adapter.layers, label)
1749
+ if nxt is None:
1750
+ raise Refused(f"no consumer frame after t{row}.{label}")
1751
+ focus = f"t{row}.{nxt}"
1752
+ ctx.focus, ctx.focus_stack = focus, stack
1753
+ if ctx.focus == run.where:
1754
+ ctx.focus = None
1755
+ focus = ctx.focus or run.where
1756
+ return {"focus": focus, "frame": _stop(ctx, resolve_target(ctx, focus).run_target)}
1757
+
1758
+
1759
+ # --------------------------------------------------------------------------- info
1760
+
1761
+
1762
+ def _program_info(ctx) -> dict[str, Any]:
1763
+ program = _program(ctx)
1764
+ adapter = ctx.run.adapter if ctx.run is not None else ctx.debugger.adapter
1765
+ return {
1766
+ "family": program.family,
1767
+ "modeling": program.modeling,
1768
+ "layers": adapter.layers,
1769
+ "hidden_size": adapter.hidden_size,
1770
+ "heads": adapter.num_heads,
1771
+ "kv_heads": adapter.num_kv_heads,
1772
+ "head_dim": adapter.head_dim,
1773
+ "vocab_size": adapter.vocab_size,
1774
+ "max_positions": adapter.max_positions,
1775
+ "dtype": str(adapter.dtype).removeprefix("torch."),
1776
+ "device": str(adapter.device),
1777
+ "attention": adapter.execution.get("attention"),
1778
+ "lookahead": getattr(ctx.run, "lookahead", None),
1779
+ "port_names": list(program.names),
1780
+ "globals": list(GLOBALS),
1781
+ }
1782
+
1783
+
1784
+ @op("info", "Show debugger tables or the program (lists are paged: offset=, limit=)",
1785
+ Arg("subject", "choice", required=True,
1786
+ choices=("ports", "breakpoints", "watch", "display", "checkpoints", "edits",
1787
+ "program", "runs")),
1788
+ _OFFSET, _LIMIT,
1789
+ effect="read", needs_live=False, usage="info ports|breakpoints|watch|display|checkpoints|"
1790
+ "edits|program|runs [offset=N] [limit=N]")
1791
+ def _op_info(ctx, subject, offset, limit):
1792
+ if subject == "runs":
1793
+ runs = getattr(ctx.debugger, "runs", {}) if ctx.debugger is not None else {}
1794
+ items = [{"name": name, "where": run.where, "prompt_tokens": len(run.tokens),
1795
+ "staged": len(run.edits), "staged_cells": len(run.cells),
1796
+ "prefill": procedure_json(run),
1797
+ "current": run is ctx.run} for name, run in runs.items()]
1798
+ shown, meta = _page(items, offset, limit)
1799
+ return {"subject": subject, "runs": shown, **meta}
1800
+ if subject == "program":
1801
+ return {"subject": subject, "program": _program_info(ctx)}
1802
+ if subject == "ports":
1803
+ program = _program(ctx)
1804
+ return {"subject": subject, "family": program.family,
1805
+ "ports": [spec.to_dict() for spec in program.ports]}
1806
+ if subject in ("breakpoints", "watch"):
1807
+ items = [item.describe() for item in ctx.table.listed()] if ctx._table else []
1808
+ if subject == "watch":
1809
+ items = [item for item in items if item["kind"] == "watch"]
1810
+ page, meta = _page(items, offset, limit)
1811
+ return {"subject": subject, "items": page, **meta}
1812
+ if subject == "display":
1813
+ shown, meta = _page([{"id": number, "address": text}
1814
+ for number, text in sorted(ctx.displays.items())], offset, limit)
1815
+ return {"subject": subject, "displays": shown, **meta}
1816
+ if subject == "checkpoints":
1817
+ shown, meta = _page(_checkpoint_list(ctx), offset, limit)
1818
+ return {"subject": subject, "checkpoints": shown, **meta}
1819
+ if ctx.run is None:
1820
+ raise Refused("info edits needs a live run")
1821
+ staged = ctx.run.staged_info()
1822
+ groups: dict[int, dict[str, Any]] = {}
1823
+ for record in ctx.run.committed_edits():
1824
+ group = groups.setdefault(record["transition"], {
1825
+ "transition": record["transition"], "layer": record["layer"], "row": record["row"],
1826
+ "edits": []})
1827
+ group["edits"].append(record)
1828
+ entries = list(groups.values())
1829
+ # One window over the staged edits followed by the committed layers.
1830
+ total = len(staged) + len(entries)
1831
+ out_staged = [_edit_json(m) for m in staged[offset:offset + limit]]
1832
+ lo = max(0, offset - len(staged))
1833
+ hi = max(0, offset + limit - len(staged))
1834
+ out_committed = []
1835
+ for entry in entries[lo:hi]:
1836
+ edits = entry["edits"]
1837
+ item = {"transition": entry["transition"], "layer": entry["layer"], "row": entry["row"],
1838
+ "edits": [_edit_json(m) for m in edits[:limit]],
1839
+ "edits_total": len(edits)}
1840
+ if len(edits) > limit:
1841
+ item["omitted"] = len(edits) - limit
1842
+ out_committed.append(item)
1843
+ out = {"subject": subject, "staged": out_staged, "committed": out_committed,
1844
+ "where": ctx.run.where, "staged_total": len(staged),
1845
+ "committed_total": len(entries), "total": total, "offset": offset, "limit": limit}
1846
+ staged_cells, committed_cells = ctx.run.staged_cells(), ctx.run.committed_cells()
1847
+ if staged_cells or committed_cells:
1848
+ out["cells"] = {"staged": [_edit_json(m) for m in staged_cells[:limit]],
1849
+ "committed": [_edit_json(m) for m in committed_cells[:limit]],
1850
+ "staged_total": len(staged_cells),
1851
+ "committed_total": len(committed_cells)}
1852
+ left = {kind: len(listed) - limit for kind, listed in
1853
+ (("staged", staged_cells), ("committed", committed_cells))
1854
+ if len(listed) > limit}
1855
+ if left: # +N more: never a silent cut at ``limit``
1856
+ out["cells"]["omitted"] = left
1857
+ return out
1858
+
1859
+
1860
+ # --------------------------------------------------------------------------- checkpoints
1861
+
1862
+
1863
+ def _checkpoint_list(ctx) -> list[dict[str, Any]]:
1864
+ rows = {name: {"name": name, "where": cp["where"], "staged": len(cp["edits"]),
1865
+ "committed": len(cp["path_edits"])}
1866
+ for name, cp in ctx.checkpoints.items()}
1867
+ if project_of(ctx) is not None: # the project's, this process's or an earlier one's
1868
+ for cp in ctx.debugger.checkpoints(): # oldest first: the latest of a name wins
1869
+ row = rows.setdefault(cp["name"], {"name": cp["name"], "where": cp["where"]})
1870
+ row["record"] = cp["state"]
1871
+ return list(rows.values())
1872
+
1873
+
1874
+ @op("checkpoint", "Name the cursor position (about 1 KB of plain data)",
1875
+ Arg("name", "str"), effect="mutate", usage="checkpoint [NAME]")
1876
+ def _op_checkpoint(ctx, name):
1877
+ if name is not None and len(name) > MAX_CHECKPOINT_NAME:
1878
+ raise Refused(f"a checkpoint name is at most {MAX_CHECKPOINT_NAME} characters (this one "
1879
+ f"has {len(name)})")
1880
+ if len(ctx.checkpoints) >= MAX_CHECKPOINTS and name not in ctx.checkpoints:
1881
+ raise Refused(f"at most {MAX_CHECKPOINTS} checkpoints; reuse a name or start again")
1882
+ name = name or ctx.next_checkpoint_name()
1883
+ checkpoint = ctx.run.checkpoint(name)
1884
+ result = {"name": name, "where": checkpoint["where"],
1885
+ "bytes": len(json.dumps(checkpoint, sort_keys=True))}
1886
+ if project_of(ctx) is not None: # durable: recipe, edit blobs and cursor go to the project
1887
+ # Durable first: an interrupt leaves no checkpoint, or a durable one `restart` finds;
1888
+ # never an in-memory checkpoint that the project does not hold.
1889
+ stored = ctx.debugger.checkpoint(ctx.run, name)
1890
+ # record: the stored state, what `start from=` takes; edit_blobs: the recipe's edit
1891
+ # tensors (the state's own tensors are blobs of that record)
1892
+ result["durable"] = {"record": stored["state"], "recipe": stored["recipe"],
1893
+ "edit_blobs": stored["blobs"]}
1894
+ ctx.checkpoints[name] = checkpoint
1895
+ return result
1896
+
1897
+
1898
+ def project_of(ctx):
1899
+ return getattr(ctx.debugger, "project", None)
1900
+
1901
+
1902
+ @op("checkpoints", "List named checkpoints (paged: offset=, limit=)", _OFFSET, _LIMIT,
1903
+ effect="read", needs_live=False, usage="checkpoints [offset=N] [limit=N]")
1904
+ def _op_checkpoints(ctx, offset, limit):
1905
+ shown, meta = _page(_checkpoint_list(ctx), offset, limit)
1906
+ return {"checkpoints": shown, **meta}
1907
+
1908
+
1909
+ @op("restart", "Return to a named checkpoint (rewinds or replays)",
1910
+ Arg("name", "str", required=True), effect="navigate", motion=True, needs_live=False,
1911
+ usage="restart NAME")
1912
+ def _op_restart(ctx, name):
1913
+ if ctx.run is not None and name in ctx.checkpoints:
1914
+ ctx.run.restore(ctx.checkpoints[name])
1915
+ elif project_of(ctx) is not None: # a checkpoint an earlier process stored in the project
1916
+ ctx.set_run(ctx.debugger.restart(name))
1917
+ elif ctx.run is None:
1918
+ raise Refused("no run to rewind; start one with run, or attach with project= to "
1919
+ "restart a stored checkpoint")
1920
+ else:
1921
+ known = ", ".join(ctx.checkpoints) or "none"
1922
+ raise Refused(f"no checkpoint {name!r} (have: {known})")
1923
+ ctx.table.reset_watches()
1924
+ return moved(ctx, {"name": name})
1925
+
1926
+
1927
+ # --------------------------------------------------------------------------- reverse
1928
+
1929
+
1930
+ @op("reverse-step", "Step back one port (or N units; layer/token units enter at most `budget` "
1931
+ "rows)", _N,
1932
+ Arg("unit", "choice", default="port", choices=("port", "sublayer", "layer", "token")),
1933
+ _BUDGET, effect="navigate", motion=True,
1934
+ usage="reverse-step [N] [unit] [budget=ROWS]")
1935
+ def _op_reverse_step(ctx, n, unit, budget):
1936
+ return _step_back(ctx, n, unit, budget)
1937
+
1938
+
1939
+ @op("reverse-next", "Step back to the previous sublayer end", _N, effect="navigate",
1940
+ motion=True, usage="reverse-next [N]")
1941
+ def _op_reverse_next(ctx, n):
1942
+ return _step_back(ctx, n, "sublayer", 1)
1943
+
1944
+
1945
+ @op("reverse-finish", "Step back to the boundary before the pending layer (its input)",
1946
+ effect="navigate", motion=True)
1947
+ def _op_reverse_finish(ctx):
1948
+ return _step_back(ctx, 1, "layer", 1)
1949
+
1950
+
1951
+ @op("reverse-continue", "Run backwards to the previous breakpoint or watch hit",
1952
+ effect="navigate", motion=True)
1953
+ def _op_reverse_continue(ctx):
1954
+ result = _bp().run_reverse(ctx.run, ctx.table, tokenizer=ctx.tokenizer)
1955
+ return _stopped(ctx, result, {})
1956
+
1957
+
1958
+ # --------------------------------------------------------------------------- slots
1959
+
1960
+ @op("export", "Write a durable checkpoint and the records that reference it to a new directory "
1961
+ "another project imports (start from=DIR)",
1962
+ Arg("name", "str", required=True, help="a durable checkpoint name (checkpoints)"),
1963
+ Arg("to", "str", required=True, positional=False, help="the bundle directory (new or empty)"),
1964
+ effect="mutate", needs_live=False, usage="export NAME to=DIR") # it writes a directory
1965
+ def _op_export(ctx, name, to):
1966
+ if ctx.debugger is None:
1967
+ raise Refused("no model attached; use mdb.attach(model) or --tiny")
1968
+ manifest = ctx.debugger.export_bundle(name, to)
1969
+ return {"export": name, "path": str(Path(to).expanduser().absolute()),
1970
+ "state": manifest["state"], "checkpoint": manifest["checkpoint"],
1971
+ "recipe": manifest["recipe"], "records": manifest["records"]}
1972
+
1973
+ # old private names, kept for one commit
1974
+ _target, _value_source, _finite_limit = resolve_target, value_source, finite_limit
1975
+ _moved, _project = moved, project_of
1976
+
1977
+ from . import sweep as _sweep # noqa: E402,F401 - registers `sweep` (it imports from here)