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
@@ -0,0 +1,248 @@
1
+ """Edit plans: what an edit changes before anything is predicted or measured.
2
+
3
+ ``Edit`` is one edit (address, value, op, mask), ``plan``/``cell_plan`` resolve it against a
4
+ run into a ``Plan`` (the edited stops, the consumer row, the rows in between) and ``affected``
5
+ lists the stops downstream of it; ``state_digest`` fingerprints the run state a plan was made
6
+ on.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ from mdb.core.pointers import seal_digest
15
+
16
+ from .consumers import Logit, Margin, Refusal
17
+ from .rowmodel import _split, producers
18
+
19
+ OPS = ("replace", "add", "scale")
20
+ CELL_OPS = ("replace", "add", "scale", "mix")
21
+ CELL_READ = {"k": "kr", "v": "A"} # mdb.engine.edits.CELL_READ (engine is torch-heavy)
22
+ CELL_BOUNDARY = {"k": "kr", "v": "p"} # mdb.engine.edits.CELL_BOUNDARY
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Edit:
27
+ """A requested edit at ``address`` (``t<row>.L<i>.<port>``): ``value`` a float or a tensor
28
+ in the port's run shape, ``op`` one of ``replace | add | scale``, ``mask`` an optional bool
29
+ tensor (broadcastable to the port) limiting the op, ``selection``/``source`` the texts it came
30
+ from (recorded verbatim)."""
31
+
32
+ address: str
33
+ value: Any
34
+ op: str = "replace"
35
+ mask: Any = None
36
+ selection: str | None = None
37
+ source: str | None = None
38
+ cell: dict[str, Any] | None = None # {layer, tensor, rows, kv, d}: a state-cell edit
39
+ dose: float | None = None # mix only
40
+ origin: dict[str, Any] | None = None # pointer of a value from another run
41
+
42
+
43
+ @dataclass
44
+ class Plan:
45
+ """The resolved request: edit site, consumer, the stops each row's edit reaches, and how the
46
+ measurement reaches the edited layer (``pending``: stage now; ``ahead``: run forward to the
47
+ layer; ``rewind``: back by layer boundaries, then forward)."""
48
+
49
+ row: int
50
+ label: str
51
+ key: tuple[int, int]
52
+ consumer_row: int
53
+ consumer_label: str
54
+ consumer_key: tuple[int, int]
55
+ consumer_text: str
56
+ margin: Margin | None
57
+ logit: Logit | None
58
+ affected: dict[int, set[str]]
59
+ here: tuple[int, int]
60
+ mode: str
61
+ stage_at: str | None = None # a cell edit: the cursor it is staged at
62
+
63
+ @property
64
+ def edit_stop(self) -> str:
65
+ return f"t{self.row}.{self.label}"
66
+
67
+ @property
68
+ def consumer_stop(self) -> str:
69
+ return f"t{self.consumer_row}.{self.consumer_label}"
70
+
71
+
72
+ def state_digest(run: Any) -> str:
73
+ """Digest of what a what-if must leave unchanged: ``Run.checkpoint()`` without its name
74
+ (cursor, cut fingerprint, transition count, staged edits, committed path edits, lookahead,
75
+ numeric scope) and ``Run.status()``."""
76
+ checkpoint = {key: value for key, value in run.checkpoint().items() if key != "name"}
77
+ return seal_digest({"checkpoint": checkpoint, "status": run.status()})
78
+
79
+
80
+ # --------------------------------------------------------------------------- planning
81
+
82
+
83
+ def affected(run: Any, row: int, label: str, last_row: int, *, every_row: bool = False
84
+ ) -> dict[int, set[str]]:
85
+ """Stops of rows ``row..last_row`` whose value an edit at ``t<row>.<label>`` can change: the
86
+ stops downstream of it in its own row, and in each later row the stops downstream of a cache
87
+ row it changed (``L<i>.kr`` reads the key cache, ``L<i>.A`` the value cache) or of a sampled
88
+ token it changed (``emb`` of a row past the prompt). ``every_row``: ``label`` is a cache
89
+ read every later row makes again (a state-cell edit), so it seeds every row."""
90
+ program, layers = run.program, run.adapter.layers
91
+ children: dict[str, list[str]] = {}
92
+ for stop in run.stops():
93
+ for name in producers(program, layers, stop):
94
+ children.setdefault(name, []).append(stop)
95
+
96
+ def closure(seeds: set[str]) -> set[str]:
97
+ found, todo = set(seeds), list(seeds)
98
+ while todo:
99
+ for child in children.get(todo.pop(), ()):
100
+ if child not in found:
101
+ found.add(child)
102
+ todo.append(child)
103
+ return found
104
+
105
+ out = {row: closure({label})}
106
+ keys: set[int] = set()
107
+ values: set[int] = set()
108
+ for j in range(row + 1, last_row + 1):
109
+ previous = out[j - 1]
110
+ keys |= {i for i in range(layers) if f"L{i}.kr" in previous}
111
+ values |= {i for i in range(layers) if f"L{i}.v" in previous}
112
+ seeds = {f"L{i}.kr" for i in keys} | {f"L{i}.A" for i in values}
113
+ if every_row:
114
+ seeds.add(label)
115
+ if "sample" in previous and j >= len(run.tokens):
116
+ seeds.add("emb")
117
+ out[j] = closure(seeds)
118
+ return out
119
+
120
+
121
+ def _consumer(run: Any, consumer: Any) -> tuple[int, str, Margin | None, Logit | None, str]:
122
+ vocab = int(run.adapter.model.config.vocab_size)
123
+ if isinstance(consumer, Margin):
124
+ if not (0 <= consumer.a < vocab and 0 <= consumer.b < vocab) or consumer.a == consumer.b:
125
+ raise Refusal(f"M[a,b] needs two different token ids in 0..{vocab - 1}")
126
+ return consumer.row, "logits", consumer, None, consumer.text
127
+ if isinstance(consumer, Logit):
128
+ if not 0 <= consumer.i < vocab:
129
+ raise Refusal(f"logit index must be in 0..{vocab - 1}")
130
+ return consumer.row, "logits", None, consumer, consumer.text
131
+ key = run.parse(consumer)
132
+ label = run.stops()[key[1]]
133
+ if label in ("start", "sample"):
134
+ raise Refusal(f"{label} is a token id, not a value with a change; use a margin M[a,b] "
135
+ "or a logit as the consumer")
136
+ return key[0], label, None, None, f"t{key[0]}.{label}"
137
+
138
+
139
+ def _read_ahead(run: Any, layer: int, tensor: str) -> bool:
140
+ """Whether the cursor's row has still to read ``cache.L<layer>.<tensor>`` (an edit staged
141
+ now is realised before that read)."""
142
+ status = run.status()
143
+ here = run.parse(run.where)
144
+ if status["pending_layer"] == layer and status["port"] is not None:
145
+ names = run.program.names
146
+ return names.index(status["port"]) < names.index(CELL_BOUNDARY[tensor])
147
+ return here < run.parse(f"t{here[0]}.L{layer}.{CELL_READ[tensor]}")
148
+
149
+
150
+ def _later_edits(run: Any, row: int, layer: int) -> str | None:
151
+ """A committed edit or cell edit after ``(row, layer)``: rewinding there would drop it."""
152
+ later = [e for e in run.committed_edits() if (int(e["row"]), int(e["layer"])) > (row, layer)]
153
+ later += [e for e in run.committed_cells() if (int(e["row"]), int(e["layer"])) >= (row, layer)]
154
+ if later:
155
+ first = later[0]
156
+ return (f"the committed edit at t{first['row']}.L{first['layer']} ({first['port']}) comes "
157
+ "after the stage point: stepping back to it would drop that edit from the "
158
+ "measured run")
159
+ return None
160
+
161
+
162
+ def cell_plan(run: Any, edit: Edit, consumer: Any) -> Plan:
163
+ """Resolve and check a state-cell what-if without running anything native: where it is
164
+ staged, its first read, the stops it reaches and whether the consumer is among them."""
165
+ if edit.op not in CELL_OPS:
166
+ raise Refusal(f"a cell op is one of {', '.join(CELL_OPS)}")
167
+ cell = edit.cell
168
+ layer, tensor, rows = int(cell["layer"]), cell["tensor"], list(cell["rows"])
169
+ read = f"L{layer}.{CELL_READ[tensor]}"
170
+ row_c, label_c, margin, logit, text = _consumer(run, consumer)
171
+ key_c = run.parse(f"t{row_c}.{label_c}")
172
+ here = run.parse(run.where)
173
+ if key_c > here:
174
+ mode, stage_at = "pending", run.where
175
+ first = here[0] if _read_ahead(run, layer, tensor) else here[0] + 1
176
+ length = int(run.read_cache(layer, tensor, staged=False).shape[2])
177
+ if max(rows) >= length:
178
+ raise Refusal(f"{edit.address}: row {max(rows)} is not in the cache at {run.where} "
179
+ f"(it holds rows 0..{length - 1})")
180
+ else:
181
+ mode, first = "rewind", row_c
182
+ stage_at = f"t{row_c}.L{layer}.h"
183
+ if max(rows) >= row_c:
184
+ raise Refusal(f"{text} is computed at the cursor and its row t{row_c} reads cache "
185
+ f"rows 0..{row_c - 1} only: the cell rows {rows} cannot reach it")
186
+ if run.edits or run.cells:
187
+ raise Refusal("the consumer is already computed and edits are staged: reaching the "
188
+ "stage point means stepping back, which drops the staged edits; commit "
189
+ "or abort them first")
190
+ conflict = _later_edits(run, row_c, layer)
191
+ if conflict is not None:
192
+ raise Refusal(conflict)
193
+ reach = affected(run, first, read, max(row_c, first), every_row=True)
194
+ if row_c < first or label_c not in reach[row_c]:
195
+ raise Refusal(f"{text} is not downstream of {edit.address} staged at {stage_at}: its "
196
+ f"first read is t{first}.{read}")
197
+ return Plan(first, read, run.parse(f"t{first}.{read}"), row_c, label_c, key_c, text, margin,
198
+ logit, reach, here, mode, stage_at)
199
+
200
+
201
+ def plan(run: Any, edit: Edit, consumer: Any) -> Plan:
202
+ """Resolve and check a what-if request without running anything native."""
203
+ if edit.cell is not None:
204
+ return cell_plan(run, edit, consumer)
205
+ if edit.op not in OPS:
206
+ raise Refusal(f"op must be one of {', '.join(OPS)}")
207
+ key = run.parse(edit.address)
208
+ label = run.stops()[key[1]]
209
+ if not label.startswith("L"):
210
+ raise Refusal(f"edits apply to layer ports, not {label}")
211
+ spec = run.program.spec(_split(label)[1])
212
+ if not spec.editable:
213
+ raise Refusal(f"port {spec.name} is not editable: {spec.edit}")
214
+ row_c, label_c, margin, logit, text = _consumer(run, consumer)
215
+ key_c = run.parse(f"t{row_c}.{label_c}")
216
+ if key_c <= key:
217
+ raise Refusal(f"{text} is not downstream of the edit at t{key[0]}.{label}: it is "
218
+ "computed before (or is) the edited port")
219
+ reach = affected(run, key[0], label, row_c)
220
+ if label_c not in reach[row_c]:
221
+ raise Refusal(f"{text} is not downstream of the edit at t{key[0]}.{label}: no path of "
222
+ "the port program (or of the cache / sampled token) leads from it")
223
+ here = run.parse(run.where)
224
+ status = run.status()
225
+ layer = _split(label)[0]
226
+ entry = run.parse(f"t{key[0]}.L{layer}.h")
227
+ if status["port"] is not None and status["pending_layer"] == layer and here[0] == key[0]:
228
+ mode = "pending"
229
+ elif entry > here:
230
+ mode = "ahead"
231
+ else:
232
+ mode = "rewind"
233
+ if run.edits:
234
+ raise Refusal("the edited layer is already committed and edits are staged: reaching "
235
+ "it means stepping back, which drops the staged edits; commit or abort "
236
+ "them first")
237
+ later = [e for e in run.committed_edits()
238
+ if (int(e["row"]), int(e["layer"])) > (key[0], layer)]
239
+ if later:
240
+ first = later[0]
241
+ raise Refusal(f"the committed edit at t{first['row']}.L{first['layer']}."
242
+ f"{first['port']} comes after the edited layer: stepping back to it "
243
+ "would drop that edit from the measured run")
244
+ return Plan(key[0], label, key, row_c, label_c, key_c, text, margin, logit, reach, here,
245
+ mode)
246
+
247
+
248
+ __all__ = ["CELL_OPS", "OPS", "Edit", "Plan", "affected", "cell_plan", "plan", "state_digest"]