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,265 @@
1
+ """Row captures: the ports of one token row, held for the explain identities.
2
+
3
+ ``capture_row`` captures a row from a model and prompt, ``captures_from_run`` from a debugger
4
+ run at its cursor (with what each port's value is: native, edited, supplied), and
5
+ ``RowCapture`` holds the ports, the final norm's input and the logits.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping, Sequence
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+
14
+ from ..numerics.labels import EXACT, MEASURED
15
+
16
+ _RUN_STOPS = ("logits", "sample")
17
+ # Edits at these ports change the residual stream at a layer boundary; explain_margin books them as
18
+ # their own listed terms ``L{l}.edit_{port}`` instead of letting them fall into rounding.
19
+ _BOUNDARY_EDIT_PORTS = ("h", "h_out")
20
+
21
+
22
+ @dataclass
23
+ class RowCapture:
24
+ """All ports of one pending-token row, with the operands the identities need.
25
+
26
+ ``ports[l][name]`` is the native capture at layer ``l`` (shapes as in ``engine.ports``);
27
+ ``keys``/``values`` are the per-layer caches after the row (``(1, H_KV, T, d_h)``, keys
28
+ post-RoPE); ``normed`` is the native final-norm output and ``logits`` the native logits.
29
+ ``edits`` maps layer -> edit manifests realised in THIS row (``edits_this_row`` is the same
30
+ data keyed ``(row, layer)``); ``edits_history`` maps ``(row, layer)`` of an EARLIER row ->
31
+ manifests (they reach this row only through the cache). ``originals[l]`` holds the pre-edit
32
+ capture of each edited port of layer ``l`` (the engine's ``controller.originals``); it is
33
+ what lets ``explain_margin`` book an ``h``/``h_out`` edit as its own term.
34
+ ``originals_missing`` lists ``(layer, port)`` of this-row ``h``/``h_out`` edits whose pre-edit
35
+ value was not retained (``captures_from_run`` without ``recompute_originals``);
36
+ ``originals_source`` says where each held original came from.
37
+
38
+ ``infos[l][port]`` is ``Run.read_info`` of that value when the capture came from a ``Run``
39
+ (``captures_from_run``); a ``capture_row`` capture leaves it empty and ``_info`` summarises
40
+ the same fields from ``edits`` (the manifests) and ``realisations[l]`` (the controller's
41
+ realisation record of layer ``l``).
42
+ """
43
+
44
+ family: str
45
+ tokens: tuple[int, ...]
46
+ position: int
47
+ ports: list[dict[str, Any]]
48
+ keys: list[Any]
49
+ values: list[Any]
50
+ normed: Any
51
+ logits: Any
52
+ adapter: Any
53
+ edits: dict[int, list[dict[str, Any]]] = field(default_factory=dict)
54
+ checks: list[dict[str, Any]] = field(default_factory=list)
55
+ originals: list[dict[str, Any]] = field(default_factory=list)
56
+ edits_history: dict[tuple[int, int], list[dict[str, Any]]] = field(default_factory=dict)
57
+ originals_missing: list[tuple[int, str]] = field(default_factory=list)
58
+ originals_source: dict[tuple[int, str], str] = field(default_factory=dict)
59
+ infos: list[dict[str, dict[str, Any]]] = field(default_factory=list)
60
+ realisations: list[dict[str, Any]] = field(default_factory=list)
61
+
62
+ @property
63
+ def edits_this_row(self) -> dict[tuple[int, int], list[dict[str, Any]]]:
64
+ return {(self.position, layer): v for layer, v in self.edits.items()}
65
+
66
+
67
+ def capture_row(adapter: Any, tokens: Sequence[int], *,
68
+ edits: Mapping[int, Sequence[Any]] | None = None) -> RowCapture:
69
+ """Run the pending row of ``tokens`` once through every layer with an all-port controller.
70
+
71
+ ``edits`` maps a layer to ``engine.ports.PortEdit`` objects committed at that layer. Prefix
72
+ rows come from the adapter's native prefill.
73
+ """
74
+ from mdb.engine.ports import PortController, program_for
75
+
76
+ program = program_for(adapter)
77
+ edits = dict(edits or {})
78
+ session = adapter.session(list(tokens))
79
+ session.continue_()
80
+ ports, checks, manifests, originals, sources, realisations = [], [], {}, [], {}, []
81
+ for layer in range(adapter.layers):
82
+ controller = PortController(program, layer, edits=tuple(edits.get(layer, ())))
83
+ session.continue_(1, ports=controller)
84
+ ports.append(dict(controller.captures))
85
+ checks.append(dict(controller.checks))
86
+ realisations.append(dict(getattr(controller, "realisation", None) or {}))
87
+ originals.append({k: v.clone() for k, v in controller.originals.items()})
88
+ for key in controller.originals:
89
+ if key in _BOUNDARY_EDIT_PORTS:
90
+ sources[(layer, key)] = "controller.originals"
91
+ if edits.get(layer):
92
+ manifests[layer] = [edit.manifest() for edit in edits[layer]]
93
+ payload = session.capture(retain=False).payload
94
+ keys = [k.clone() for k in payload["keys"]]
95
+ values = [v.clone() for v in payload["values"]]
96
+ session.continue_()
97
+ normed = session.read("hidden")
98
+ session.continue_()
99
+ logits = session.read("logits")
100
+ return RowCapture(program.family, tuple(int(t) for t in tokens), len(tokens) - 1, ports, keys,
101
+ values, normed, logits, adapter, manifests, checks, originals, {}, [], sources,
102
+ [], realisations)
103
+
104
+
105
+ def captures_from_run(run: Any, *, recompute_originals: bool = False) -> RowCapture:
106
+ """Read a ``RowCapture`` from an ``engine.run.Run`` whose cursor is at ``logits``/``sample``.
107
+
108
+ Every layer port is read through ``Run.read`` (which replays the row's committed edits); the
109
+ key/value caches through ``Run.read_cache``. Edits come from ``Run.committed_edits()``, keyed
110
+ by ``(row, layer)``: those of the explained row go to ``edits`` (layer -> records), those of
111
+ earlier rows to ``edits_history``.
112
+
113
+ The pre-edit value of an ``h``/``h_out`` edit of the explained row is not retained for a
114
+ committed layer. With ``recompute_originals=True`` it is rebuilt: ``h`` through
115
+ ``Run.original(target, recompute=True)`` (a re-probe that leaves the run unchanged);
116
+ ``h_out`` (which ``Run.original`` does not return) as the native add ``r + m`` of the
117
+ captured ``r`` and ``m`` (the add the layer performed before the edit). Without it the edits
118
+ land in ``originals_missing`` and ``explain_margin`` reports their terms ``unresolved``.
119
+ With it, the pre-edit native value of every other port an edit or realisation wrote is also
120
+ rebuilt (``Run.original(..., recompute=True)``) for ``explain_port``'s ``original`` field.
121
+ ``Run.read_info`` of every port of the row is kept in ``RowCapture.infos``.
122
+ """
123
+ where = run.where
124
+ row_text, label = where.split(".", 1)
125
+ if label not in _RUN_STOPS:
126
+ raise ValueError(f"explain needs the cursor at t<row>.logits or .sample, not {where}")
127
+ row = int(row_text[1:])
128
+ program = run.program
129
+ layers = run.adapter.layers
130
+ ports = [{name: run.read(f"t{row}.L{layer}.{name}") for name in program.names}
131
+ for layer in range(layers)]
132
+ tokens = tuple(int(t) for t in run.session.read("tokens")[0].tolist())
133
+ edits: dict[int, list[dict[str, Any]]] = {}
134
+ history: dict[tuple[int, int], list[dict[str, Any]]] = {}
135
+ for record in run.committed_edits():
136
+ if int(record["row"]) != row:
137
+ history.setdefault((int(record["row"]), int(record["layer"])), []).append(record)
138
+ else:
139
+ edits.setdefault(int(record["layer"]), []).append(record)
140
+ infos = [{name: run.read_info(f"t{row}.L{layer}.{name}") for name in program.names}
141
+ for layer in range(layers)]
142
+ originals: list[dict[str, Any]] = [{} for _ in range(layers)]
143
+ missing: list[tuple[int, str]] = []
144
+ source: dict[tuple[int, str], str] = {}
145
+ for layer, records in sorted(edits.items()):
146
+ for port in sorted({program.spec(r["port"]).name for r in records}
147
+ & set(_BOUNDARY_EDIT_PORTS)):
148
+ value = None
149
+ if recompute_originals and port == "h":
150
+ value = run.original(f"t{row}.L{layer}.h", recompute=True)
151
+ source[(layer, port)] = "Run.original(recompute=True)"
152
+ elif recompute_originals:
153
+ value = ports[layer]["r"] + ports[layer]["m"]
154
+ source[(layer, port)] = "native add r + m of the captured r and m"
155
+ if value is None:
156
+ source.pop((layer, port), None)
157
+ missing.append((layer, port))
158
+ else:
159
+ originals[layer][port] = value.clone()
160
+ if recompute_originals:
161
+ # pre-edit native value of every other port an edit or realisation wrote (explain_port)
162
+ for layer in range(layers):
163
+ for name, info in infos[layer].items():
164
+ if (info["kind"] in ("edit", "realisation") and name not in _BOUNDARY_EDIT_PORTS):
165
+ value = run.original(f"t{row}.L{layer}.{name}", recompute=True)
166
+ if value is not None:
167
+ originals[layer][name] = value.clone()
168
+ return RowCapture(program.family, tokens, row, ports,
169
+ [run.read_cache(layer, "k")[..., : row + 1, :].clone()
170
+ for layer in range(layers)],
171
+ [run.read_cache(layer, "v")[..., : row + 1, :].clone()
172
+ for layer in range(layers)],
173
+ run.read(f"t{row}.fn"), run.read(f"t{row}.logits"), run.adapter, edits,
174
+ [], originals, history, missing, source, infos, [])
175
+
176
+
177
+ def _as_capture(source: Any) -> RowCapture:
178
+ return source if isinstance(source, RowCapture) else captures_from_run(source)
179
+
180
+
181
+ def _info(caps: RowCapture, layer: int, port: str) -> dict[str, Any]:
182
+ """How the value at ``L{layer}.{port}`` of the captured row came about (``Run.read_info`` keys).
183
+
184
+ A capture from a ``Run`` carries ``Run.read_info`` itself (``caps.infos``). A ``capture_row``
185
+ capture has only the edit manifests, so the same keys are summarised from them with the
186
+ engine's rules: ``supplied`` only when the last write is an unmasked ``replace``; any other
187
+ written value is ``derived-exact`` with its ``ops``; ``o`` under an ``r`` edit is a
188
+ ``realisation``; ``r`` realised inexactly is ``measured``; ``s`` (and ``p``/``A`` under an
189
+ ``s``/``p`` edit) is a ``replica`` whose check is read from ``caps.checks``.
190
+ """
191
+ if caps.infos:
192
+ return caps.infos[layer][port]
193
+ program = _program(caps.adapter)
194
+ names, spec = program.names, program.spec
195
+ index = names.index(port)
196
+ records = caps.edits.get(layer, [])
197
+
198
+ def name_of(record):
199
+ return spec(record["port"]).name
200
+
201
+ boundary = ([r for r in caps.edits.get(layer - 1, []) if name_of(r) == "h_out"]
202
+ if port == "h" and layer > 0 else [])
203
+ here = [r for r in records if name_of(r) == port]
204
+ upstream = [{"row": int(row), "layer": int(l), "port": r["port"], "op": r["op"],
205
+ "staged": False}
206
+ for (row, l), recs in sorted(caps.edits_history.items()) for r in recs]
207
+ for l, recs in sorted(caps.edits.items()):
208
+ for r in recs:
209
+ if r in boundary:
210
+ continue
211
+ if l < layer or (l == layer and names.index(name_of(r)) < index):
212
+ upstream.append({"row": caps.position, "layer": int(l), "port": r["port"],
213
+ "op": r["op"], "staged": False})
214
+ info: dict[str, Any] = {
215
+ "edited": False, "by": None, "kind": "native", "authority": "measured",
216
+ "state": "resolved", "reason": None, "ops": [], "selective": False,
217
+ "upstream_edits": upstream, "replica_equal": None, "replica_checked": None,
218
+ "max_abs_diff": None, "max_abs_diff_authority": None, "realisation_exact": None,
219
+ "realisation_max_abs_error": None, "same_port_edit": None}
220
+ edited_ports = {name_of(r) for r in records}
221
+ r_edits = [r for r in records if name_of(r) == "r"]
222
+ realisation = caps.realisations[layer] if layer < len(caps.realisations) else {}
223
+ base = (port == "s" or (port == "p" and "s" in edited_ports)
224
+ or (port == "A" and bool(edited_ports & {"s", "p"})))
225
+ writes = boundary + here
226
+ if port == "o" and r_edits:
227
+ info.update(kind="realisation", authority=EXACT, by="r", ops=[r["op"] for r in r_edits],
228
+ selective=any("mask_count" in r for r in r_edits))
229
+ if "exact" in realisation:
230
+ info.update(realisation_exact=bool(realisation["exact"]),
231
+ realisation_max_abs_error=float(realisation["max_abs_error"]))
232
+ elif writes:
233
+ numel = int(caps.ports[layer][port].numel())
234
+ last = writes[-1]
235
+ full = "mask_count" not in last or int(last["mask_count"]) == numel
236
+ info.update(edited=True, kind="edit", ops=[r["op"] for r in writes],
237
+ by=",".join(sorted({"h_out" if r in boundary else port for r in writes},
238
+ key=names.index)),
239
+ selective=any("mask_count" in r for r in writes),
240
+ authority="supplied" if last["op"] == "replace" and full else EXACT)
241
+ if port == "r" and "exact" in realisation:
242
+ info.update(realisation_exact=bool(realisation["exact"]),
243
+ realisation_max_abs_error=float(realisation["max_abs_error"]))
244
+ if not realisation["exact"]:
245
+ info.update(kind="realisation", authority=MEASURED)
246
+ if base and not info["edited"] and info["kind"] == "native":
247
+ info.update(kind="replica", authority=EXACT)
248
+ if port in ("s", "A") and layer < len(caps.checks):
249
+ check = caps.checks[layer].get("s" if port == "s" else "mix_replica")
250
+ info["replica_checked"] = check is not None
251
+ if check is not None:
252
+ info.update(replica_equal=bool(check["equal"]),
253
+ max_abs_diff=float(check.get("max_abs_diff", 0.0)),
254
+ max_abs_diff_authority=MEASURED)
255
+ if base and info["authority"] != "supplied" and not check["equal"]:
256
+ info.update(state="refused", authority=None,
257
+ reason=f"replica check failed: max |replica - native| = "
258
+ f"{float(check.get('max_abs_diff', 0.0))}")
259
+ return info
260
+
261
+
262
+ def _program(adapter: Any) -> Any:
263
+ from mdb.engine.ports import program_for
264
+
265
+ return program_for(adapter)
@@ -0,0 +1,52 @@
1
+ """Consumers and refusals shared by every predict, measure and symbols module.
2
+
3
+ ``Margin`` (``M[a,b] = logits[a] - logits[b]`` of one token row) and ``Logit`` (one logit) are
4
+ the declared consumers, ``Refusal`` is raised when a premise fails, and ``run_session_id`` is the
5
+ record session id of an in-process run.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ from mdb.core.pointers import seal_digest
14
+
15
+
16
+ class Refusal(ValueError):
17
+ """A forecast or prediction whose premise fails; ``reason`` says which."""
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Margin:
22
+ """The declared margin ``M[a,b] = logits[a] - logits[b]`` of token row ``row``."""
23
+
24
+ row: int
25
+ a: int
26
+ b: int
27
+
28
+ @property
29
+ def text(self) -> str:
30
+ return f"t{self.row}.M[{self.a},{self.b}]"
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Logit:
35
+ """One logit ``logits[i]`` of token row ``row``."""
36
+
37
+ row: int
38
+ i: int
39
+
40
+ @property
41
+ def text(self) -> str:
42
+ return f"t{self.row}.logits[i={self.i}]"
43
+
44
+
45
+ def run_session_id(run: Any) -> str:
46
+ """The record session id of an in-process run: its model identity and prompt digest."""
47
+ checkpoint = run.checkpoint()
48
+ return "mdb-run:" + seal_digest({"model": checkpoint["model_identity"],
49
+ "prompt": checkpoint["prompt_sha256"]})[:32]
50
+
51
+
52
+ __all__ = ["Logit", "Margin", "Refusal", "run_session_id"]