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,86 @@
1
+ """Gate-side attribution of gated MLP units (measured on a binary).
2
+
3
+ On the binary's gated-MLP dispatch, contribution attribution on ``f = gate * up`` named the
4
+ right unit or nothing; it named nothing on 3.7% of lane-steps, all of them steps where the
5
+ selected unit's output was zero (a ``mov`` of 0): the selection lived only in the gate (MEASURED). A unit can be
6
+ *selected but zero-valued*: its gate is on, and its value channel carries ~nothing, so it
7
+ contributes ~0 and contribution ranking never lists it.
8
+
9
+ ``selected_zero(gate, contribution)`` marks those units: ``|gate| >= gate_floor`` and
10
+ ``|contribution| <= zero_tol`` (absolute thresholds; ``relative`` scales them by the row's
11
+ largest ``|gate|`` and ``|contribution|``). For a SwiGLU layer the gate activation is
12
+ ``sg = silu(g)`` and the contribution is the unit's direct share of the consumer through
13
+ ``u``: ``rho^F c^T W_down[:, i] sg_i u_i`` (``swiglu_units``, ``derived-exact`` on the native
14
+ captures). The x86 dispatch uses the same rule with its one-hot gate
15
+ (``machines.x86.mlp.attribute``).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import Any
21
+
22
+ from .labels import EXACT, MEASURED, SUPPLIED, f64, num
23
+
24
+ GATE_FLOOR = 0.25 # relative: |sg_i| >= 0.25 max_j |sg_j| (supplied)
25
+ ZERO_TOL = 0.01 # relative: |contribution_i| <= 0.01 max_j |contribution_j| (supplied)
26
+
27
+
28
+ def _torch():
29
+ import torch
30
+
31
+ return torch
32
+
33
+
34
+ def selected_zero(gate: Any, contribution: Any, *, gate_floor: float, zero_tol: float,
35
+ relative: bool = False) -> Any:
36
+ """Bool mask of units with an active gate and a ~zero contribution (last axis = units)."""
37
+ torch = _torch()
38
+ gate, contribution = torch.as_tensor(gate).abs(), torch.as_tensor(contribution).abs()
39
+ if relative:
40
+ gate_floor = gate_floor * gate.amax(-1, keepdim=True)
41
+ zero_tol = zero_tol * contribution.amax(-1, keepdim=True)
42
+ return (gate >= gate_floor) & (gate > 0) & (contribution <= zero_tol)
43
+
44
+
45
+ def swiglu_units(caps: Any, rho: Any, c: Any, *, top: int = 8, gate_floor: float = GATE_FLOOR,
46
+ zero_tol: float = ZERO_TOL) -> dict[str, Any]:
47
+ """Per layer: the units' direct contributions to the explained margin and the selected but
48
+ zero-valued units. ``caps`` a ``RowCapture`` (ports ``sg``, ``u``), ``rho``/``c`` the final
49
+ norm scale and readout of ``explain_margin``. Lists the ``top`` units by |contribution| and
50
+ the ``top`` selected-zero units by |sg| over all layers, with per-layer counts."""
51
+ torch = _torch()
52
+ rows, zero_rows, per_layer = [], [], []
53
+ for layer, ports in enumerate(caps.ports):
54
+ if "sg" not in ports or "u" not in ports:
55
+ per_layer.append({"layer": layer, "state": "refused", "reason": "no sg/u capture"})
56
+ continue
57
+ adapter = caps.adapter
58
+ down = getattr(adapter.backbone, adapter.spec.layers)[layer].mlp.down_proj.weight
59
+ sg, u = f64(ports["sg"]).reshape(-1), f64(ports["u"]).reshape(-1)
60
+ share = float(rho) * (f64(c) @ f64(down)) * sg * u
61
+ mask = selected_zero(sg, share, gate_floor=gate_floor, zero_tol=zero_tol, relative=True)
62
+ on = sg.abs() >= gate_floor * sg.abs().max()
63
+ per_layer.append({"layer": layer, "selected": int(on.sum()),
64
+ "selected_zero": int(mask.sum()),
65
+ "sum": num(float(share.sum()), EXACT, "P19")})
66
+ for i in share.abs().topk(min(top, share.numel())).indices.tolist():
67
+ rows.append((abs(float(share[i])), layer, i, float(share[i]), float(sg[i]),
68
+ float(u[i])))
69
+ for i in torch.nonzero(mask).flatten().tolist():
70
+ zero_rows.append((abs(float(sg[i])), layer, i, float(share[i]), float(sg[i]),
71
+ float(u[i])))
72
+
73
+ def listed(found: list[tuple]) -> list[dict[str, Any]]:
74
+ return [{"unit": f"L{layer}.f[i={i}]", "contribution": num(share, EXACT, "P19"),
75
+ "sg": num(sg, MEASURED), "u": num(u, MEASURED)}
76
+ for _, layer, i, share, sg, u in sorted(found, reverse=True)[:top]]
77
+
78
+ return {"rule": f"selected = |sg_i| >= {gate_floor:g} x max |sg| of the layer; zero-valued = "
79
+ f"|contribution_i| <= {zero_tol:g} x max |contribution| of the layer; "
80
+ "contribution_i = rho^F c^T W_down[:, i] sg_i u_i",
81
+ "gate_floor": num(gate_floor, SUPPLIED), "zero_tol": num(zero_tol, SUPPLIED),
82
+ "top_contribution": listed(rows), "selected_zero": listed(zero_rows),
83
+ "per_layer": per_layer}
84
+
85
+
86
+ __all__ = ["GATE_FLOOR", "ZERO_TOL", "selected_zero", "swiglu_units"]
@@ -0,0 +1,244 @@
1
+ """Effect verdicts from the P20 accounting against an emulated prediction, not a noise floor.
2
+
3
+ P20 (chapter 07, recursive error) and chapter 09 section 1 give the exact accounting of a native
4
+ change: ``native delta = exact delta + rounding``, with ``exact delta`` the float64 identity chain
5
+ on the retained operands (``derived-exact``). The emulated chains (``forecast.EmulatedRowModel``:
6
+ the run's dtype rounding at every point where eager HF rounds, the backend's own kernels) split the
7
+ rounding into ``rounding effect = emulated delta - exact delta`` (``derived-exact`` under the
8
+ emulation premises) and ``residual = native delta - emulated delta`` (``measured``), which is 0
9
+ when the emulation holds (measured bit-exact on tiny models and Qwen2.5-1.5B). A
10
+ verdict reads:
11
+
12
+ * ``floor = FLOOR_SPACINGS x spacing`` (``FLOOR_SPACINGS`` = 1, ``supplied``, the one constant
13
+ ``confirm`` uses too), ``spacing`` the gap between adjacent values of the consumer's dtype at
14
+ the consumer's magnitude (both logits of a margin, before and after the edit; the logit; the
15
+ largest element of a vector).
16
+ * ``effect`` (resolved) when every element's ``|native - emulated|`` is within the floor, the
17
+ native delta is not zero and the emulated delta has its sign; ``no effect`` (resolved) when
18
+ they agree and both are zero: the dtype shows no change at the consumer. Within the floor but
19
+ with different signs (or one of them zero) ``unresolved``: a floor of one spacing cannot decide
20
+ a change no bigger than itself. ``size_spacings`` is ``|native delta|`` in spacings and
21
+ ``rests_on`` says what an effect rests on. The exact delta is reported either way, as a fact
22
+ beside the verdict (``note``: an exact change the dtype cannot show; a native change that is
23
+ the dtype's rounding).
24
+ * beyond the floor: what the caller found where emulation and native part (``parting``: ``not
25
+ confirmed`` when a stage does not reproduce its native value from its native operands within
26
+ its identity's bound, else ``unresolved``), or ``unresolved`` with the numbers.
27
+ * No emulated chain (the prediction is refused, or the verb measures natively only, as
28
+ ``compare``): ``effect`` when the edited and base native values differ, ``no effect`` when they
29
+ are equal; ``basis`` says so.
30
+
31
+ A vector consumer is reported at its element of largest ``|native delta|``.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import math
37
+ from typing import Any
38
+
39
+ from .labels import EXACT, MEASURED, SUPPLIED
40
+
41
+ EFFECT = "effect"
42
+ NO_EFFECT = "no effect"
43
+ UNRESOLVED = "unresolved"
44
+ CRITERION = ("effect when native Δ and emulated Δ agree within the floor (1 x dtype spacing at "
45
+ "the consumer, supplied) and on the sign, and native Δ != 0; no effect when they "
46
+ "agree and both are 0; within the floor but not on the sign unresolved; beyond the "
47
+ "floor not confirmed or unresolved by where emulation and native part; P20: native "
48
+ "Δ = exact Δ + rounding effect (emulated - exact) + residual (native - emulated)")
49
+ NATIVE_ONLY = ("effect when the edited and base native values differ (native Δ != 0), no effect "
50
+ "when they are equal (no prediction: native only)")
51
+
52
+
53
+ def _torch():
54
+ import torch
55
+
56
+ return torch
57
+
58
+
59
+ def spacing(magnitude: float, dtype: Any) -> float:
60
+ """Gap between adjacent ``dtype`` values at ``|magnitude|`` (one ulp; bf16 near 20: 0.125)."""
61
+ info = _torch().finfo(dtype)
62
+ size = max(abs(float(magnitude)), float(info.tiny))
63
+ return 2.0 ** math.floor(math.log2(size)) * float(info.eps)
64
+
65
+
66
+ MARGIN_FLOOR_SPACINGS = 2.0 # the wording that held: 2 spacings
67
+
68
+
69
+ def margin_floor(logits: Any, a: int, b: int, *, dtype: Any = None,
70
+ spacings: float = MARGIN_FLOOR_SPACINGS, extra: float = 0.0) -> float:
71
+ """The noise floor of a margin ``logits[a] - logits[b]``: ``spacings`` x the dtype spacing
72
+ at the larger ``|logit|`` of the pair, plus a measured kernel-path delta ``extra`` (on
73
+ ``spacing``). ``dtype``
74
+ defaults to the logits' dtype (read the logits in the model dtype, not upcast)."""
75
+ flat = logits.reshape(-1)
76
+ size = max(abs(float(flat[a])), abs(float(flat[b])))
77
+ return float(spacings) * spacing(size, dtype if dtype is not None else logits.dtype) + abs(
78
+ float(extra))
79
+
80
+
81
+ def floors(effect: float, floor: float) -> float:
82
+ """``|effect|`` in floor units (the effect-in-floors column; ``inf`` for a zero floor and a
83
+ nonzero effect)."""
84
+ effect, floor = abs(float(effect)), float(floor)
85
+ if floor > 0:
86
+ return effect / floor
87
+ return math.inf if effect else 0.0
88
+
89
+
90
+ def magnitude(consumer: Any, *tensors: Any) -> float:
91
+ """The consumer's magnitude over native tensors read at its stop: the two logits of a margin
92
+ (``consumer.a``/``.b``), the logit (``.i``), else the largest element."""
93
+ out = 0.0
94
+ for tensor in tensors:
95
+ flat = tensor.reshape(-1).detach().abs()
96
+ if hasattr(consumer, "a") and hasattr(consumer, "b"):
97
+ out = max(out, float(flat[consumer.a].float()), float(flat[consumer.b].float()))
98
+ elif hasattr(consumer, "i"):
99
+ out = max(out, float(flat[consumer.i].float()))
100
+ else:
101
+ out = max(out, float(flat.float().max()))
102
+ return out
103
+
104
+
105
+ def _num(value: float, authority: str) -> dict[str, Any]:
106
+ return {"value": float(value), "authority": authority, "proof": "P20"}
107
+
108
+
109
+ def decide(native: Any, emulated: Any, size: float, dtype: Any, *, exact: Any = None,
110
+ why_native_only: str | None = None, parting: dict[str, Any] | None = None,
111
+ donors: tuple[int, int | None] = (1, None)) -> dict[str, Any]:
112
+ """``_decide`` stamped with its donor count (``donors.stamp``: ``(n, informative)``; one
113
+ donor whose informativeness was not compared by default), so no ``no effect`` leaves without
114
+ saying how many donors it rests on."""
115
+ from .pooling import stamp
116
+
117
+ return stamp(_decide(native, emulated, size, dtype, exact=exact,
118
+ why_native_only=why_native_only, parting=parting), *donors)
119
+
120
+
121
+ def _decide(native: Any, emulated: Any, size: float, dtype: Any, *, exact: Any = None,
122
+ why_native_only: str | None = None, parting: dict[str, Any] | None = None
123
+ ) -> dict[str, Any]:
124
+ """The verdict on one change. ``native`` (measured), ``emulated`` (the emulated chains'
125
+ delta, None when there is none, ``why_native_only`` saying why) and ``exact`` (the float64
126
+ chain's delta, optional, reported): float64 tensors, scalar or vector; ``size`` the
127
+ consumer's magnitude; ``dtype`` its native dtype; ``parting``: the caller's finding where
128
+ emulation and native part (``verdict``, ``state``, ``reason`` and its details), used when
129
+ they disagree beyond the floor."""
130
+ torch = _torch()
131
+ native = torch.as_tensor(native, dtype=torch.float64).reshape(-1)
132
+ k = int(native.abs().argmax())
133
+ n = float(native[k])
134
+ step = spacing(size, dtype)
135
+ floor = FLOOR_SPACINGS * step
136
+ out: dict[str, Any] = {"native": _num(n, MEASURED), "spacing": _num(step, MEASURED),
137
+ "floor": _num(floor, SUPPLIED),
138
+ "floor_spacings": _num(FLOOR_SPACINGS, SUPPLIED),
139
+ "dtype": str(dtype).removeprefix("torch.")}
140
+ if native.numel() > 1:
141
+ out["index"] = k
142
+ changed = bool((native != 0).any())
143
+ if exact is not None:
144
+ exact = torch.as_tensor(exact, dtype=torch.float64).reshape(-1)
145
+ out["exact"] = _num(float(exact[k]), EXACT)
146
+ if emulated is None:
147
+ out.update(criterion=NATIVE_ONLY,
148
+ basis=f"native only: {why_native_only or 'no emulated chain'}",
149
+ verdict=EFFECT if changed else NO_EFFECT, state="resolved")
150
+ return out
151
+ emulated = torch.as_tensor(emulated, dtype=torch.float64).reshape(-1)
152
+ residual = native - emulated
153
+ worst = float(residual.abs().max())
154
+ out.update(emulated=_num(float(emulated[k]), EXACT), residual=_num(float(residual[k]), MEASURED),
155
+ residual_spacings=_num(worst / step, MEASURED), criterion=CRITERION,
156
+ basis="P20: native against the emulated delta")
157
+ if exact is not None:
158
+ out["rounding_effect"] = _num(float(emulated[k] - exact[k]), EXACT)
159
+ out["size_spacings"] = _num(abs(n) / step, MEASURED)
160
+ if worst > floor:
161
+ found = parting or {"verdict": UNRESOLVED, "state": "unresolved",
162
+ "reason": f"native and emulated Δ part by {worst / step:.3g} "
163
+ "spacings"}
164
+ out.update(found)
165
+ return out
166
+ m = float(emulated[k])
167
+ if (n == 0) != (m == 0) or n * m < 0:
168
+ # within the floor, but the two disagree on whether (or which way) the consumer moved:
169
+ # the floor cannot decide a change no bigger than itself
170
+ out.update(verdict=UNRESOLVED, state="unresolved",
171
+ reason=f"native Δ {n:.5g} and emulated Δ {m:.5g} agree within the floor "
172
+ f"({worst / step:.2g} spacings) but not on the sign of the change")
173
+ return out
174
+ out["state"] = "resolved"
175
+ rests = (f"rests on native = emulated within {worst / step:.2g} spacings at a change of "
176
+ f"{abs(n) / step:.2g} spacings")
177
+ if changed:
178
+ out["verdict"] = EFFECT
179
+ out["rests_on"] = rests
180
+ if exact is not None:
181
+ e = float(exact[k])
182
+ if e == 0 or (e > 0) != (n > 0):
183
+ out["note"] = (f"the native change is the dtype's rounding: exact Δ {e:.5g}; "
184
+ + rests)
185
+ else:
186
+ out["verdict"] = NO_EFFECT
187
+ if exact is not None:
188
+ x = float(exact[int(exact.abs().argmax())])
189
+ out["note"] = (f"no change at {out['dtype']} resolution (spacing {step:g}); exact Δ "
190
+ f"{x:.5g}" + (", which the dtype cannot show" if x != 0 else ""))
191
+ return out
192
+
193
+
194
+ CONFIRMED = "confirmed"
195
+ NOT_CONFIRMED = "not confirmed"
196
+ # The one supplied constant of `confirm` and `decide`: the floor in spacings between the native value and the
197
+ # emulated prediction (`forecast.EmulatedRowModel`, the run's dtype rounding at every eager-HF
198
+ # rounding point). Above it `forecast.verify` names where emulation and native part (not
199
+ # confirmed, or unresolved for rounding drift); it does not widen.
200
+ FLOOR_SPACINGS = 1.0
201
+ FLOOR_SUPPORT = ("largest |native - emulated| in spacings of the consumer at every stop from the "
202
+ "sealing stop to the logits: 0 (bit-exact) on tiny qwen2/qwen3/llama/mistral bf16 "
203
+ "and fp32, 2-28 layers, 3 prompts (CPU), and on Qwen2.5-1.5B bf16 (28 layers) and "
204
+ "fp32 (2 layers), 3 prompts, sealed at L0.h and L14.h (CUDA)")
205
+ CONFIRM_CRITERION = ("confirmed when every element's |native - emulated| <= floor = 1 (supplied) x "
206
+ "dtype spacing at the magnitude of the consumer (a margin: the sum of its two "
207
+ "logits' spacings); above it, not confirmed unless every stage from where "
208
+ "emulation and native part to the target is the native step (then "
209
+ "unresolved: rounding drift); P20: residual = native - emulated")
210
+
211
+
212
+ def confirm(residual: Any, size: float, dtype: Any, *, partner: float | None = None) -> dict[str, Any]:
213
+ """The verdict on one forecast: confirmed when every element's measured residual (native -
214
+ emulated prediction; scalar or vector) is within ``floor = FLOOR_SPACINGS x step``, else not
215
+ confirmed (``forecast.verify`` then says where emulation and native part).
216
+
217
+ ``step`` is the spacing of ``dtype`` at ``size``, the consumer's magnitude (a margin, the
218
+ difference of two rounded logits: ``size`` and ``partner``, the step is the sum of the two
219
+ spacings). A non-floating ``dtype`` (token ids) has no spacing: the floor is 0. ``residual``
220
+ is the largest ``|.|``; ``residual_spacings`` (``measured``) says how close to the floor it
221
+ came."""
222
+ torch = _torch()
223
+ gap = torch.as_tensor(residual, dtype=torch.float64).abs().reshape(-1)
224
+ floating = dtype is not None and torch.empty(0, dtype=dtype).is_floating_point()
225
+ step = 0.0
226
+ if floating:
227
+ step = spacing(size, dtype) + (0.0 if partner is None else spacing(partner, dtype))
228
+ floor = FLOOR_SPACINGS * step
229
+ worst = float(gap.max())
230
+ out = {"verdict": CONFIRMED if worst <= floor else NOT_CONFIRMED, "state": "resolved",
231
+ "residual": _num(worst, MEASURED), "spacing": _num(step, MEASURED),
232
+ "floor": _num(floor, SUPPLIED),
233
+ "floor_spacings": {**_num(FLOOR_SPACINGS, SUPPLIED), "support": FLOOR_SUPPORT},
234
+ "criterion": CONFIRM_CRITERION, "dtype": str(dtype).removeprefix("torch.")}
235
+ if step:
236
+ out["residual_spacings"] = _num(worst / step, MEASURED)
237
+ if gap.numel() > 1:
238
+ out["index"] = int(gap.argmax())
239
+ return out
240
+
241
+
242
+ __all__ = ["CONFIRMED", "CONFIRM_CRITERION", "CRITERION", "EFFECT", "MARGIN_FLOOR_SPACINGS",
243
+ "NATIVE_ONLY", "NOT_CONFIRMED", "NO_EFFECT", "UNRESOLVED", "FLOOR_SPACINGS", "confirm",
244
+ "decide", "floors", "magnitude", "margin_floor", "spacing"]
@@ -0,0 +1,162 @@
1
+ """Grouped-unit frames for ``why`` on transformers (why v2): pure frame logic, no model code.
2
+
3
+ A transformer ``why`` walks residual-stream units u = (row, level): level l is the residual entering layer l
4
+ (level 0 = embedding, level L = final). The parents of (w, l+1) are (w, l) (own row: skip, attention to self, MLP)
5
+ and (r, l) for every row r that w attends to at layer l (a *read* of row r at level l). Every frame is one level.
6
+
7
+ Held effects (computed by the caller): inject a parent's donor delta, let only the child respond at l+1, let only
8
+ the units already in the walk respond above, hold everything else at base, and read the consumer margin change as a
9
+ share of D (median over the item's donors). For each child the caller supplies
10
+
11
+ single[j] held effect of parent j alone,
12
+ prefix[s] held effect of the top-(s+1) parents (by ``single``) injected together,
13
+ own held effect of the child's own donor delta.
14
+
15
+ ``choose_set`` keeps a single parent when it explains >= 1 - eps of ``own`` (a chain frame), otherwise the shortest
16
+ prefix that does (an influence-set frame); parents below ``tau`` are never added. ``1 - prefix/own`` is the unit
17
+ remainder; it says whether a chain view is valid at that unit.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+
23
+ import numpy as np
24
+
25
+ DATA, ADDR, MIXED = "data", "addr", "mixed"
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Edge:
30
+ src: tuple # (row, level) read
31
+ dst: tuple # (row, level written)
32
+ share: float # held effect of src alone through dst, / D
33
+ channel: str = DATA # data | addr | mixed (attention pattern frozen at base keeps >= hi of the edge -> data)
34
+
35
+ @property
36
+ def read(self) -> bool:
37
+ return self.src[0] != self.dst[0]
38
+
39
+
40
+ @dataclass
41
+ class Frame:
42
+ k: int
43
+ level: int
44
+ units: list # rows kept at this level
45
+ edges: list = field(default_factory=list) # Edge into frame k-1 units
46
+ unit_rem: dict = field(default_factory=dict) # child row (frame k-1) -> remainder of its parent set
47
+ mode: dict = field(default_factory=dict) # child row -> chain | set | stall
48
+ remainder: float | None = None # 1 - joint(frame units, through the walk) / D
49
+
50
+
51
+ @dataclass
52
+ class Walk:
53
+ """What a walk visited, in residual coordinates (any unit type converts to this for scoring)."""
54
+ visited: set
55
+ edges: list
56
+ frames: int
57
+ remainders: list = field(default_factory=list) # frame / unit remainders seen on the walk
58
+
59
+
60
+ def med_ratio(x: np.ndarray, D: np.ndarray) -> np.ndarray:
61
+ """x, D: [..., donors] -> median over donors of x / D (|D| <= 1e-6 ignored; all ignored -> nan)."""
62
+ with np.errstate(invalid="ignore", divide="ignore"):
63
+ r = np.where(np.abs(D) > 1e-6, x / np.where(np.abs(D) > 1e-6, D, 1.0), np.nan)
64
+ out = np.full(r.shape[:-1], np.nan)
65
+ ok = ~np.isnan(r).all(-1)
66
+ out[ok] = np.nanmedian(r[ok], -1)
67
+ return out
68
+
69
+
70
+ def choose_set(single, prefix, own, tau: float, eps: float, chain_only: bool = False):
71
+ """Parents to keep for one child. ``single``: effects in the order the prefixes were built (descending).
72
+ Returns (n kept, remainder, mode). mode: chain (1 parent), set (> 1), stall (none >= tau)."""
73
+ single = np.asarray(single, float)
74
+ n_ok = int(np.sum(np.nan_to_num(single, nan=-np.inf) >= tau))
75
+ if n_ok == 0:
76
+ return 0, 1.0, "stall"
77
+ if not np.isfinite(own) or abs(own) < 1e-9:
78
+ own = 1.0
79
+ if chain_only:
80
+ n = 1
81
+ else:
82
+ n = n_ok
83
+ for s in range(n_ok):
84
+ if np.isfinite(prefix[s]) and prefix[s] / own >= 1 - eps:
85
+ n = s + 1
86
+ break
87
+ rem = 1.0 - float(prefix[n - 1]) / own if np.isfinite(prefix[n - 1]) else 1.0
88
+ return n, rem, "chain" if n == 1 else "set"
89
+
90
+
91
+ def channel(total: float, frozen: float, lo: float = .35, hi: float = .65) -> str:
92
+ """Share of an edge kept with the attention pattern frozen at base: >= hi data, <= lo addr, else mixed."""
93
+ if not np.isfinite(total) or abs(total) < 1e-9 or not np.isfinite(frozen):
94
+ return MIXED
95
+ s = frozen / total
96
+ return DATA if s >= hi else ADDR if s <= lo else MIXED
97
+
98
+
99
+ def to_walk(frames: list) -> Walk:
100
+ vis, edges, rems = set(), [], []
101
+ for f in frames:
102
+ vis |= {(r, f.level) for r in f.units}
103
+ edges += list(f.edges)
104
+ if f.remainder is not None:
105
+ rems.append(f.remainder)
106
+ return Walk(vis, edges, len(frames), rems)
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class Truth:
111
+ """Sealed truth for one specimen. Read-site specimens: a read of ``bridge`` by the consumer at a level in
112
+ ``read_levels`` (and, if given, a visit of one of ``site``). Address specimens: an own-row edge at ``own_row``
113
+ with level in ``own_levels``. Control: no unit of ``bridge`` (level >= 1) on the walk."""
114
+ bridge: int | None = None
115
+ read_levels: tuple = ()
116
+ site: tuple = ()
117
+ channel: str = DATA
118
+ wrong_levels: tuple = ()
119
+ own_row: int | None = None
120
+ own_levels: tuple = ()
121
+ control: bool = False
122
+
123
+
124
+ def score(walk: Walk, truth: Truth, consumer: int) -> dict:
125
+ reads = [e for e in walk.edges if e.read and e.src[0] == truth.bridge and e.dst[0] == consumer]
126
+ dom = max(reads, key=lambda e: e.share).src[1] if reads else None
127
+ out = {"frames": walk.frames, "dominant_read_level": dom, "n_reads": len(reads)}
128
+ if truth.control:
129
+ hit = any(e.src[0] == truth.bridge for e in walk.edges) or any(
130
+ r == truth.bridge and l >= 1 for r, l in walk.visited)
131
+ out.update(false_reach=bool(hit), reach=None, channel_ok=None)
132
+ return out
133
+ if truth.own_row is not None:
134
+ tr = [e for e in walk.edges if e.src[0] == e.dst[0] == truth.own_row and e.src[1] in truth.own_levels]
135
+ out.update(reach=bool(tr), channel_ok=any(e.channel == truth.channel for e in tr) if tr else False)
136
+ return out
137
+ tr = [e for e in reads if e.src[1] in truth.read_levels]
138
+ site_ok = (not truth.site) or any(u in walk.visited for u in truth.site)
139
+ out.update(reach=bool(tr) and site_ok, read_ok=bool(tr), site_ok=site_ok,
140
+ channel_ok=any(e.channel == truth.channel for e in tr) if tr else False,
141
+ wrong_level=any(e.src[1] in truth.wrong_levels for e in reads) if truth.wrong_levels else None,
142
+ dominant_ok=dom in truth.read_levels if dom is not None else False)
143
+ return out
144
+
145
+
146
+ def render(frames: list, consumer: int, *, names=None) -> str:
147
+ """One line per frame: level, units, and the edges into the previous frame with share, channel, remainder."""
148
+ nm = names or (lambda r: f"t{r}")
149
+ out = [f"#0 M@{nm(consumer)}"]
150
+ for f in frames:
151
+ parts = []
152
+ for e in f.edges:
153
+ parts.append(f"{nm(e.src[0])}.h{e.src[1]}->{nm(e.dst[0])} {e.share:.2f} {e.channel}"
154
+ f"{' READ' if e.read else ''}")
155
+ rem = "" if f.remainder is None else f" rem {f.remainder:.2f}"
156
+ modes = ",".join(f"{nm(w)}:{m}" for w, m in sorted(f.mode.items()))
157
+ out.append(f"#{f.k} h{f.level} [{' '.join(nm(r) for r in f.units)}]{rem} ({modes}) " + "; ".join(parts))
158
+ return "\n".join(out)
159
+
160
+
161
+ __all__ = ["Edge", "Frame", "Walk", "Truth", "med_ratio", "choose_set", "channel", "to_walk", "score", "render",
162
+ "DATA", "ADDR", "MIXED"]
@@ -0,0 +1,7 @@
1
+ """Predict: sealed forecasts of native values, their verification, and the predicted and
2
+ measured change an edit makes downstream (``explain``, ``forecast``, ``propagate``,
3
+ ``supplied``).
4
+
5
+ Sublayer above ``numerics`` (``numerics < predict < measure < circuits < symbols < features``):
6
+ module-level imports reach only ``numerics`` and ``predict``.
7
+ """