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,417 @@
1
+ """Finite splits of a binding's effect on a scalar consumer between two captures of one prompt.
2
+
3
+ ``run`` is the native run at ``t<j>.logits``; ``edited`` the same tokens with the binding's
4
+ cache cells moved (``edit_bindings``: every k/v cell the binding holds at rows ``<= j`` set to
5
+ ``x + dose (target - x)``, target zero or a donor run's cell; dose 1 replaces). ``c`` is the
6
+ consumer's readout vector at the native final state (``reads.readout``: ``rho_0 gamma_F *
7
+ (W_U[a] - W_U[b])``); every term below is ``c`` applied to a change at the reader row ``j``.
8
+
9
+ * ``credit`` (key-cell credit, P07 ``transport_finite_split``): per layer and head,
10
+ ``Delta A_h = sum_s [Delta p_s v0_s + p0_s Delta v_s + Delta p_s Delta v_s]`` (routing: where
11
+ the head looks; payload: what the old route carries; interaction), read through
12
+ ``W_O,h^T c``. Exact in real arithmetic (``closure_max``: the float64 summation gap); the
13
+ ``remainder`` is the native ``A`` difference minus the float64 split (measured), so the terms
14
+ sum to the native change at that attention output. ``*_on_binding`` restrict each term to the
15
+ sources whose k or v cell the binding holds; a binding of ``k`` cells only gets a routing term.
16
+ * ``indirect`` (P15 ``swiglu_finite_split`` + the residual telescoping of ``symbols.hop.hop_edge``):
17
+ ``Delta M_native = direct + attention_rest + sum_l [gate_l + up_l + interaction_l + mlp
18
+ remainder_l] + norm + rounding``. ``direct`` is the credit on the binding's own sources at
19
+ every layer; ``attention_rest`` the rest of the attention change (renormalisation onto other
20
+ sources, the reader row's own recomputed q/k/v, ``o_proj`` and mix rounding); per MLP layer
21
+ the finite SwiGLU split ``Delta f = u0 Delta s + s0 Delta u + Delta s Delta u`` read through
22
+ ``W_down^T c`` (exact) with the native ``Delta m`` remainder (measured); ``norm`` the exact
23
+ final-RMS term ``(rho_1 - rho_0)/rho_0 c . h_1``; ``rounding`` the measured rest. This splits
24
+ the hop table's lumped ``indirect_share = 1 - direct/native`` by layer and part.
25
+ ``through`` (optional): the same MLP parts and each layer's attention change weighted by the
26
+ consumer adjoint through the remaining layers (``explain.consumer_gradient`` at each layer
27
+ input, past K/V fixed; the P14 pullback to the attention write): what a layer's change
28
+ does through everything after it, first order (``derived-local``). These double count across
29
+ layers (a change and its downstream response both appear) and do not sum to the native delta.
30
+ * ``interactions`` (P29 ``mobius``): native consumer values under joint edits of subsets of at
31
+ most ``MAX_BINDINGS`` bindings (every subset up to ``order``); ``I(T) = sum_{U <= T}
32
+ (-1)^{|T|-|U|} F(U)`` exactly, checked by ``mobius_inverse`` against the measured ``F``. A pair
33
+ term ``I({A,B}) = F(AB) - F(A) - F(B) + F()`` is 0 when A and B act separately.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import itertools
39
+ from typing import Any
40
+
41
+ from ..measure.readout import head_mix, layer_module
42
+ from ..numerics.finite import mobius, mobius_inverse, swiglu_finite_split, transport_finite_split
43
+ from ..numerics.labels import EXACT, LOCAL, MEASURED, SUPPLIED, f64, num
44
+ from ..predict.consumers import Margin, Refusal
45
+
46
+ MAX_BINDINGS = 12
47
+ _PORTS = ("k", "v")
48
+
49
+
50
+ def _torch():
51
+ import torch
52
+
53
+ return torch
54
+
55
+
56
+ def _tokens(run: Any, row: int) -> list[int]:
57
+ from .table import _token_at
58
+
59
+ return [_token_at(run, r) for r in range(row + 1)]
60
+
61
+
62
+ def binding_cells(binding: Any, row: int, layers: int, kv: int) -> dict[tuple, list[int]]:
63
+ """``(layer, port, source row) -> KV heads`` of the binding's cells at rows ``<= row``."""
64
+ out: dict[tuple, set] = {}
65
+ for cell in binding.cells:
66
+ if cell.row > row:
67
+ continue
68
+ for layer in cell.layers if cell.layers is not None else range(layers):
69
+ for port in cell.ports or _PORTS:
70
+ heads = cell.kv if cell.kv is not None else range(kv)
71
+ out.setdefault((layer, port, cell.row), set()).update(heads)
72
+ return {key: sorted(heads) for key, heads in sorted(out.items())}
73
+
74
+
75
+ def _donor_cell(donor: Any, layer: int, port: str, row: int, heads: list[int], *,
76
+ own: bool = False) -> Any:
77
+ """The donor's cell block ``(len(heads), d_h)`` as its reads see it (native dtype);
78
+ ``own``: the reader row's port value instead (pre-RoPE for a key)."""
79
+ cache = donor.read_cache(layer, port)[0]
80
+ if cache.shape[1] > row and not own:
81
+ return cache[heads, row]
82
+ adapter = donor.adapter
83
+ own = donor.read(f"t{row}.L{layer}.{_own_port(donor, port)}")
84
+ return own.reshape(adapter.num_kv_heads, adapter.head_dim)[heads]
85
+
86
+
87
+ def _own_port(run: Any, port: str) -> str:
88
+ """The reader row's port that writes its cache cell: ``v``; ``kn`` (Qwen3) or ``k`` (the
89
+ RoPE that follows is linear and fixed by the position, so the edit reaches the key)."""
90
+ return "v" if port == "v" else "kn" if "kn" in run.program.names else "k"
91
+
92
+
93
+ def edit_bindings(run: Any, bindings: list[Any], row: int, *, dose: float = 1.0,
94
+ donor: Any = None) -> Any:
95
+ """A fresh run of ``run``'s tokens to ``t<row>.logits`` with every k/v cell of
96
+ ``bindings`` at rows ``<= row`` moved to ``x + dose (target - x)`` (target 0, or the
97
+ ``donor`` run's cell). Earlier rows are state-cell edits (``Run.set_cell``, op ``mix``);
98
+ the reader row's own cells are port edits of ``v`` and ``k`` (``kn`` on Qwen3) at that
99
+ row. The caller closes the returned run."""
100
+ from mdb.engine import Run
101
+
102
+ if run.edited:
103
+ raise Refusal("a binding edit is measured against a native run; this run carries edits")
104
+ adapter = run.adapter
105
+ layers, kv = adapter.layers, adapter.num_kv_heads
106
+ if row < run.first_row:
107
+ raise Refusal(f"t{row} was prefilled: its reads were never stopped at")
108
+ cells: dict[tuple, set] = {}
109
+ for binding in bindings:
110
+ for key, heads in binding_cells(binding, row, layers, kv).items():
111
+ cells.setdefault(key, set()).update(heads)
112
+ edited = Run(adapter, _tokens(run, row), prefill=min(run.prefill, row))
113
+ names = edited.program.names
114
+ edited.until(f"t{row}.L0.{names[0]}")
115
+ if dose != 0.0:
116
+ for (layer, port, s), heads in sorted(cells.items()):
117
+ if s == row:
118
+ continue
119
+ heads = sorted(heads)
120
+ value = 0.0 if donor is None else \
121
+ _donor_cell(donor, layer, port, s, heads).clone()[None, :, None, :]
122
+ edited.set_cell(layer, port, value, "mix", rows=[s], kv=heads, dose=float(dose))
123
+ for layer in range(layers):
124
+ for port in sorted(_PORTS, key=lambda p: names.index(_own_port(edited, p))):
125
+ heads = sorted(cells.get((layer, port, row), ()))
126
+ if heads:
127
+ _own_edit(edited, donor, layer, port, row, heads, dose)
128
+ edited.until(f"t{row}.logits")
129
+ return edited
130
+
131
+
132
+ def _own_edit(edited: Any, donor: Any, layer: int, port: str, row: int, heads: list[int],
133
+ dose: float) -> None:
134
+ torch = _torch()
135
+ adapter = edited.adapter
136
+ kv, dh = adapter.num_kv_heads, adapter.head_dim
137
+ address = f"t{row}.L{layer}.{_own_port(edited, port)}"
138
+ edited.until(address)
139
+ native = edited.read(address)
140
+ x = f64(native).reshape(kv, dh)
141
+ target = torch.zeros(len(heads), dh, dtype=torch.float64) if donor is None else \
142
+ f64(_donor_cell(donor, layer, port, row, heads, own=True))
143
+ new = x.clone()
144
+ new[heads] = x[heads] + dose * (target - x[heads])
145
+ mask = torch.zeros(kv, dh, dtype=torch.bool)
146
+ mask[heads] = True
147
+ edited.set(address, new.reshape(native.shape).to(native.dtype), "replace",
148
+ mask=mask.reshape(native.shape))
149
+
150
+
151
+ def _scalar(reader: Any) -> Any:
152
+ if reader is None or not reader.scalar:
153
+ raise Refusal("a finite split needs a scalar consumer (a margin or a logit)")
154
+ return f64(reader.vector).reshape(-1)
155
+
156
+
157
+ def _value(run: Any, reader: Any) -> float:
158
+ logits = run.read(f"t{reader.row}.logits").reshape(-1)
159
+ t = reader.target
160
+ if isinstance(t, Margin):
161
+ return float(f64(logits[t.a]) - f64(logits[t.b]))
162
+ return float(f64(logits[t.i]))
163
+
164
+
165
+ _CREDIT = ("routing", "routing_on_binding", "payload", "payload_on_binding", "interaction",
166
+ "interaction_on_binding")
167
+
168
+
169
+ def credit(run: Any, edited: Any, reader: Any, binding: Any) -> dict[str, Any]:
170
+ """Key-cell credit of ``binding`` at the reader row (module docstring), per layer and in
171
+ total: the terms (derived-exact P07), ``remainder`` and ``native`` (measured; the terms plus
172
+ the remainder are the native change at the attention output, read through
173
+ ``W_O,h^T c``), and ``closure_max``, the largest float64 gap of one head's split against
174
+ ``mix(p1, v1) - mix(p0, v0)`` (the identity's own check)."""
175
+ torch = _torch()
176
+ c = _scalar(reader)
177
+ j, adapter = reader.row, run.adapter
178
+ heads, kv, dh = adapter.num_heads, adapter.num_kv_heads, adapter.head_dim
179
+ weights: dict[int, Any] = {}
180
+ rows, closure = [], 0.0
181
+ for layer in range(adapter.layers):
182
+ m0 = head_mix(run, j, layer, weights, lazy=True)
183
+ m1 = head_mix(edited, j, layer, weights, lazy=True)
184
+ if m0.A is None or m1.A is None:
185
+ raise Refusal(f"t{j}.L{layer}.A was not captured on both runs")
186
+ back = torch.einsum("dhe,d->he", m0.weight.reshape(-1, heads, dh), c) # (H, d_h)
187
+ count = m0.p.shape[1]
188
+ own = torch.tensor([[binding.covers(s, layer, g, "k") or binding.covers(s, layer, g, "v")
189
+ for s in range(count)] for g in range(kv)], dtype=torch.bool)
190
+ total = dict.fromkeys((*_CREDIT, "remainder", "native"), 0.0)
191
+ for h in range(heads):
192
+ g = m0.kappa[h]
193
+ split = transport_finite_split(m0.p[h], m1.p[h], m0.values[g], m1.values[g],
194
+ native0=m0.A[h], native1=m1.A[h])
195
+ closure = max(closure, float(split.closure))
196
+ z0 = m0.values[g] @ back[h] # (T,)
197
+ dz, dp = m1.values[g] @ back[h] - z0, m1.p[h] - m0.p[h]
198
+ for name, per in (("routing", dp * z0), ("payload", m0.p[h] * dz),
199
+ ("interaction", dp * dz)):
200
+ total[name] += float(per.sum())
201
+ total[name + "_on_binding"] += float(per[own[g]].sum())
202
+ native = float(back[h] @ (m1.A[h] - m0.A[h]))
203
+ total["native"] += native
204
+ total["remainder"] += native - float(back[h] @ split.total)
205
+ rows.append({"layer": layer, **total})
206
+ sums = {k: sum(r[k] for r in rows) for k in rows[0] if k != "layer"}
207
+
208
+ def label(entry):
209
+ return {k: v if k == "layer" else num(v, MEASURED if k in ("remainder", "native") else
210
+ EXACT, "P07") for k, v in entry.items()}
211
+ return {"layers": [label(r) for r in rows], "total": label(sums),
212
+ "closure_max": num(closure, EXACT, "P07")}
213
+
214
+
215
+ def adjoints(run: Any, reader: Any) -> list[Any]:
216
+ """``lambda_l`` for ``l = 1..L``: the consumer's gradient at the reader row's residual
217
+ entering layer ``l`` (``l = L``: the final state). ``explain.consumer_gradient`` (model-dtype
218
+ autograd, past K/V fixed, on a fresh session of the same tokens) for ``l < L``; the float64
219
+ RMS-readout gradient ``c - rho_0^2/d (c . h) h`` for ``l = L``. Margins only."""
220
+ from ..predict.explain import consumer_gradient
221
+
222
+ if not isinstance(reader.target, Margin):
223
+ raise Refusal("the adjoint column needs a margin consumer M[a,b]")
224
+ adapter, j, t = run.adapter, reader.row, reader.target
225
+ session = adapter.session(_tokens(run, j))
226
+ session.continue_()
227
+ out = []
228
+ for _ in range(1, adapter.layers):
229
+ session.continue_()
230
+ out.append(f64(consumer_gradient(session, int(t.a), int(t.b))[1]).reshape(-1))
231
+ h = f64(run.read(f"t{j}.L{adapter.layers - 1}.h_out")).reshape(-1)
232
+ c = _scalar(reader)
233
+ out.append(c - (reader.rho ** 2 / h.numel()) * float(c @ h) * h)
234
+ return out
235
+
236
+
237
+ def indirect(run: Any, edited: Any, reader: Any, binding: Any, *,
238
+ found: dict[str, Any] | None = None, through: list[Any] | None = None
239
+ ) -> dict[str, Any]:
240
+ """The native consumer change split into the binding's direct reads and the indirect
241
+ parts by layer (module docstring). ``found``: ``credit`` of the same runs when already
242
+ computed; ``through``: ``adjoints(run, reader)`` to add the derived-local column.
243
+ ``closure`` is the sum of every part minus the native delta (float64 summation only)."""
244
+ c = _scalar(reader)
245
+ j, adapter = reader.row, run.adapter
246
+ last = adapter.layers - 1
247
+ found = credit(run, edited, reader, binding) if found is None else found
248
+
249
+ def port(r, layer, name):
250
+ return f64(r.read(f"t{j}.L{layer}.{name}")).reshape(-1)
251
+
252
+ native = _value(edited, reader) - _value(run, reader)
253
+ direct = sum(found["total"][k]["value"] for k in _CREDIT if k.endswith("_on_binding"))
254
+ layers, attn, mlp_sum = [], 0.0, 0.0
255
+ for layer in range(adapter.layers):
256
+ module = layer_module(adapter, layer)
257
+ d_o = port(edited, layer, "o") - port(run, layer, "o")
258
+ d_m = port(edited, layer, "m") - port(run, layer, "m")
259
+ split = swiglu_finite_split(port(run, layer, "g"), port(edited, layer, "g"),
260
+ port(run, layer, "u"), port(edited, layer, "u"),
261
+ native0=port(run, layer, "f"), native1=port(edited, layer, "f"))
262
+ down = f64(module.mlp.down_proj.weight)
263
+ parts = {k: float((c @ down) @ v) for k, v in split.terms.items()}
264
+ captured = float(c @ d_m)
265
+ entry = {"layer": layer, "attention": num(float(c @ d_o), EXACT, "P07"),
266
+ **{k: num(v, EXACT, "P15") for k, v in parts.items()},
267
+ "mlp_remainder": num(captured - sum(parts.values()), MEASURED),
268
+ "swiglu_closure": num(float(split.closure), EXACT, "P15")}
269
+ if through is not None:
270
+ lam = through[layer]
271
+ ld = lam @ down
272
+ entry["through"] = {**{k: num(float(ld @ v), LOCAL, "P14")
273
+ for k, v in split.terms.items()},
274
+ "mlp": num(float(lam @ d_m), LOCAL, "P14"),
275
+ "attention": num(float(_pullback(run, j, layer, ld, lam) @ d_o),
276
+ LOCAL, "P14")}
277
+ del down
278
+ attn += float(c @ d_o)
279
+ mlp_sum += captured
280
+ layers.append(entry)
281
+ h0, h1 = port(run, last, "h_out"), port(edited, last, "h_out")
282
+ eps = float(getattr(adapter.backbone, adapter.spec.final_norm).variance_epsilon)
283
+ rho0, rho1 = (float((h.pow(2).mean() + eps) ** -0.5) for h in (h0, h1))
284
+ norm_term = (rho1 - rho0) / rho0 * float(c @ h1)
285
+ stream = float(c @ (h1 - h0)) - attn - mlp_sum
286
+ rounding = native - float(c @ (h1 - h0)) - norm_term
287
+ mlp = {k: sum(e[k]["value"] for e in layers) for k in ("gate", "up", "interaction",
288
+ "mlp_remainder")}
289
+ total = direct + (attn - direct) + sum(mlp.values()) + norm_term + stream + rounding
290
+
291
+ def share(x):
292
+ return num(x / native, MEASURED) if native else {"state": "unresolved",
293
+ "reason": "native delta 0"}
294
+ return {"native_delta": num(native, MEASURED), "direct": num(direct, EXACT, "P07"),
295
+ "attention_rest": num(attn - direct, EXACT, "P07"),
296
+ "mlp": {k: num(v, MEASURED if k == "mlp_remainder" else EXACT, "P15")
297
+ for k, v in mlp.items()},
298
+ "norm": num(norm_term, EXACT), "stream_rounding": num(stream, MEASURED),
299
+ "rounding": num(rounding, MEASURED), "closure": num(total - native, MEASURED),
300
+ "indirect_share": share(native - direct),
301
+ "shares": {"attention_rest": share(attn - direct), "gate": share(mlp["gate"]),
302
+ "up": share(mlp["up"]), "interaction": share(mlp["interaction"]),
303
+ "remainder": share(mlp["mlp_remainder"] + norm_term + stream
304
+ + rounding)},
305
+ "layers": layers}
306
+
307
+
308
+ def _pullback(run: Any, j: int, layer: int, ld: Any, lam: Any) -> Any:
309
+ """``(I + J_M)^T lam`` at the native ``r`` of the layer (``finite.mlp_pullback``, P14) as
310
+ a vector product: ``ld = W_down^T lam``, ``y = W_gate^T (u S'(g) ld) + W_up^T (S(g) ld)``,
311
+ ``J_N^T y = rho gamma y - rho^3/d ((gamma r) . y) r``; the matrices are never formed."""
312
+ from ..numerics.finite import silu, silu_d1
313
+
314
+ module = layer_module(run.adapter, layer)
315
+ norm = module.post_attention_layernorm
316
+
317
+ def port(name):
318
+ return f64(run.read(f"t{j}.L{layer}.{name}")).reshape(-1)
319
+
320
+ r, g, u = port("r"), port("g"), port("u")
321
+ y = f64(module.mlp.gate_proj.weight).T @ (u * silu_d1(g) * ld) + \
322
+ f64(module.mlp.up_proj.weight).T @ (silu(g) * ld)
323
+ gamma = f64(norm.weight).reshape(-1)
324
+ rho = float((r.pow(2).mean() + float(norm.variance_epsilon)) ** -0.5)
325
+ return lam + rho * gamma * y - (rho ** 3 / r.numel()) * float((gamma * r) @ y) * r
326
+
327
+
328
+ def split(run: Any, binding: Any, reader: Any, *, donor: Any = None, dose: float = 1.0,
329
+ through: list[Any] | None = None) -> dict[str, Any]:
330
+ """``credit`` and ``indirect`` of one binding under ``edit_bindings(run, [binding],
331
+ reader.row, dose=dose, donor=donor)`` (the edited run is made and closed here)."""
332
+ edited = edit_bindings(run, [binding], reader.row, dose=dose, donor=donor)
333
+ try:
334
+ found = credit(run, edited, reader, binding)
335
+ return {"edit": {"dose": num(float(dose), SUPPLIED),
336
+ "target": "zero" if donor is None else f"donor {_name(donor)}"},
337
+ "credit": found,
338
+ "indirect": indirect(run, edited, reader, binding, found=found, through=through)}
339
+ finally:
340
+ edited.close()
341
+
342
+
343
+ def _name(run: Any) -> str:
344
+ return str(getattr(run, "name", None) or "run")
345
+
346
+
347
+ def compact(found: dict[str, Any], *, store: Any = None, run: Any = None) -> dict[str, Any]:
348
+ """A table cell of ``split``: credit totals, the indirect parts and shares, and the per-layer
349
+ detail behind a sha256-checked pointer (``core.bounded``)."""
350
+ from mdb.core.bounded import put_json
351
+
352
+ ind = found["indirect"]
353
+ return {"edit": found["edit"], "credit": found["credit"]["total"],
354
+ "closure_max": found["credit"]["closure_max"],
355
+ "indirect": {k: v for k, v in ind.items() if k not in ("layers", "shares")},
356
+ "full": put_json(found, store=store, run=run)}
357
+
358
+
359
+ def interactions(run: Any, bindings: list[Any], reader: Any, *, order: int = 2,
360
+ dose: float = 1.0, donor: Any = None, min_effect: float = 0.0
361
+ ) -> dict[str, Any]:
362
+ """Moebius interaction terms of joint edits (module docstring). ``F(S)``: the native
363
+ consumer on ``edit_bindings(run, S, ...)``, measured for every subset ``S`` of at most
364
+ ``order`` bindings (``order = len(bindings)``: the whole lattice, ``2^n`` runs). The terms
365
+ are exact integer combinations of measured values (labelled measured); ``inverse_gap`` is
366
+ ``max |F - mobius_inverse(I)|`` over the measured subsets (float64 summation only), and
367
+ ``floor`` is ``|F() - the run's own consumer|`` (the null edit's run-to-run noise). A pair
368
+ acts ``jointly`` when ``|I(AB)| > max(floor, min_effect)``."""
369
+ if not 2 <= len(bindings) <= MAX_BINDINGS:
370
+ raise Refusal(f"interactions take 2..{MAX_BINDINGS} bindings, not {len(bindings)}")
371
+ names = [b.name for b in bindings]
372
+ if len(set(names)) != len(names):
373
+ raise Refusal("interaction bindings need distinct names")
374
+ _scalar(reader)
375
+ order = min(int(order), len(bindings))
376
+ outcomes = {}
377
+ for size in range(order + 1):
378
+ for subset in itertools.combinations(range(len(bindings)), size):
379
+ edited = edit_bindings(run, [bindings[i] for i in subset], reader.row, dose=dose,
380
+ donor=donor)
381
+ try:
382
+ outcomes[frozenset(names[i] for i in subset)] = _value(edited, reader)
383
+ finally:
384
+ edited.close()
385
+ terms = mobius(outcomes)
386
+ back = mobius_inverse(terms)
387
+ gap = max(abs(back[s] - outcomes[s]) for s in back)
388
+ base = outcomes[frozenset()]
389
+ floor = abs(base - _value(run, reader))
390
+
391
+ def text(s):
392
+ return "+".join(sorted(s, key=names.index)) or "none"
393
+ pairs = []
394
+ for a, b in itertools.combinations(names, 2):
395
+ joint = frozenset((a, b))
396
+ if joint not in terms:
397
+ continue
398
+ both = outcomes[joint] - base
399
+ pairs.append({"pair": [a, b], "interaction": num(terms[joint], MEASURED, "P29"),
400
+ "joint_delta": num(both, MEASURED),
401
+ "separate_sum": num(both - terms[joint], MEASURED),
402
+ "acts": "jointly" if abs(terms[joint]) > max(floor, min_effect)
403
+ else "separately"})
404
+ return {"bindings": names, "order": order, "runs": len(outcomes),
405
+ "edit": {"dose": num(float(dose), SUPPLIED),
406
+ "target": "zero" if donor is None else f"donor {_name(donor)}"},
407
+ "outcomes": {text(s): num(v, MEASURED) for s, v in outcomes.items()},
408
+ "terms": {text(s): num(v, MEASURED, "P29") for s, v in terms.items() if s},
409
+ "pairs": pairs, "floor": num(floor, MEASURED),
410
+ "min_effect": num(float(min_effect), SUPPLIED),
411
+ "inverse_gap": num(gap, MEASURED, "P29"),
412
+ "meaning": "I(T) = sum over U <= T of (-1)^(|T|-|U|) F(U); a pair acts jointly "
413
+ "when |I(AB)| exceeds max(floor, min_effect)"}
414
+
415
+
416
+ __all__ = ["MAX_BINDINGS", "adjoints", "binding_cells", "compact", "credit", "edit_bindings",
417
+ "indirect", "interactions", "split"]