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,103 @@
1
+ """Library-supplied forecasts and vector edits.
2
+
3
+ A library (nnsight ``grads`` x activation, a transcoder edge, a TransformerLens patch on a
4
+ processed bridge) nominates an edit and predicts its effect on a consumer. mdb seals that
5
+ prediction before the native arm runs, as a ``supplied-forecast`` record holding the library's
6
+ number (``supplied``, with the library, its version and the address map used), and beside it
7
+ mdb's own terms when computed (``exact``: the float64 chain; ``linear``: the first-order term).
8
+ ``judge`` scores the record against the native change with mdb's floor (``verdict.spacing``,
9
+ ``floor_spacings`` x the consumer dtype's spacing at the larger magnitude): the supplied number
10
+ never becomes a measurement.
11
+
12
+ ``vector_edit`` is the supplied-vector edit at any cache cell or at the pending row's ports:
13
+ ``Run.set`` / ``Run.set_cell`` already take tensors; this records the origin (library, address
14
+ map) with the edit so the manifest says where the vector came from.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any
20
+
21
+ from mdb.core.kinds import SUPPLIED_FORECAST, procedure
22
+ from mdb.core.records import seal_record
23
+
24
+ from ..numerics.labels import EXACT, LOCAL, MEASURED, SUPPLIED, num
25
+ from .consumers import Refusal, run_session_id
26
+
27
+ SCHEMA = "mdb-supplied-forecast-v1"
28
+
29
+
30
+ def seal(run: Any, *, target: dict[str, Any], edit: dict[str, Any], value: float, library: str,
31
+ version: str, address_map: dict[str, str], method: str, exact: float | None = None,
32
+ linear: float | None = None, session_id: str | None = None) -> dict[str, Any]:
33
+ """Seal one supplied forecast (returns the sealed record)."""
34
+ if not library or not version:
35
+ raise Refusal("a supplied forecast names its library and version")
36
+ row, index = run.parse(run.where)
37
+ body: dict[str, Any] = {
38
+ "schema": SCHEMA, "target": dict(target), "edit": dict(edit),
39
+ "supplied": num(float(value), SUPPLIED),
40
+ "library": {"name": library, "version": version, "method": method},
41
+ "address_map": dict(address_map),
42
+ "sealed_at": {"where": run.where, "row": num(row, EXACT), "index": num(index, EXACT)},
43
+ "procedure": procedure(run),
44
+ }
45
+ if exact is not None:
46
+ body["exact"] = num(float(exact), EXACT)
47
+ if linear is not None:
48
+ body["linear"] = num(float(linear), LOCAL)
49
+ return seal_record(session_id=session_id or run_session_id(run), kind="supplied-forecast",
50
+ model_identity=run.adapter.model_identity,
51
+ execution=dict(run.adapter.execution), authority=SUPPLIED, body=body, run=run)
52
+
53
+
54
+ def judge(record: dict[str, Any], native_delta: float, *, magnitude: float, dtype: Any,
55
+ floor_spacings: float = 2.0, extra_floor: float = 0.0,
56
+ kernel_path: str | None = None, calibration: Any = None,
57
+ stable_floors: float | None = None) -> dict[str, Any]:
58
+ """Score a sealed supplied forecast against the native change. ``magnitude`` is the
59
+ consumer's size for the spacing (e.g. the larger |logit| of the margin's pair);
60
+ ``extra_floor`` adds a measured kernel-path delta (batched vs stepped) to the floor.
61
+
62
+ The floor is a noise bound, not a stability margin: ``stability`` marks the verdict
63
+ ``stable`` only when ``|native| > k`` floors, else ``kernel-sensitive`` (``native_effect``
64
+ and ``sign_agrees`` are unchanged). ``k`` comes from the model's ``calibration``
65
+ (``stability.Calibration``, its JSON or a path), else ``stable_floors``, else
66
+ ``stability.STABLE_FLOORS`` = 4; ``kernel_path`` names the realisation ``native_delta`` was
67
+ measured on (``mdb-stepped``, ``batched``, or any declared string; ``undeclared`` if None)."""
68
+ from ..numerics.stability import stability
69
+ from ..numerics.verdict import spacing
70
+
71
+ body = record["body"]
72
+ supplied = float(body["supplied"]["value"])
73
+ floor = floor_spacings * spacing(abs(magnitude), dtype) + abs(extra_floor)
74
+ native = float(native_delta)
75
+ out: dict[str, Any] = {
76
+ "record": record.get("id"), "supplied": supplied, "native": num(native, MEASURED),
77
+ "floor": num(floor, MEASURED), "error": num(native - supplied, MEASURED),
78
+ "ratio": (num(supplied / native, MEASURED) if native else None),
79
+ "native_effect": abs(native) > floor,
80
+ "sign_agrees": (supplied > 0) == (native > 0) if abs(native) > floor else None,
81
+ }
82
+ out.update(stability(native, floor, kernel_path=kernel_path, calibration=calibration,
83
+ k=stable_floors))
84
+ for key in ("exact", "linear"):
85
+ if key in body:
86
+ out[f"{key}_error"] = num(native - float(body[key]["value"]), MEASURED)
87
+ return out
88
+
89
+
90
+ def vector_edit(run: Any, address: str, value: Any, *, library: str, version: str,
91
+ address_map: dict[str, str], op: str = "replace", **cell: Any) -> dict[str, Any]:
92
+ """Stage a library-supplied vector at ``address``: a pending-row port ``t<r>.L<l>.<port>``
93
+ (``Run.set``) or a cache cell ``cache.L<l>.<k|v>`` with ``rows=``/``kv=`` (``Run.set_cell``);
94
+ the origin names the library."""
95
+ origin = {"kind": "supplied", "library": library, "version": version,
96
+ "address_map": dict(address_map)}
97
+ if address.startswith("cache."):
98
+ _, layer, tensor = address.split(".")
99
+ return run.set_cell(int(layer[1:]), tensor, value, op, origin=origin, **cell)
100
+ return run.set(address, value, op, origin=origin)
101
+
102
+
103
+ __all__ = ["SCHEMA", "SUPPLIED_FORECAST", "judge", "seal", "vector_edit"]
@@ -0,0 +1,433 @@
1
+ """Verify sealed forecasts against the native values once native code has run.
2
+
3
+ ``verify`` checks every open forecast of a run whose target has been computed, by stage
4
+ (``stage_checks``: each stop of the chain inside its rounding interval), with the containment
5
+ check of the consumer and the first stage where exact and emulated part (``stage_parting``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from typing import Any
12
+
13
+ from mdb.core.bounded import MAX_ITEMS
14
+ from mdb.core.records import num
15
+
16
+ from ..numerics import verdict as _verdict
17
+ from ..numerics.labels import BOUND, EXACT, MEASURED, f64
18
+ from .consumers import Margin, Refusal
19
+ from .forecast import (
20
+ Forecast,
21
+ _digest,
22
+ _edit_key,
23
+ _known,
24
+ _labelled_edits,
25
+ _summary,
26
+ _target,
27
+ ledger,
28
+ )
29
+ from .rowmodel import LIBRARY_ULPS, EmulatedRowModel, RowModel, _split
30
+
31
+
32
+ def _lineage(run: Any, sealed: dict[str, Any]) -> dict[str, Any]:
33
+ """Whether the sealed cut is an ancestor of the current cut: the sealed cut (its fingerprint
34
+ at its transition count) is a mark of the run's trail, which holds the whole path of the
35
+ current cut however deep the model is and is rebuilt identically by a restore (``whatif``).
36
+ A cut on another path (an edit or a rewind before the seal) is not on the trail."""
37
+ trail = run.cut_trail()
38
+ current = trail[-1][0]
39
+ wanted = (sealed["cut"], sealed.get("transition"))
40
+ at = next((i for i in range(len(trail) - 1, -1, -1)
41
+ if trail[i][0] == wanted[0] and (wanted[1] is None or trail[i][1] == wanted[1])),
42
+ None)
43
+ after = 0 if at is None else trail[-1][1] - trail[at][1]
44
+ return {"sealed_cut": sealed["cut"], "current_cut": current,
45
+ "receipts_after_seal": {"count": after}, "descends": at is not None,
46
+ "same_cut": current == sealed["cut"]}
47
+
48
+
49
+ def _rounded_steps(entry: Forecast) -> int:
50
+ """Rounded operations between the sealed operands and the target: the identities of the chain
51
+ up to and including the target's (a margin: through the logits). Each rounds its result to the
52
+ model dtype, so their errors accumulate; ``derived-exact``, a count of the chain."""
53
+ stops = [step["stop"] for step in entry.chain]
54
+ address = f"t{entry.key[0]}.{entry.label}"
55
+ return stops.index(address) + 1 if address in stops else max(len(stops), 1)
56
+
57
+
58
+ def _native(run: Any, entry: Forecast) -> tuple[Any, dict[str, Any], Any]:
59
+ """The native value as float64, its read info, and the raw native tensor (its dtype and
60
+ magnitude set the verdict floor)."""
61
+ row = entry.key[0]
62
+ stop = f"t{row}.{entry.label}"
63
+ value = run.read(stop)
64
+ info = run.read_info(stop)
65
+ if entry.margin is not None:
66
+ flat = value.reshape(-1)
67
+ return f64(flat[entry.margin.a]) - f64(flat[entry.margin.b]), info, value
68
+ if entry.label == "sample":
69
+ return f64(value).reshape(()), info, value
70
+ return f64(value).reshape(entry.predicted.shape), info, value
71
+
72
+
73
+ def verify(run: Any, ids: list[int] | None = None, *, kernel_path: str = "mdb-stepped",
74
+ calibration: Any = None, stable_floors: float | None = None) -> list[dict[str, Any]]:
75
+ """Compare open forecasts (or the given ids) whose target the cursor has passed with the
76
+ native value. Each result: ``verdict`` (``confirmed | not confirmed | unresolved | edited |
77
+ open``), decided by the measured residual native - emulated (P20) against ``floor`` =
78
+ ``verdict.FLOOR_SPACINGS`` (supplied) x the dtype spacing at the consumer's magnitude (a
79
+ margin: the sum of its two logits' spacings), judged per element; above the floor, where
80
+ emulation and native part (``_parting``); ``rounding_effect`` = native - exact
81
+ (``measured``); the sealed ``rounding_origin``; ``bound_max`` / ``within_bound`` against the
82
+ exact prediction only when the bound is finite (information, not the verdict); and
83
+ ``order`` (sealing stop before the target; lineage of cuts).
84
+
85
+ Every decided result names ``kernel_path``, the realisation the native value comes from
86
+ (``mdb-stepped`` for this run; a caller replaying another path declares its own). A margin
87
+ forecast also carries ``stability`` (``analysis.numerics.stability``): the sign of the native
88
+ margin is ``stable`` only when ``|M| > k`` noise floors (2 spacings at the larger |logit|,
89
+ the ``supplied.judge`` floor), else ``kernel-sensitive``; ``k`` from ``calibration`` (per
90
+ model), else ``stable_floors``, else ``stability.STABLE_FLOORS`` = 4. The ``verdict`` field
91
+ is unchanged."""
92
+ entries = ledger(run)
93
+ here = run.parse(run.where)
94
+ chosen = [entries[i] for i in ids] if ids else [e for e in entries.values()
95
+ if e.status == "open"]
96
+ results = []
97
+ for entry in chosen:
98
+ body = entry.record["body"]
99
+ sealed = body["sealed_at"]
100
+ out: dict[str, Any] = {"id": entry.id, "target": body["target"]["address"],
101
+ "record": entry.record["id"], "sealed_at": sealed["where"]}
102
+ if entry.status != "open":
103
+ results.append({**out, **(entry.verdict or {}), "status": entry.status})
104
+ continue
105
+ if entry.key > here:
106
+ results.append({**out, "status": "open", "verdict": "open",
107
+ "reason": f"target not reached (cursor {run.where})"})
108
+ continue
109
+ lineage = _lineage(run, sealed)
110
+ sealed_key = (sealed["row"], sealed["index"])
111
+ order = {"sealed": {"row": sealed_key[0], "index": sealed_key[1]},
112
+ "target": {"row": entry.key[0], "index": entry.key[1]},
113
+ "sealed_before_target": sealed_key < entry.key, **lineage}
114
+ if not lineage["descends"]:
115
+ results.append({**out, "status": "open", "verdict": "open", "order": order,
116
+ "reason": "the current cut does not descend from the sealed cut "
117
+ "(rewound onto another path); the sealed target was not "
118
+ "reached"})
119
+ continue
120
+ native, info, raw = _native(run, entry)
121
+ later = [e for e in info["upstream_edits"] if _edit_key(e) not in entry.edits]
122
+ verdict: dict[str, Any] = {"order": order}
123
+ written = info["edited"] or info["kind"] in ("edit", "realisation")
124
+ if written and entry.included and entry.label.startswith("L"):
125
+ # sealed with staged="include": the target's own layer edits are in the chain
126
+ layer = _split(entry.label)[0]
127
+ own = {_edit_key(e) for e in _labelled_edits(run)
128
+ if int(e["row"]) == entry.key[0] and int(e["layer"]) == layer
129
+ and not str(e["port"]).startswith("cache.")}
130
+ written = not own <= entry.included
131
+ if entry.included:
132
+ verdict["staged_included"] = sorted(
133
+ f"t{k[0]}.L{k[1]}.{k[2]} {k[3]}" for k in entry.included)
134
+ if written or later:
135
+ what = [f"t{e['row']}.L{e['layer']}.{e['port']} {e['op']}" for e in later]
136
+ if written:
137
+ what.insert(0, f"{entry.label} written by {info['by']}")
138
+ verdict.update(verdict="edited", edited_after_seal=what,
139
+ note="an edit reached the target after sealing; not a forecast "
140
+ "failure")
141
+ else:
142
+ label = info["authority"] # measured, or derived-exact for the replica s
143
+ if label is None:
144
+ verdict.update(verdict="unresolved", state="unresolved", reason=info["reason"])
145
+ else:
146
+ verdict.update(_decide(run, entry, native, raw, label))
147
+ verdict["kernel_path"] = kernel_path
148
+ if entry.margin is not None:
149
+ verdict["stability"] = _margin_stability(
150
+ native, raw, entry.margin, kernel_path, calibration, stable_floors)
151
+ entry.status = "closed"
152
+ entry.verdict = verdict
153
+ results.append({**out, "status": "closed", **verdict})
154
+ return results
155
+
156
+
157
+ STABILITY_FLOOR_SPACINGS = 2.0 # the noise floor stability counts in (supplied.judge's)
158
+
159
+
160
+ def _margin_stability(native: Any, raw: Any, margin: Margin, kernel_path: str,
161
+ calibration: Any, stable_floors: float | None) -> dict[str, Any]:
162
+ """The stability of a margin's sign: ``|M|`` in noise floors (2 spacings of the
163
+ dtype at the larger |logit| of the pair) against ``k``."""
164
+ from ..numerics.stability import stability
165
+
166
+ flat = raw.reshape(-1).detach().abs().float()
167
+ size = max(float(flat[margin.a]), float(flat[margin.b]))
168
+ floor = STABILITY_FLOOR_SPACINGS * _verdict.spacing(size, raw.dtype)
169
+ out = stability(float(native), floor, kernel_path=kernel_path, calibration=calibration,
170
+ k=stable_floors)
171
+ out["floor"] = num(floor, MEASURED)
172
+ out["floor_spacings"] = num(STABILITY_FLOOR_SPACINGS, "supplied")
173
+ return out
174
+
175
+
176
+ def _decide(run: Any, entry: Forecast, native: Any, raw: Any, label: str) -> dict[str, Any]:
177
+ """The verdict of one reached, unedited forecast from its native value (``label`` the
178
+ native value's authority)."""
179
+ out: dict[str, Any] = {}
180
+ gap = (native - entry.emulated).abs()
181
+ out["residual_max_abs"] = num(float(gap.max()), label)
182
+ out["native"] = (num(float(native), label) if native.dim() == 0
183
+ else _summary(native, label))
184
+ # the consumer's magnitude: the margin's two logits (both spacings), else the largest element
185
+ size = _verdict.magnitude(entry.margin if entry.margin is not None else object(), raw)
186
+ partner = None
187
+ if entry.margin is not None:
188
+ flat = raw.reshape(-1).detach().abs().float()
189
+ size, partner = float(flat[entry.margin.a]), float(flat[entry.margin.b])
190
+ decided = _verdict.confirm(gap, size, raw.dtype, partner=partner)
191
+ out.update({k: decided[k] for k in (
192
+ "verdict", "state", "floor", "floor_spacings", "spacing", "residual_spacings", "dtype",
193
+ "criterion", "index") if k in decided}, basis="measured residual native - emulated, P20")
194
+ step = decided["spacing"]["value"]
195
+ effect = float((native - entry.predicted).abs().max())
196
+ out["rounding_effect"] = {"max_abs": num(effect, label),
197
+ "basis": "native - exact (the float64 chain), measured"}
198
+ if step:
199
+ out["rounding_effect"]["spacings"] = num(effect / step, label)
200
+ out["rounding_origin"] = entry.record["body"]["emulated"]["rounding_origin"]
201
+ out["rounded_steps"] = num(_rounded_steps(entry), EXACT)
202
+ row = entry.key[0]
203
+ started = time.perf_counter()
204
+ checks = stage_checks(run, [(row, step["stop"].split(".", 1)[1]) for step in entry.chain])
205
+ out["stages"] = containment(checks, label, seconds=time.perf_counter() - started)
206
+ if decided["verdict"] != _verdict.CONFIRMED:
207
+ out.update(_parting(run, entry, label, checks))
208
+ bound = entry.bound
209
+ sealed = entry.record["body"]["bound"]
210
+ if sealed.get("informative") is False: # finite but not informative: the note, no "within"
211
+ out["bound_note"] = sealed["note"]
212
+ elif bound is not None and bool(bound.isfinite().all()):
213
+ # information only: the worst-case propagated bound of the exact prediction
214
+ exact_gap = (native - entry.predicted).abs()
215
+ within = bool((exact_gap <= bound).all())
216
+ out.update(within_bound=within, bound_max=num(float(bound.max()), BOUND))
217
+ if not within:
218
+ out["worst_excess"] = num(float((exact_gap - bound).max()), label)
219
+ elif "note" in sealed:
220
+ out["bound_note"] = sealed["note"]
221
+ else:
222
+ out["bound_note"] = f"no worst-case interval ({sealed['state']}: {sealed['reason']})"
223
+ return out
224
+
225
+
226
+ MAX_TIES = 3
227
+ PER_STAGE = ("per stage: the rounding bound of each stage's own identity evaluated on that "
228
+ "stage's native operands (read after the native run), against |native - identity|; "
229
+ "it says each native step is its identity up to its own rounding, not how far a "
230
+ "target can sit from the exact chain (that is a chain bound)")
231
+
232
+
233
+ def stage_checks(run: Any, stages: list[tuple[int, str]],
234
+ skip: dict[tuple[int, str], str] | None = None) -> list[dict[str, Any]]:
235
+ """Each stage ``(row, stop)`` of a walked chain evaluated by its identity on its native
236
+ operands (``RowModel`` with bounds, ``cut=False``: one identity, every producer read
237
+ natively), the cursor at or past every stage: ``{stop, row, name, ratio, excess, within}``
238
+ with ``ratio`` the largest ``|native - identity| / bound`` over elements with a positive
239
+ bound and ``excess`` the largest ``|native - identity| - bound``; or ``{.., unchecked}``
240
+ with why (``skip``, a port an edit wrote, no bound). Costs one float64 identity per stage
241
+ (about one exact chain evaluation with bounds) and the native reads."""
242
+ skip = skip or {}
243
+ out: list[dict[str, Any]] = []
244
+ for row, name in stages:
245
+ stop = f"t{row}.{name}"
246
+ item: dict[str, Any] = {"stop": stop, "row": row, "name": name}
247
+ out.append(item)
248
+ if (row, name) in skip:
249
+ item["unchecked"] = skip[row, name]
250
+ continue
251
+ info = run.read_info(stop)
252
+ if info["edited"] or info["kind"] in ("edit", "realisation"):
253
+ item["unchecked"] = f"written by an edit ({info['by']})"
254
+ continue
255
+ if info["authority"] is None:
256
+ item["unchecked"] = info.get("reason") or "no native label"
257
+ continue
258
+ model = RowModel(run, row, lambda n, at=name, r=row: None if n == at else run.read(
259
+ f"t{r}.{n}"), cut=False)
260
+ try:
261
+ value, bound = model.get(name), model.bound(name)
262
+ except Refusal as error:
263
+ item["unchecked"] = str(error)
264
+ continue
265
+ if bound is None:
266
+ item["unchecked"] = model.unbounded.get(name, "no bound")
267
+ continue
268
+ native = f64(run.read(stop)).reshape(value.shape)
269
+ gap = (native - value).abs()
270
+ if not bool(gap.isfinite().all()):
271
+ # e.g. a structural attention mask installed outside the adapter (a pre-hook):
272
+ # native scores carry -inf entries the row model's identity does not
273
+ item["unchecked"] = ("native and identity differ by a non-finite amount (masked "
274
+ "entries the row model does not carry)")
275
+ continue
276
+ positive = bound > 0
277
+ ratio = (gap[positive] / bound[positive]) if bool(positive.any()) else gap.new_zeros(1)
278
+ item.update(ratio=float(ratio.max()), excess=float((gap - bound).max()),
279
+ premises=model.premises)
280
+ item["within"] = item["excess"] <= 0
281
+ if bool(((~positive) & (gap > 0)).any()):
282
+ item["zero_bound_exceeded"] = True
283
+ del model, value, bound, native, gap
284
+ return out
285
+
286
+
287
+ def containment(checks: list[dict[str, Any]], label: str,
288
+ seconds: float | None = None) -> dict[str, Any]:
289
+ """The summary of ``stage_checks``: ``each stage within its own rounding bound on
290
+ native operands: 77/77`` with the worst ratio and its stage, the failing stages and the
291
+ unchecked ones (each list capped at ``MAX_TIES``, with its count). A finite statement about
292
+ every native step walked; labelled as a per-stage bound (``PER_STAGE``), not a chain bound."""
293
+ done = [c for c in checks if "ratio" in c]
294
+ failing = [c for c in done if not c["within"]]
295
+ unchecked = [c for c in checks if "unchecked" in c]
296
+ premises: set[str] = set()
297
+ for c in done:
298
+ premises |= c["premises"]
299
+ out: dict[str, Any] = {"checked": num(len(done), EXACT),
300
+ "within": num(len(done) - len(failing), EXACT),
301
+ "walked": num(len(checks), EXACT),
302
+ "kind": "per-stage bound on native operands",
303
+ "authority": BOUND, "premise": PER_STAGE,
304
+ "premises": sorted(premises | {
305
+ "round to nearest; underflow bounded absolutely where stated",
306
+ f"float32 library functions within {LIBRARY_ULPS} ulp"}),
307
+ "cost": f"{len(done)} float64 identity evaluations on native operands"}
308
+ text = (f"each stage within its own rounding bound on native operands: "
309
+ f"{len(done) - len(failing)}/{len(done)}")
310
+ if done:
311
+ worst = max(done, key=lambda c: c["ratio"])
312
+ out["worst_ratio"] = num(worst["ratio"], label)
313
+ out["worst_stage"] = worst["stop"]
314
+ text += f" (worst |native - identity|/bound {worst['ratio']:.3g} at {worst['stop']})"
315
+ if failing:
316
+ out["failing"] = [{"stop": c["stop"], "ratio": num(c["ratio"], label),
317
+ "excess": num(c["excess"], label),
318
+ **({"zero_bound_exceeded": True} if c.get("zero_bound_exceeded")
319
+ else {})} for c in failing[:MAX_TIES]]
320
+ out["failing_count"] = num(len(failing), EXACT)
321
+ text += "; outside: " + ", ".join(
322
+ f"{c['stop']} by {c['excess']:.3g}" for c in failing[:MAX_TIES]) + (
323
+ f" (+{len(failing) - MAX_TIES} more)" if len(failing) > MAX_TIES else "")
324
+ if unchecked:
325
+ out["not_checked"] = [f"{c['stop']} ({c['unchecked']})" for c in unchecked[:MAX_TIES]]
326
+ out["not_checked_count"] = num(len(unchecked), EXACT)
327
+ text += f"; {len(unchecked)} not checked"
328
+ if seconds is not None:
329
+ out["seconds"] = num(seconds, MEASURED)
330
+ out["text"] = text
331
+ return out
332
+
333
+
334
+ def _parting(run: Any, entry: Forecast, label: str,
335
+ checks: list[dict[str, Any]]) -> dict[str, Any]:
336
+ """Where emulation and native part, for a residual above the floor.
337
+
338
+ ``not confirmed`` when the prediction is not the emulated chain of the sealed operands (the
339
+ held prediction or an operand read now differs from its sealed digest) or when a stage of
340
+ the chain, from the first stop where emulated and native part by more than the floor to the
341
+ target, does not reproduce its native value from its native operands within the rounding
342
+ bound of its identity (``checks``, ``stage_checks``): the identity does not describe that
343
+ native step. Otherwise ``unresolved``: every such stage is the native step, and the residual
344
+ is rounding drift between stages (one-spacing differences of the sums carried forward);
345
+ native top-score ties where the emulated softmax parts are named."""
346
+ body = entry.record["body"]
347
+ sealed_digest = body["digests"]["emulated"]
348
+ row = entry.key[0]
349
+ if _digest(entry.emulated) != sealed_digest:
350
+ return {"verdict": _verdict.NOT_CONFIRMED, "state": "resolved",
351
+ "reason": "the held prediction differs from its sealed digest"}
352
+ sealed = (body["sealed_at"]["row"], body["sealed_at"]["index"])
353
+ emulator = EmulatedRowModel(run, row, _known(run, row, sealed))
354
+ if _digest(_target(emulator, entry.label, entry.margin)) != sealed_digest:
355
+ return {"verdict": _verdict.NOT_CONFIRMED, "state": "resolved",
356
+ "reason": "the emulated chain of the operands read now differs from the sealed "
357
+ "prediction: an operand is not the one sealed"}
358
+ return stage_parting(run, [emulator], label, checks)
359
+
360
+
361
+ def stage_parting(run: Any, emulators: list[EmulatedRowModel], label: str,
362
+ checks: list[dict[str, Any]]) -> dict[str, Any]:
363
+ """Where emulated row models (one per row of a chain, in row order, each evaluated through
364
+ what the chain needed) and the native values part, the cursor at or past every stop they
365
+ computed (``_parting``; the whatif checks of ``propagate`` use it inside the edited
366
+ excursion, over several rows too). The first stop, in row order, where they part by
367
+ more than ``verdict.FLOOR_SPACINGS`` spacings; from there on, each stage's check on its
368
+ native operands (``checks``, ``stage_checks`` over the same walk): a native value outside
369
+ its identity's bound is ``not confirmed`` (the identity does not describe the native step),
370
+ else ``unresolved`` (rounding drift), naming native top-score ties where the emulated softmax
371
+ parts. ``label``: the authority of the native values."""
372
+ dtype = run.adapter.dtype
373
+ floor = _verdict.FLOOR_SPACINGS
374
+ first, parts, step = None, 0.0, 0.0
375
+ walk = [(m, name) for m in emulators for name in m.computed if name != "sample"]
376
+ for model, name in walk:
377
+ native = f64(run.read(f"t{model.row}.{name}")).reshape(model.shape(name))
378
+ if not bool((model.values[name] - native).isfinite().all()):
379
+ return {"verdict": _verdict.UNRESOLVED, "state": "unresolved",
380
+ "reason": f"emulated and native part at t{model.row}.{name} by a non-finite "
381
+ "amount: masked (-inf) entries the row model does not carry (an "
382
+ "attention mask installed outside the adapter)"}
383
+ step = _verdict.spacing(float(native.abs().max()), dtype)
384
+ parts = float((model.values[name] - native).abs().max()) / step
385
+ if parts > floor:
386
+ first = (model.row, name)
387
+ break
388
+ if first is None: # every stop within the floor; the target (margin, token) is not
389
+ first = (walk[-1][0].row, walk[-1][1]) if walk else None
390
+ order = [(c["row"], c["name"]) for c in checks]
391
+ start = order.index(first) if first in order else 0
392
+ first_text = f"t{first[0]}.{first[1]}" if first is not None else "the target"
393
+ unchecked, ties = [], []
394
+ by_row = {m.row: m for m in emulators}
395
+ for item in checks[start:]:
396
+ if "unchecked" in item:
397
+ unchecked.append(f"{item['stop']} ({item['unchecked']})")
398
+ continue
399
+ if not item["within"]:
400
+ return {"verdict": _verdict.NOT_CONFIRMED, "state": "resolved",
401
+ "parting": {"stop": first_text, "spacings": num(parts, label),
402
+ "stage": item["stop"], "excess": num(item["excess"], label)},
403
+ "reason": f"{item['stop']}: the native value lies {item['excess']:.3g} "
404
+ "outside the rounding bound of its identity on the native operands"}
405
+ name, row = item["name"], item["row"]
406
+ model = by_row.get(row)
407
+ if name.endswith(".p") and model is not None and name in model.values:
408
+ scores = f64(run.read(f"t{row}.{name[:-1]}s")).reshape(model.shape(name))
409
+ native = f64(run.read(item["stop"])).reshape(model.shape(name))
410
+ top = scores.topk(min(2, scores.shape[-1]), dim=-1).values
411
+ apart = (model.values[name] != native).any(-1)
412
+ for head in range(scores.shape[0]):
413
+ if top.shape[-1] == 2 and top[head, 0] == top[head, 1] and bool(apart[head]):
414
+ size = float(top[head, 0].abs())
415
+ ties.append(f"{item['stop']}[h{head}]: native top scores tie at "
416
+ f"{float(top[head, 0]):g} (score spacing "
417
+ f"{_verdict.spacing(size, dtype):g})")
418
+ reason = (f"rounding drift: emulated and native part first at {first_text} by "
419
+ f"{parts:.3g} spacings; every stage from there to the target reproduces its native "
420
+ "value from its native operands within its rounding bound")
421
+ if ties:
422
+ reason += "; at native ties: " + "; ".join(ties[:MAX_TIES]) + (
423
+ f" (+{len(ties) - MAX_TIES} more)" if len(ties) > MAX_TIES else "")
424
+ if unchecked:
425
+ reason += "; not checked: " + ", ".join(unchecked[:MAX_TIES]) + (
426
+ f" (+{len(unchecked) - MAX_TIES} more)" if len(unchecked) > MAX_TIES else "")
427
+ return {"verdict": _verdict.UNRESOLVED, "state": "unresolved", "reason": reason,
428
+ "parting": {"stop": first_text, "spacings": num(parts, label),
429
+ "spacing": num(step, label), "ties": ties[:MAX_ITEMS],
430
+ "stages_checked": {"count": len(checks) - start - len(unchecked)}}}
431
+
432
+
433
+ __all__ = ["PER_STAGE", "containment", "stage_checks", "verify"]