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,380 @@
1
+ """Subspace bindings: a named subspace of one value cell.
2
+
3
+ A ``SubspaceBinding`` is a sub-cell binding like ``components.ComponentBinding``: it holds no
4
+ cells of its own (the partition of value cells is unchanged) and names a ``k``-dimensional
5
+ subspace of the value cell ``cache.L<layer>.v[kv<g>,row=r]`` (``d_h`` coordinates) by an
6
+ orthonormal basis ``Q`` (``d_h, k``, float64), with its provenance and the authority of the basis
7
+ itself (``BASIS_AUTHORITIES``):
8
+
9
+ * ``derived-exact``: a deterministic function of the weights and a declared token set, e.g. the
10
+ span of the symbol table's content readout directions mapped into the cell
11
+ (``readout_subspace``: ``W_g^T (gamma_F * W_U[t])`` per token ``t``, P06/P07/P19, PCA top ``k``);
12
+ * ``fitted``: learnt from data, e.g. a pyvene ``LowRankRotatedSpaceIntervention`` trained by DAS
13
+ (``from_pyvene``) or class means of cell values (``class_mean_subspace``); the provenance
14
+ must name the data and the training (items digest, steps, seed, job);
15
+ * ``supplied``: the caller's basis, taken as given.
16
+
17
+ Numbers computed FROM a basis are labelled with the record vocabulary (``finite.AUTHORITIES``):
18
+ ``mass`` (the share of a cell value's energy, or of a value difference's, in the subspace) and
19
+ the direct consumer share at fixed attention are ``derived-exact``; an interchange result
20
+ (``interchange``: the cell set to ``v + Q Q^T (v_src - v)`` on an mdb branch and run to the
21
+ consumer) is ``measured``. ``iia`` summarises interchange records with the floor rule
22
+ (flip: ``M0 > floor`` and ``M_after < -m * floor``, ``m`` = 1 and a 4-floor margin).
23
+ Measured IIA can be attached to the binding as labels (``attach``), so the symbol table
24
+ (``symbols.table(subspaces=...)``) reports per binding: basis, authority, provenance, the mass of
25
+ the native cell at the cursor and the attached IIA.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import json
32
+ from dataclasses import dataclass, field
33
+ from typing import Any
34
+
35
+ from ..numerics.labels import EXACT, MEASURED, f64, num
36
+ from ..predict.consumers import Refusal
37
+ from .binding import Binding
38
+
39
+ BASIS_AUTHORITIES = ("fitted", "derived-exact", "derived-local", "supplied")
40
+ SCHEMA = "mdb-subspace-binding-v1"
41
+
42
+
43
+ def _torch():
44
+ import torch
45
+
46
+ return torch
47
+
48
+
49
+ def orthonormal(basis: Any, tol: float = 1e-9) -> Any:
50
+ """An orthonormal float64 basis of the column span of ``basis`` (QR, rank-revealing by the
51
+ diagonal of R); ``Refusal`` when the span is empty."""
52
+ torch = _torch()
53
+ m = f64(basis)
54
+ if m.dim() == 1:
55
+ m = m[:, None]
56
+ q, r = torch.linalg.qr(m)
57
+ d = r.diagonal().abs()
58
+ if d.numel() == 0 or float(d.max()) == 0.0:
59
+ raise Refusal("a subspace binding needs a non-empty span")
60
+ keep = d > tol * d.max()
61
+ return q[:, keep].contiguous()
62
+
63
+
64
+ def principal_angles(a: Any, b: Any) -> list[float]:
65
+ """Principal angles in degrees (ascending) between the spans of two orthonormal bases."""
66
+ torch = _torch()
67
+ s = torch.linalg.svdvals(f64(a).T @ f64(b)).clamp(-1.0, 1.0)
68
+ return [float(x) for x in torch.rad2deg(torch.arccos(s))]
69
+
70
+
71
+ @dataclass
72
+ class SubspaceBinding(Binding):
73
+ """A subspace of the value cell ``cache.L<layer>.v[kv<kv>]`` (module docstring). ``row`` is
74
+ the bound row (``None``: a row-free template the caller applies to any row, e.g. a carrier
75
+ rule's row)."""
76
+
77
+ layer: int = -1
78
+ kv: int = -1
79
+ row: int | None = None
80
+ basis: Any = None
81
+ authority: str = "supplied"
82
+ provenance: dict[str, Any] = field(default_factory=dict)
83
+
84
+ @property
85
+ def k(self) -> int:
86
+ return int(self.basis.shape[1])
87
+
88
+ @property
89
+ def cell(self) -> str:
90
+ where = "" if self.row is None else f",row={self.row}"
91
+ return f"cache.L{self.layer}.v[kv{self.kv}{where}]"
92
+
93
+ def digest(self) -> str:
94
+ return hashlib.sha256(f64(self.basis).contiguous().numpy().tobytes()).hexdigest()
95
+
96
+ def project(self, value: Any) -> Any:
97
+ q = self.basis
98
+ return q @ (q.T @ f64(value).reshape(-1))
99
+
100
+ def swap(self, base: Any, source: Any) -> Any:
101
+ """``base + Q Q^T (source - base)``: the subspace interchange (float64)."""
102
+ b = f64(base).reshape(-1)
103
+ return b + self.project(f64(source).reshape(-1) - b)
104
+
105
+ def mass(self, value: Any, reference: Any = None) -> dict[str, Any]:
106
+ """The share of ``|value - reference|^2`` inside the subspace (derived-exact given the
107
+ basis); ``reference`` defaults to zero (the raw value)."""
108
+ x = f64(value).reshape(-1)
109
+ if reference is not None:
110
+ x = x - f64(reference).reshape(-1)
111
+ total = float(x @ x)
112
+ inside = float((self.basis.T @ x).pow(2).sum())
113
+ return num(inside / total if total else 0.0, EXACT)
114
+
115
+ def angles(self, other: Any) -> list[float]:
116
+ return principal_angles(self.basis, other.basis if isinstance(other, SubspaceBinding) else other)
117
+
118
+ def at(self, row: int) -> list[Any]: # no cells of its own
119
+ return []
120
+
121
+ def bound(self, row: int) -> "SubspaceBinding":
122
+ """This template bound to ``row`` (same basis and provenance)."""
123
+ return SubspaceBinding(self.name, "subspace", [], [], layer=self.layer, kv=self.kv, row=row,
124
+ basis=self.basis, authority=self.authority,
125
+ provenance=dict(self.provenance), labels=dict(self.labels))
126
+
127
+ def attach(self, name: str, value: Any, authority: str = MEASURED) -> None:
128
+ """Attach a result (e.g. ``iia``) as a label ``(value, authority)``."""
129
+ self.labels[name] = (value, authority)
130
+
131
+ def decompose(self, run: Any) -> Any:
132
+ """This bound subspace as a ``components.ComponentBinding`` of the native cell at the cursor:
133
+ parts ``subspace`` (``Q Q^T v``) and ``complement`` (``v - Q Q^T v``, the residual), with
134
+ ``linear = native = v`` (no residual-stream image). One decomposition family: the result
135
+ feeds ``components.component_table`` / ``symbols.table(components=...)`` unchanged; its
136
+ ``basis`` carries this binding's description (authority, provenance, digest)."""
137
+ from .components import Component, ComponentBinding
138
+
139
+ if self.row is None:
140
+ raise Refusal(f"subspace {self.name} is a template: bind it to a row first (bound(row))")
141
+ v = f64(run.read_cache(self.layer, "v", staged=False)[0, self.kv, self.row]).cpu()
142
+ inside = self.project(v)
143
+ parts = [Component("subspace", None, None, None, inside),
144
+ Component("complement", None, None, None, v - inside)]
145
+ return ComponentBinding(self.name, "component", [], [], row=self.row, layer=self.layer,
146
+ kv=self.kv, basis={**self.describe(), "kind": "subspace"},
147
+ components=parts, native=v, linear=v,
148
+ provenance={"decomposition": "subspace", "basis_authority": self.authority,
149
+ **self.provenance})
150
+
151
+ def describe(self) -> dict[str, Any]:
152
+ return {"schema": SCHEMA, "name": self.name, "cell": self.cell, "k": self.k,
153
+ "authority": self.authority, "provenance": self.provenance,
154
+ "digest": self.digest(),
155
+ "labels": {k: {"value": v[0], "authority": v[1]} for k, v in self.labels.items()}}
156
+
157
+ def to_json(self) -> dict[str, Any]:
158
+ return {**self.describe(), "layer": self.layer, "kv": self.kv, "row": self.row,
159
+ "basis": f64(self.basis).tolist()}
160
+
161
+ @classmethod
162
+ def from_json(cls, data: dict[str, Any]) -> "SubspaceBinding":
163
+ torch = _torch()
164
+ sb = subspace_binding(data["name"], data["layer"], data["kv"],
165
+ torch.tensor(data["basis"], dtype=torch.float64),
166
+ authority=data["authority"], provenance=data["provenance"],
167
+ row=data.get("row"), orthonormalize=False)
168
+ if sb.digest() != data["digest"]:
169
+ raise Refusal(f"subspace {data['name']}: basis digest mismatch")
170
+ for key, val in data.get("labels", {}).items():
171
+ sb.labels[key] = (val["value"], val["authority"])
172
+ return sb
173
+
174
+
175
+ def subspace_binding(name: str, layer: int, kv: int, basis: Any, *, authority: str = "supplied",
176
+ provenance: dict[str, Any] | None = None, row: int | None = None,
177
+ orthonormalize: bool = True) -> SubspaceBinding:
178
+ """A subspace binding over ``basis`` (``d_h, k``; orthonormalised unless told it already
179
+ is, which is then checked to 1e-6)."""
180
+ if authority not in BASIS_AUTHORITIES:
181
+ raise Refusal(f"basis authority must be one of {', '.join(BASIS_AUTHORITIES)}")
182
+ if authority == "fitted" and not provenance:
183
+ raise Refusal("a fitted subspace needs its provenance (data, training, job)")
184
+ torch = _torch()
185
+ q = orthonormal(basis) if orthonormalize else f64(basis)
186
+ err = float((q.T @ q - torch.eye(q.shape[1], dtype=torch.float64)).abs().max())
187
+ if err > 1e-6:
188
+ raise Refusal(f"subspace {name}: basis not orthonormal (max |Q^T Q - I| = {err:.2e})")
189
+ where = f"cache.L{layer}.v[kv{kv}" + ("" if row is None else f",row={row}") + "]"
190
+ return SubspaceBinding(name, "subspace", [], [where], layer=layer, kv=kv, row=row, basis=q,
191
+ authority=authority, provenance=dict(provenance or {}))
192
+
193
+
194
+ def readout_directions(adapter: Any, layer: int, kv: int, tokens: list[int]) -> Any:
195
+ """``W_g^T (gamma_F * W_U[t])`` per token (n, d_h) float64: the symbol table's content readout
196
+ (``symbols.content``, P19 at unit final rho) of a KV-group write, mapped into the cell
197
+ (``W_g`` = the group's summed ``W_O`` blocks, ``circuit_map.group_writers``)."""
198
+ torch = _torch()
199
+ from ..measure.readout import layer_module
200
+ from .circuit_map import group_writers
201
+
202
+ final = getattr(adapter.backbone, adapter.spec.final_norm)
203
+ gamma = f64(final.weight).reshape(-1)
204
+ w_u = adapter.model.lm_head.weight
205
+ rows = f64(w_u.index_select(0, torch.tensor(list(tokens), dtype=torch.long,
206
+ device=w_u.device))).cpu() * gamma.cpu()
207
+ w_g = group_writers(layer_module(adapter, layer).self_attn.o_proj.weight, adapter.num_heads,
208
+ adapter.num_kv_heads)[kv].cpu()
209
+ return rows @ w_g
210
+
211
+
212
+ def _pca(rows: Any, k: int, center: bool) -> tuple[Any, Any]:
213
+ torch = _torch()
214
+ x = f64(rows)
215
+ if center:
216
+ x = x - x.mean(0, keepdim=True)
217
+ _, s, vt = torch.linalg.svd(x, full_matrices=False)
218
+ if k > vt.shape[0]:
219
+ raise Refusal(f"k={k} exceeds the {vt.shape[0]} directions available")
220
+ return vt[:k].T.contiguous(), s
221
+
222
+
223
+ def readout_subspace(adapter: Any, name: str, layer: int, kv: int, tokens: list[int], k: int, *,
224
+ set_name: str = "tokens", center: bool = True) -> SubspaceBinding:
225
+ """The top-``k`` principal subspace of the cell-space readout directions of ``tokens``
226
+ (derived-exact: weights + the declared token set)."""
227
+ toks = sorted(dict.fromkeys(int(t) for t in tokens))
228
+ q, s = _pca(readout_directions(adapter, layer, kv, toks), k, center)
229
+ prov = {"method": "PCA of W_g^T (gamma_F * W_U[t]) over a declared token set",
230
+ "set": set_name, "tokens_sha256": hashlib.sha256(json.dumps(toks).encode()).hexdigest(),
231
+ "n_tokens": len(toks), "centered": center,
232
+ "explained": float((s[:k] ** 2).sum() / (s ** 2).sum())}
233
+ return subspace_binding(name, layer, kv, q, authority=EXACT, provenance=prov,
234
+ orthonormalize=False)
235
+
236
+
237
+ def class_mean_subspace(name: str, layer: int, kv: int, values: dict[str, list[Any]], k: int, *,
238
+ provenance: dict[str, Any]) -> SubspaceBinding:
239
+ """The top-``k`` principal subspace of the centred class means of cell values (label ->
240
+ values): the supervised mean-difference baseline (``fitted``)."""
241
+ torch = _torch()
242
+ means = torch.stack([torch.stack([f64(v).reshape(-1) for v in vs]).mean(0) for vs in values.values()])
243
+ q, s = _pca(means, k, True)
244
+ prov = {"method": "PCA of centred class means of cell values", "classes": sorted(values),
245
+ "explained": float((s[:k] ** 2).sum() / (s ** 2).sum()), **provenance}
246
+ return subspace_binding(name, layer, kv, q, authority="fitted", provenance=prov,
247
+ orthonormalize=False)
248
+
249
+
250
+ def from_pyvene(intervention: Any, name: str, layer: int, kv: int, *,
251
+ provenance: dict[str, Any]) -> SubspaceBinding:
252
+ """The subspace of a trained pyvene ``LowRankRotatedSpaceIntervention`` (``rotate_layer.
253
+ weight``, ``(d_h, k)`` with orthonormal columns under its orthogonal parametrisation): its
254
+ interchange ``base + (R s - R b) R^T`` is ``swap`` of this binding (``fitted``)."""
255
+ weight = intervention.rotate_layer.weight.detach()
256
+ return subspace_binding(name, layer, kv, weight, authority="fitted",
257
+ provenance={"tool": "pyvene", "intervention": type(intervention).__name__,
258
+ **provenance}, orthonormalize=False)
259
+
260
+
261
+ def interchange(debugger: Any, sb: SubspaceBinding, ids: list[int], row: int, source_value: Any,
262
+ consumer: Any, floor: float | None = None, keep: bool = False) -> dict[str, Any]:
263
+ """Measure the subspace interchange on mdb branches (``branches.Branches``): a run of ``ids``
264
+ with prefill = ``row`` branched at ``t<row>.L<layer>.h``; arms ``M`` (the cell's value
265
+ projection set to ``swap(native, source_value)``) and ``M_whole`` (set to ``source_value``),
266
+ each run to the consumer (``forecast.Margin``/``Logit``, or a callable of the last row's
267
+ logits), against the base ``M0`` and ONE floor shared with every other arm of the branch
268
+ point: the caller's ``floor``, else the branches' default (2 spacings at the base margin)
269
+ for a margin or logit. ``branches`` in the result is the ``Branches`` object (seal it, add
270
+ nulls, compare) when ``keep``; ``arms`` is its plain table (JSON-able) always.
271
+ ``source_value``: a ``d_h`` tensor, or a ``ValueRef`` (``donor.ref("t<r>.L<l>.v[kv<g>]")``):
272
+ then both arms are selector edits ``t<row>.L<l>.v[kv<g>]`` whose origin carries the ref's
273
+ pointer under ``source`` (the donor run, address, sha256, cut)."""
274
+ from ..measure.branches import Branches, edit
275
+
276
+ torch = _torch()
277
+ adapter = debugger.adapter
278
+ dh = adapter.head_dim
279
+ last = len(ids) - 1
280
+ run = debugger.run(list(ids), name="subspace", prefill=row)
281
+ br = Branches(run, consumer, at=f"t{row}.L{sb.layer}.h", row=last, floor=floor,
282
+ name=f"interchange:{sb.name}")
283
+ native = f64(br.reference.read_cache(sb.layer, "v", staged=False)[0, sb.kv, row]).cpu()
284
+ shape = run.port_shape("v")
285
+ mask = torch.zeros(shape, dtype=torch.bool)
286
+ mask.reshape(-1)[sb.kv * dh:(sb.kv + 1) * dh] = True
287
+ from mdb.engine.refs import ValueRef
288
+
289
+ pointer = None
290
+ if isinstance(source_value, ValueRef): # a donor read with Run.ref: keep its origin
291
+ pointer = dict(source_value.pointer)
292
+ source_value = source_value.value
293
+ source_value = f64(source_value).reshape(-1).cpu()
294
+ if source_value.numel() != dh:
295
+ raise Refusal(f"interchange source has {source_value.numel()} values; the cell has {dh}")
296
+ for key, value in (("M", sb.swap(native, source_value)), ("M_whole", source_value)):
297
+ origin = {"kind": "subspace-interchange", "subspace": sb.name, "digest": sb.digest(),
298
+ "arm": key}
299
+ if pointer is not None:
300
+ origin["source"] = pointer
301
+ # selector edit: ONE masked edit at the KV group, value cast once
302
+ br.add(key, [edit(f"t{row}.L{sb.layer}.v[kv{sb.kv}]", value, origin=origin)])
303
+ continue
304
+ full = torch.zeros(shape, dtype=adapter.dtype)
305
+ full.reshape(-1)[sb.kv * dh:(sb.kv + 1) * dh] = value.reshape(-1).to(adapter.dtype)
306
+ br.add(key, [edit(f"t{row}.L{sb.layer}.v", full, mask=mask, origin=origin)])
307
+ rows = {r["name"]: r for r in br.run()}
308
+ out = {"M0": num(br.M0, MEASURED), "M": rows["M"]["M"], "M_whole": rows["M_whole"]["M"]}
309
+ out["mass_of_delta"] = sb.mass(f64(source_value) - native)
310
+ shared = floor if floor else br.floor
311
+ if shared: # effect in floors: the numeric column the
312
+ out["floor"] = num(float(shared), EXACT if floor else MEASURED) # band derives from
313
+ for key in ("M0", "M", "M_whole"):
314
+ out[f"{key}_floors"] = num(out[key]["value"] / float(shared), MEASURED)
315
+ out["arms"] = br.table()
316
+ if keep:
317
+ out["branches"] = br
318
+ return out
319
+
320
+
321
+ def iia(records: list[dict[str, Any]], arm: str = "M", margins: tuple[float, ...] = (1.0, 4.0)) -> dict[str, Any]:
322
+ """Interchange intervention accuracy over records with ``M0``, ``floor`` and ``arm`` (plain
323
+ floats or labelled numbers): flip at margin ``m`` = ``M0 > m*floor and M_arm < -m*floor``."""
324
+ def val(x: Any) -> float:
325
+ return float(x["value"]) if isinstance(x, dict) else float(x)
326
+
327
+ out: dict[str, Any] = {}
328
+ for m in margins:
329
+ elig = [r for r in records if val(r["M0"]) > m * val(r["floor"])]
330
+ flips = sum(val(r[arm]) < -m * val(r["floor"]) for r in elig)
331
+ out[f"margin{m:g}"] = {"flips": flips, "eligible": len(elig),
332
+ "iia": (flips / len(elig)) if elig else None}
333
+ return out
334
+
335
+
336
+ def _labelled(value: Any, authority: str) -> Any:
337
+ """Numbers inside an attached label wrapped as ``num(x, authority)`` (records hold no bare
338
+ numbers); strings, None and booleans kept."""
339
+ if isinstance(value, dict):
340
+ return {k: _labelled(v, authority) for k, v in value.items()}
341
+ if isinstance(value, (list, tuple)):
342
+ return [_labelled(v, authority) for v in value]
343
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
344
+ return num(value, authority)
345
+ return value
346
+
347
+
348
+ def table_row(run: Any, sb: SubspaceBinding, consumer: Any = None) -> dict[str, Any]:
349
+ """One subspace binding's symbol-table row at the cursor: the native cell value's mass in the
350
+ subspace and, under a scalar consumer, the direct consumer share of the in-subspace part at
351
+ fixed attention (P19), plus the attached labels (e.g. measured IIA)."""
352
+ if sb.row is None:
353
+ raise Refusal(f"subspace {sb.name} is a template: bind it to a row first (bound(row))")
354
+ v = f64(run.read_cache(sb.layer, "v", staged=False)[0, sb.kv, sb.row]).cpu()
355
+ prov = json.dumps(sb.provenance, sort_keys=True, default=str)
356
+ row: dict[str, Any] = {
357
+ "schema": SCHEMA, "name": sb.name, "cell": sb.cell, "k": num(sb.k, EXACT),
358
+ "basis_authority": sb.authority, "digest": sb.digest(), "provenance_json": prov,
359
+ "labels": {k: {"result": _labelled(val, auth), "source_authority": auth}
360
+ for k, (val, auth) in sb.labels.items()},
361
+ "mass_native": sb.mass(v)}
362
+ if consumer is not None:
363
+ from ..measure.readout import readout
364
+ from .components import write_of
365
+
366
+ reader = readout(run, consumer)
367
+ if reader.scalar:
368
+ c = f64(reader.vector).reshape(-1).cpu()
369
+ j = int(reader.row)
370
+ whole = float(c @ write_of(run, sb, v, j))
371
+ part = float(c @ write_of(run, sb, sb.project(v), j))
372
+ row["cell_to_consumer"] = num(whole, EXACT, "P19")
373
+ row["subspace_to_consumer"] = num(part, EXACT, "P19")
374
+ row["share_of_cell"] = num(part / whole, EXACT) if whole else None
375
+ return row
376
+
377
+
378
+ __all__ = ["BASIS_AUTHORITIES", "SubspaceBinding", "class_mean_subspace", "from_pyvene", "iia",
379
+ "interchange", "orthonormal", "principal_angles", "readout_directions",
380
+ "readout_subspace", "subspace_binding", "table_row"]