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,635 @@
1
+ """Sealed forecasts of native values at the cursor, verified after the native step.
2
+
3
+ A forecast is computed only from values that exist at the cursor of an ``engine.run.Run``: the
4
+ ports at or before the cursor (``Run.read``), the key/value cache rows of earlier tokens
5
+ (``Run.read_cache``) and the weights. ``RowModel`` evaluates the port program's identities
6
+ (``finite``: P01 lookup and adds, P02 RMS, P04 affine reads and RoPE, P05 scores and softmax,
7
+ P10 SwiGLU, P19 readout) in float64 from those values, one stop of the token row at a time;
8
+ nothing native runs for the target. The prediction is ``derived-exact`` (exact real arithmetic
9
+ on captured operands) and carries a per-element rounding ``bound``: how far the native value can
10
+ sit from it under stated premises (round to nearest, the matmul accumulation precision of
11
+ ``accumulation.accumulation`` (float32 unless the run's numeric scope allows CUDA reduced-precision
12
+ reductions, when a matmul bound is refused past ``n u >= 1``), float32 library functions within ``LIBRARY_ULPS`` ulp, no overflow or underflow). The bound of a
13
+ stop whose operands are themselves predictions propagates the operands' bounds through the
14
+ identity (linear maps exactly, SiLU by its Lipschitz constant, RMS and softmax by their exact
15
+ range over the operand box), so a forecast several stops ahead keeps a bound.
16
+
17
+ ``EmulatedRowModel`` evaluates the same chain with the run's dtype rounding at every point where
18
+ eager HF rounds, each step with the backend's own kernels: a second prediction, of the native
19
+ bits (``derived-exact`` under ``EMULATION_PREMISE``). ``verify`` decides on it: the exact
20
+ chain can sit tens of spacings from native where rounded attention scores tie, and that
21
+ ``rounding_effect`` (native - exact) is reported beside the verdict, not hidden in a floor.
22
+
23
+ ``seal`` stores a sealed record (``mdb.core.records``, kind ``forecast``, no arrays: the
24
+ prediction is reached by an occurrence pointer and its digest) in the run's ledger. ``verify``
25
+ compares every open forecast whose target the cursor has passed with the native value, proves
26
+ order (the sealing stop precedes the target, and the session's receipts after sealing lead from
27
+ the sealed cut to the current one) and reports an edit staged or committed after sealing instead
28
+ of counting it as a failure. A forecast whose target was never reached stays open.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import math
34
+ import weakref
35
+ from collections.abc import Callable
36
+ from dataclasses import dataclass, field
37
+ from typing import Any
38
+
39
+ from mdb.core.bounded import MAX_ITEMS, bound_list, load_json, put_json
40
+ from mdb.core.kinds import FORECAST, procedure
41
+ from mdb.core.pointers import occurrence_pointer, seal_digest
42
+ from mdb.core.records import num, seal_record
43
+
44
+ from ..numerics import verdict as _verdict
45
+ from ..numerics.accumulation import bound_state
46
+ from ..numerics.labels import BOUND, EXACT
47
+ from .consumers import Margin, Refusal, run_session_id
48
+ from .rowmodel import (
49
+ EMULATION_PREMISE,
50
+ EMULATION_PREMISES,
51
+ LIBRARY_ULPS,
52
+ NO_IDENTITY,
53
+ NOT_INFORMATIVE,
54
+ EmulatedRowModel,
55
+ RowModel,
56
+ _split,
57
+ _torch,
58
+ )
59
+
60
+ SCHEMA = "mdb-forecast-v1"
61
+
62
+
63
+ # (function, proof) of the identity that computes each port from its producers
64
+ IDENTITY = {
65
+ "h": ("copy", "P01"), "a": ("rms_norm", "P02"), "q": ("affine", "P04"),
66
+ "k": ("affine", "P04"), "v": ("affine", "P04"), "qn": ("rms_norm", "P02"),
67
+ "kn": ("rms_norm", "P02"), "qr": ("rope_rotate", "P04"), "kr": ("rope_rotate", "P04"),
68
+ "s": ("scores", "P05"), "p": ("softmax", "P05"), "A": ("transport", "P01"),
69
+ "o": ("head_write", "P01"), "r": ("residual_add", "P01"), "n": ("rms_norm", "P02"),
70
+ "g": ("affine", "P10"), "u": ("affine", "P10"), "sg": ("swiglu_gate", "P10"),
71
+ "f": ("swiglu_product", "P10"), "m": ("affine", "P10"), "h_out": ("residual_add", "P01"),
72
+ "emb": ("embedding_lookup", "P01"), "fn": ("rms_norm", "P02"),
73
+ "logits": ("readout_logits", "P19"), "sample": ("argmax", None),
74
+ }
75
+ GLOBAL_OPERATORS = {
76
+ "emb": "emb = embed(token)", "fn": "fn = final_norm(h_out of the last layer)",
77
+ "logits": "logits = lm_head(fn)", "sample": "sample = argmax(logits) (greedy)",
78
+ }
79
+
80
+
81
+
82
+ # --------------------------------------------------------------------------- ledger
83
+
84
+
85
+ @dataclass
86
+ class Forecast:
87
+ """One sealed forecast and the in-process tensors its record points at."""
88
+
89
+ id: int
90
+ record: dict[str, Any]
91
+ label: str
92
+ margin: Margin | None
93
+ key: tuple[int, int]
94
+ predicted: Any
95
+ bound: Any
96
+ edits: frozenset
97
+ status: str = "open"
98
+ verdict: dict[str, Any] | None = field(default=None)
99
+ chain: list = field(default_factory=list) # the full identity chain (the record keeps a summary)
100
+ emulated: Any = None # the emulated prediction (EmulatedRowModel): what verify decides on
101
+ included: frozenset = frozenset() # staged port edits the chains apply (staged="include")
102
+
103
+
104
+ _LEDGERS: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
105
+
106
+
107
+ def ledger(run: Any) -> dict[int, Forecast]:
108
+ """The forecasts sealed on ``run`` in this process, by id."""
109
+ if run not in _LEDGERS:
110
+ _LEDGERS[run] = {}
111
+ return _LEDGERS[run]
112
+
113
+
114
+ def _labelled_edits(run: Any) -> list[dict[str, Any]]:
115
+ """Every edit present at sealing: committed ones and the staged ones of the pending layer."""
116
+ out = [{"row": int(e["row"]), "layer": int(e["layer"]), "port": e["port"], "op": e["op"]}
117
+ for e in run.committed_edits()]
118
+ row = run.parse(run.where)[0]
119
+ for edit in run.staged_info():
120
+ out.append({"row": row, "layer": int(edit["layer"]), "port": edit["port"],
121
+ "op": edit["op"]})
122
+ out += [{"row": int(e["row"]), "layer": int(e["cell"]["layer"]), "port": e["port"],
123
+ "op": e["op"]} for e in run.committed_cells()]
124
+ out += [{"row": row, "layer": int(e["cell"]["layer"]), "port": e["port"], "op": e["op"]}
125
+ for e in run.staged_cells()]
126
+ return out
127
+
128
+
129
+ def _staged_between(run: Any, row: int, low: tuple[int, int], high: tuple[int, int]) -> list[str]:
130
+ """Staged edits at ports strictly after ``low`` and at or before ``high``."""
131
+ found = []
132
+ for edit in run.staged_info():
133
+ port = run.program.spec(edit["port"]).name
134
+ key = run.parse(f"t{row}.L{edit['layer']}.{port}")
135
+ realised = run.parse(f"t{row}.L{edit['layer']}.o") if port == "r" else key
136
+ if low < min(key, realised) <= high:
137
+ found.append(f"t{row}.L{edit['layer']}.{port}")
138
+ return found
139
+
140
+
141
+ STAGED_MODES = ("refuse", "include")
142
+ STAGED_RULE = {
143
+ "refuse": "a staged port edit between the cursor and the target refuses the seal; staged "
144
+ "cache-cell edits are in the operands (the cache reads see them)",
145
+ "include": "the staged port edits of the pending layer are applied where the chain computes "
146
+ "their stop (exact: the real-number edit with the bound of its native write; "
147
+ "emulated: the engine's own PortEdit on the dtype value); staged cache-cell edits "
148
+ "are in the operands (the cache reads see them)",
149
+ }
150
+
151
+
152
+ def _staged_edits(run: Any, row: int) -> tuple[dict[str, Any], dict[str, Any], list[dict]]:
153
+ """``(exact, emulated, manifests)``: the ``RowModel.edits`` functions of the staged port
154
+ edits of the pending layer (``propagate``'s edit functions) and their manifests."""
155
+ from mdb.engine.ports import PortEdit
156
+
157
+ from .propagate import _edit_function
158
+
159
+ layer = run.status()["pending_layer"]
160
+ if layer is None:
161
+ return {}, {}, []
162
+ tensors = run.edit_tensors()
163
+ stops: dict[str, list[Any]] = {}
164
+ manifests = []
165
+ for manifest in run.edits:
166
+ described = manifest["value"]
167
+ value = (described["value"] if described["kind"] == "scalar"
168
+ else tensors[described["sha256"]])
169
+ mask = tensors[manifest["mask_sha256"]] if manifest.get("mask_sha256") else None
170
+ port = run.program.spec(manifest["port"]).name
171
+ stops.setdefault(f"L{layer}.{port}", []).append(
172
+ PortEdit(port, value, manifest["op"], mask=mask))
173
+ manifests.append({"address": f"t{row}.L{layer}.{port}", "row": row, "layer": int(layer),
174
+ "port": manifest["port"], "op": manifest["op"],
175
+ "value": _value_view(described),
176
+ "mask_sha256": manifest.get("mask_sha256"),
177
+ "selection": manifest.get("selection")})
178
+ exact = {label: _edit_function(run, f"t{row}.{label}", label, edits, "exact")
179
+ for label, edits in stops.items()}
180
+ emulated = {label: _edit_function(run, f"t{row}.{label}", label, edits, "emulated")
181
+ for label, edits in stops.items()}
182
+ return exact, emulated, manifests
183
+
184
+
185
+ def _value_view(described: dict[str, Any]) -> dict[str, Any]:
186
+ """An edit's value descriptor with its scalar as a labelled number (``supplied``)."""
187
+ if described["kind"] == "scalar":
188
+ return {"kind": "scalar", "value": num(float(described["value"]), "supplied")}
189
+ return {k: described[k] for k in ("kind", "sha256", "shape", "dtype") if k in described}
190
+
191
+
192
+ def _staged_view(run: Any, mode: str, ports: list[dict[str, Any]]) -> dict[str, Any]:
193
+ """The sealed ``staged`` block: the mode, the staged edits the chain includes (port edits in
194
+ ``include`` mode; cache cells always, through the cache reads) and their digest."""
195
+ row = run.parse(run.where)[0]
196
+ cells = [{"address": c["port"], "row": row, "layer": int(c["cell"]["layer"]),
197
+ "port": c["port"], "op": c["op"], "value": _value_view(c["value"]),
198
+ "rows": list(c["cell"]["rows"]), "kv": c["cell"]["kv"], "d": c["cell"]["d"],
199
+ "timing": c["cell"]["timing"]}
200
+ for c in run.cells]
201
+ included = {"ports": ports, "cells": cells}
202
+ return {"mode": mode, "rule": STAGED_RULE[mode], "included": included,
203
+ "count": len(ports) + len(cells), "sha256": seal_digest(included)}
204
+
205
+
206
+ def _resolve_target(run: Any, target: str | Margin | None) -> tuple[str, Margin | None,
207
+ tuple[int, int]]:
208
+ here = run.parse(run.where)
209
+ row = here[0]
210
+ if isinstance(target, Margin):
211
+ if target.row != row:
212
+ raise Refusal(f"forecasts stay in the cursor's row t{row}; {target.text} is not")
213
+ vocab = int(run.adapter.model.config.vocab_size)
214
+ if not (0 <= target.a < vocab and 0 <= target.b < vocab) or target.a == target.b:
215
+ raise Refusal(f"M[a,b] needs two different token ids in 0..{vocab - 1}")
216
+ return "logits", target, run.parse(f"t{row}.logits")
217
+ if target is None:
218
+ stops = run.stops()
219
+ index = here[1] + 1
220
+ if index >= len(stops):
221
+ raise Refusal(f"the next stop t{row + 1}.start is the token list of the next row: "
222
+ + NO_IDENTITY["start"])
223
+ key = (row, index)
224
+ else:
225
+ key = run.parse(target)
226
+ if key[0] != row:
227
+ raise Refusal(f"forecasts stay in the cursor's row t{row}; t{key[0]} is another row")
228
+ return run.stops()[key[1]], None, key
229
+
230
+
231
+ def refuse_held(run: Any) -> None:
232
+ """Measured on a tiny qwen2 in fp32: the forecast chains reason from the
233
+ committed edits, not from the edits active holds will stage ahead of the cursor, so a
234
+ whatif under ``t@last.L>0.p`` held predicted the free continuation bit for bit (-8.6021e-05)
235
+ while the held native change was -8.4773e-05. Until holds are part of the edit plan, a
236
+ forecast on a run with active holds is refused (``run.release()`` first, or measure the
237
+ held arm with ``Branches``)."""
238
+ holds = getattr(run, "holds", None)
239
+ if holds:
240
+ names = ", ".join(h["name"] for h in holds)
241
+ raise Refusal(f"the run has active holds ({names}); forecasts do not model the edits "
242
+ "a hold stages ahead of the cursor, so the prediction would be the free "
243
+ "continuation's. Release them (run.release()) or measure the held arm "
244
+ "with Branches")
245
+
246
+
247
+ def seal(run: Any, target: str | Margin | None = None, *, store: Any = None,
248
+ staged: str = "refuse") -> dict[str, Any]:
249
+ """Predict ``target`` (default: the next stop) from values at the cursor and seal it.
250
+
251
+ ``staged``: ``"refuse"`` (default) refuses while a staged port edit sits between the
252
+ cursor and the target; ``"include"`` applies the staged port edits of the pending layer in
253
+ both chains where they compute the edited stop, so a forecast sealed before the edited
254
+ layer computes covers the edit's own layer (a repair forecast, not an engine-fidelity check
255
+ sealed after the edit). Staged cache-cell edits are in the operands in either mode (the
256
+ chain's cache reads see them, ``Run.read_cache(staged=True)``). The record's
257
+ ``staged`` block names the mode, every staged edit the chain includes and their sha256;
258
+ ``verify`` then decides a target that an included edit wrote instead of reporting it
259
+ ``edited``.
260
+
261
+ The record keeps a bounded summary of the identity chain (``method.summary``); the full
262
+ chain is stored as a JSON blob in ``store`` (a project ``LocalStore``) and the record points
263
+ at it (``method.chain_pointer``, a tensor pointer to the uint8 bytes). Without a store the
264
+ pointer is absent with its reason and the full chain stays on the ledger entry.
265
+
266
+ Returns the forecast view (``id``, ``target``, ``method``, ``predicted``, ``bound``,
267
+ ``record``); raises ``Refusal`` when the target is already computed (at or before the cursor,
268
+ or past it by the native call: ``Run.status()["computed_past_cursor"]``), lies in another
269
+ row, has no identity, or a staged edit sits between the cursor and the target.
270
+ """
271
+ refuse_held(run)
272
+ here = run.parse(run.where)
273
+ row = here[0]
274
+ label, margin, key = _resolve_target(run, target)
275
+ address = margin.text if margin is not None else f"t{row}.{label}"
276
+ if label in NO_IDENTITY:
277
+ raise Refusal(f"{address}: {NO_IDENTITY[label]}")
278
+ if key <= here:
279
+ raise Refusal(f"{address} is already computed at the cursor {run.where}: a forecast "
280
+ "must be sealed before the native value exists")
281
+ status = run.status()
282
+ if status["pending_layer"] is not None and label.startswith(f"L{status['pending_layer']}."):
283
+ port = label.split(".", 1)[1]
284
+ if port in status["computed_past_cursor"]:
285
+ raise Refusal(f"{address} was already computed by the native call at {run.where} "
286
+ "(computed_past_cursor); seal before that call")
287
+ if staged not in STAGED_MODES:
288
+ raise ValueError(f"staged must be one of {STAGED_MODES}")
289
+ between = _staged_between(run, row, here, key)
290
+ exact_edits: dict[str, Any] = {}
291
+ emulated_edits: dict[str, Any] = {}
292
+ ports: list[dict[str, Any]] = []
293
+ if between and staged == "refuse":
294
+ raise Refusal(f"staged edit(s) at {', '.join(between)} rewrite an operand between the "
295
+ "cursor and the target; seal with staged='include' to forecast through "
296
+ "them, or use whatif to predict an edit's effect")
297
+ if staged == "include":
298
+ exact_edits, emulated_edits, ports = _staged_edits(run, row)
299
+ if label.endswith(".o") and f"{label[:-2]}.r" in exact_edits:
300
+ raise Refusal(f"{address} is the realisation of a staged r edit (o' = op(h + o) - h); "
301
+ "forecast the r port or a later stop")
302
+
303
+ known = _known(run, row, here)
304
+ model = RowModel(run, row, known, edits=exact_edits)
305
+ value = model.get(label)
306
+ bound = model.bound(label)
307
+ if margin is not None:
308
+ value = value[margin.a] - value[margin.b]
309
+ bound = None if bound is None else bound[margin.a] + bound[margin.b]
310
+ emulator = EmulatedRowModel(run, row, known, edits=emulated_edits)
311
+ emulated = _target(emulator, label, margin)
312
+ checkpoint = run.checkpoint()
313
+ entries = ledger(run)
314
+ number = max(entries, default=0) + 1
315
+ chain = _chain(run, model, row)
316
+ summary, chain_pointer = _store_chain(chain, store)
317
+ body = _body(run, model, label, margin, address, key, here, value, bound, checkpoint,
318
+ status, summary)
319
+ body["emulated"] = _emulated_view(emulated, label, margin, emulator,
320
+ _rounding_origin(model, emulator, row, run.adapter.dtype))
321
+ body["digests"] = {"exact": _digest(value), "emulated": _digest(emulated)}
322
+ staged_view = _staged_view(run, staged, ports)
323
+ if staged == "include" or staged_view["count"]: # absent otherwise: legacy record bytes
324
+ body["staged"] = staged_view
325
+ body["procedure"] = procedure(run) # the prefill split the operands come from
326
+ pointers = [] if chain_pointer is None else [chain_pointer]
327
+ body["operands"], operands_summary = bound_list(
328
+ body["operands"], MAX_ITEMS, store=store, run=run,
329
+ keep=f"the first {MAX_ITEMS} in capture order (a row's ports, then its cache reads)")
330
+ if operands_summary is not None: # the operand list grows with the layers too
331
+ tensor = operands_summary["pointer"].pop("tensor", None)
332
+ pointers += [] if tensor is None else [tensor]
333
+ body["operands_summary"] = operands_summary
334
+ if margin is None and label != "sample":
335
+ from mdb.engine.ports import tensor_digest
336
+
337
+ pointers.append(occurrence_pointer(
338
+ f"t{row}.{label}", program="forecast", shape=list(value.shape), dtype="float64",
339
+ sha256=tensor_digest(value.contiguous()), cut=checkpoint["cut"], authority=EXACT,
340
+ ports=run.program.names))
341
+ record = seal_record(session_id=run_session_id(run), kind="forecast",
342
+ model_identity=run.adapter.model_identity,
343
+ execution=dict(run.adapter.execution), authority=EXACT, body=body,
344
+ pointers=pointers, run=run)
345
+ # the row model is dropped on return: the entry owns these tensors, no copy needed
346
+ entry = Forecast(number, record, label, margin, key, value.detach(),
347
+ None if bound is None else bound.detach(),
348
+ frozenset(_edit_key(e) for e in body["edits_at_seal"]), chain=chain,
349
+ emulated=emulated.detach(),
350
+ included=frozenset(_edit_key(e) for e in ports))
351
+ entries[number] = entry
352
+ return view(entry)
353
+
354
+
355
+ def _known(run: Any, row: int, here: tuple[int, int]) -> Callable[[str], Any]:
356
+ """The operands of a forecast sealed at ``here``: the native stops of ``row`` at or before
357
+ it (None for later stops and the token list)."""
358
+
359
+ def known(name: str) -> Any:
360
+ if name == "start" or run.parse(f"t{row}.{name}") > here:
361
+ return None
362
+ return run.read(f"t{row}.{name}")
363
+
364
+ return known
365
+
366
+
367
+ def _target(model: RowModel, label: str, margin: Margin | None) -> Any:
368
+ value = model.get(label)
369
+ return value if margin is None else value[margin.a] - value[margin.b]
370
+
371
+
372
+ def _digest(value: Any) -> str:
373
+ """sha256 of a prediction as float64 (vector, margin scalar or token id alike)."""
374
+ from mdb.engine.ports import tensor_digest
375
+
376
+ torch = _torch()
377
+ return tensor_digest(torch.as_tensor(value, dtype=torch.float64).reshape(-1).contiguous())
378
+
379
+
380
+ def _emulated_view(value: Any, label: str, margin: Margin | None, model: EmulatedRowModel,
381
+ origin: dict[str, Any]) -> dict[str, Any]:
382
+ """The second sealed prediction: the emulated chain (``derived-exact`` under its premise)."""
383
+ out: dict[str, Any] = {"authority": EXACT, "premise": EMULATION_PREMISE,
384
+ "premises": list(EMULATION_PREMISES), "sums": model.sums,
385
+ "sha256": _digest(value)}
386
+ if margin is not None:
387
+ out["margin"] = num(float(value), EXACT, proof="P19")
388
+ elif label == "sample":
389
+ out["token"] = int(value)
390
+ else:
391
+ out.update(shape=list(value.shape), **_summary(value, EXACT))
392
+ out["rounding_origin"] = origin
393
+ return out
394
+
395
+
396
+ def _rounding_origin(model: RowModel, emulator: EmulatedRowModel, row: int,
397
+ dtype: Any) -> dict[str, Any]:
398
+ """The first stop of the chain where the exact and the emulated values part by more than one
399
+ spacing of the dtype at the stop's magnitude (scores and softmax: the head, and the score
400
+ magnitude and spacing that rounding acts on). Sealed with the forecast: where the rounding
401
+ effect ``native - exact`` is born, before the native value exists."""
402
+ for name in emulator.computed:
403
+ if name == "sample" or name not in model.values:
404
+ continue
405
+ exact, emulated = model.values[name], emulator.values[name]
406
+ size = float(emulated.abs().max())
407
+ step = _verdict.spacing(size, dtype)
408
+ gap = (exact - emulated).abs()
409
+ parts = float(gap.max()) / step
410
+ if parts <= 1.0:
411
+ continue
412
+ out: dict[str, Any] = {"state": "found", "stop": f"t{row}.{name}",
413
+ "spacings": num(parts, EXACT), "magnitude": num(size, EXACT),
414
+ "spacing": num(step, EXACT)}
415
+ port = name.rsplit(".", 1)[-1]
416
+ if port in ("s", "p"):
417
+ head = int(gap.reshape(gap.shape[0], -1).max(-1).values.argmax())
418
+ scores = emulator.values.get(name[:-1] + "s", emulated) if port == "p" else emulated
419
+ score = float(scores[head].abs().max())
420
+ score_step = _verdict.spacing(score, dtype)
421
+ out.update(head=head, score_magnitude=num(score, EXACT),
422
+ score_spacing=num(score_step, EXACT))
423
+ out["text"] = (f"t{row}.{name}[h{head}]: score spacing {score_step:g} at |s| "
424
+ f"{score:.3g}; exact and emulated part by {parts:.3g} spacings")
425
+ else:
426
+ out["text"] = (f"t{row}.{name}: exact and emulated part by {parts:.3g} spacings at "
427
+ f"|x| {size:.3g}")
428
+ return out
429
+ return {"state": "none", "text": "exact and emulated agree within one spacing at every "
430
+ "stop of the chain"}
431
+
432
+
433
+ def _edit_key(edit: dict[str, Any]) -> tuple[int, int, str, str]:
434
+ return int(edit["row"]), int(edit["layer"]), str(edit["port"]), str(edit["op"])
435
+
436
+
437
+ def _operator(program: Any, label: str) -> tuple[str, list[str]]:
438
+ if label in GLOBAL_OPERATORS:
439
+ return GLOBAL_OPERATORS[label], []
440
+ spec = program.spec(_split(label)[1])
441
+ return spec.operator, list(spec.proofs)
442
+
443
+
444
+ def _summary(value: Any, authority: str) -> dict[str, Any]:
445
+ flat = value.reshape(-1)
446
+ return {"max_abs": num(float(flat.abs().max()), authority),
447
+ "norm": num(float(flat.norm()), authority)}
448
+
449
+
450
+ def _chain(run: Any, model: RowModel, row: int) -> list[dict[str, Any]]:
451
+ """The identities the row model evaluated, in order (can be hundreds on a real model)."""
452
+ chain = []
453
+ for name in model.computed:
454
+ operator, proofs = _operator(run.program, name)
455
+ function, proof = IDENTITY[name.split(".", 1)[-1]]
456
+ chain.append({"stop": f"t{row}.{name}", "operator": operator, "proofs": proofs,
457
+ "identity": function, "proof": proof})
458
+ return chain
459
+
460
+
461
+ EDGE_STEPS = 3 # identities kept at each end of the chain in the record summary
462
+ MAX_LAYER_COUNTS = 64 # per-layer totals are listed only up to the record's sequence bound
463
+
464
+
465
+ def _store_chain(chain: list[dict[str, Any]], store: Any) -> tuple[dict[str, Any], Any]:
466
+ """``(summary, tensor pointer or None)``: the bounded summary the record holds (count, proof
467
+ use, first and last identities, per-layer totals) and, with a store, the pointer to the full
468
+ chain blob (JSON bytes as a uint8 tensor)."""
469
+ proofs: dict[str, int] = {}
470
+ for step in chain:
471
+ for proof in {step["proof"], *step["proofs"]} - {None}:
472
+ proofs[proof] = proofs.get(proof, 0) + 1
473
+ layers: dict[int, int] = {}
474
+ for step in chain:
475
+ port = step["stop"].split(".", 1)[1]
476
+ if port in GLOBAL_OPERATORS:
477
+ continue
478
+ layer = _split(port)[0]
479
+ layers[layer] = layers.get(layer, 0) + 1
480
+ summary: dict[str, Any] = {
481
+ "count": len(chain),
482
+ "proof_counts": [{"proof": k, "count": v} for k, v in sorted(proofs.items())],
483
+ "first": chain[:EDGE_STEPS], "last": chain[-EDGE_STEPS:],
484
+ "global_steps": {"count": sum(1 for s in chain
485
+ if s["stop"].split(".", 1)[1] in GLOBAL_OPERATORS)}}
486
+ if layers and len(layers) <= MAX_LAYER_COUNTS:
487
+ summary["layer_counts"] = [{"layer": i, "count": layers.get(i, 0)}
488
+ for i in range(max(layers) + 1)]
489
+ held = put_json(chain, store=store, absent_reason=(
490
+ "no project store: the full chain is held in memory on the forecast entry "
491
+ "(Forecast.chain), not stored"))
492
+ summary["chain_sha256"] = held["sha256"]
493
+ if held["state"] != "stored":
494
+ summary["chain_pointer"] = {"state": "absent", "reason": held["reason"]}
495
+ return summary, None
496
+ summary["chain_pointer"] = {"state": "stored", "ref": held["ref"], "bytes": held["bytes"]}
497
+ return summary, held["tensor"]
498
+
499
+
500
+ def load_chain(record: dict[str, Any], store: Any) -> list[dict[str, Any]]:
501
+ """The full identity chain a forecast record points at, from ``store``; checked against the
502
+ record's ``chain_sha256`` (``Unresolved`` or a refusal when absent or changed)."""
503
+ summary = record["body"]["method"]["summary"]
504
+ if summary["chain_pointer"]["state"] != "stored":
505
+ raise Refusal("the record holds no chain pointer: " + summary["chain_pointer"]["reason"])
506
+ pointer = next(p for p in record["pointers"] if p.get("kind") == "tensor"
507
+ and p["ref"] == summary["chain_pointer"]["ref"])
508
+ try:
509
+ return load_json({"state": "stored", "sha256": summary["chain_sha256"]}, store=store,
510
+ tensor=pointer)
511
+ except ValueError:
512
+ raise Refusal("the stored chain differs from the record's chain_sha256") from None
513
+
514
+
515
+ def _body(run, model, label, margin, address, key, here, value, bound, checkpoint,
516
+ status, summary) -> dict[str, Any]:
517
+ from mdb.engine.ports import tensor_digest
518
+
519
+ row = here[0]
520
+ operands = [{"address": f"t{row}.{name}", "sha256": tensor_digest(tensor.contiguous()),
521
+ "shape": list(tensor.shape), "dtype": str(tensor.dtype).removeprefix("torch.")}
522
+ for name, tensor in model.captured.items()]
523
+ operands += [{"address": f"{name}[row=0:{row}]" if row else name,
524
+ "sha256": tensor_digest(tensor.contiguous()), "shape": list(tensor.shape),
525
+ "dtype": str(tensor.dtype).removeprefix("torch.")}
526
+ for name, tensor in model.cache_reads.items()]
527
+ if margin is not None:
528
+ predicted: dict[str, Any] = {"value": num(float(value), EXACT, proof="P19"), "shape": []}
529
+ elif label == "sample":
530
+ predicted = {"token": int(value), "shape": []}
531
+ else:
532
+ predicted = {"shape": list(value.shape), "dtype": "float64",
533
+ "sha256": tensor_digest(value.contiguous()), **_summary(value, EXACT)}
534
+ bound_view = bound_view_of(model, label, bound, run.adapter.dtype, value)
535
+ return {
536
+ "schema": SCHEMA,
537
+ "target": {"address": address, "stop": f"t{row}.{label}", "row": key[0],
538
+ "index": key[1],
539
+ "kind": "margin" if margin is not None else "token" if label == "sample"
540
+ else "value",
541
+ **({"indices": [margin.a, margin.b]} if margin is not None else {})},
542
+ "sealed_at": {"where": run.where, "cut": checkpoint["cut"], "row": here[0],
543
+ "index": here[1], "transition": int(checkpoint["transitions"]),
544
+ "receipts": {"count": len(run.session.receipts),
545
+ "last": (run.session.receipts[-1].fingerprint
546
+ if run.session.receipts else None)},
547
+ "lookahead": status["lookahead"],
548
+ "computed_past_cursor": list(status["computed_past_cursor"])},
549
+ "method": {"authority": EXACT, "summary": summary,
550
+ "rule": "identities of the port program on values that exist at the cursor; "
551
+ "no native call for the target"},
552
+ "operands": operands,
553
+ "predicted": predicted,
554
+ "bound": bound_view,
555
+ "edits_at_seal": _labelled_edits(run),
556
+ }
557
+
558
+
559
+ BOUND_ROLE = ("information: the worst-case interval (every rounding error aligned) beside the "
560
+ "prediction; it never decides a verdict or a result's state")
561
+
562
+
563
+ def consumer_note(worst: float, size: float, stage: str,
564
+ wide: dict[str, str] | None) -> dict[str, Any] | None:
565
+ """Whether the worst-case bound at the consumer says anything: None when it is finite and
566
+ smaller than ``|value|`` (``size``; zero bound always informative), else ``{stage, text,
567
+ value}``: the note names the first wide stage of the chain (``wide``, with its numbers) and
568
+ the consumer bound beside ``|value|``, so the reader sees the size. ``value`` is the number
569
+ (kept in the record as ``bound_value``, never printed as a confirmation)."""
570
+ if not math.isfinite(worst) or worst == 0.0 or worst < size:
571
+ return None
572
+ if wide is None:
573
+ text = (f"{NOT_INFORMATIVE} {stage} (consumer bound {worst:.3g} >= |value| {size:.3g}; "
574
+ "no earlier stage was wide)")
575
+ return {"stage": stage, "text": text, "value": worst}
576
+ first = wide["stage"]
577
+ text = (f"{NOT_INFORMATIVE} {first} ({wide['cause']}); at the consumer {stage} the bound is "
578
+ f"{worst:.3g} >= |value| {size:.3g}")
579
+ return {"stage": first, "text": text, "value": worst}
580
+
581
+
582
+ def bound_view_of(model: RowModel, label: str, bound: Any, dtype: Any,
583
+ value: Any = None) -> dict[str, Any]:
584
+ """The sealed ``bound`` sub-dict of a forecast: the worst-case interval with its
585
+ premises; or, where it stopped being informative, the stop and the cause with its numbers
586
+ (``informative: False``, no state: an uninformative worst case is information, not an
587
+ unresolved result); or the refused premise; else unresolved with the reason. Always marked
588
+ ``information`` (``ops.registry.has_unresolved`` does not count it)."""
589
+ if bound is None:
590
+ reason = model.unbounded.get(label, "no rounding bound for this step")
591
+ if model.broken is not None and bound_state(reason) != "refused":
592
+ return {"informative": False, "from": model.broken["stage"],
593
+ "cause": model.broken["cause"], "note": model.broken["text"],
594
+ "information": True, "role": BOUND_ROLE}
595
+ return {"state": bound_state(reason), "reason": reason, "information": True,
596
+ "role": BOUND_ROLE}
597
+ worst = float(bound.reshape(-1).max())
598
+ size = float(value.abs().max()) if value is not None and value.numel() else math.inf
599
+ premises = sorted(model.premises | {
600
+ "round to nearest; underflow bounded absolutely where stated, no overflow",
601
+ f"float32 library functions within {LIBRARY_ULPS} ulp",
602
+ f"model dtype {str(dtype).removeprefix('torch.')}"})
603
+ note = consumer_note(worst, size, f"t{model.row}.{label}", model.wide)
604
+ if note is not None: # finite, at least |value|: the note, the number kept
605
+ return {"informative": False, "from": note["stage"], "note": note["text"],
606
+ "bound_value": num(worst, BOUND), "information": True, "role": BOUND_ROLE,
607
+ "premises": premises}
608
+ return {"max": num(worst, BOUND), "elementwise": True,
609
+ "information": True, "role": BOUND_ROLE, "premises": premises}
610
+
611
+
612
+ def view(entry: Forecast) -> dict[str, Any]:
613
+ """The bounded JSON of one forecast: its id, record digest and sealed body."""
614
+ body = entry.record["body"]
615
+ out = {"id": entry.id, "record": entry.record["id"], "target": body["target"]["address"],
616
+ "status": entry.status, "sealed_at": body["sealed_at"]["where"],
617
+ "method": entry.chain[:MAX_ITEMS], "method_summary": body["method"]["summary"],
618
+ "predicted": body["predicted"],
619
+ "emulated": body.get("emulated"),
620
+ "bound": body["bound"]}
621
+ if len(entry.chain) > MAX_ITEMS: # the view obeys the record bound too
622
+ out["method_listed"] = {
623
+ "count": len(entry.chain), "listed": MAX_ITEMS,
624
+ "keep": f"the first {MAX_ITEMS} identities; all of them are in Forecast.chain and "
625
+ "(with a project) behind method_summary.chain_pointer (load_chain)"}
626
+ if entry.verdict is not None:
627
+ out["verdict"] = entry.verdict
628
+ return out
629
+
630
+
631
+
632
+ _session_id = run_session_id # old private name, kept for one commit
633
+
634
+
635
+ __all__ = ["FORECAST", "IDENTITY", "bound_view_of", "ledger", "seal", "view"]