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/sweep.py ADDED
@@ -0,0 +1,574 @@
1
+ """``sweep``: the position x layer activation-patching sweep, measured natively.
2
+
3
+ ``sweep PORT [rows=R0:R1] [layers=L0:L1] = ORIGIN --consumer C`` patches ``t<r>.L<l>.PORT``
4
+ with the value of the run ``ORIGIN`` at the same address (``set t<r>.L<l>.PORT =
5
+ ORIGIN:t<r>.L<l>.PORT``, the cross-run port edit of ``set``), runs natively to the consumer,
6
+ reads it, and goes on to the next cell; the session is restored once at the end and checked
7
+ unchanged. Every number is ``measured``: the base consumer value, each patched value, and the
8
+ delta ``patched - base`` (arithmetic on two measured values). No prediction is made.
9
+
10
+ Rows must be stepped rows of both runs (``start ... prefill=K``: a prefilled row has no ports).
11
+ The cells are visited from the latest layer boundary to the earliest: each one rewinds to the
12
+ boundary before its layer (``t<r>.emb`` or ``t<r>.L<l-1>.h_out``) with one restore of a trail
13
+ mark the earlier cells never touched (the trail below an edit is that of the unedited run), so
14
+ no cell replays the prompt; the edit is staged there with no probe. At the end the run
15
+ comes back to the trail it held before the sweep (``Run.excursion``/``come_back``: a restore of
16
+ the held cut, no replay). Cost model (derived before the sweep runs; the counts in the result
17
+ are measured): a cell ``(r, l)`` with the consumer in row ``c`` costs ``L - l`` native layer
18
+ calls in row ``r`` plus ``L`` per row ``r+1..c`` (plus the post-layer transitions of each row)
19
+ and at most one full-layer probe of the origin run to read its value (cached per layer); the
20
+ base reading costs the forward from the cursor to the consumer. The rows between a cell and
21
+ the consumer are the cost that remains: each is stepped at batch 1 under the run's split, and
22
+ batching them would change the procedure. The plan is printed before the sweep runs
23
+ (``Context.notice``) and a plan over ``max_calls`` (default ``MAX_LAYER_CALLS``) is refused.
24
+
25
+ ``path=true`` (one origin) runs ``analysis.measure.paths.paired`` for each cell's patch after the
26
+ sweep: three stepped arms (base, free, frozen with every downstream ``p`` held at the base's)
27
+ from the cell's layer, so about three times the cells' layer calls, included in the plan and
28
+ the cap. The table gains ``path_diverged`` (a downstream attention argmax moved) and
29
+ ``frozen_delta``; ``path`` counts the diverged cells.
30
+
31
+ The result is bounded JSON: the rows x layers table of deltas inline (``delta`` a
32
+ ``{value: [[...]], authority: measured}`` claim, indexed [layer][row]; ``tokens`` per row),
33
+ or, when it exceeds ``INLINE_BYTES`` or the record's item bound (``MAX_INLINE_ITEMS`` items
34
+ across nested lists, so about 50 cells), a sha256-checked JSON blob
35
+ (``mdb.core.bounded.put_json``: in the project store, else held in memory on the run) with the
36
+ top ``top`` cells by ``|delta|`` and the heat text (``heat``) inline. It is also sealed as a
37
+ ``sweep`` record (``core.kinds.SWEEP``: the table always by blob pointer, the procedure of both
38
+ runs, no wall clock), stored when a writable project is attached (``stored``).
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import re
44
+ import time
45
+ from typing import Any
46
+
47
+ from mdb.core.bounded import put_json
48
+ from mdb.core.pointers import RecordError, check_bounded
49
+
50
+ from .builtin import procedure_json, project_of
51
+ from .errors import BadArgs, Refused
52
+ from .registry import Arg, Op, register
53
+
54
+ INLINE_BYTES = 32 * 1024 # a table larger than this goes to a blob (the record bound is 64 KiB)
55
+ MAX_CELLS = 4096
56
+ SCHEMA = "mdb-sweep-v1"
57
+ HEAT_BYTES = 4000 # the heat text of a blob table (a record text holds 4 KiB)
58
+ # The default cap on planned decoder-layer calls (``max_calls=`` overrides it). About 5 minutes
59
+ # at the 5.2 ms per layer commit measured on Qwen2.5-1.5B bf16 (RTX 4080, README); the full
60
+ # 22 rows x 28 layers of that model's 22-token prompt plan about 190k.
61
+ MAX_LAYER_CALLS = 50_000
62
+ _SPAN = re.compile(r"(?P<a>\d+)(?::(?P<b>\d+))?")
63
+ _PORT = re.compile(r"(?P<port>[A-Za-z_]\w*)(?P<selector>\[[^\]]*\])?")
64
+ USAGE = ("sweep PORT [rows=R0:R1] [layers=L0:L1] = ORIGIN --consumer C [top=K] [max_calls=N] "
65
+ "[path=true] "
66
+ "(PORT: h, m, A[h2], ...; ranges half-open; ORIGIN a run name)")
67
+
68
+
69
+ def _span(text: str | None, default: tuple[int, int], what: str, limit: int) -> list[int]:
70
+ """``R`` or ``A:B`` (half-open) -> the indices, inside ``0..limit-1``."""
71
+ if text is None:
72
+ a, b = default
73
+ else:
74
+ match = _SPAN.fullmatch(str(text).strip())
75
+ if match is None:
76
+ raise BadArgs(f"{what} is N or A:B (half-open), not {text!r}")
77
+ a = int(match["a"])
78
+ b = int(match["b"]) if match["b"] is not None else a + 1
79
+ if not 0 <= a < b <= limit:
80
+ raise Refused(f"{what} {a}:{b} is outside 0:{limit} (or empty)")
81
+ return list(range(a, b))
82
+
83
+
84
+ def _origin_name(text: str) -> str:
85
+ """``NAME`` or ``NAME:ADDR`` (as ``@pair:ADDR`` binds in a prompt set) -> ``NAME``."""
86
+ name = text.strip().partition(":")[0].strip()
87
+ if not name or name.startswith("@"):
88
+ raise BadArgs(f"the origin is a run name (info runs), not {text!r}")
89
+ return name
90
+
91
+
92
+ def _refuse_edits(run: Any, first: tuple[int, int]) -> None:
93
+ if run.edits or run.cells:
94
+ raise Refused("edits are staged at the cursor: a sweep steps back to each cell's layer, "
95
+ "which drops them; commit or abort them first")
96
+ later = [e for e in run.committed_edits() if (int(e["row"]), int(e["layer"])) >= first]
97
+ later += [e for e in run.committed_cells() if (int(e["row"]), int(e["layer"])) >= first]
98
+ if later:
99
+ found = later[0]
100
+ raise Refused(f"the committed edit at t{found['row']}.L{found['layer']} "
101
+ f"({found['port']}) comes at or after the first swept cell: stepping back "
102
+ "would drop it from the measured runs")
103
+
104
+
105
+ def _token_texts(ctx: Any, rows: list[int]) -> list[dict[str, Any]]:
106
+ run, tokenizer = ctx.run, ctx.tokenizer
107
+ out = []
108
+ held = [int(t) for t in run.session.read("tokens")[0].tolist()]
109
+ tokens = held if len(held) > len(run.tokens) else list(run.tokens) # prompt, then sampled
110
+ for row in rows:
111
+ item: dict[str, Any] = {"row": row}
112
+ if row < len(tokens): # a generated row's own token is known once it is sampled
113
+ item["token"] = tokens[row]
114
+ if tokenizer is not None:
115
+ item["text"] = tokenizer.decode([tokens[row]])
116
+ out.append(item)
117
+ return out
118
+
119
+
120
+ def _calls(*runs: Any) -> dict[str, int]:
121
+ total = {"layer": 0, "transition": 0, "probe": 0}
122
+ for run in runs:
123
+ for key in total:
124
+ total[key] += int(getattr(run, "calls", {}).get(key, 0))
125
+ return total
126
+
127
+
128
+ def _layer_calls(run: Any, after: tuple[int, int], upto: tuple[int, int]) -> int:
129
+ """Decoder-layer transitions committed moving forward from stop key ``after`` to ``upto``:
130
+ the ``L<l>.h_out`` stops in ``(after, upto]`` (one native layer call each)."""
131
+ stops = run.stops()
132
+ outs = [i for i, label in enumerate(stops) if label.endswith(".h_out")]
133
+ return sum(1 for row in range(after[0], upto[0] + 1) for i in outs
134
+ if after < (row, i) <= upto)
135
+
136
+
137
+ def _boundary(run: Any, row: int, layer: int) -> str:
138
+ """The boundary stop before layer ``layer`` of row ``row`` (``emb`` or ``L<l-1>.h_out``):
139
+ a trail mark whose pending layer is ``layer``, reached by a restore with no probe."""
140
+ return f"t{row}.emb" if layer == 0 else f"t{row}.L{layer - 1}.h_out"
141
+
142
+
143
+ def _heat(grid: list[list[float]], rows: list[int], layers: list[int],
144
+ tokens: list[dict[str, Any]]) -> dict[str, Any]:
145
+ """The heat table as text, for a table kept as a blob: one line per layer, each cell the
146
+ signed tenths of the largest |delta| (``+9``..``-9``, ``.`` below a twentieth, ``0`` exact);
147
+ the REPL draws it as it draws an inline table."""
148
+ scale = max((abs(v) for line in grid for v in line), default=0.0)
149
+
150
+ def code(value: float) -> str:
151
+ if value == 0:
152
+ return "0"
153
+ if scale == 0 or abs(value) / scale < 0.05:
154
+ return "."
155
+ return ("+" if value > 0 else "-") + str(min(9, max(1, round(abs(value) / scale * 10))))
156
+
157
+ out: dict[str, Any] = {
158
+ "rows": f"{rows[0]}:{rows[-1] + 1}", "layers": f"{layers[0]}:{layers[-1] + 1}",
159
+ "scale": {"value": scale, "authority": "measured"},
160
+ "cells": "\n".join(" ".join(code(v) for v in line) for line in grid),
161
+ "meaning": "one line per layer, one cell per row: the signed tenths of the largest "
162
+ "|delta| (9 caps), '.' below a twentieth, '0' exact"}
163
+ if len(out["cells"].encode()) > HEAT_BYTES:
164
+ out.pop("cells")
165
+ out["state"] = "absent"
166
+ out["reason"] = f"the heat text exceeds {HEAT_BYTES} bytes: read the table blob"
167
+ texts = [item.get("text") for item in tokens]
168
+ if len(texts) <= 64 and all(isinstance(t, str) for t in texts):
169
+ out["tokens"] = texts
170
+ return out
171
+
172
+
173
+ def sweep(ctx: Any, port: str, rows: str | None, layers: str | None, origin: str,
174
+ consumer: str, top: int, max_calls: int = MAX_LAYER_CALLS, path: bool = False
175
+ ) -> dict[str, Any]:
176
+ """One origin: the sweep (module docstring). Several (``= A,B,C``, multi-donor mode,
177
+ ``analysis.measure.donors``): one sweep per origin, then per cell the donors that changed the
178
+ consumer (``n_effect``) and those whose value differed from the base (``n_informative``),
179
+ and how many single-origin nulls a cell's other origins overturn."""
180
+ origins = [o.strip() for o in origin.split(",") if o.strip()]
181
+ if len(origins) < 2:
182
+ out = _sweep_one(ctx, port, rows, layers, origin, consumer, top, max_calls, path)
183
+ out.pop("_table")
184
+ return out
185
+ if path:
186
+ raise Refused("path=true takes one origin (sweep each origin on its own)")
187
+ from mdb.analysis.numerics.pooling import pooled
188
+
189
+ each = [_sweep_one(ctx, port, rows, layers, o, consumer, top, max_calls) for o in origins]
190
+ tables = [r.pop("_table") for r in each]
191
+ layer_list, row_list = tables[0]["layers"], tables[0]["rows"]
192
+ cells, flips, nulls = [], 0, 0
193
+ grid_effect = [[0] * len(row_list) for _ in layer_list]
194
+ grid_inf = [[0] * len(row_list) for _ in layer_list]
195
+ for i, _l in enumerate(layer_list):
196
+ for jj, _r in enumerate(row_list):
197
+ per = [{"verdict": "effect" if t["delta"]["value"][i][jj] != 0 else "no effect",
198
+ "informative": t["informative"][i][jj]} for t in tables]
199
+ found = pooled(per)
200
+ grid_effect[i][jj], grid_inf[i][jj] = found["n_effect"], found["n_informative"] or 0
201
+ single = sum(p["verdict"] == "no effect" for p in per)
202
+ nulls += single
203
+ flips += single if found["verdict"] == "effect" else 0
204
+ cells.append(found)
205
+ return {
206
+ "port": each[0]["port"], "origin": ",".join(origins), "origins": origins,
207
+ "consumer": consumer, "stop": each[0]["stop"], "cells": each[0]["cells"],
208
+ "base": each[0]["base"], "where": each[0]["where"],
209
+ "donors": {"layers": layer_list, "rows": row_list,
210
+ "n_effect": {"value": grid_effect, "authority": "measured"},
211
+ "n_informative": {"value": grid_inf, "authority": "measured"},
212
+ "n_donors": {"value": len(origins), "authority": "supplied"},
213
+ "cells_effect": {"value": sum(c["verdict"] == "effect" for c in cells),
214
+ "authority": "measured"},
215
+ "single_origin_nulls": {"value": nulls, "authority": "measured"},
216
+ "single_origin_nulls_overturned": {"value": flips, "authority": "measured"},
217
+ "rule": "effect = delta != 0 (native only, as sweep); a cell is an effect when "
218
+ ">= 1 origin changed the consumer; informative = the origin's value "
219
+ "differs from the base value at the cell"},
220
+ "records": [r["record"] for r in each],
221
+ "per_origin": [{"origin": o, "record": r["record"], "top": r["top"]}
222
+ for o, r in zip(origins, each)],
223
+ }
224
+
225
+
226
+ def _sweep_one(ctx: Any, port: str, rows: str | None, layers: str | None, origin: str,
227
+ consumer: str, top: int, max_calls: int = MAX_LAYER_CALLS, path: bool = False
228
+ ) -> dict[str, Any]:
229
+ from mdb.analysis.measure.compare import _guard, consumer_stop, consumer_value, restore_exactly
230
+ from mdb.analysis.numerics.pooling import informative
231
+ from mdb.analysis.predict.consumers import Logit, Margin, Refusal
232
+
233
+ from .predict import build_edit, parse_consumer, session_digest
234
+
235
+ run = ctx.run
236
+ found = _PORT.fullmatch(port.strip())
237
+ if found is None or found["port"] not in run.program.names:
238
+ raise BadArgs(f"PORT is a port name with an optional selector ({', '.join(run.program.names)}"
239
+ f"; e.g. h, m, A[h2]), not {port!r}")
240
+ spec = run.program.spec(found["port"])
241
+ if not spec.editable:
242
+ raise Refused(f"port {spec.name} is not editable: {spec.edit}")
243
+ selector = found["selector"] or ""
244
+ branch = _origin_name(origin)
245
+ debugger = ctx.debugger
246
+ donor = getattr(debugger, "runs", {}).get(branch)
247
+ if donor is run:
248
+ raise Refused(f"the origin {branch} is the swept run itself; start the clean run under "
249
+ "another name (start name=clean ...)")
250
+ try:
251
+ chosen = parse_consumer(ctx, consumer)
252
+ stop = consumer_stop(run, chosen)
253
+ except Refusal as error:
254
+ raise Refused(str(error)) from None
255
+ if not isinstance(chosen, (Margin, Logit)):
256
+ raise Refused(f"a sweep consumer is one number per cell: a margin M[a,b] or a logit "
257
+ f"logits[i], not the whole stop {stop}")
258
+ stop_key = run.parse(stop)
259
+ last = stop_key[0]
260
+ row_list = _span(rows, (run.first_row, last + 1), "rows", last + 1)
261
+ layer_list = _span(layers, (0, run.adapter.layers), "layers", run.adapter.layers)
262
+ if len(row_list) * len(layer_list) > MAX_CELLS:
263
+ raise Refused(f"{len(row_list)} x {len(layer_list)} cells exceed {MAX_CELLS}; sweep "
264
+ "narrower rows= or layers=")
265
+ if row_list[0] < run.first_row:
266
+ raise Refused(f"rows {row_list[0]}..: {run.prefilled_reason(row_list[0])}")
267
+ if donor is not None and row_list[0] < donor.first_row:
268
+ raise Refused(f"the origin {branch} prefilled row {row_list[0]} (prefill="
269
+ f"{donor.first_row}): start it with `start name={branch} prefill=K ...` "
270
+ f"for a K <= {row_list[0]}")
271
+ cells = [(r, l) for r in row_list for l in layer_list]
272
+ for r, l in cells:
273
+ if run.parse(f"t{r}.L{l}.{spec.name}") >= stop_key:
274
+ raise Refused(f"the consumer {stop} is not downstream of t{r}.L{l}.{spec.name}; "
275
+ f"sweep rows that end at or before t{last}")
276
+ _refuse_edits(run, (row_list[0], layer_list[0]))
277
+
278
+ # the plan (cost model, derived before any native call): the forward to the consumer for
279
+ # the base reading, then per cell the layers from its boundary to the consumer
280
+ here = run.parse(run.where)
281
+ plan_base = _layer_calls(run, here, stop_key) if stop_key > here else 0
282
+ per_cell = {(r, l): _layer_calls(run, run.parse(_boundary(run, r, l)), stop_key)
283
+ for r, l in cells}
284
+ planned = plan_base + sum(per_cell.values())
285
+ # path=true: paths.paired per cell runs three arms (base, free, frozen) from the cell's layer
286
+ path_planned = 3 * sum(per_cell.values()) if path else 0
287
+ planned += path_planned
288
+ plan_text = (f"sweep plan: {len(cells)} cells ({len(row_list)} rows x {len(layer_list)} "
289
+ f"layers), {planned} layer calls planned (base {plan_base}, cells "
290
+ f"{planned - plan_base - path_planned}"
291
+ + (f", path {path_planned}" if path else "") + f"; cap {max_calls})")
292
+ if planned > max_calls:
293
+ raise Refused(f"{plan_text}: over the cap. Each cell runs natively from its layer to the "
294
+ f"consumer, so rows far before the consumer cost {run.adapter.layers} layer "
295
+ "calls per row in between; narrow rows= or layers=, or pass "
296
+ f"max_calls={planned} to run it anyway")
297
+ notice = getattr(ctx, "notice", None)
298
+ if notice is not None:
299
+ notice(plan_text)
300
+
301
+ before = session_digest(ctx)
302
+ checkpoint = run.checkpoint(pin=False) # its edits are all before the first cell: kept
303
+ try:
304
+ _guard(run, [checkpoint])
305
+ except Refusal as error:
306
+ raise Refused(str(error)) from None
307
+ calls0 = _calls(run, donor) if donor is not None else _calls(run)
308
+ started = time.perf_counter()
309
+ # latest boundary first: each cell rewinds to a trail mark the earlier cells never touched
310
+ order = sorted(cells, key=lambda cell: run.parse(_boundary(run, *cell)), reverse=True)
311
+ deltas: dict[tuple[int, int], float] = {}
312
+ differs: dict[tuple[int, int], bool | None] = {}
313
+ base_ports: dict[tuple[int, int], Any] = {}
314
+ base_value: float | None = None
315
+ dtype = None
316
+ held = run.excursion() # the unedited trail, to come back to without a replay
317
+ try:
318
+ if stop_key > run.parse(run.where):
319
+ run.until(stop)
320
+ native = run.read(stop)
321
+ dtype = str(native.dtype).removeprefix("torch.")
322
+ base_value = float(consumer_value(chosen, native))
323
+ for r, l in order: # the unedited values at the cells (informative donors)
324
+ try:
325
+ base_ports[r, l] = run.read(f"t{r}.L{l}.{spec.name}").clone()
326
+ except (ValueError, KeyError, IndexError, RuntimeError):
327
+ base_ports[r, l] = None
328
+ for r, l in order:
329
+ boundary = _boundary(run, r, l)
330
+ if run.parse(run.where) > run.parse(boundary):
331
+ run.rewind(boundary) # a restore of a held mark: no native call
332
+ elif run.where != boundary:
333
+ run.until(boundary)
334
+ address = f"t{r}.L{l}.{spec.name}{selector}"
335
+ edit = build_edit(ctx, address, f"{branch}:{address}", "replace")
336
+ run.set(edit.address, edit.value, "replace", mask=edit.mask,
337
+ selection=edit.selection, origin=edit.origin)
338
+ run.until(stop)
339
+ deltas[r, l] = float(consumer_value(chosen, run.read(stop))) - base_value
340
+ differs[r, l] = informative(base_ports[r, l],
341
+ run.read(f"t{r}.L{l}.{spec.name}"))
342
+ finally:
343
+ try:
344
+ run.come_back(held)
345
+ except BaseException:
346
+ restore_exactly(run, checkpoint)
347
+ raise
348
+ del held
349
+ seconds = time.perf_counter() - started
350
+ paired_cells = _paired_cells(ctx, run, cells, spec.name, selector, branch, chosen) if path \
351
+ else None
352
+ after = session_digest(ctx)
353
+ if after != before:
354
+ raise RuntimeError("sweep changed the debugger session")
355
+ calls1 = _calls(run, donor) if donor is not None else _calls(run)
356
+ calls = {key: calls1[key] - calls0[key] for key in calls1}
357
+
358
+ grid = [[deltas[r, l] for r in row_list] for l in layer_list] # rows of the table: layers
359
+ tokens = _token_texts(ctx, row_list)
360
+ table = {"layers": layer_list, "rows": row_list,
361
+ "delta": {"value": grid, "authority": "measured"},
362
+ "informative": [[differs[r, l] for r in row_list] for l in layer_list],
363
+ "tokens": tokens,
364
+ "note": "delta[i][j] = consumer patched at t<rows[j]>.L<layers[i]> minus base; "
365
+ "informative[i][j]: the origin's value there differs from the base's"}
366
+ if paired_cells is not None:
367
+ table["path_diverged"] = [[paired_cells[r, l]["path"]["diverged"] for r in row_list]
368
+ for l in layer_list]
369
+ table["frozen_delta"] = {"value": [[paired_cells[r, l]["frozen"]["dM"]["value"]
370
+ for r in row_list] for l in layer_list],
371
+ "authority": "measured"}
372
+ table["note"] += ("; path_diverged[i][j]: the patch moved a downstream attention argmax "
373
+ "(paths.paired); frozen_delta[i][j]: the same patch with every "
374
+ "downstream p held at the base's")
375
+ zero = [cell for cell in cells if deltas[cell] == 0]
376
+ ranked = sorted(cells, key=lambda cell: (-abs(deltas[cell]), cell))[:top]
377
+ model = ("per cell (r, l), consumer in row c: (L - l) + L x (c - r) layer calls from the "
378
+ "boundary before layer l (a restore of a held trail mark), plus the post-layer "
379
+ "transitions of rows r..c and at most three probes (the origin's value, the base "
380
+ "value and the patched value at the cell: the informative check); once: the "
381
+ "forward to the "
382
+ "consumer for the base; the return is a restore of the held trail (no call)")
383
+ out: dict[str, Any] = {
384
+ "port": f"{spec.name}{selector}", "origin": branch, "consumer": consumer, "stop": stop,
385
+ "cells": {"count": len(cells)},
386
+ "nulls": {"count": len(zero),
387
+ "informative": {"value": sum(bool(differs[c]) for c in zero),
388
+ "authority": "measured"},
389
+ "label": f"{len(zero)} cells no effect (1 donor; "
390
+ f"{sum(bool(differs[c]) for c in zero)} informative)",
391
+ "rule": "no effect = delta exactly 0 (native only); one origin = one donor"},
392
+ "base": {"value": base_value, "authority": "measured", "dtype": dtype},
393
+ "top": [{"row": r, "layer": l, "delta": {"value": deltas[r, l], "authority": "measured"}}
394
+ for r, l in ranked],
395
+ "prefill": procedure_json(run),
396
+ "cost": {
397
+ "planned": {"layer": {"value": planned, "authority": "derived-exact"},
398
+ "cap": {"value": max_calls, "authority": "supplied"},
399
+ "note": "decoder-layer transitions the cost model gives before the sweep "
400
+ "runs (the cap refuses a larger plan; max_calls= overrides)"},
401
+ "native": {**{key: {"value": n, "authority": "measured"} for key, n in calls.items()},
402
+ "note": "native calls made by this run and the origin run during the "
403
+ "sweep (layer: decoder-layer transitions; probe: layer calls up "
404
+ "to a stop or a cached full-layer read)"},
405
+ "seconds": {"value": seconds, "authority": "measured"},
406
+ "model": model,
407
+ },
408
+ "session": {"unchanged": True, "debugger_before": before, "debugger_after": after},
409
+ "where": run.where,
410
+ }
411
+ if paired_cells is not None:
412
+ from mdb.analysis.measure.paths import RULE
413
+
414
+ moved = [(r, l) for r, l in cells if paired_cells[r, l]["path"]["diverged"]]
415
+ out["path"] = {"diverged": {"value": len(moved), "authority": "measured"},
416
+ "cells": [f"t{r}.L{l}" for r, l in moved[:top]], "rule": RULE,
417
+ "frozen": "every downstream p held at the base's (hold t*.L>=k.p)"}
418
+ if donor is not None:
419
+ out["origin_prefill"] = procedure_json(donor)
420
+ project = project_of(ctx)
421
+ store = project.store if project is not None and not project.read_only else None
422
+ pointer = put_json(table, store=store, run=run)
423
+ try: # inline when it fits a record part: bytes, and items across nested lists
424
+ out["table"] = check_bounded(table, "sweep table", max_bytes=INLINE_BYTES)
425
+ except RecordError:
426
+ shown = dict(pointer)
427
+ shown.pop("tensor", None)
428
+ out["table_pointer"] = shown
429
+ out["heat"] = _heat(grid, row_list, layer_list, tokens)
430
+ record = _record(ctx, run, donor, out, pointer, row_list, layer_list, model)
431
+ out["record"] = record["id"]
432
+ if store is not None:
433
+ from mdb.core import index
434
+
435
+ out["stored"] = index.put_record(project, record)
436
+ out["_table"] = table
437
+ return out
438
+
439
+
440
+ def _paired_cells(ctx: Any, run: Any, cells: list[tuple[int, int]], port: str, selector: str,
441
+ branch: str, consumer: Any) -> dict[tuple[int, int], dict[str, Any]]:
442
+ """``paths.paired`` for the patch of every cell (each restores the run)."""
443
+ from mdb.analysis.measure.paths import paired
444
+ from mdb.analysis.predict.consumers import Refusal
445
+
446
+ from .predict import build_edit
447
+
448
+ out = {}
449
+ for r, l in cells:
450
+ address = f"t{r}.L{l}.{port}{selector}"
451
+ edit = build_edit(ctx, address, f"{branch}:{address}", "replace")
452
+ try:
453
+ out[r, l] = paired(run, [(edit.address, edit.value, "replace", edit.mask)], consumer)
454
+ except Refusal as error:
455
+ raise Refused(str(error)) from None
456
+ return out
457
+
458
+
459
+ def _record(ctx: Any, run: Any, donor: Any, out: dict[str, Any], pointer: dict[str, Any],
460
+ rows: list[int], layers: list[int], model: str) -> dict[str, Any]:
461
+ """The sweep as one ``sweep`` record: no array inline (the table is the blob ``pointer``;
462
+ rows and layers as half-open spans), the procedure of both runs, no wall clock (a record id
463
+ is the same for the same sweep, REPL or server)."""
464
+ from mdb.analysis.predict.consumers import run_session_id
465
+ from mdb.core.kinds import procedure
466
+ from mdb.core.records import num, seal_record
467
+
468
+ table: dict[str, Any] = {"state": pointer["state"], "sha256": pointer["sha256"]}
469
+ pointers = []
470
+ if pointer["state"] == "stored":
471
+ table.update(ref=pointer["ref"], tensor_sha256=pointer["tensor"]["sha256"],
472
+ bytes=num(pointer["bytes"], "derived-exact"))
473
+ pointers.append(pointer["tensor"])
474
+ else:
475
+ table["reason"] = pointer["reason"]
476
+ body: dict[str, Any] = {
477
+ "schema": SCHEMA, "port": out["port"], "origin": out["origin"],
478
+ "consumer": out["consumer"], "stop": out["stop"],
479
+ "rows": f"{rows[0]}:{rows[-1] + 1}", "layers": f"{layers[0]}:{layers[-1] + 1}",
480
+ "cells": out["cells"], "top": out["top"], "table": table,
481
+ "base": {k: out["base"][k] for k in ("value", "authority")},
482
+ "dtype": out["base"]["dtype"],
483
+ "cost": {"planned": out["cost"]["planned"], "native": out["cost"]["native"],
484
+ "model": model},
485
+ "procedure": procedure(run),
486
+ "session": {"before": out["session"]["debugger_before"],
487
+ "after": out["session"]["debugger_after"], "unchanged": True},
488
+ }
489
+ if "heat" in out:
490
+ body["heat"] = out["heat"]
491
+ if "path" in out:
492
+ body["path"] = out["path"]
493
+ if donor is not None:
494
+ body["origin_procedure"] = procedure(donor)
495
+ project = project_of(ctx)
496
+ session_id = (ctx.debugger.session_id if project is not None and not project.read_only
497
+ else run_session_id(run))
498
+ try:
499
+ return seal_record(session_id=session_id, kind="sweep",
500
+ model_identity=run.adapter.model_identity,
501
+ execution=dict(run.adapter.execution), authority="measured",
502
+ body=check_bounded(body, "sweep record"), pointers=pointers,
503
+ run=[run] if donor is None else [run, donor])
504
+ except RecordError as error:
505
+ raise Refused(f"the sweep result does not fit one record ({error})") from None
506
+
507
+
508
+ register(Op("sweep", "Patch PORT from another run at every (row, layer) of a range, measure the "
509
+ "consumer natively for each, restore: one table of deltas (activation patching)",
510
+ (Arg("port", "str", required=True, help="the port, with an optional selector (h, m, "
511
+ "A[h2])"),
512
+ Arg("origin", "str", required=True, positional=False,
513
+ help="the run the value comes from (start name=NAME ...)"),
514
+ Arg("consumer", "str", required=True, positional=False,
515
+ help="M[a,b], logits[i] or a stop"),
516
+ Arg("rows", "str", positional=False, help="R or R0:R1 (half-open; default the "
517
+ "run's stepped rows up to the consumer)"),
518
+ Arg("layers", "str", positional=False, help="L or L0:L1 (default all layers)"),
519
+ Arg("top", "int", default=8, minimum=1, maximum=64, positional=False,
520
+ help="cells listed by |delta|"),
521
+ Arg("max_calls", "int", default=MAX_LAYER_CALLS, minimum=1, positional=False,
522
+ configurable=True,
523
+ help=f"refuse a sweep whose planned decoder-layer calls exceed this (default "
524
+ f"{MAX_LAYER_CALLS}; pass the planned count to run a larger one)"),
525
+ Arg("path", "bool", default=False, positional=False,
526
+ help="also run paths.paired per cell: path_diverged and frozen_delta tables "
527
+ "(about 3x the cells' layer calls; one origin)")),
528
+ "navigate", True,
529
+ lambda ctx, port, origin, consumer, rows, layers, top, max_calls, path=False:
530
+ sweep(ctx, port, rows, layers, origin, consumer, top, max_calls, path), usage=USAGE))
531
+
532
+
533
+ def parse_line(text: str) -> dict[str, Any]:
534
+ """``PORT [rows=..] [layers=..] [top=K] = ORIGIN --consumer C`` -> op args."""
535
+ from .lines import _consumer_option, split
536
+
537
+ consumer, rest = _consumer_option(text)
538
+ words = [word for word, _, _ in split(rest)]
539
+ args: dict[str, Any] = {}
540
+ if consumer is not None:
541
+ args["consumer"] = consumer
542
+ i = 0
543
+ while i < len(words):
544
+ word = words[i]
545
+ key, equals, value = word.partition("=")
546
+ if word == "=" and i + 1 < len(words) and "origin" not in args:
547
+ args["origin"], i = words[i + 1], i + 2
548
+ continue
549
+ if word.startswith("=") and len(word) > 1 and "origin" not in args: # `=clean`
550
+ args["origin"], i = word[1:], i + 1
551
+ continue
552
+ if equals and key in ("rows", "layers", "top", "max_calls", "origin", "consumer") \
553
+ and value:
554
+ args[key] = (int(value) if key in ("top", "max_calls") and value.isdigit()
555
+ else value)
556
+ elif equals and key == "path" and value:
557
+ args["path"] = value.lower() in ("true", "1", "yes")
558
+ elif "port" not in args and not equals and "origin" not in args:
559
+ args["port"] = word
560
+ else:
561
+ raise BadArgs(USAGE)
562
+ i += 1
563
+ if "port" not in args or "origin" not in args or "consumer" not in args:
564
+ raise BadArgs(USAGE)
565
+ return args
566
+
567
+
568
+ def _register_parser() -> None:
569
+ from . import lines
570
+
571
+ lines.SPECIAL.setdefault("sweep", parse_line)
572
+
573
+
574
+ _register_parser()
mdb/repl/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """The gdb-style REPL over ``mdb.ops``. Importing it loads no model library."""
2
+
3
+ from .shell import Shell
4
+
5
+ __all__ = ["Shell"]