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/registry.py ADDED
@@ -0,0 +1,332 @@
1
+ """The one operation registry: every front end (REPL, ``--json``, server, remote worker)
2
+ dispatches through ``dispatch(ctx, name, args)``.
3
+
4
+ Ops take and return plain JSON: addresses travel as strings, tensors never (a tensor result is
5
+ a reduction). Every result passes ``check_bounded`` (64 KiB, no arrays). Every claimed number
6
+ is a ``num(value, authority)`` mapping, or sits inside a mapping with an ``authority`` key, or
7
+ is an integer under a key in ``INTEGER_KEYS`` (ids, indices, shapes, counts).
8
+
9
+ Effects: ``read`` changes nothing; ``navigate`` moves the cursor or the focus (it may run the
10
+ native model, replayably); ``mutate`` changes run values (edits) or debugger tables
11
+ (breakpoints, watches, displays, checkpoints); ``native`` builds a new run.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass, field
19
+ from typing import Any
20
+
21
+ from mdb.core.pointers import RecordError, check_bounded
22
+
23
+ from .errors import BadArgs, OpError, Refused, UnknownOp, internal
24
+
25
+ EFFECTS = ("read", "navigate", "mutate", "native")
26
+ ARG_TYPES = (
27
+ "str", "int", "number", "bool", "address", "pattern", "condition", "choice", "ints",
28
+ "value", "prompt",
29
+ )
30
+ SCHEMA = "mdb-ops-v1"
31
+
32
+ # Integer fields that are identities, positions, shapes or counts, not claims about values.
33
+ INTEGER_KEYS = frozenset({
34
+ "id", "ids", "index", "indices", "shape", "selected_shape", "row", "layer", "rows",
35
+ "count", "hits", "n", "k", "offset", "tokens_total", "bytes", "level", "transition",
36
+ "layers", "hidden_size", "heads", "kv_heads", "head_dim", "vocab_size", "intermediate_size",
37
+ "max_positions", "budget", "ignore", "deleted", "numel", "argmax", "argmax_index",
38
+ "position", "prompt_tokens", "feature", "d_sae", "d_model", "active", "cache", "loaded", "sae_layer", "shift", "staged", "committed", "token", "step",
39
+ "total", "limit", "omitted", "hits_total", "nan", "posinf", "neginf", "edits_total",
40
+ "deleted_total", "mask_count", "mask_shape", "under_edits_total", "staged_total", "committed_total", "depth", "line", "lines",
41
+ "kv", "d", "staged_at", "staged_cells", "committed_cells", "realised_in_layer",
42
+ "prefill", "first_row", "prompt_rows", # a record's procedure (prefill split)
43
+ })
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Arg:
48
+ """One argument. ``positional`` args fill in order from a command line. ``configurable``:
49
+ a display default a config file may change (``[repl] defaults``): it changes how much of a
50
+ result is shown, never what is measured, where a run stops, or what a sealed record holds
51
+ as a reading (``symbols limit`` sets the Unbound row and budgets move the cursor, so neither
52
+ is configurable)."""
53
+
54
+ name: str
55
+ type: str
56
+ required: bool = False
57
+ default: Any = None
58
+ choices: tuple = ()
59
+ help: str = ""
60
+ positional: bool = True
61
+ minimum: int | None = None
62
+ maximum: int | None = None
63
+ configurable: bool = False
64
+
65
+ def __post_init__(self) -> None:
66
+ if self.type not in ARG_TYPES:
67
+ raise ValueError(f"arg type {self.type!r} is not one of {ARG_TYPES}")
68
+ if self.type == "choice" and not self.choices:
69
+ raise ValueError(f"choice arg {self.name} needs choices")
70
+
71
+ def to_json(self) -> dict[str, Any]:
72
+ out: dict[str, Any] = {"name": self.name, "type": self.type, "required": self.required}
73
+ if self.default is not None:
74
+ out["default"] = self.default
75
+ if self.choices:
76
+ out["choices"] = list(self.choices)
77
+ if self.minimum is not None:
78
+ out["minimum"] = self.minimum
79
+ if self.maximum is not None:
80
+ out["maximum"] = self.maximum
81
+ if self.help:
82
+ out["help"] = self.help
83
+ return out
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class Op:
88
+ name: str
89
+ summary: str
90
+ args: tuple[Arg, ...]
91
+ effect: str
92
+ needs_live: bool
93
+ fn: Callable[..., dict[str, Any]]
94
+ motion: bool = False
95
+ milestone: str | None = None
96
+ usage: str = ""
97
+ extra: dict = field(default_factory=dict)
98
+
99
+ def __post_init__(self) -> None:
100
+ if self.effect not in EFFECTS:
101
+ raise ValueError(f"effect must be one of {EFFECTS}")
102
+ names = [arg.name for arg in self.args]
103
+ if len(names) != len(set(names)):
104
+ raise ValueError(f"op {self.name} repeats an argument name")
105
+
106
+ def to_json(self) -> dict[str, Any]:
107
+ out = {
108
+ "name": self.name,
109
+ "summary": self.summary,
110
+ "effect": self.effect,
111
+ "needs_live": self.needs_live,
112
+ "motion": self.motion,
113
+ "args": [arg.to_json() for arg in self.args],
114
+ "usage": self.usage or self.name,
115
+ }
116
+ if self.milestone is not None:
117
+ out["refused_until"] = self.milestone
118
+ return out
119
+
120
+
121
+ _REGISTRY: dict[str, Op] = {}
122
+
123
+
124
+ def register(op: Op, *, replace: bool = False) -> Op:
125
+ if op.name in _REGISTRY and not replace:
126
+ raise ValueError(f"op {op.name!r} is already registered")
127
+ _REGISTRY[op.name] = op
128
+ return op
129
+
130
+
131
+ def op(
132
+ name: str,
133
+ summary: str,
134
+ *args: Arg,
135
+ effect: str,
136
+ needs_live: bool = True,
137
+ motion: bool = False,
138
+ usage: str = "",
139
+ ):
140
+ """Decorator registering ``fn(ctx, **args) -> dict`` as an op."""
141
+
142
+ def wrap(fn):
143
+ register(Op(name, summary, tuple(args), effect, needs_live, fn, motion, usage=usage))
144
+ return fn
145
+
146
+ return wrap
147
+
148
+
149
+ def slot(name: str, summary: str, milestone: str, usage: str = "") -> Op:
150
+ """A named op that exists in the catalogue but refuses until its milestone lands."""
151
+
152
+ def refuse(ctx, **_):
153
+ raise Refused(f"not built yet: {milestone}")
154
+
155
+ return register(
156
+ Op(name, summary, (), "read", False, refuse, milestone=milestone, usage=usage,
157
+ extra={"accepts_any": True})
158
+ )
159
+
160
+
161
+ def registry() -> dict[str, Op]:
162
+ return dict(_REGISTRY)
163
+
164
+
165
+ def check_default(name: str, value: Any) -> tuple[str, str, Any]:
166
+ """``OP.ARG = value`` of ``[repl] defaults``: the op's own name (aliases and prefixes are not
167
+ accepted), a ``configurable`` argument, and a value the argument accepts. Raises BadArgs."""
168
+ op_name, _, arg_name = name.partition(".")
169
+ found = _REGISTRY.get(op_name)
170
+ if found is None:
171
+ raise BadArgs(f"no command {op_name!r}")
172
+ arg = next((a for a in found.args if a.name == arg_name), None)
173
+ if arg is None:
174
+ raise BadArgs(f"{op_name} has no argument {arg_name!r}")
175
+ if not arg.configurable:
176
+ allowed = sorted(f"{o.name}.{a.name}" for o in _REGISTRY.values() for a in o.args
177
+ if a.configurable)
178
+ raise BadArgs(f"{name} is not a display default a config file may set "
179
+ f"(those are: {', '.join(allowed)})")
180
+ return op_name, arg_name, _check(arg, value)
181
+
182
+
183
+ # (before, after): ``before(ctx, name, values) -> (values, notes)`` rewrites validated arguments
184
+ # (``ops.named`` expands symbol names into addresses; its notes go in the result as
185
+ # ``symbol_uses``), ``after(ctx, name, result)`` observes each successful result.
186
+ _HOOKS: list[tuple[Callable[..., Any] | None, Callable[..., Any] | None]] = []
187
+
188
+
189
+ def hook(*, before: Callable[..., Any] | None = None,
190
+ after: Callable[..., Any] | None = None) -> None:
191
+ """Register an argument rewriter and/or a result observer run by ``dispatch``."""
192
+ if (before, after) not in _HOOKS:
193
+ _HOOKS.append((before, after))
194
+
195
+
196
+ def describe() -> dict[str, Any]:
197
+ """The whole catalogue as JSON (name, summary, args, effect, needs_live)."""
198
+ return {"schema": SCHEMA, "ops": [_REGISTRY[name].to_json() for name in sorted(_REGISTRY)]}
199
+
200
+
201
+ def _check(arg: Arg, value: Any) -> Any:
202
+ def bad(what: str):
203
+ return BadArgs(f"argument {arg.name!r} must be {what}, got {value!r}")
204
+
205
+ kind = arg.type
206
+ if kind == "bool":
207
+ if not isinstance(value, bool):
208
+ raise bad("true or false")
209
+ return value
210
+ if kind == "int":
211
+ if type(value) is not int:
212
+ raise bad("an integer")
213
+ if arg.minimum is not None and value < arg.minimum:
214
+ raise bad(f">= {arg.minimum}")
215
+ if arg.maximum is not None and value > arg.maximum:
216
+ raise bad(f"<= {arg.maximum}")
217
+ return value
218
+ if kind == "number":
219
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
220
+ raise bad("a number")
221
+ if not math.isfinite(value):
222
+ raise bad("finite")
223
+ return value
224
+ if kind == "choice":
225
+ if value not in arg.choices:
226
+ raise bad("one of " + ", ".join(map(str, arg.choices)))
227
+ return value
228
+ if kind == "ints":
229
+ if not isinstance(value, list) or not value or any(type(v) is not int for v in value):
230
+ raise bad("a non-empty list of integers")
231
+ return list(value)
232
+ if kind == "value":
233
+ if isinstance(value, str) and value.strip():
234
+ return value.strip()
235
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
236
+ raise bad("a number or an address")
237
+ if not math.isfinite(value):
238
+ raise bad("finite")
239
+ return value
240
+ if kind == "prompt":
241
+ if isinstance(value, str) and value:
242
+ return value
243
+ if isinstance(value, list) and value and all(type(v) is int and v >= 0 for v in value):
244
+ return list(value)
245
+ raise bad("prompt text or a non-empty list of token ids")
246
+ if not isinstance(value, str) or not value.strip():
247
+ raise bad("non-empty text")
248
+ if len(value) > 4096:
249
+ raise bad("at most 4096 characters")
250
+ return value.strip()
251
+
252
+
253
+ def validate(op: Op, args: dict[str, Any] | None) -> dict[str, Any]:
254
+ if args is None:
255
+ args = {}
256
+ if not isinstance(args, dict):
257
+ raise BadArgs(f"{op.name}: arguments must be a JSON object")
258
+ if op.extra.get("accepts_any"):
259
+ return {}
260
+ known = {arg.name: arg for arg in op.args}
261
+ unknown = sorted(set(args) - set(known))
262
+ if unknown:
263
+ raise BadArgs(f"{op.name}: unknown argument {unknown[0]!r} "
264
+ f"(arguments: {', '.join(known) or 'none'})")
265
+ out = {}
266
+ for arg in op.args:
267
+ if arg.name in args and args[arg.name] is not None:
268
+ out[arg.name] = _check(arg, args[arg.name])
269
+ elif arg.required:
270
+ raise BadArgs(f"{op.name}: missing argument {arg.name!r}")
271
+ else:
272
+ out[arg.name] = arg.default
273
+ return out
274
+
275
+
276
+ def has_unresolved(node: Any) -> bool:
277
+ """Whether any field of a result is ``{"state": "unresolved", ...}``. A field marked
278
+ ``"information": True`` (a forecast's worst-case interval) is information beside the
279
+ result and never makes it unresolved."""
280
+ if isinstance(node, dict):
281
+ if node.get("information") is True:
282
+ return False
283
+ if node.get("state") == "unresolved":
284
+ return True
285
+ return any(has_unresolved(item) for item in node.values())
286
+ if isinstance(node, (list, tuple)):
287
+ return any(has_unresolved(item) for item in node)
288
+ return False
289
+
290
+
291
+ def dispatch(ctx: Any, name: str, args: dict[str, Any] | None = None) -> dict[str, Any]:
292
+ """Validate, run one op, and return its bounded JSON result.
293
+
294
+ Raises ``UnknownOp``, ``BadArgs`` or ``Refused`` (all ``OpError``); a ``ValueError`` from
295
+ the engine (a request the run cannot honour, such as a target behind the cursor) becomes
296
+ ``Refused``, and any other ``Exception`` becomes ``OpError(kind="internal")`` carrying the
297
+ exception type and message, so no traceback ever reaches a front end.
298
+
299
+ Every result carries a top-level ``state``: ``resolved``, or ``unresolved`` when some
300
+ requested part could not be computed (that part is ``{"state": "unresolved", "reason"}``).
301
+ """
302
+ found = _REGISTRY.get(name)
303
+ if found is None:
304
+ raise UnknownOp(f"no operation {name!r}")
305
+ values = validate(found, args)
306
+ if found.needs_live and getattr(ctx, "run", None) is None:
307
+ raise Refused(f"{name} needs a live run; start one with `start`")
308
+ notes: list[Any] = []
309
+ try:
310
+ for before, _ in _HOOKS:
311
+ if before is not None:
312
+ values, extra = before(ctx, found.name, values)
313
+ notes += extra
314
+ result = found.fn(ctx, **values)
315
+ except OpError:
316
+ raise
317
+ except ValueError as error:
318
+ raise Refused(str(error)) from error
319
+ except Exception as error: # noqa: BLE001 - the contract: never a traceback to the user
320
+ raise internal(error) from error
321
+ body = {"op": found.name, **result}
322
+ if notes:
323
+ body.setdefault("symbol_uses", notes)
324
+ body.setdefault("state", "unresolved" if has_unresolved(result) else "resolved")
325
+ try:
326
+ out = check_bounded(body, f"{name} result")
327
+ except RecordError as error:
328
+ raise Refused(f"result exceeds the record bound: {error}") from error
329
+ for _, after in _HOOKS:
330
+ if after is not None:
331
+ after(ctx, found.name, out)
332
+ return out