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,379 @@
1
+ """Bridge and channel instruments for a batched Llama-family forward.
2
+
3
+ These are the verbs that decided the organism results, lifted out of the study drivers so a session can call them
4
+ on any small Llama-type HF model (eager, MHA or GQA with equal heads), optionally under a structural attention mask.
5
+
6
+ Sites (strings):
7
+ ``t{r}.h{lev}`` residual stream at row r entering layer lev (lev 0 = token embedding, lev L = after the last
8
+ layer); an edit there reaches layers >= lev.
9
+ ``t{r}.L{l}.v{h}`` value vector of head h at layer l, row r (what other rows read from r at layer l through head h).
10
+
11
+ Verbs:
12
+ ``Fwd(model, allow=None)`` batched functional forward over the model's weights with ``edit``/``hold``/``capture``;
13
+ matches HF logits to ~1e-5 (fp32).
14
+ ``capture(fwd, ids, sites)`` -> {site: [N, d]}.
15
+ ``transplant(fwd, base, donor, site, rows, y, yd)`` donor value at one site into the base run. Per answer row:
16
+ effect (|dM| >= 0.5), transfer (argmax becomes the donor's answer), median fraction of
17
+ the margin moved, M = logit[y] - logit[y_donor]. Use many donors per base (16 by
18
+ default in ``pairs``): one donor misses a large share of real uses (MEASURED .14-.25
19
+ on binaries, .01-.10 on organisms, .50 on Qwen).
20
+ ``paired(fwd, base, donor, site, rows, y, yd)`` total effect vs frozen-selection effect (every attention pattern
21
+ from the first layer the edit reaches held at the base's). ``ratio`` = median
22
+ frozen/total over items with an effect. Content-carried value ~1.0 (organisms
23
+ .96-1.05); a value used as an address (it chooses where attention reads) ~0
24
+ (.04-.05 on an organism built to use it so). ``channel`` turns the ratio into a word.
25
+ ``class_swap(...)`` class mean-difference swap at a site: site += sum_k sign_k (mean over prompts of the
26
+ donor's class_k - mean of the base's class_k), means excluding prompts of the same
27
+ input. Swapping a *class* (b, or one answer) instead of the whole value separates
28
+ what the readers use.
29
+ ``bridge_verdict(...)`` per site, for a shared row read by several answer rows (consumers): b swap, null swap
30
+ (b of a permuted input: same collision structure, unrelated to the computation),
31
+ each answer's own swap, answer-sum swap and the gap b - answer-sum, and a verdict:
32
+ not read b swap joint < .5
33
+ side by side read, and each answer's own swap moves its consumer within .25 of
34
+ the b swap (the row holds the answers precomputed)
35
+ abstract read, own swaps fall >= .25 short of the b swap, and the answer-sum
36
+ swap falls >= .25 short of the b swap jointly (b beyond the answers
37
+ is read)
38
+ joint answers read, own swaps short, gap < .25 (the answers' subspace read jointly)
39
+ ``unreliable`` is set when the null swap transfers > .05.
40
+ ``pairs(groups, cls, n, rng, differ=())`` base/donor index pairs with different ``cls`` (and different values for
41
+ every array in ``differ``), ``n`` donors per base.
42
+
43
+ Validated (MEASURED, single seed) on small trained organisms whose mechanism was fixed by design, one per verdict
44
+ (side by side, abstract, not read although b decodes at 1.0 and passes novelty, address-carried): each verdict
45
+ reproduced the study's label, and the paired ratio separated content (.96-1.05) from address (.04-.05). The
46
+ thresholds are the studies' sealed thresholds. Decodable != used: a probe or novelty pass alone never implies a read.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import re
52
+ from typing import Any
53
+
54
+ import numpy as np
55
+
56
+ RULE = ("not read: b swap joint < .5; side by side: read and every own-answer swap >= b swap - .25 on its consumer; "
57
+ "abstract: read, every own swap < b swap - .25 and b joint - answer-sum joint >= .25; joint answers: read, own "
58
+ "swaps short, gap < .25; unreliable: null swap > .05")
59
+ SITE = re.compile(r"^t(\d+)\.(?:h(\d+)|L(\d+)\.v(\d+))$")
60
+
61
+
62
+ def _torch():
63
+ import torch
64
+
65
+ return torch
66
+
67
+
68
+ def parse(site: str) -> tuple:
69
+ m = SITE.match(site)
70
+ if not m:
71
+ raise ValueError(f"site {site!r}: use 't{{r}}.h{{lev}}' or 't{{r}}.L{{l}}.v{{h}}'")
72
+ r, lev, l, h = m.groups()
73
+ return ("h", int(r), int(lev), None) if lev is not None else ("v", int(r), int(l), int(h))
74
+
75
+
76
+ def _rms(x, w, eps):
77
+ torch = _torch()
78
+ return w * (x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps))
79
+
80
+
81
+ def _rot(x):
82
+ torch = _torch()
83
+ a, b = x.chunk(2, dim=-1)
84
+ return torch.cat((-b, a), dim=-1)
85
+
86
+
87
+ class Fwd:
88
+ """Batched functional forward of a Llama-family HF model. ``allow``: [L, T, T] or [T, T] bool structural mask
89
+ (query row may attend to key row), None = causal."""
90
+
91
+ def __init__(self, model: Any, allow: Any = None):
92
+ torch = _torch()
93
+ self.m = model
94
+ c = model.config
95
+ self.L, self.H = c.num_hidden_layers, c.num_attention_heads
96
+ self.KV = getattr(c, "num_key_value_heads", self.H) or self.H
97
+ self.hd = getattr(c, "head_dim", None) or c.hidden_size // self.H
98
+ self.eps = c.rms_norm_eps
99
+ self.layers = model.model.layers
100
+ a = None if allow is None else torch.as_tensor(np.asarray(allow, bool))
101
+ self.allow = None if a is None else (a if a.dim() == 3 else a[None].expand(self.L, *a.shape))
102
+ self._cs: dict = {}
103
+
104
+ def _mask(self, T, device):
105
+ torch = _torch()
106
+ a = (torch.ones(T, T, dtype=torch.bool).tril()[None].expand(self.L, T, T) if self.allow is None
107
+ else self.allow[:, :T, :T])
108
+ return torch.zeros(a.shape, device=device).masked_fill(~a.to(device), float("-inf"))
109
+
110
+ def __call__(self, ids, edit=None, hold=None, capture=False):
111
+ """ids [B, T] long. edit(kind, layer, t) -> t for kind in v [B,H,T,hd] / p [B,H,T,T] / h_in (residual entering
112
+ the layer, [B,T,D]; layer L = final residual). hold {layer: p}. capture=True -> dict with h (list of L+1
113
+ residuals), v, p, logits."""
114
+ torch = _torch()
115
+ with torch.no_grad():
116
+ ids = torch.as_tensor(ids)
117
+ B, T = ids.shape
118
+ h = self.m.model.embed_tokens(ids)
119
+ key = (T, str(h.device))
120
+ if key not in self._cs:
121
+ self._cs[key] = self.m.model.rotary_emb(h, torch.arange(T, device=h.device)[None])
122
+ cos, sin = (t[:, None] for t in self._cs[key])
123
+ mask = self._mask(T, h.device)
124
+ cap = {"h": [], "v": [], "p": []} if capture else None
125
+ rep = self.H // self.KV
126
+ for l, lay in enumerate(self.layers):
127
+ if edit is not None:
128
+ h = edit("h_in", l, h)
129
+ if capture:
130
+ cap["h"].append(h)
131
+ at = lay.self_attn
132
+ x = _rms(h, lay.input_layernorm.weight, self.eps)
133
+ q = at.q_proj(x).view(B, T, self.H, self.hd).transpose(1, 2)
134
+ k = at.k_proj(x).view(B, T, self.KV, self.hd).transpose(1, 2)
135
+ v = at.v_proj(x).view(B, T, self.KV, self.hd).transpose(1, 2)
136
+ if hasattr(at, "q_norm"):
137
+ q, k = at.q_norm(q), at.k_norm(k)
138
+ q, k = q * cos + _rot(q) * sin, k * cos + _rot(k) * sin
139
+ if rep > 1:
140
+ k, v = k.repeat_interleave(rep, 1), v.repeat_interleave(rep, 1)
141
+ if edit is not None:
142
+ v = edit("v", l, v)
143
+ s = (q @ k.transpose(-1, -2)) * self.hd ** -0.5 + mask[l]
144
+ p = torch.softmax(s.float(), dim=-1).to(q.dtype)
145
+ if hold is not None and l in hold:
146
+ p = hold[l]
147
+ if edit is not None:
148
+ p = edit("p", l, p)
149
+ if capture:
150
+ cap["v"].append(v)
151
+ cap["p"].append(p)
152
+ h = h + at.o_proj((p @ v).transpose(1, 2).reshape(B, T, self.H * self.hd))
153
+ x2 = _rms(h, lay.post_attention_layernorm.weight, self.eps)
154
+ h = h + lay.mlp.down_proj(torch.nn.functional.silu(lay.mlp.gate_proj(x2)) * lay.mlp.up_proj(x2))
155
+ if edit is not None:
156
+ h = edit("h_in", self.L, h)
157
+ if capture:
158
+ cap["h"].append(h)
159
+ logits = self.m.lm_head(_rms(h, self.m.model.norm.weight, self.eps))
160
+ if capture:
161
+ cap["logits"] = logits
162
+ return cap
163
+ return logits
164
+
165
+
166
+ def _value(cap, s):
167
+ k, r, l, h = s
168
+ return cap["h"][l][:, r] if k == "h" else cap["v"][l][:, h, r]
169
+
170
+
171
+ def _setter(s, value=None, delta=None):
172
+ k, r, l, h = s
173
+
174
+ def edit(kind, layer, t):
175
+ if (k == "h" and (kind != "h_in" or layer != l)) or (k == "v" and (kind != "v" or layer != l)):
176
+ return t
177
+ t = t.clone()
178
+ if k == "h":
179
+ t[:, r] = value if delta is None else t[:, r] + delta
180
+ else:
181
+ t[:, h, r] = value if delta is None else t[:, h, r] + delta
182
+ return t
183
+ return edit
184
+
185
+
186
+ def capture(fwd: Fwd, ids, sites) -> dict:
187
+ cap = fwd(ids, capture=True)
188
+ return {s: _value(cap, parse(s)) for s in sites}
189
+
190
+
191
+ def _margin(lg, rows, y, yd):
192
+ torch = _torch()
193
+ y, yd = torch.as_tensor(np.asarray(y)), torch.as_tensor(np.asarray(yd))
194
+ lr = lg[:, rows] # [B, C, V]
195
+ return lr.gather(-1, y[..., None])[..., 0] - lr.gather(-1, yd[..., None])[..., 0], lr.argmax(-1)
196
+
197
+
198
+ def _summ(M0, M1, Md, top, yd):
199
+ torch = _torch()
200
+ dM, D = M1 - M0, Md - M0
201
+ frac = dM / torch.where(D.abs() > 1e-6, D, torch.ones_like(D))
202
+ tr = (top == torch.as_tensor(np.asarray(yd)))
203
+ eff = dM.abs() >= 0.5
204
+ return {"transfer": tr.float().mean(0).tolist(), "joint": float(tr.all(1).float().mean()),
205
+ "effect": eff.float().mean(0).tolist(), "median_frac": frac.median(0).values.tolist(), "n": int(len(M0))}
206
+
207
+
208
+ def transplant(fwd: Fwd, base, donor, site: str, rows, y, yd) -> dict:
209
+ """base/donor ids [N, T] (aligned rows); y/yd [N, C] correct answers of base and donor at ``rows``."""
210
+ s = parse(site)
211
+ cb, cd = fwd(base, capture=True), fwd(donor, capture=True)
212
+ M0, _ = _margin(cb["logits"], rows, y, yd)
213
+ Md, _ = _margin(cd["logits"], rows, y, yd)
214
+ lg = fwd(base, edit=_setter(s, value=_value(cd, s)))
215
+ M1, top = _margin(lg, rows, y, yd)
216
+ return {"site": site, **_summ(M0, M1, Md, top, yd)}
217
+
218
+
219
+ def paired(fwd: Fwd, base, donor, site: str, rows, y, yd) -> dict:
220
+ torch = _torch()
221
+ s = parse(site)
222
+ cb, cd = fwd(base, capture=True), fwd(donor, capture=True)
223
+ M0, _ = _margin(cb["logits"], rows, y, yd)
224
+ ed = _setter(s, value=_value(cd, s))
225
+ Mt, top = _margin(fwd(base, edit=ed), rows, y, yd)
226
+ first = s[2]
227
+ hold = {l: cb["p"][l] for l in range(first, fwd.L)}
228
+ Mf, _ = _margin(fwd(base, edit=ed, hold=hold), rows, y, yd)
229
+ dt, df = Mt - M0, Mf - M0
230
+ eff = dt.abs() >= 0.5
231
+ ratio = (df[eff] / dt[eff]).median().item() if bool(eff.any()) else None
232
+ return {"site": site, "total_dM_median": dt.median(0).values.tolist(),
233
+ "frozen_dM_median": df.median(0).values.tolist(), "ratio": ratio, "n_effect": int(eff.sum()),
234
+ "channel": channel(ratio), "transfer": (top == torch.as_tensor(np.asarray(yd))).float().mean(0).tolist()}
235
+
236
+
237
+ def channel(ratio) -> str:
238
+ if ratio is None:
239
+ return "no effect"
240
+ if ratio >= 0.8:
241
+ return "content (value carried; selections unchanged)"
242
+ if ratio <= 0.2:
243
+ return "address (the edit acts by moving attention selections)"
244
+ return "mixed"
245
+
246
+
247
+ def pairs(groups, cls, n: int = 16, rng=None, differ=()) -> tuple[np.ndarray, np.ndarray]:
248
+ """For each prompt i, up to n donor prompts j with groups[j] != groups[i], cls[j] != cls[i] and arr[j] != arr[i]
249
+ for every arr in ``differ`` (arr [N] or [N, C]: every column must differ). Returns (base_idx, donor_idx)."""
250
+ rng = np.random.default_rng(0) if rng is None else rng
251
+ groups, cls = np.asarray(groups), np.asarray(cls)
252
+ bi, di = [], []
253
+ for i in range(len(cls)):
254
+ ok = (groups != groups[i]) & (cls != cls[i])
255
+ for arr in differ:
256
+ arr = np.asarray(arr)
257
+ d = arr != arr[i]
258
+ ok &= d.all(1) if d.ndim == 2 else d
259
+ cand = np.where(ok)[0]
260
+ if len(cand):
261
+ pick = rng.choice(cand, min(n, len(cand)), replace=False)
262
+ bi += [i] * len(pick)
263
+ di += pick.tolist()
264
+ return np.asarray(bi), np.asarray(di)
265
+
266
+
267
+ def class_swap(fwd: Fwd, ids, groups, classes: dict, base_idx, donor_idx, site: str, combo, rows, cap=None):
268
+ """Argmax at ``rows`` [P, C] after site += sum_k sign_k (mean_{classes[k] == class of donor} - mean_{... of base}),
269
+ over the prompts ``ids`` (the grid), excluding prompts whose group equals the base's/donor's. combo: [(name, sign)].
270
+ Also returns valid [P] (every class has other members and differs between base and donor)."""
271
+ torch = _torch()
272
+ s = parse(site)
273
+ X = _value(cap if cap is not None else fwd(ids, capture=True), s)
274
+ groups = np.asarray(groups)
275
+ _, ginv = np.unique(groups, return_inverse=True)
276
+ g = torch.as_tensor(ginv)
277
+ bi, di = torch.as_tensor(base_idx), torch.as_tensor(donor_idx)
278
+ delta = torch.zeros(len(bi), X.shape[1])
279
+ valid = torch.ones(len(bi), dtype=torch.bool)
280
+ for name, sign in combo:
281
+ c = torch.as_tensor(np.unique(np.asarray(classes[name]), return_inverse=True)[1])
282
+ Sc = torch.zeros(int(c.max()) + 1, X.shape[1]).index_add_(0, c, X)
283
+ nc = torch.bincount(c).float()
284
+ # same-class sums over the grid minus this input's own prompts (prompts of one group share a class)
285
+ cb, cd = c[bi], c[di]
286
+ gb, gd = g[bi], g[di]
287
+ same_b = (c[None, :] == cb[:, None]) & (g[None, :] == gb[:, None])
288
+ same_d = (c[None, :] == cd[:, None]) & (g[None, :] == gd[:, None])
289
+ own_b, nb_own = same_b.float() @ X, same_b.float().sum(1)
290
+ own_d, nd_own = same_d.float() @ X, same_d.float().sum(1)
291
+ nb, nd = nc[cb] - nb_own, nc[cd] - nd_own
292
+ valid &= (nb > 0) & (nd > 0) & (cb != cd)
293
+ mu_b = (Sc[cb] - own_b) / nb.clamp(min=1)[:, None]
294
+ mu_d = (Sc[cd] - own_d) / nd.clamp(min=1)[:, None]
295
+ delta += sign * (mu_d - mu_b)
296
+ delta = delta * valid[:, None]
297
+ lg = fwd(torch.as_tensor(np.asarray(ids))[bi], edit=_setter(s, delta=delta))
298
+ return lg[:, rows].argmax(-1), valid
299
+
300
+
301
+ def bridge_verdict(fwd: Fwd, ids, groups, b, answers, y_tok, rows, sites, n_donors: int = 4, seed: int = 0,
302
+ max_pairs: int = 2048) -> dict:
303
+ """ids [N, T] grid prompts (several prompts per input, e.g. fillers); groups [N] input id (x); b [N] bridge class;
304
+ answers [N, C] answer class per consumer; y_tok [N, C] correct answer token per consumer row (``rows``).
305
+ Pairs: each prompt with ``n_donors`` donors of a different input, different b and every answer different."""
306
+ torch = _torch()
307
+ rng = np.random.default_rng(seed)
308
+ groups, b, answers, y_tok = (np.asarray(a) for a in (groups, b, answers, y_tok))
309
+ C = answers.shape[1]
310
+ perm = rng.permutation(int(groups.max()) + 1)
311
+ bx = {int(gg): int(bb) for gg, bb in zip(groups, b)}
312
+ null = np.array([bx.get(int(perm[gg]), -1) for gg in groups])
313
+ classes = {"b": b, "null": null, **{f"a{c}": answers[:, c] for c in range(C)}}
314
+ combos = {"b": [("b", 1)], "null": [("null", 1)], **{f"a{c}": [(f"a{c}", 1)] for c in range(C)}}
315
+ if C >= 2:
316
+ combos["asum"] = [(f"a{c}", 1) for c in range(C)]
317
+ bi, di = pairs(groups, b, n_donors, rng, differ=(answers,))
318
+ if len(bi) > max_pairs:
319
+ keep = rng.choice(len(bi), max_pairs, replace=False)
320
+ bi, di = bi[keep], di[keep]
321
+ cap = fwd(ids, capture=True)
322
+ yd = torch.as_tensor(y_tok[di])
323
+ out = {}
324
+ for site in sites:
325
+ rec = {}
326
+ for name, co in combos.items():
327
+ top, valid = class_swap(fwd, ids, groups, classes, bi, di, site, co, rows, cap=cap)
328
+ v = valid.numpy()
329
+ tr = (top == yd).numpy()[v]
330
+ rec[name] = {"transfer": tr.mean(0).round(3).tolist() if v.any() else None,
331
+ "joint": float(tr.all(1).mean().round(3)) if v.any() else None, "n": int(v.sum())}
332
+ sb, sbj = rec["b"]["transfer"], rec["b"]["joint"]
333
+ own = [rec[f"a{c}"]["transfer"][c] if rec[f"a{c}"]["transfer"] else None for c in range(C)]
334
+ asum = rec.get("asum", {}).get("joint")
335
+ nullmax = max(rec["null"]["transfer"]) if rec["null"]["transfer"] else None
336
+ read = sbj is not None and sbj >= 0.5
337
+ side = read and all(o is not None and o >= sb[c] - 0.25 for c, o in enumerate(own))
338
+ short = read and all(o is not None and o < sb[c] - 0.25 for c, o in enumerate(own))
339
+ gap = None if (asum is None or sbj is None) else round(sbj - asum, 3)
340
+ if not read:
341
+ verdict = "not read"
342
+ elif side:
343
+ verdict = "side by side"
344
+ elif short and gap is not None and gap >= 0.25:
345
+ verdict = "abstract"
346
+ elif short:
347
+ verdict = "joint answers"
348
+ else:
349
+ verdict = "mixed"
350
+ out[site] = {"swaps": rec, "b_joint": sbj, "own": own, "answer_sum_joint": asum, "gap": gap,
351
+ "null_max": nullmax, "unreliable": nullmax is not None and nullmax > 0.05, "verdict": verdict}
352
+ return {"n_pairs": int(len(bi)), "sites": out, "rule": RULE}
353
+
354
+
355
+ def attach_mask(model: Any, allow: Any) -> list:
356
+ """Make an HF Llama-family model apply a structural attention mask ([L, T, T] or [T, T] bool) in every forward,
357
+ including mdb's adapter, which steps decoder layers with ``attention_mask=None``: a forward pre-hook on every
358
+ attention module replaces its ``attention_mask``. Query rows are [past, past + Tq). Returns the hook handles.
359
+ (Organism v4 found mdb's adapter ignoring the HF mask; this hook is how v4/v5 crosschecked mdb to <= 9e-5.)"""
360
+ torch = _torch()
361
+ L = len(model.model.layers)
362
+ a = torch.as_tensor(np.asarray(allow, bool))
363
+ a = a if a.dim() == 3 else a[None].expand(L, *a.shape)
364
+ adds = torch.zeros(a.shape).masked_fill(~a, float("-inf"))
365
+
366
+ def make(i):
367
+ add = adds[i]
368
+
369
+ def pre(mod, args, kwargs):
370
+ x = kwargs.get("hidden_states", args[0] if args else None)
371
+ B, Tq = x.shape[0], x.shape[1]
372
+ pkv = kwargs.get("past_key_values")
373
+ past = int(pkv.get_seq_length(i)) if pkv is not None else 0
374
+ m = add[past:past + Tq, :past + Tq].to(device=x.device, dtype=x.dtype)
375
+ kwargs["attention_mask"] = m[None, None].expand(B, 1, Tq, past + Tq)
376
+ return args, kwargs
377
+ return pre
378
+ return [lay.self_attn.register_forward_pre_hook(make(i), with_kwargs=True)
379
+ for i, lay in enumerate(model.model.layers)]
@@ -0,0 +1,201 @@
1
+ """Finite computation changes between aligned native branches.
2
+
3
+ This experimental Python API accounts for endpoint differences, not isolated causal
4
+ credit. Consumer projections use the edited final RMS scale and the direct residual
5
+ readout; they are not suffix derivatives. Full tensor terms stay outside the JSON view.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from mdb.core.pointers import check_bounded
14
+
15
+ from ..numerics import finite
16
+ from ..numerics.labels import EXACT, MEASURED, f64, num
17
+ from ..predict.consumers import Margin, Refusal
18
+ from ..predict.plan import state_digest
19
+ from .readout import layer_module
20
+
21
+
22
+ @dataclass
23
+ class BranchChanges:
24
+ report: dict[str, Any]
25
+ tensors: dict[str, Any] = field(default_factory=dict)
26
+
27
+
28
+ def _norm(value: Any, authority: str = EXACT) -> dict:
29
+ return num(float(f64(value).norm()), authority)
30
+
31
+
32
+ def _identity(result: Any) -> dict:
33
+ out = {"proof": result.proof, "function": result.name,
34
+ "terms": {name: {"norm": _norm(value)} for name, value in result.terms.items()},
35
+ "algebra_closure": _norm(result.total - result.reference)}
36
+ if result.native is not None:
37
+ out["native_discrepancy"] = _norm(result.native - result.total, MEASURED)
38
+ return out
39
+
40
+
41
+ def _rank(parts: dict[str, Any], top: int, address: Any, axis: str) -> dict:
42
+ """Signed direct projections, with one exact aggregate of every omitted row."""
43
+ torch = finite._torch()
44
+ total = sum(parts.values())
45
+ order = torch.argsort(total.abs(), descending=True, stable=True)[:top].tolist()
46
+ entries = [{axis: i, "address": address(i), "total": num(float(total[i]), EXACT),
47
+ "parts": {name: num(float(value[i]), EXACT) for name, value in parts.items()}}
48
+ for i in order]
49
+ tail = {name: num(float(value.sum() - value[order].sum()), EXACT)
50
+ for name, value in parts.items()}
51
+ return {"ranking": "absolute signed total under the fixed direct readout",
52
+ "rows": entries, "omitted": total.numel() - len(order), "tail": tail,
53
+ "total": num(float(total.sum()), EXACT)}
54
+
55
+
56
+ def explain_changes(base: Any, edited: Any, consumer: Margin, *, layer: int,
57
+ top: int = 5) -> BranchChanges:
58
+ """Explain one block between completed runs of the same adapter and token history.
59
+
60
+ Supports Qwen2/Qwen3 native ports. Edits to K/V producers or cache cells are
61
+ supported. Direct edits of the explained intermediates are refused rather than
62
+ being hidden inside an arithmetic discrepancy. Different prompts need a separate
63
+ alignment contract. The supplied layer is not automatically discovered.
64
+ """
65
+ if base is edited:
66
+ raise Refusal("use two distinct branch runs (an identical-copy sham is supported)")
67
+ if base.adapter is not edited.adapter:
68
+ raise Refusal("branches must share the same adapter and checkpoint instance")
69
+ if not isinstance(consumer, Margin):
70
+ raise Refusal("this prototype requires a declared Margin consumer")
71
+ if not 0 <= layer < base.adapter.layers or not 1 <= top <= 8:
72
+ raise Refusal("layer is outside the model or top is outside 1..8")
73
+ before = [state_digest(run) for run in (base, edited)]
74
+ tokens = [run.session.read("tokens").tolist() for run in (base, edited)]
75
+ if tokens[0] != tokens[1]:
76
+ raise Refusal("branches need identical consumed tokens and visibility")
77
+ row = consumer.row
78
+ if any(run.where not in (f"t{row}.logits", f"t{row}.sample") for run in (base, edited)):
79
+ raise Refusal("both branches must be at the consumer row's logits or sample")
80
+ if not 0 <= min(consumer.a, consumer.b) <= max(consumer.a, consumer.b) < (
81
+ base.adapter.model.config.vocab_size):
82
+ raise Refusal("consumer token is outside the vocabulary")
83
+ names = ("h", "a", "p", "A", "o", "r", "n", "g", "sg", "u", "f", "m", "h_out")
84
+ ports = []
85
+ for run in (base, edited):
86
+ captured = {}
87
+ for name in names:
88
+ address = f"t{row}.L{layer}.{name}"
89
+ info = run.read_info(address)
90
+ if info["kind"] in ("edit", "realisation"):
91
+ raise Refusal(f"direct edit of explained intermediate {address} needs "
92
+ "explicit edit-displacement accounting")
93
+ captured[name] = run.read(address)
94
+ if not bool(finite._torch().isfinite(captured[name]).all()):
95
+ raise Refusal(f"nonfinite native operand at {address}")
96
+ ports.append(captured)
97
+ p0, p1 = ports
98
+ adapter = base.adapter
99
+ module = layer_module(adapter, layer)
100
+ torch = finite._torch()
101
+ heads, width = adapter.num_heads, adapter.head_dim
102
+ kappa = finite.gqa_kappa(heads, adapter.num_kv_heads)
103
+ probs = [p["p"].reshape(heads, row + 1) for p in ports]
104
+ values = [run.read_cache(layer, "v")[0, kappa, :row + 1, :]
105
+ for run in (base, edited)]
106
+ if any(tuple(v.shape) != (heads, row + 1, width) for v in values):
107
+ raise Refusal("the cache does not cover the aligned visible source set")
108
+ attn = finite.transport_finite_split(*probs, *values,
109
+ native0=p0["A"].reshape(heads, width), native1=p1["A"].reshape(heads, width))
110
+ mlp = finite.swiglu_finite_split(p0["g"].reshape(-1), p1["g"].reshape(-1),
111
+ p0["u"].reshape(-1), p1["u"].reshape(-1),
112
+ native0=p0["f"].reshape(-1), native1=p1["f"].reshape(-1))
113
+ norms = {name: finite.rms_finite_change(p0[src], p1[src], norm.weight,
114
+ float(norm.variance_epsilon), native0=p0[dst], native1=p1[dst])
115
+ for name, src, dst, norm in (
116
+ ("attention_norm", "h", "a", module.input_layernorm),
117
+ ("mlp_norm", "r", "n", module.post_attention_layernorm))}
118
+
119
+ # Slice vocabulary rows before casting; do not materialize a float64 unembedding.
120
+ head = adapter.model.lm_head
121
+ final_norm = getattr(adapter.backbone, adapter.spec.final_norm)
122
+ last = adapter.layers - 1
123
+ final = [f64(run.read(f"t{row}.L{last}.h_out")).reshape(-1)
124
+ for run in (base, edited)]
125
+ rho = [(float(final_norm.variance_epsilon) + h.square().mean()).rsqrt() for h in final]
126
+ readout = (f64(head.weight[consumer.a]) - f64(head.weight[consumer.b])) * f64(
127
+ final_norm.weight)
128
+ c = rho[1] * readout
129
+ native_margin = [f64(run.read(f"t{row}.logits")).reshape(-1)[consumer.a] -
130
+ f64(run.read(f"t{row}.logits")).reshape(-1)[consumer.b]
131
+ for run in (base, edited)]
132
+ delta = native_margin[1] - native_margin[0]
133
+ final_terms = {"residual": c @ (final[1] - final[0]),
134
+ "scale": (rho[1] - rho[0]) * (readout @ final[0])}
135
+
136
+ # One layer's matrices, cast once and released before returning.
137
+ out_weight = f64(module.self_attn.o_proj.weight)
138
+ head_readout = (c @ out_weight).reshape(heads, width)
139
+ pv0, pv1, vv0, vv1 = map(f64, (*probs, *values))
140
+ dp, dv = pv1 - pv0, vv1 - vv0
141
+ source_parts = {
142
+ "payload": (pv0 * torch.einsum("hd,hjd->hj", head_readout, dv)).sum(0),
143
+ "routing": (dp * torch.einsum("hd,hjd->hj", head_readout, vv0)).sum(0),
144
+ "interaction": (dp * torch.einsum("hd,hjd->hj", head_readout, dv)).sum(0)}
145
+ attn_write = {name: out_weight @ value.reshape(-1) for name, value in attn.terms.items()}
146
+ del out_weight
147
+ down = f64(module.mlp.down_proj.weight)
148
+ neuron_readout = c @ down
149
+ neuron_parts = {name: neuron_readout * value for name, value in mlp.terms.items()}
150
+ mlp_write = {name: down @ value for name, value in mlp.terms.items()}
151
+ del down
152
+ changes = {name: f64(p1[name]).reshape(-1) - f64(p0[name]).reshape(-1)
153
+ for name in ("h", "o", "r", "m", "h_out")}
154
+ attn_gap = changes["o"] - sum(attn_write.values())
155
+ mlp_gap = changes["m"] - sum(mlp_write.values())
156
+ add_gap = changes["h_out"] - changes["h"] - changes["o"] - changes["m"]
157
+ projection = {name: c @ value for name, value in changes.items()}
158
+ projection["arithmetic_discrepancy"] = c @ add_gap
159
+ after = [state_digest(run) for run in (base, edited)]
160
+ if before != after:
161
+ raise RuntimeError("branch explanation changed a run state")
162
+ report = {
163
+ "schema": "mdb-branch-changes-v1", "row": row, "layer": layer,
164
+ "scope": "observed endpoint accounting; direct final readout, not isolated suffix effects",
165
+ "lineage": {"base": before[0], "edited": before[1], "session_unchanged": True,
166
+ "model_identity": adapter.model_identity,
167
+ "execution": dict(adapter.execution)},
168
+ "consumer": {"address": consumer.text,
169
+ "base": num(float(native_margin[0]), MEASURED),
170
+ "edited": num(float(native_margin[1]), MEASURED),
171
+ "delta": num(float(delta), MEASURED),
172
+ "residual_change": num(float(final_terms["residual"]), EXACT),
173
+ "normalization_scale_change": num(float(final_terms["scale"]), EXACT),
174
+ "native_discrepancy": num(float(delta - sum(final_terms.values())), MEASURED)},
175
+ "attention": {**_identity(attn),
176
+ "sources": _rank(source_parts, top, lambda i: f"cache.L{layer}.v[row={i}]", "row"),
177
+ "write_discrepancy_norm": _norm(attn_gap, MEASURED),
178
+ "write_discrepancy_projection": num(float(c @ attn_gap), MEASURED)},
179
+ "mlp": {**_identity(mlp),
180
+ "neurons": _rank(neuron_parts, top, lambda i: f"t{row}.L{layer}.f[i={i}]", "index"),
181
+ "write_discrepancy_norm": _norm(mlp_gap, MEASURED),
182
+ "write_discrepancy_projection": num(float(c @ mlp_gap), MEASURED)},
183
+ "normalization": {name: _identity(value) for name, value in norms.items()},
184
+ "block_direct_projection": {name: num(float(value), MEASURED)
185
+ for name, value in projection.items()},
186
+ "equations": [
187
+ {"output": f"L{layer}.A", "inputs": [f"L{layer}.p", f"cache.L{layer}.v"],
188
+ "proof": "P07", "meaning": "payload + routing + interaction + native discrepancy"},
189
+ {"output": f"L{layer}.n", "inputs": [f"L{layer}.r"], "proof": "P03"},
190
+ {"output": f"L{layer}.f", "inputs": [f"L{layer}.g", f"L{layer}.u"], "proof": "P15"},
191
+ {"output": f"L{layer}.h_out", "inputs": [f"L{layer}.h", f"L{layer}.o", f"L{layer}.m"],
192
+ "proof": "P14"}],
193
+ "limitations": ["top rows ranked by direct projection; cancellations can hide large terms",
194
+ "unlisted rows remain in the aggregate tail",
195
+ "native discrepancies are observations, not certified error bounds",
196
+ "this is not automatic circuit localization or semantic discovery"]}
197
+ check_bounded(report, "branch-change report")
198
+ return BranchChanges(report, {"attention": attn, "mlp": mlp, "normalization": norms,
199
+ "source_parts": source_parts, "neuron_parts": neuron_parts,
200
+ "attention_write": attn_write, "mlp_write": mlp_write,
201
+ "attention_gap": attn_gap, "mlp_gap": mlp_gap, "readout": c})