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,600 @@
1
+ """``circuit test``: a built circuit checked against a REFERENCE run by native activation patching.
2
+
3
+ Zero-ablation is not offered: zeroing components is off-distribution, and on
4
+ Qwen2.5-1.5B zeroing the 26,924-node complement moved the margin by 27.75 against a circuit
5
+ effect of 1.81, so the old sufficiency verdict was always ``not sufficient``. Here every
6
+ patched component takes the value a reference computed instead: another run of the debugger
7
+ (the corrupted / counterfactual / opposite-answer prompt), or the per-component mean over a
8
+ prompt set's items.
9
+
10
+ Components (what is patched) live at the consumer's row ``r`` and are exactly what the engine
11
+ can stage there with ``Run.set``:
12
+
13
+ * ``embedding``: the row's input ``t<r>.L0.h`` (one component);
14
+ * ``head``: head ``h``'s block of ``t<r>.L<l>.A`` (the o_proj input), every head of every layer;
15
+ * ``mlp``: ``t<r>.L<l>.m`` (the MLP output) as one component, or, in a layer whose MLP the
16
+ circuit expanded into neurons, ``neuron``: neuron ``i`` of ``t<r>.L<l>.f`` (the down_proj
17
+ input), every neuron of that layer.
18
+
19
+ A circuit node maps to components: the embedding to ``L0.h``; a head node to its head; a source
20
+ row node under a head to that head (coarsened: the reference's attention row has another
21
+ length whenever the prompts differ, so ``p[h,src]`` is not patched); a neuron node to its
22
+ neuron; an attention or MLP term that the circuit did not expand (depth 1) to every head of
23
+ that layer, resp. its ``m``. Remainder, bias and edit nodes are not components. ``+N more``
24
+ groups are not in the circuit: their members are the complement, counted (``from_groups``),
25
+ and members whose own subtree was never built are counted again as ``unexamined``. Paged
26
+ groups were examined: the in-memory node tree holds every node, paged ones included (paging
27
+ applies to the record only).
28
+
29
+ Earlier rows reach the consumer row only through the cache: they stay this run's. The test is
30
+ over the consumer row's components (``rows: consumer``); once every head's ``A`` is patched
31
+ the cache is not read at all, which is why patching every component reproduces the reference
32
+ (``full``).
33
+
34
+ Measurements, each ONE native pass of the consumer row from layer 0 with all of its edits
35
+ staged layer by layer (``compare.measure``; the session is restored and its digest checked):
36
+
37
+ * ``base``: this run, nothing patched; ``ref``: the consumer read in the reference run at its
38
+ ``@last`` row (for a prompt-set mean there is no single run: ``ref`` is then ``full``);
39
+ * ``ko`` (knock-out): only the circuit's components patched;
40
+ * ``keep`` (keep-only): every component NOT in the circuit patched, the circuit's components
41
+ computed natively;
42
+ * ``full``: every component patched (a check: equal to ``ref`` bit for bit for a reference run).
43
+
44
+ ``faithfulness = (keep - ref) / (base - ref)`` and ``knockout_share = (base - ko) / (base -
45
+ ref)``, both ``measured`` (arithmetic on measured values). They are refused when ``|base -
46
+ ref|`` is under one spacing of the consumer's dtype at its magnitude: the reference does not
47
+ change the consumer. There is no pass/fail bar; the words given are derived from the stated
48
+ one-spacing rule only.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import re
54
+ import time
55
+ from dataclasses import dataclass, field
56
+ from typing import Any
57
+
58
+ from mdb.core.bounded import put_json
59
+ from mdb.core.kinds import CIRCUIT_TEST, procedure
60
+ from mdb.core.pointers import RecordError, check_bounded
61
+ from mdb.core.records import num, seal_record
62
+
63
+ from ..measure.readout import layer_module
64
+ from ..numerics.labels import EXACT, MEASURED, f64
65
+ from ..predict.consumers import Logit, Margin, Refusal, run_session_id
66
+ from ..predict.plan import Edit
67
+
68
+ SCHEMA = "mdb-circuit-test-v1"
69
+ _PORT = re.compile(r"t(?P<row>\d+)\.L(?P<layer>\d+)\.(?P<port>\w+)")
70
+
71
+ DEFINITION = (
72
+ "components at the consumer's row: the row input L0.h (embedding), each head's block of "
73
+ "L<l>.A (o_proj input), and per layer the MLP output L<l>.m, or each neuron of L<l>.f where "
74
+ "the circuit expanded that MLP into neurons; source-row nodes count as their head (p is not "
75
+ "patched); remainder, bias and edit nodes are not components")
76
+ ROWS = ("the test is over the consumer row's components; earlier rows are this run's (they "
77
+ "reach the consumer row only through the cache, which a fully patched A does not read)")
78
+ RULE = ("one spacing = the gap between adjacent values of the consumer's dtype at the largest "
79
+ "|logit| the consumer read in base, ref, ko and keep; a difference under one spacing is "
80
+ "not measurable")
81
+
82
+
83
+ def _torch():
84
+ import torch
85
+
86
+ return torch
87
+
88
+
89
+ # --------------------------------------------------------------------------- components
90
+
91
+
92
+ @dataclass
93
+ class Port:
94
+ """One patchable port at the consumer row: ``unit`` (embedding, head, mlp, neuron), ``size``
95
+ components, the indices in the circuit and the indices held by ``+N more`` members
96
+ (``grouped``; ``unexamined`` those whose subtree was never built)."""
97
+
98
+ address: str # t<r>.L<l>.<port>
99
+ layer: int
100
+ unit: str
101
+ size: int
102
+ circuit: set[int] = field(default_factory=set)
103
+ grouped: set[int] = field(default_factory=set)
104
+ unexamined: set[int] = field(default_factory=set)
105
+
106
+ @property
107
+ def complement(self) -> list[int]:
108
+ return [i for i in range(self.size) if i not in self.circuit]
109
+
110
+
111
+ def _split(port: str) -> tuple[int, int, str]:
112
+ found = _PORT.fullmatch(port)
113
+ if found is None:
114
+ raise Refusal(f"circuit node at {port!r} is not a layer port of the consumer row")
115
+ return int(found["row"]), int(found["layer"]), found["port"]
116
+
117
+
118
+ def components(run: Any, circuit: Any) -> tuple[list[Port], dict[str, int]]:
119
+ """The component table of ``circuit`` at its consumer row (layer order: ``L0.h``, then per
120
+ layer ``A`` and ``m`` or ``f``) and counts of nodes that are not components or were
121
+ coarsened (``source`` nodes listed under a head)."""
122
+ config = run.adapter.model.config
123
+ heads = int(config.num_attention_heads)
124
+ d_ff = int(config.intermediate_size)
125
+ row = circuit.consumer.row
126
+ depth = int(circuit.record["body"]["depth"])
127
+ expanded_mlp = set()
128
+ stack = [circuit.root]
129
+ while stack: # layers whose MLP the circuit expanded into neurons (kept or grouped)
130
+ node = stack.pop()
131
+ stack += node.children
132
+ members = [(node.kind, node.port)] + [(m.kind, m.port) for m in node.members]
133
+ for kind, port in members:
134
+ if kind == "neuron":
135
+ expanded_mlp.add(_split(port)[1])
136
+ table = {f"t{row}.L0.h": Port(f"t{row}.L0.h", 0, "embedding", 1)}
137
+ for layer in range(run.adapter.layers):
138
+ table[f"t{row}.L{layer}.A"] = Port(f"t{row}.L{layer}.A", layer, "head", heads)
139
+ if layer in expanded_mlp:
140
+ table[f"t{row}.L{layer}.f"] = Port(f"t{row}.L{layer}.f", layer, "neuron", d_ff)
141
+ else:
142
+ table[f"t{row}.L{layer}.m"] = Port(f"t{row}.L{layer}.m", layer, "mlp", 1)
143
+ notes: dict[str, Any] = {"source_nodes_coarsened": 0, "grouped_sources_coarsened": 0,
144
+ "circuit_nodes": [], "group_nodes": []}
145
+
146
+ def port_of(kind: str, port: str) -> tuple[Port, list[int]]:
147
+ r, layer, name = _split(port)
148
+ if r != row:
149
+ raise Refusal(f"circuit node at {port} is not on the consumer row t{row}")
150
+ if kind == "embedding":
151
+ return table[f"t{row}.L0.h"], [0]
152
+ if kind == "attn":
153
+ return table[f"t{row}.L{layer}.A"], list(range(heads))
154
+ if kind == "mlp":
155
+ entry = table.get(f"t{row}.L{layer}.m") or table[f"t{row}.L{layer}.f"]
156
+ return entry, list(range(entry.size))
157
+ raise Refusal(f"no component for a {kind} node at {port}")
158
+
159
+ def walk(node: Any) -> None:
160
+ for child in node.children:
161
+ if child.kind == "more":
162
+ notes["group_nodes"].append(child.ref)
163
+ expands = {"attn": depth > 1, "mlp": depth > 1, "head": depth > 2}
164
+ for member in child.members:
165
+ if member.kind == "source":
166
+ notes["grouped_sources_coarsened"] += 1
167
+ continue
168
+ if member.kind in ("head", "neuron"):
169
+ entry = table[f"t{row}.L{_split(member.port)[1]}."
170
+ f"{'A' if member.kind == 'head' else 'f'}"]
171
+ indices = [member.index[0]]
172
+ else:
173
+ entry, indices = port_of(member.kind, member.port)
174
+ entry.grouped.update(indices)
175
+ if expands.get(member.kind, False):
176
+ entry.unexamined.update(indices)
177
+ continue
178
+ if child.kind in ("remainder", "bias", "edit"):
179
+ continue
180
+ if child.kind in ("head", "neuron", "embedding", "attn", "mlp"):
181
+ expanded = any(c.kind in ("head", "neuron", "more") for c in child.children)
182
+ if child.kind in ("head", "neuron", "embedding") or not expanded:
183
+ notes["circuit_nodes"].append(child.ref)
184
+ if child.kind == "head":
185
+ table[f"t{row}.L{_split(child.port)[1]}.A"].circuit.add(child.index[0])
186
+ notes["source_nodes_coarsened"] += sum(1 for c in child.children
187
+ if c.kind == "source")
188
+ continue
189
+ if child.kind == "neuron":
190
+ table[f"t{row}.L{_split(child.port)[1]}.f"].circuit.add(child.index[0])
191
+ continue
192
+ if child.kind in ("attn", "mlp") and any(c.kind in ("head", "neuron", "more")
193
+ for c in child.children):
194
+ walk(child) # expanded: its heads / neurons are the components
195
+ continue
196
+ entry, indices = port_of(child.kind, child.port)
197
+ entry.circuit.update(indices)
198
+
199
+ walk(circuit.root)
200
+ return list(table.values()), notes
201
+
202
+
203
+ def component_list(ports: list[Port]) -> list[dict[str, Any]]:
204
+ """The full table as plain JSON (what the record's sha256-checked blob holds)."""
205
+ return [{"address": p.address, "unit": p.unit, "size": p.size,
206
+ "circuit": sorted(p.circuit), "from_groups": sorted(p.grouped - p.circuit),
207
+ "unexamined": sorted(p.unexamined - p.circuit)} for p in ports]
208
+
209
+
210
+ def counts(ports: list[Port]) -> dict[str, Any]:
211
+ """Component counts (``derived-exact``): total, circuit, complement, the complement held by
212
+ ``+N more`` groups, and of those the ones in subtrees never built; per unit too."""
213
+ def tally(selected: list[Port]) -> dict[str, int]:
214
+ circuit = sum(len(p.circuit) for p in selected)
215
+ total = sum(p.size for p in selected)
216
+ grouped = sum(len(p.grouped - p.circuit) for p in selected)
217
+ return {"total": total, "circuit": circuit, "complement": total - circuit,
218
+ "from_groups": grouped,
219
+ "unexamined": sum(len(p.unexamined - p.circuit) for p in selected),
220
+ "not_listed": total - circuit - grouped}
221
+
222
+ whole = tally(ports)
223
+ out: dict[str, Any] = {key: num(value, EXACT) for key, value in whole.items()}
224
+ out["by_unit"] = {unit: {key: num(value, EXACT) for key, value in tally(
225
+ [p for p in ports if p.unit == unit]).items()}
226
+ for unit in ("embedding", "head", "mlp", "neuron") if any(p.unit == unit for p in ports)}
227
+ return out
228
+
229
+
230
+ # --------------------------------------------------------------------------- reference values
231
+
232
+
233
+ @dataclass
234
+ class Reference:
235
+ """Reference values per component port (each the port's tensor at the reference row, in the
236
+ run's dtype and device), what they came from, and the reference consumer when one run
237
+ computed it."""
238
+
239
+ kind: str # run | set-mean
240
+ name: str
241
+ values: dict[str, Any] # port suffix L<l>.<port> -> tensor
242
+ origin: dict[str, Any] # the pointer fields every edit's origin shares
243
+ consumer: Any = None # (float64 value, magnitude) at the reference row, run only
244
+ info: dict[str, Any] = field(default_factory=dict)
245
+
246
+
247
+ def _suffix(address: str) -> str:
248
+ return address.split(".", 1)[1]
249
+
250
+
251
+ def _check_model(run: Any, other: Any, name: str) -> None:
252
+ if other.adapter.model_identity != run.adapter.model_identity:
253
+ raise Refusal(f"reference {name} is another model than this run: a component of one "
254
+ "cannot be patched into the other (same model required)")
255
+ if other.program.family != run.program.family:
256
+ raise Refusal(f"reference {name} is family {other.program.family}, this run is "
257
+ f"{run.program.family}")
258
+ scope = run.adapter.execution.get("numeric_scope")
259
+ if other.adapter.execution.get("numeric_scope") != scope:
260
+ raise Refusal(f"reference {name} runs under another numeric scope than this run")
261
+
262
+
263
+ def _read_row(run: Any, other: Any, row: int, ports: list[Port], label: str) -> dict[str, Any]:
264
+ """The component ports of ``other`` at ``row`` (``read`` copies; committed layers are served
265
+ by one full-layer probe each), shape-checked against this run's ports."""
266
+ out = {}
267
+ for port in ports:
268
+ address = f"t{row}.{_suffix(port.address)}"
269
+ try:
270
+ value = other.read(address)
271
+ except ValueError as error:
272
+ raise Refusal(f"{label}: {address} cannot be read ({error})") from None
273
+ want = tuple(run.address_shape(port.address))
274
+ if tuple(value.shape) != want:
275
+ raise Refusal(f"{label}: {address} has shape {list(value.shape)}, this run's "
276
+ f"{port.address} has {list(want)} (shape mismatch: not the same model)")
277
+ if value.dtype != run.adapter.dtype or value.device != run.adapter.device:
278
+ value = value.to(device=run.adapter.device, dtype=run.adapter.dtype)
279
+ out[_suffix(port.address)] = value
280
+ return out
281
+
282
+
283
+ def from_run(run: Any, other: Any, name: str, ports: list[Port], consumer: Any) -> Reference:
284
+ """Reference values from another run at its ``@last`` row; refused for this run itself,
285
+ another model, or a reference that has not computed that row's logits."""
286
+ from ..measure.compare import consumer_value
287
+ from ..numerics.verdict import magnitude
288
+
289
+ if other is run:
290
+ raise Refusal(f"reference {name} is this run: name another run (info runs)")
291
+ _check_model(run, other, name)
292
+ row = len(other.tokens) - 1
293
+ stop = f"t{row}.logits"
294
+ if other.parse(stop) > other.parse(other.where):
295
+ raise Refusal(f"reference {name} has not computed {stop} (it is at {other.where}): "
296
+ f"run it there first (frame {name}: then until logits)")
297
+ values = _read_row(run, other, row, ports, f"reference {name}")
298
+ logits = other.read(stop)
299
+ origin = {"origin": name, "via": "live", "where": other.where,
300
+ "cut": other.checkpoint(pin=False)["cut"], "recipe": None, "row": row}
301
+ return Reference("run", name, values, origin,
302
+ consumer=(consumer_value(consumer, logits), magnitude(consumer, logits)),
303
+ info={"row": row, "where": other.where,
304
+ "edited": bool(other.edited)})
305
+
306
+
307
+ def from_set(run: Any, name: str, prompts: list[tuple[str, list[int]]], ports: list[Port]
308
+ ) -> Reference:
309
+ """The per-component mean over a prompt set's items, each read at the item's ``@last``
310
+ row: one fresh batch-1 run per item, made, read and released in turn. The sum is float64
311
+ while the call runs; the mean is cast once to the run's dtype and nothing wider is kept."""
312
+ from mdb.engine import Run
313
+
314
+ torch = _torch()
315
+ if not prompts:
316
+ raise Refusal(f"set {name} has no items")
317
+ sums: dict[str, Any] = {}
318
+ rows = []
319
+ for item, tokens in prompts:
320
+ other = Run(run.adapter, tokens)
321
+ try:
322
+ row = len(tokens) - 1
323
+ other.until(f"t{row}.L{run.adapter.layers - 1}.h_out")
324
+ for key, value in _read_row(run, other, row, ports,
325
+ f"set {name} item {item}").items():
326
+ wide = value.to(dtype=torch.float64)
327
+ sums[key] = wide if key not in sums else sums[key].add_(wide)
328
+ del wide
329
+ rows.append(row)
330
+ finally:
331
+ other.close()
332
+ del other
333
+ count = len(prompts)
334
+ values = {}
335
+ for key in list(sums):
336
+ values[key] = sums.pop(key).div_(count).to(dtype=run.adapter.dtype)
337
+ origin = {"origin": f"set:{name}", "via": "mean", "where": None, "cut": None,
338
+ "recipe": None, "items": count}
339
+ return Reference("set-mean", name, values, origin,
340
+ info={"items": count, "rows": sorted(set(rows))})
341
+
342
+
343
+ # --------------------------------------------------------------------------- patching
344
+
345
+
346
+ def _mask(run: Any, port: Port, indices: list[int]) -> Any:
347
+ torch = _torch()
348
+ mask = torch.zeros(tuple(run.address_shape(port.address)), dtype=torch.bool)
349
+ if port.unit == "head":
350
+ dh = run.adapter.head_dim
351
+ for h in indices:
352
+ mask[..., h * dh:(h + 1) * dh] = True
353
+ else:
354
+ mask[..., indices] = True
355
+ return mask
356
+
357
+
358
+ def _selection(port: Port, indices: list[int]) -> str:
359
+ if port.unit == "head":
360
+ return "|".join(f"h{h}" for h in indices)
361
+ return "|".join(f"i={i}" for i in indices)
362
+
363
+
364
+ def patches(run: Any, ports: list[Port], which: str, reference: Reference) -> list[Edit]:
365
+ """The edits that patch ``which`` (``circuit``, ``complement`` or ``all``) from the
366
+ reference: one ``replace`` per port with any selected component, masked to the selected
367
+ heads / neurons unless the whole port is selected; each carries an origin pointer."""
368
+ from mdb.engine.ports import tensor_digest
369
+
370
+ edits = []
371
+ for port in ports:
372
+ chosen = (sorted(port.circuit) if which == "circuit" else port.complement
373
+ if which == "complement" else list(range(port.size)))
374
+ if not chosen:
375
+ continue
376
+ suffix = _suffix(port.address)
377
+ value = reference.values[suffix]
378
+ source = (f"{reference.name}:t{reference.origin['row']}.{suffix}"
379
+ if reference.kind == "run" else f"set:{reference.name}:t@last.{suffix}")
380
+ origin = {**{k: v for k, v in reference.origin.items() if k != "row"},
381
+ "address": source, "sha256": tensor_digest(value),
382
+ "shape": list(value.shape), "dtype": str(value.dtype).removeprefix("torch.")}
383
+ if len(chosen) == port.size:
384
+ edits.append(Edit(port.address, value, "replace", source=source, origin=origin))
385
+ else:
386
+ edits.append(Edit(port.address, value, "replace", _mask(run, port, chosen),
387
+ _selection(port, chosen), source=source, origin=origin))
388
+ return edits
389
+
390
+
391
+ class _Calls:
392
+ """Native decoder-layer calls counted by hooks on the layer modules while it is open:
393
+ ``entered`` (every call, stop-probes that halt at the layer input included) and
394
+ ``completed`` (calls that ran the whole layer). The hooks only count, so they are marked
395
+ ``own_hook``: a foreign hook would switch the native K/V cache to its copying path."""
396
+
397
+ def __init__(self, adapter: Any):
398
+ self.modules = [layer_module(adapter, i) for i in range(adapter.layers)]
399
+ self.entered = self.completed = 0
400
+ self.handles: list[Any] = []
401
+
402
+ def __enter__(self) -> _Calls:
403
+ from saturn.core import own_hook
404
+
405
+ @own_hook
406
+ def pre(*_):
407
+ self.entered += 1
408
+
409
+ @own_hook
410
+ def post(*_):
411
+ self.completed += 1
412
+
413
+ for module in self.modules:
414
+ self.handles.append(module.register_forward_pre_hook(pre))
415
+ self.handles.append(module.register_forward_hook(post))
416
+ return self
417
+
418
+ def __exit__(self, *_):
419
+ for handle in self.handles:
420
+ handle.remove()
421
+ self.handles = []
422
+
423
+ def view(self) -> dict[str, Any]:
424
+ return {"entered": num(self.entered, MEASURED), "completed": num(self.completed,
425
+ MEASURED)}
426
+
427
+
428
+ def _measured(run: Any, edits: list[Edit], consumer: Any) -> tuple[dict[str, Any], dict]:
429
+ from ..measure.compare import measure
430
+
431
+ started = time.perf_counter()
432
+ with _Calls(run.adapter) as calls:
433
+ found = measure(run, edits, consumer)
434
+ found["seconds"] = time.perf_counter() - started
435
+ return found, {"calls": calls.view(), "seconds": num(found["seconds"], MEASURED),
436
+ "edits": num(len(edits), EXACT)}
437
+
438
+
439
+ # --------------------------------------------------------------------------- test
440
+
441
+
442
+ def _spacing(magnitude_: float, dtype: Any) -> float:
443
+ from ..numerics.verdict import spacing
444
+
445
+ return spacing(magnitude_, dtype)
446
+
447
+
448
+ def test(run: Any, circuit: Any, reference: Any, *, session_id: str | None = None,
449
+ store: Any = None, name: str | None = None,
450
+ prompts: list[tuple[str, list[int]]] | None = None) -> dict[str, Any]:
451
+ """Patch the circuit's components (knock-out) and, separately, every other component
452
+ (keep-only) from the reference natively; seal a ``circuit-test`` record.
453
+
454
+ ``reference`` is another ``Run`` (``name`` names it) or, with ``prompts`` (item name, token
455
+ ids) and ``reference=None``, the mean over a prompt set ``name``. Returns ``{result,
456
+ record}``; the session (and the reference run's) is restored and checked unchanged."""
457
+ from ..predict.plan import state_digest
458
+
459
+ torch = _torch()
460
+ consumer = circuit.consumer
461
+ if not isinstance(consumer, (Margin, Logit)):
462
+ raise Refusal(f"circuit {circuit.id}: the consumer {circuit.record['body']['consumer']} "
463
+ "is a vector; circuit test reports ratios of a scalar consumer (a margin "
464
+ "M[a,b] or a logit)")
465
+ if run.where != circuit.where:
466
+ raise Refusal(f"circuit {circuit.id} was built at {circuit.where}; the cursor is at "
467
+ f"{run.where} (restart there to test it)")
468
+ started = time.perf_counter()
469
+ before = state_digest(run)
470
+ ports, notes = components(run, circuit)
471
+ ref_before = None if reference is None else state_digest(reference)
472
+ with _Calls(run.adapter) as reads:
473
+ if reference is not None:
474
+ ref = from_run(run, reference, name or getattr(reference, "name", None) or "ref",
475
+ ports, consumer)
476
+ else:
477
+ ref = from_set(run, name or "set", prompts or [], ports)
478
+ if reference is not None and state_digest(reference) != ref_before:
479
+ raise RuntimeError("reading the reference changed its session")
480
+ found, cost = {}, {}
481
+ for key, which in (("base", None), ("ko", "circuit"), ("keep", "complement"),
482
+ ("full", "all")):
483
+ edits = [] if which is None else patches(run, ports, which, ref)
484
+ found[key], cost[key] = _measured(run, edits, consumer)
485
+ if state_digest(run) != before:
486
+ raise RuntimeError("circuit test did not leave the session where it was")
487
+ values = {key: float(item["value"]) for key, item in found.items()}
488
+ if ref.consumer is not None:
489
+ values["ref"] = float(ref.consumer[0])
490
+ ref_label, ref_size = MEASURED, ref.consumer[1]
491
+ else:
492
+ values["ref"] = values["full"]
493
+ ref_label, ref_size = found["full"]["authority"], found["full"]["scale"][0]
494
+ dtype = found["base"]["scale"][1]
495
+ magnitude_ = max([ref_size] + [found[k]["scale"][0] for k in ("base", "ko", "keep", "full")])
496
+ resolution = _spacing(magnitude_, dtype)
497
+ span = values["base"] - values["ref"]
498
+ knock = values["base"] - values["ko"]
499
+ margins = {key: num(values[key], found[key]["authority"] if key in found else ref_label)
500
+ for key in ("base", "ref", "ko", "keep", "full")}
501
+ meaning = {
502
+ "base": "this run, nothing patched",
503
+ "ref": ("the consumer read in the reference run at its @last row" if ref.kind == "run"
504
+ else "every component set to the set's mean (there is no single reference run)"),
505
+ "ko": "knock-out: only the circuit's components patched from the reference",
506
+ "keep": ("keep-only: every component outside the circuit patched from the reference; "
507
+ "the circuit's components computed natively"),
508
+ "full": "every component patched from the reference",
509
+ }
510
+ out: dict[str, Any] = {
511
+ "schema": SCHEMA, "id": num(circuit.id, EXACT), "circuit": circuit.record["id"],
512
+ "consumer": circuit.record["body"]["consumer"], "where": run.where,
513
+ "reference": {"kind": ref.kind, "name": ref.name,
514
+ **{k: (num(v, EXACT) if isinstance(v, int) and not isinstance(v, bool)
515
+ else v) for k, v in ref.info.items() if k != "rows"}},
516
+ "components": {"definition": DEFINITION, "rows": ROWS, **counts(ports),
517
+ "coarsened": {"source_nodes": num(notes["source_nodes_coarsened"], EXACT),
518
+ "grouped_sources": num(notes["grouped_sources_coarsened"],
519
+ EXACT),
520
+ "rule": "a source-row node is its head"},
521
+ "groups": "`+N more` groups and unexamined members are in the complement; "
522
+ "paged groups were examined (enumerated from the node tree)"},
523
+ "nodes": {key: {"refs": [r for r in notes[f"{key}_nodes"] if r][:64],
524
+ "count": num(len(notes[f"{key}_nodes"]), EXACT)}
525
+ for key in ("circuit", "group")},
526
+ "margins": margins, "meaning": meaning,
527
+ "resolution": {"spacing": num(resolution, EXACT), "dtype": str(dtype).removeprefix(
528
+ "torch."), "magnitude": num(magnitude_, MEASURED), "rule": RULE},
529
+ }
530
+ if ref.kind == "set-mean":
531
+ out["reference"]["rows"] = [num(r, EXACT) for r in ref.info["rows"][:16]]
532
+ if ref.kind == "run":
533
+ same = values["full"] == values["ref"]
534
+ out["full_equals_ref"] = same
535
+ out["full_meaning"] = ("patching every component reproduces the reference's consumer bit "
536
+ "for bit: the components are the whole row" if same else
537
+ "patching every component does NOT reproduce the reference's "
538
+ "consumer: the row has an input the components do not cover "
539
+ "(an edit of the reference, or another kernel path)")
540
+ if abs(span) < resolution:
541
+ reason = (f"the reference does not change the consumer: |base - ref| = {abs(span):.6g} "
542
+ f"is under one spacing ({resolution:.6g}); pick another reference")
543
+ out["ratios"] = {"state": "refused", "reason": reason}
544
+ else:
545
+ out["ratios"] = {
546
+ "faithfulness": num((values["keep"] - values["ref"]) / span, MEASURED),
547
+ "knockout_share": num(knock / span, MEASURED),
548
+ "formulas": {"faithfulness": "(keep - ref) / (base - ref)",
549
+ "knockout_share": "(base - ko) / (base - ref)"},
550
+ "meaning": {"faithfulness": "the share of base - ref that the circuit keeps when "
551
+ "everything else takes the reference's values (1: all "
552
+ "of it, 0: none)",
553
+ "knockout_share": "the share of base - ref that patching only the circuit "
554
+ "removes (1: all of it, 0: none)"}}
555
+ out["reading"] = {
556
+ "knockout": ("no measurable effect" if abs(knock) < resolution else "measurable effect"),
557
+ "keep_vs_base": ("keep equals base within one spacing"
558
+ if abs(values["keep"] - values["base"]) < resolution
559
+ else "keep differs from base"),
560
+ "keep_vs_ref": ("keep equals ref within one spacing"
561
+ if abs(values["keep"] - values["ref"]) < resolution
562
+ else "keep differs from ref"),
563
+ "rule": "each word compares two measured margins at one spacing (resolution.rule); no "
564
+ "other threshold"}
565
+ held = put_json(component_list(ports), store=store, run=None if store is not None else run)
566
+ out["components"]["list"] = {
567
+ "state": held["state"], "sha256": held["sha256"],
568
+ **({"ref": held["ref"], "tensor_sha256": held["tensor"]["sha256"],
569
+ "bytes": num(held["bytes"], EXACT)} if held["state"] == "stored"
570
+ else {"reason": held["reason"]})}
571
+ total = time.perf_counter() - started
572
+ out["cost"] = {
573
+ "passes": num(4, EXACT),
574
+ "per_pass": cost,
575
+ "reference_read": {"calls": reads.view(),
576
+ "what": "layer calls to read the reference values" + (
577
+ " (one run per item, released in turn)" if ref.kind == "set-mean"
578
+ else " (committed reads, cached per layer)")},
579
+ "seconds": num(total, MEASURED),
580
+ }
581
+ if torch.cuda.is_available() and str(run.adapter.device).startswith("cuda"):
582
+ out["cost"]["peak_vram_bytes"] = num(int(torch.cuda.max_memory_allocated()), MEASURED)
583
+ out["cost"]["peak_vram_meaning"] = "torch.cuda.max_memory_allocated since process start"
584
+ out["session"] = {"before": before, "after": state_digest(run), "unchanged": True}
585
+ out["procedure"] = procedure(run)
586
+ del ref
587
+ try:
588
+ body = check_bounded(out, "circuit test record")
589
+ record = seal_record(session_id=session_id or run_session_id(run), kind="circuit-test",
590
+ model_identity=run.adapter.model_identity,
591
+ execution=dict(run.adapter.execution), authority=MEASURED,
592
+ body=body, run=run)
593
+ except RecordError as error:
594
+ raise Refusal(f"the circuit test result does not fit one record ({error})") from None
595
+ out["record"] = record["id"]
596
+ return {"result": out, "record": record}
597
+
598
+
599
+ __all__ = ["CIRCUIT_TEST", "DEFINITION", "Port", "Reference", "SCHEMA", "component_list",
600
+ "components", "counts", "from_run", "from_set", "patches", "test"]
@@ -0,0 +1,5 @@
1
+ """Features: SAE and transcoder bases and the run-level functions on them (``sae``), and feature
2
+ addresses with watch predicates (``watch``).
3
+
4
+ Top analysis sublayer (``numerics < predict < measure < circuits < symbols < features``).
5
+ """