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,690 @@
1
+ """Circuit records: a consumer's exact decomposition walked back to token rows, with the unlisted
2
+ remainder explicit, and a native test of what was retained.
3
+
4
+ ``build(run, consumer, top=K, depth=D)`` decomposes a consumer of the cursor's row (a margin
5
+ ``M[a,b]``, a logit, a residual port ``h``/``r``/``h_out`` or ``o``; see ``reads.readout``):
6
+
7
+ * depth 1: the residual-stream terms that reach it, ``embedding`` (``L0.h``), ``L<l>.attn``
8
+ (``o``) and ``L<l>.mlp`` (``m``), each read through the consumer's exact linear map (P19
9
+ for a margin or logit: ``rho`` evaluated once at the native final state);
10
+ * depth 2: an attention term into its heads, ``W_o,h A_h`` (P07), and an MLP term into its
11
+ neurons, ``W_down[:, i] f_i`` (P15);
12
+ * depth 3: a head into its source rows, ``p[h, s] W_o,h v[kappa(h), s]`` (P06): the leaves are
13
+ token rows.
14
+
15
+ At every node the ``top`` largest children (by ``|value|``, the norm for a vector consumer) are
16
+ retained; the others are one ``+N more`` node holding their exact sum. Every node whose
17
+ children are not exact identities of native values has a ``remainder`` child (``measured``:
18
+ the native value minus the exact sum) with a rounding ``bound`` (round to nearest; matmul
19
+ partial sums at the run's accumulation precision, ``accumulation.accumulation``: float32 unless
20
+ CUDA reduced-precision reductions are allowed, when a sum with ``n u >= 1`` has no bound and the
21
+ remainder's bound is refused; one rounding to the model dtype; residual adds round once; the final
22
+ norm term is explain's a-priori ``k = 2`` multiple, flagged) and a ``within`` flag. A committed
23
+ or staged edit that wrote the native value there (``Run.read_info``) is its own ``edit`` node
24
+ (the native value minus the pre-edit value, labelled as ``read_info`` labels the port), never
25
+ part of a remainder. At every node the children sum to the node by construction; ``closure``
26
+ checks only the float64 summation, and ``remainders_within`` is the rounding check.
27
+
28
+ ``test(run, circuit, reference)`` (``analysis.circuits.test``) patches the circuit's components
29
+ natively from a REFERENCE run (or a prompt set's per-component mean) at the consumer's row:
30
+ only the circuit (knock-out) and everything but the circuit (keep-only), and reports the
31
+ measured margins with ``(keep - ref) / (base - ref)`` and ``(base - ko) / (base - ref)``.
32
+ Zero-ablation is not offered.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import hashlib
38
+ import weakref
39
+ from collections.abc import Callable
40
+ from dataclasses import dataclass, field
41
+ from typing import Any, NamedTuple
42
+
43
+ from mdb.core import circuit_pages as pages_mod
44
+ from mdb.core.bounded import json_bytes, load_json, put_json
45
+ from mdb.core.circuit_pages import PAGE_BYTES, PAGE_SCHEMA, PAGE_VALUES # noqa: F401
46
+ from mdb.core.kinds import CIRCUIT, procedure
47
+ from mdb.core.pointers import RecordError, check_bounded
48
+ from mdb.core.records import num, seal_record
49
+
50
+ from ..measure.readout import (
51
+ claim,
52
+ computed,
53
+ head_mask,
54
+ head_mix,
55
+ layer_module,
56
+ readout,
57
+ size,
58
+ unit_roundoff,
59
+ )
60
+ from ..numerics.accumulation import accumulation
61
+ from ..numerics.labels import BOUND, EXACT, LOCAL, MEASURED, SUPPLIED, f64
62
+ from ..predict.consumers import Margin, Refusal, run_session_id
63
+ from ..predict.plan import Edit
64
+
65
+ SCHEMA = "mdb-circuit-v1"
66
+ KINDS = ("consumer", "embedding", "attn", "mlp", "head", "neuron", "source", "bias",
67
+ "remainder", "edit", "more", "residual", "feature", "error")
68
+ # fixed children are never ranked into "+N more": an SAE error node is always listed
69
+ _FIXED = ("remainder", "bias", "edit", "error")
70
+
71
+
72
+ def _torch():
73
+ import torch
74
+
75
+ return torch
76
+
77
+
78
+ class Member(NamedTuple):
79
+ """A child folded into a ``+N more`` node (and, before grouping, a candidate child): what
80
+ ``test`` ablates. ``port`` is the address a ``replace 0`` edit writes, ``index`` where in
81
+ it: ``()`` the whole port, ``(i,)`` neuron ``i`` of ``f``, ``(h,)`` head ``h``'s block of
82
+ ``A``, ``(h, s)`` source ``s`` of head ``h`` in ``p``; None: not ablatable (the
83
+ embedding). ``value`` is its float64 contribution while the circuit is built; ``build``
84
+ folds the members' values into ``Circuit.complement`` and keeps None."""
85
+
86
+ name: str
87
+ kind: str
88
+ port: str
89
+ index: tuple[int, ...] | None
90
+ value: Any
91
+
92
+
93
+ @dataclass
94
+ class Node:
95
+ """One node: ``value`` (float64) is the contribution its edge carries into its parent, and
96
+ so into the consumer; ``authority`` labels it. ``port`` and ``index`` (as in ``Member``)
97
+ say what ablates it natively (None for a remainder, bias or edit: not components).
98
+ ``grow`` builds the node's children; ``_group`` calls it only for a node it keeps."""
99
+
100
+ name: str
101
+ kind: str
102
+ address: str
103
+ value: Any
104
+ authority: str
105
+ proof: str | None = None
106
+ children: list[Node] = field(default_factory=list)
107
+ port: str | None = None
108
+ index: tuple[int, ...] | None = None
109
+ members: list[Member] = field(default_factory=list)
110
+ note: str | None = None
111
+ bound: Any = None
112
+ ref: str | None = None
113
+ unexamined: int = 0 # ``more`` only: members dropped whose own subtree was never built
114
+ grow: Callable[[], list[Node]] | None = field(default=None, repr=False)
115
+
116
+ @property
117
+ def within(self) -> bool | None:
118
+ """``|value| <= bound`` (per coordinate for a vector), None when unbounded."""
119
+ if self.bound is None:
120
+ return None
121
+ return bool((f64(self.value).abs() <= f64(self.bound)).all())
122
+
123
+ def view(self, ids: list[int]) -> dict[str, Any]:
124
+ ids[0] += 1
125
+ self.ref = f"n{ids[0]}"
126
+ out: dict[str, Any] = {"id": self.ref, "name": self.name, "kind": self.kind,
127
+ "address": self.address,
128
+ "value": claim(self.value, self.authority, self.proof)}
129
+ if self.bound is not None:
130
+ out["bound"] = claim(self.bound, BOUND)
131
+ out["within"] = self.within
132
+ if self.note:
133
+ out["note"] = self.note
134
+ if self.unexamined:
135
+ out["unexamined"] = True
136
+ out["unexamined_count"] = num(self.unexamined, EXACT)
137
+ if self.children:
138
+ out["children"] = [child.view(ids) for child in self.children]
139
+ return out
140
+
141
+
142
+ @dataclass
143
+ class Circuit:
144
+ """A built circuit: the sealed ``record``, the node tree and what ``test`` needs."""
145
+
146
+ id: int
147
+ record: dict[str, Any]
148
+ root: Node
149
+ consumer: Any
150
+ where: str
151
+ tests: list[dict[str, Any]] = field(default_factory=list)
152
+ complement: Any = None # minus the members' summed contributions (the embedding aside)
153
+ pages: dict[str, Any] = field(default_factory=dict, repr=False)
154
+ """Child pages by sha256 when there was no project store to put them in (they travel with
155
+ the circuit, so one carried to a later run still resolves)."""
156
+
157
+
158
+ _LEDGERS: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
159
+
160
+
161
+ def ledger(run: Any) -> dict[int, Circuit]:
162
+ """The circuits built on ``run`` in this process, by id."""
163
+ if run not in _LEDGERS:
164
+ _LEDGERS[run] = {}
165
+ return _LEDGERS[run]
166
+
167
+
168
+ # --------------------------------------------------------------------------- decomposition
169
+
170
+
171
+ def _group(children: list[Any], top: int, parent: str,
172
+ promote: Callable[[Member], Node] | None = None) -> list[Node]:
173
+ """Keep the ``top`` largest exact children; the rest become one ``+N more`` node holding
174
+ them as ``Member`` tuples. A kept ``Member`` becomes its ``Node`` (``promote``) and a kept
175
+ node's subtree is built now: nothing is built for a child that is not kept. A dropped child
176
+ that has a subtree at this depth is counted in the group's ``unexamined``: a refusal its
177
+ expansion would raise (a premise failing, a port not computed) was never seen."""
178
+ exact = [c for c in children if c.kind not in _FIXED]
179
+ fixed = [c for c in children if c.kind in _FIXED]
180
+ exact.sort(key=lambda c: -size(c.value))
181
+ kept, rest = exact[:top], exact[top:]
182
+ kept = [promote(c) if isinstance(c, Member) else c for c in kept]
183
+ for node in kept:
184
+ if node.grow is not None:
185
+ node.children, node.grow = node.grow(), None
186
+ if rest:
187
+ total = sum((c.value for c in rest[1:]), rest[0].value)
188
+ members = [c if isinstance(c, Member) else Member(c.name, c.kind, c.port, c.index,
189
+ c.value) for c in rest]
190
+ expands = getattr(promote, "expands", False)
191
+ skipped = sum(1 for c in rest if (c.grow is not None if isinstance(c, Node) else expands))
192
+ note = f"+{len(rest)} more, sum of their exact contributions"
193
+ if skipped:
194
+ note += f"; {skipped} have subtrees that were not expanded (not examined)"
195
+ kept.append(Node(f"+{len(rest)} more", "more", f"{parent} (unlisted)", total, EXACT,
196
+ members=members, note=note, unexamined=skipped))
197
+ return kept + fixed
198
+
199
+
200
+ def _selection(kind: str, index: tuple[int, ...]) -> str:
201
+ """The selection text of one ablated index (as ``Run.set`` records it)."""
202
+ if kind == "neuron":
203
+ return f"i={index[0]}"
204
+ if kind == "head":
205
+ return f"h{index[0]}"
206
+ return f"h{index[0]},src={index[1]}"
207
+
208
+
209
+ def _promoter(proof: str, grow: Callable[[Member], Any] | None = None
210
+ ) -> Callable[[Member], Node]:
211
+ """``_group``'s ``promote`` for neurons, heads or sources: the kept member's node (its
212
+ address names the index), with ``grow(member)`` as its subtree builder."""
213
+
214
+ def promote(m: Member) -> Node:
215
+ return Node(m.name, m.kind, f"{m.port}[{_selection(m.kind, m.index)}]", m.value, EXACT,
216
+ proof, port=m.port, index=m.index,
217
+ grow=None if grow is None else (lambda: grow(m)))
218
+
219
+ promote.expands = grow is not None # type: ignore[attr-defined]
220
+ return promote
221
+
222
+
223
+ def _remainder(name: str, address: str, value: Any, why: str, bound: Any = None) -> Node:
224
+ return Node(name, "remainder", address, value, MEASURED, note=why, bound=bound)
225
+
226
+
227
+ def _through(reader: Any, bound: Any) -> Any:
228
+ """A per-coordinate bound (residual frame) mapped through the consumer's linear map (None
229
+ stays None: a refused bound)."""
230
+ if bound is None:
231
+ return None
232
+ bound = f64(bound).reshape(-1)
233
+ return reader.vector.abs() @ bound if reader.scalar else bound
234
+
235
+
236
+ def _matmul_bound(exact: Any, spread: Any, n: int, dtype: Any, acc: Any) -> Any:
237
+ """``|fl(W x) - W x|`` per output from ``exact = W x`` and ``spread = |W| |x|`` (``n``
238
+ terms): partial sums at the precision of ``acc`` (``accumulation.Accumulation``) in any
239
+ order, one rounding to ``dtype``; None when ``acc`` has no ``gamma_n``."""
240
+ gamma = acc.gamma(n)
241
+ if gamma is None:
242
+ return None
243
+ return gamma * spread * (1 + unit_roundoff(dtype)) + unit_roundoff(dtype) * exact.abs()
244
+
245
+
246
+ def _edited(run: Any, address: str, select: Any = None) -> dict[str, Any] | None:
247
+ info = run.read_info(address, select=select) if select is not None else run.read_info(address)
248
+ return info if info["kind"] in ("edit", "realisation") else None
249
+
250
+
251
+ def _gap(run: Any, reader: Any, *, name: str, address: str, native: Any, exact: Any,
252
+ bound: Any, why: str, info: dict[str, Any] | None, original: Any = None,
253
+ refusal: str | None = None) -> list[Node]:
254
+ """``native - exact`` at a site (residual-frame vectors): an ``edit`` node for what an edit
255
+ wrote there (``native - original``) and a bounded ``remainder`` for the rest. With an edit
256
+ whose pre-edit value is not available the whole gap is the edit node."""
257
+ nodes = []
258
+ if info is not None:
259
+ label = info["authority"] or SUPPLIED
260
+ ops = ",".join(info["ops"]) or info["kind"]
261
+ if original is None:
262
+ return [Node(f"{name} edit", "edit", address, reader.apply(native - exact), label,
263
+ note=f"written by an edit ({ops}); the pre-edit value is not "
264
+ "available, so this holds the rounding there too")]
265
+ nodes.append(Node(f"{name} edit", "edit", address, reader.apply(native - original),
266
+ label, note=f"displacement written by an edit ({ops}): native minus "
267
+ "the pre-edit value"))
268
+ native = original
269
+ if bound is None and refusal is not None:
270
+ why = f"{why}; bound refused ({refusal})"
271
+ nodes.append(_remainder(f"{name} remainder", address, reader.apply(native - exact), why,
272
+ _through(reader, bound)))
273
+ return nodes
274
+
275
+
276
+ def _original(run: Any, address: str) -> Any:
277
+ try:
278
+ value = run.original(address, recompute=True)
279
+ except (ValueError, RuntimeError):
280
+ return None
281
+ return None if value is None else f64(value).reshape(-1)
282
+
283
+
284
+ def _attn_children(run: Any, reader: Any, row: int, layer: int, depth: int, top: int) -> list:
285
+ """Heads of ``L<layer>.attn`` (and, deeper, their sources), the o_proj bias, any edit at
286
+ ``o`` and the bounded o_proj remainder."""
287
+ torch = _torch()
288
+ mix = head_mix(run, row, layer)
289
+ if mix.A is None or mix.o is None:
290
+ raise Refusal(f"t{row}.L{layer}.o has not been computed at {run.where}")
291
+ heads, dh = mix.p.shape[0], mix.A.shape[1]
292
+ blocks = mix.weight.reshape(mix.weight.shape[0], heads, dh)
293
+ checks = mix.checks() # once per layer: the o_proj bound and every head's value-mix bound
294
+ children: list[Any] = []
295
+ writes = torch.zeros_like(mix.o)
296
+ port = f"t{row}.L{layer}.A"
297
+ for h in range(heads):
298
+ write = blocks[:, h, :] @ mix.A[h]
299
+ writes = writes + write
300
+ children.append(Member(f"L{layer}.h{h}", "head", port, (h,), reader.apply(write)))
301
+ address = f"t{row}.L{layer}.o"
302
+ module = layer_module(run.adapter, layer).self_attn.o_proj
303
+ bias = getattr(module, "bias", None)
304
+ original = None
305
+ info = _edited(run, address)
306
+ if info is not None:
307
+ original = _original(run, address)
308
+ if original is not None and bias is not None:
309
+ original = original - f64(bias)
310
+ if bias is not None:
311
+ children.append(Node(f"L{layer}.o bias", "bias", f"{address} (o_proj.bias)",
312
+ reader.apply(f64(bias)), EXACT, "P07"))
313
+ children += _gap(run, reader, name=f"L{layer}.attn", address=address, native=mix.o,
314
+ exact=writes, bound=checks["head_write"]["bound"],
315
+ why="native o minus sum_h W_o,h A_h (o_proj rounding)", info=info,
316
+ original=original, refusal=checks["head_write"].get("refused"))
317
+ bounds, refusal = checks["value_mix"]["bound"], checks["value_mix"].get("refused")
318
+ sources = None if depth <= 2 else (
319
+ lambda m: _source_children(run, reader, mix, m.index[0],
320
+ None if bounds is None else bounds[m.index[0]], top, refusal))
321
+ return _group(children, top, address, _promoter("P07", sources))
322
+
323
+
324
+ def _source_children(run: Any, reader: Any, mix: Any, head: int, bound: Any, top: int,
325
+ refusal: str | None = None) -> list:
326
+ """Source rows of one head (``bound``: its value-mix rounding bound, None and ``refusal``
327
+ when its premise fails), the edit at ``A`` if any and the bounded value-mix remainder."""
328
+ row, layer = mix.row, mix.layer
329
+ parts = mix.p[head][:, None] * mix.unit[head] # (T, d): o_parts() of this head only
330
+ port = f"t{row}.L{layer}.p"
331
+ children: list[Any] = [Member(f"t{s}", "source", port, (head, s), reader.apply(parts[s]))
332
+ for s in range(parts.shape[0])]
333
+ dh = mix.A.shape[1]
334
+ block = mix.weight.reshape(mix.weight.shape[0], -1, dh)[:, head, :]
335
+ address = f"t{row}.L{layer}.A"
336
+ info = _edited(run, address, head_mask(run, row, layer, head))
337
+ original = None
338
+ if info is not None and not any(_edited(run, f"t{row}.L{layer}.{port}")
339
+ for port in ("s", "p")):
340
+ # the pre-edit A recomputes without s/p edits too; usable only when there are none
341
+ whole = _original(run, address)
342
+ if whole is not None:
343
+ original = block @ whole.reshape(-1, dh)[head]
344
+ children += _gap(run, reader, name=f"L{layer}.h{head}", address=f"{address}[h{head}]",
345
+ native=block @ mix.A[head], exact=block @ mix.head_out()[head],
346
+ bound=None if bound is None else block.abs() @ bound,
347
+ why="native A_h minus sum_s p v (value-mix rounding)", info=info,
348
+ original=original, refusal=refusal)
349
+ return _group(children, top, f"{address}[h{head}]", _promoter("P06"))
350
+
351
+
352
+ def _mlp_children(run: Any, reader: Any, row: int, layer: int, top: int) -> list:
353
+ """Neurons of ``L<layer>.mlp``, any edit at ``m`` and the bounded down_proj remainder;
354
+ ``down_proj`` is cast once and its absolute value taken in place for the bound."""
355
+ f = f64(run.read(f"t{row}.L{layer}.f")).reshape(-1)
356
+ address = f"t{row}.L{layer}.m"
357
+ native = run.read(address)
358
+ m = f64(native).reshape(-1)
359
+ down = f64(layer_module(run.adapter, layer).mlp.down_proj.weight) # (d, d_ff)
360
+ port = f"t{row}.L{layer}.f"
361
+ children: list[Any] = [Member(f"L{layer}.f{i}", "neuron", port, (i,),
362
+ reader.apply(down[:, i] * f[i])) for i in range(f.numel())]
363
+ info = _edited(run, address)
364
+ exact = down @ f
365
+ spread = down.abs_() @ f.abs() # down is |W_down| from here on: no second copy
366
+ del down
367
+ acc = accumulation(run, native.dtype)
368
+ children += _gap(run, reader, name=f"L{layer}.mlp", address=address, native=m,
369
+ exact=exact, bound=_matmul_bound(exact, spread, f.numel(), native.dtype, acc),
370
+ why="native m minus W_down f (down_proj rounding)", info=info,
371
+ original=None if info is None else _original(run, address),
372
+ refusal=acc.refusal(f.numel()))
373
+ return _group(children, top, address, _promoter("P15"))
374
+
375
+
376
+ def terms(run: Any, reader: Any, depth: int, top: int) -> list[Node]:
377
+ """Depth-1 nodes of the consumer, without the top remainder. Below depth 1 a node's
378
+ subtree is built when ``_group`` keeps it (``Node.grow``); for an ``o`` consumer the heads
379
+ come grouped already."""
380
+ row = reader.row
381
+ layers = run.adapter.layers
382
+ if reader.kind == "o":
383
+ return _attn_children(run, reader, row, reader.layer, depth + 1, top)
384
+ nodes = []
385
+ h0 = f64(run.read(f"t{row}.L0.h")).reshape(-1)
386
+ info = run.read_info(f"t{row}.L0.h")
387
+ nodes.append(Node("embedding", "embedding", f"t{row}.L0.h", reader.apply(h0),
388
+ SUPPLIED if info["authority"] == SUPPLIED else EXACT,
389
+ "P19" if reader.scalar else "P01", port=f"t{row}.L0.h",
390
+ note=None if info["kind"] == "native" else
391
+ f"t{row}.L0.h written by an edit ({','.join(info['ops'])})"))
392
+ for layer in range(layers):
393
+ for part, port in (("attn", "o"), ("mlp", "m")):
394
+ if reader.reaches(layer, part) is not None:
395
+ continue
396
+ address = f"t{row}.L{layer}.{port}"
397
+ value = f64(run.read(address)).reshape(-1)
398
+ grow = None
399
+ if depth > 1:
400
+ grow = ((lambda layer=layer: _attn_children(run, reader, row, layer, depth, top))
401
+ if part == "attn" else
402
+ (lambda layer=layer: _mlp_children(run, reader, row, layer, top)))
403
+ nodes.append(Node(f"L{layer}.{part}", part, address, reader.apply(value), EXACT,
404
+ "P19" if reader.scalar else "P14", port=address, index=(),
405
+ grow=grow))
406
+ if reader.scalar and reader.bias:
407
+ nodes.append(Node("head bias", "bias", "lm_head.bias",
408
+ f64(reader.bias), EXACT, "P19"))
409
+ return nodes
410
+
411
+
412
+ def _stream(run: Any, reader: Any) -> tuple[Any, list[tuple[str, Any, dict]]]:
413
+ """The residual adds up to the consumer: ``(bound, edits)``. ``bound`` is the
414
+ per-coordinate ``sum 1/2 ulp`` of each add's result (the add redone in the model dtype on
415
+ its native operands, i.e. without any edit of that port); ``edits`` one ``(address,
416
+ displacement, info)`` per residual port an edit wrote (``h`` of a later layer, ``r``,
417
+ ``h_out``): the native value minus that add (or, for ``h``, minus ``h_out`` before it)."""
418
+ from ..predict.rounding import _half_ulp
419
+
420
+ row = reader.row
421
+ last = run.adapter.layers - 1
422
+ upto = (last, 2) if reader.scalar else (reader.layer, {"h": 0, "r": 1, "h_out": 2}[
423
+ reader.port])
424
+ bound = _torch().zeros(run.adapter.model.config.hidden_size, dtype=_torch().float64)
425
+ edits = []
426
+ for layer in range(upto[0] + 1):
427
+ ports = {name: run.read(f"t{row}.L{layer}.{name}") for name in ("h", "o", "r", "m",
428
+ "h_out")}
429
+ steps = [("h", None)] if layer > 0 else []
430
+ steps += [("r", ("h", "o")), ("h_out", ("r", "m"))]
431
+ for port, operands in steps:
432
+ if layer == upto[0] and ({"h": 0, "r": 1, "h_out": 2}[port] > upto[1]):
433
+ continue
434
+ address = f"t{row}.L{layer}.{port}"
435
+ if operands is None:
436
+ before = run.read(f"t{row}.L{layer - 1}.h_out")
437
+ else:
438
+ before = ports[operands[0]] + ports[operands[1]]
439
+ bound = bound + _half_ulp(before)
440
+ info = _edited(run, address)
441
+ if port == "h" and info is not None and "h" not in (info["by"] or "").split(","):
442
+ info = None # an edit of h_out before it, booked at that add
443
+ if info is not None:
444
+ edits.append((address, f64(ports[port]).reshape(-1) - f64(before).reshape(-1),
445
+ info))
446
+ return bound, edits
447
+
448
+
449
+ def top_gap(run: Any, reader: Any, gap: Any) -> list[Node]:
450
+ """The consumer minus its depth-1 terms: an ``edit`` node per edited residual port and the
451
+ bounded remainder (residual-add rounding; for a margin or logit also the final norm and
452
+ the head, as ``explain_margin`` bounds them)."""
453
+ from ..predict.rounding import _head_bound, _ulp
454
+
455
+ bound, edits = _stream(run, reader)
456
+ nodes = []
457
+ for address, displacement, info in edits:
458
+ value = reader.apply(displacement)
459
+ gap = gap - value
460
+ nodes.append(Node(f"{address.split('.', 1)[1]} edit", "edit", address, value,
461
+ info["authority"] or SUPPLIED,
462
+ note=f"displacement written by an edit ({','.join(info['ops'])}): "
463
+ "native minus the add that port performed"))
464
+ why = "native consumer minus the listed terms: residual-add rounding"
465
+ total = _through(reader, bound)
466
+ if reader.scalar:
467
+ torch = _torch()
468
+ row = reader.row
469
+ fn = run.read(f"t{row}.fn")
470
+ logits = run.read(f"t{row}.logits")
471
+ weight = run.adapter.model.lm_head.weight
472
+ bias = getattr(run.adapter.model.lm_head, "bias", None)
473
+ if isinstance(reader.target, Margin):
474
+ a, b, half = reader.target.a, reader.target.b, 1.0
475
+ else:
476
+ a = b = reader.target.i
477
+ half = 0.5 # explain's head bound sums over j in (a, b): counted once
478
+ caps = type("Caps", (), {"normed": fn, "logits": logits})()
479
+ acc = accumulation(run, logits.dtype)
480
+ head, _ = _head_bound(caps, weight, bias, a, b, acc)
481
+ w = f64(weight[a]) - (f64(weight[b]) if a != b else 0)
482
+ final = 2 * float(w.abs().sum()) * _ulp(float(f64(fn).abs().max()),
483
+ float(torch.finfo(fn.dtype).eps))
484
+ why += ", final norm (explain's a-priori k = 2 multiple, not a derived bound) and head"
485
+ if head is None:
486
+ total = None
487
+ why += f"; bound refused ({acc.refusal(int(fn.numel()))})"
488
+ else:
489
+ total = total + half * head + final
490
+ nodes.append(_remainder("remainder", reader.text, gap, why, total))
491
+ return nodes
492
+
493
+
494
+ # --------------------------------------------------------------------------- paging
495
+
496
+
497
+ def load_page(circuit: Circuit, pointer: dict[str, Any], *, store: Any = None
498
+ ) -> dict[str, Any]:
499
+ """The child page ``pointer`` names, checked: from ``store`` when it is stored, else from the
500
+ circuit's own held pages; its sha256 must match the pointer's and its schema be a circuit
501
+ page, else ``Refusal``."""
502
+ try:
503
+ if pointer.get("state") == "stored":
504
+ from mdb.core.pointers import tensor_pointer
505
+
506
+ tensor = tensor_pointer(pointer["ref"], sha256=pointer["tensor_sha256"],
507
+ shape=[int(pointer["bytes"]["value"])], dtype="uint8")
508
+ found = load_json({"state": "stored", "sha256": pointer["sha256"]}, store=store,
509
+ tensor=tensor)
510
+ else:
511
+ found = circuit.pages.get(pointer.get("sha256"))
512
+ if found is None:
513
+ raise ValueError("the page is not held: " + str(pointer.get("reason", "absent")))
514
+ if hashlib.sha256(json_bytes(found)).hexdigest() != pointer.get("sha256"):
515
+ raise ValueError("the page differs from the pointer's sha256")
516
+ except Exception as error: # noqa: BLE001 - a missing or changed page is a refusal
517
+ raise Refusal(f"circuit {circuit.id}: page refused ({error})") from None
518
+ if not isinstance(found, dict) or found.get("schema") != PAGE_SCHEMA:
519
+ raise Refusal(f"circuit {circuit.id}: the stored page is not a circuit page")
520
+ return found
521
+
522
+
523
+ def page(circuit: Circuit, node_id: str, *, store: Any = None) -> dict[str, Any]:
524
+ """The page of node ``node_id`` (``n12``): its subtree, with every group that does not fit
525
+ again as a pointer. ``Refusal`` for an unknown id or a page that is missing or changed."""
526
+ body = circuit.record["body"]
527
+ try:
528
+ return pages_mod.locate(body["root"], int(body["count"]), node_id,
529
+ lambda pointer: load_page(circuit, pointer, store=store))
530
+ except pages_mod.PageError as error:
531
+ raise Refusal(f"circuit {circuit.id}: {error}") from None
532
+
533
+
534
+ def build(run: Any, consumer: Any, *, top: int = 4, depth: int = 2,
535
+ session_id: str | None = None, store: Any = None) -> Circuit:
536
+ """Decompose ``consumer`` at the cursor's row, seal the circuit record (kind ``circuit``)
537
+ and add it to the run's ledger. ``Refusal`` when the consumer is not computed or has no
538
+ exact additive decomposition. A tree that does not fit one page (``PAGE_BYTES``) is paged:
539
+ the record keeps the root and the first levels, and each group that does not fit is a
540
+ pointer to a child page (a sha256-checked JSON blob in ``store`` or, with none, held on
541
+ the circuit); the record's ``count`` is every node, paged ones included."""
542
+ if not 1 <= top <= 8:
543
+ raise Refusal("top must be in 1..8")
544
+ if not 1 <= depth <= 3:
545
+ raise Refusal("depth must be 1 (layer terms), 2 (heads, neurons) or 3 (source rows)")
546
+ reader = readout(run, consumer)
547
+ if reader.native is None or not computed(run, _stop(reader)):
548
+ raise Refusal(f"{_stop(reader)} has not been computed at {run.where}: run `until "
549
+ f"{_stop(reader)}` first")
550
+ nodes = terms(run, reader, depth, top)
551
+ native = f64(reader.native)
552
+ listed = sum((n.value for n in nodes[1:]), nodes[0].value)
553
+ if reader.kind != "o":
554
+ nodes += top_gap(run, reader, native - listed)
555
+ nodes = _group(nodes, top, reader.text)
556
+ root = Node(reader.text, "consumer", reader.text, native,
557
+ reader.native_authority or MEASURED, children=nodes)
558
+ total = sum((n.value for n in nodes[1:]), nodes[0].value)
559
+ closure = native - total
560
+ scale = sum(size(n.value) for n in nodes) + size(native)
561
+ entries = ledger(run)
562
+ ident = max(entries, default=0) + 1
563
+ ids = [0]
564
+ tree = root.view(ids)
565
+ pages: dict[str, Any] = {}
566
+
567
+ def put(obj: dict[str, Any]) -> dict[str, Any]:
568
+ held = put_json(obj, store=store)
569
+ if held["state"] != "stored":
570
+ pages[held["sha256"]] = obj
571
+ return {"state": "absent", "sha256": held["sha256"], "reason": held["reason"]}
572
+ return {"state": "stored", "ref": held["ref"], "sha256": held["sha256"],
573
+ "tensor_sha256": held["tensor"]["sha256"], "bytes": num(held["bytes"], EXACT)}
574
+
575
+ try:
576
+ pages_mod.paginate(tree, put, {"consumer": reader.text,
577
+ "ledger_id": num(ident, EXACT)})
578
+ except pages_mod.PageError as error:
579
+ raise Refusal(str(error)) from None
580
+ remainders = _remainders(root)
581
+ unexamined = sum(g.unexamined for g in _groups(root))
582
+ body = {"schema": SCHEMA, "ledger_id": num(ident, EXACT), "consumer": reader.text,
583
+ "kind": reader.kind, "where": run.where, "k": top, "depth": depth,
584
+ "count": ids[0], "root": tree,
585
+ "closure": {"value": claim(closure, EXACT, "P19" if reader.scalar else "P14"),
586
+ "bound": num(float(64 * 2.0 ** -53 * scale), "bound"),
587
+ "within": bool(size(closure) <= 64 * 2.0 ** -53 * scale),
588
+ "by_construction": True,
589
+ "meaning": "native consumer minus the sum of the depth-1 nodes: zero "
590
+ "by construction (the remainders are defined as native "
591
+ "minus the listed terms), so this checks float64 summation "
592
+ "only; remainders_within is the rounding check"
593
+ + ("; subtrees under the unexamined `+N more` groups were "
594
+ "never expanded, so nothing here covers them"
595
+ if unexamined else "")},
596
+ "remainders_within": _within(remainders, unexamined),
597
+ "unexamined": unexamined > 0,
598
+ "unexamined_count": num(unexamined, EXACT),
599
+ "edits": {"count": sum(1 for n in _walk(root) if n.kind == "edit"),
600
+ "meaning": "edit nodes: displacements edits wrote, never in a remainder"},
601
+ "premises": reader.premises}
602
+ body["procedure"] = procedure(run)
603
+ try:
604
+ check_bounded(body, "circuit record")
605
+ record = seal_record(session_id=session_id or run_session_id(run), kind="circuit",
606
+ model_identity=run.adapter.model_identity,
607
+ execution=dict(run.adapter.execution), authority=EXACT, body=body, run=run)
608
+ except RecordError as error:
609
+ raise Refusal(f"the circuit record does not fit one record ({error}); lower top or "
610
+ "depth") from None
611
+ circuit = Circuit(ident, record, root, reader.target, run.where,
612
+ complement=_fold_members(root), pages=pages)
613
+ entries[ident] = circuit
614
+ return circuit
615
+
616
+
617
+ def _within(remainders: list[Node], unexamined: int) -> bool | None:
618
+ """Every examined remainder within its bound: False if one is outside, None when a bound is
619
+ refused or a dropped subtree was never expanded (its remainders were not looked at)."""
620
+ if any(n.within is False for n in remainders):
621
+ return False
622
+ if unexamined or any(n.within is None for n in remainders):
623
+ return None
624
+ return True
625
+
626
+
627
+ def _fold_members(root: Node) -> Any:
628
+ """``test``'s direct-path prediction for ablating every ``+N more`` member (the embedding
629
+ aside): minus their contributions summed in member order. The members then keep no value,
630
+ so a built circuit holds one number per group instead of one per folded child."""
631
+ values = []
632
+ for group in _groups(root):
633
+ values += [m.value for m in group.members if m.kind != "embedding"]
634
+ group.members = [m._replace(value=None) for m in group.members]
635
+ return -sum(values[1:], values[0]) if values else None
636
+
637
+
638
+ def _stop(reader: Any) -> str:
639
+ return f"t{reader.row}.logits" if reader.scalar else reader.text
640
+
641
+
642
+ # --------------------------------------------------------------------------- test
643
+
644
+
645
+ def _walk(node: Node) -> list[Node]:
646
+ return [node] + [n for child in node.children for n in _walk(child)]
647
+
648
+
649
+ def _remainders(node: Node) -> list[Node]:
650
+ return [n for n in _walk(node) if n.kind == "remainder"]
651
+
652
+
653
+ def _leaves(node: Node) -> list[Node]:
654
+ if node.kind in (*_FIXED, "more"):
655
+ return []
656
+ if not node.children:
657
+ return [node]
658
+ return [leaf for child in node.children for leaf in _leaves(child)]
659
+
660
+
661
+ def _groups(node: Node) -> list[Node]:
662
+ found = [c for c in node.children if c.kind == "more"]
663
+ for child in node.children:
664
+ found += _groups(child)
665
+ return found
666
+
667
+
668
+ def test(run: Any, circuit: Circuit, reference: Any = None, *, name: str | None = None,
669
+ prompts: list[tuple[str, list[int]]] | None = None, session_id: str | None = None,
670
+ store: Any = None) -> dict[str, Any]:
671
+ """Patch the circuit natively from ``reference`` (another ``Run``) or, with ``prompts``,
672
+ from the mean over a prompt set ``name`` (``analysis.circuits.test.test``); the result is
673
+ kept on the circuit (``tests``). Returns ``{result, record}``."""
674
+ from . import test as circuit_test
675
+
676
+ if reference is None and prompts is None:
677
+ raise Refusal("circuit test needs a reference: another run of this model (or a prompt "
678
+ "set's mean); zero-ablation is not offered (issue M4)")
679
+ found = circuit_test.test(run, circuit, reference, name=name, prompts=prompts,
680
+ session_id=session_id, store=store)
681
+ circuit.tests.append(found["result"])
682
+ return found
683
+
684
+
685
+ # Old private names, kept for one commit: symbols.py imported them.
686
+ _terms = terms
687
+ _top_gap = top_gap
688
+
689
+ __all__ = ["CIRCUIT", "Circuit", "KINDS", "Node", "PAGE_SCHEMA", "SCHEMA", "build", "ledger",
690
+ "load_page", "page", "terms", "test", "top_gap"]