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
mdb/core/recipe.py ADDED
@@ -0,0 +1,457 @@
1
+ """Replay recipe v2: a sealed, bounded record that rebuilds a debugger cursor from the model alone.
2
+
3
+ ::
4
+
5
+ {schema: "mdb-replay-recipe-v2", name, model_identity, layers, tokens, prompt_sha256,
6
+ prefill, numeric_scope, lookahead, transitions: [{transition, layer, edits}],
7
+ staged: [edit], target: {where, transitions, port}, cut, fingerprint}
8
+
9
+ ``prefill`` is the procedure: the number of prompt rows the run computed in one batched
10
+ call before stepping the rest row by row (``Run(prefill=K)``). A batched and a stepped row can
11
+ differ by a rounding step in their cached K/V bits, so a replay must use the same split; every
12
+ recipe written now carries it (a default run's too, so recipe fingerprints changed when it was
13
+ added). A recipe written before it reads as the default split, all prompt rows but the last.
14
+
15
+ It is ``Run.checkpoint()`` one to one (``from_checkpoint`` / ``to_checkpoint``): ``transitions``
16
+ are its ``path_edits`` (the edits committed with each native transition, in order), ``staged``
17
+ its ``edits`` (staged in the pending layer at the target), ``target`` its ``where``,
18
+ ``transitions`` and ``port``, ``cut`` the boundary cut fingerprint the replay must reproduce.
19
+ What a checkpoint holds as a tensor digest the recipe holds as a ``tensor`` pointer
20
+ (``mdb.core.pointers.tensor_pointer``: blob ref + payload sha256) into the project store; an
21
+ edit is ``{port, op, value, mask?, mask_count?, selection?}`` with ``value`` either a tensor
22
+ pointer or ``{kind: "scalar", value: num(x, "supplied")}``. A state-cell edit
23
+ (``mdb.engine.edits.CellEdit``) adds ``cell`` ``{layer, tensor, rows, kv, d, timing,
24
+ staged_at}`` and ``dose`` (``mix`` only, a supplied number). Any edit, port or cell, may carry
25
+ ``origin`` (the pointer of a value taken from another run: names and digests, never the array;
26
+ the value itself is the edit's tensor pointer, a blob, so the recipe replays after the other run
27
+ is gone). Recipes written before cells existed read unchanged. Token ids are inline up to
28
+ ``MAX_INLINE_ITEMS`` and a tensor pointer (int64) beyond. Arrays are never inline: the recipe
29
+ passes ``check_bounded`` (no array, at most 64 KiB) before it is sealed and again when read.
30
+
31
+ The seal is ``mdb.core.index.recipe_fingerprint`` (the recipe table's own convention), so a
32
+ recipe is stored with ``mdb.core.index.put_recipe`` and its id is its fingerprint.
33
+
34
+ Replaying (``mdb.ops.debugger.Debugger.restart``) refuses with a ``RecipeError`` (a
35
+ ``Refused``) whose ``code`` is one of ``CODES``, each with its own message: another model identity, another
36
+ numeric scope, a missing blob, a corrupt blob, a malformed recipe, a replay that reached
37
+ another cut fingerprint, or (``origin-edits``) a recipe whose edits at an occurrence are not
38
+ the ones an ``@cut+edit`` origin names.
39
+
40
+ Edited origins. A value read under edits is addressed ``@<cut>+<ref>+<ref>:<target>``: the
41
+ boundary cut it is computed from (whose fingerprint binds everything before it, path edits
42
+ included) and, in order, the reference (``edit_ref``: sha256 of the canonical manifest) of each
43
+ edit applied in the transition that computes it. ``occurrence_checkpoint(..., edits=refs)``
44
+ refuses a recipe whose edits there have other references, so a pointer never resolves through
45
+ edits it was not read under.
46
+ """
47
+ from __future__ import annotations
48
+
49
+ import json
50
+ from collections.abc import Mapping
51
+
52
+ from saturn.values import digest
53
+
54
+ from . import index
55
+ from .errors import Refused
56
+ from .pointers import (
57
+ MAX_INLINE_ITEMS,
58
+ MAX_RECORD_BYTES,
59
+ RecordError,
60
+ Unresolved,
61
+ _canonical,
62
+ check_bounded,
63
+ resolve_tensor,
64
+ tensor_pointer,
65
+ validate_tensor_pointer,
66
+ )
67
+ from .records import check_num, declare_kind, num, seal_record
68
+
69
+ SCHEMA = "mdb-replay-recipe-v2"
70
+ CHECKPOINT_SCHEMA = "mdb-engine-checkpoint-v1" # mdb.engine.run.CHECKPOINT_SCHEMA
71
+ FIELDS = ("schema", "name", "model_identity", "layers", "tokens", "prompt_sha256", "prefill",
72
+ "numeric_scope", "lookahead", "transitions", "staged", "target", "cut", "fingerprint")
73
+ _OPTIONAL = ("prefill",) # absent in recipes written before the prefill split was recorded
74
+ CODES = ("model-identity", "numeric-scope", "missing-blob", "corrupt-blob", "malformed",
75
+ "fingerprint", "origin-edits")
76
+ _EDIT_KEYS = {"port", "op", "value", "mask", "mask_count", "selection", "cell", "dose", "origin"}
77
+ _CELL_KEYS = {"layer", "tensor", "rows", "kv", "d", "timing", "staged_at"}
78
+
79
+
80
+ class RecipeError(Refused):
81
+ """A recipe cannot be built, read or replayed; ``code`` is one of ``CODES``."""
82
+
83
+ def __init__(self, code, message):
84
+ if code not in CODES:
85
+ raise ValueError(f"unknown recipe refusal code {code!r}")
86
+ self.code = code
87
+ super().__init__(message)
88
+
89
+
90
+ def _malformed(message):
91
+ return RecipeError("malformed", f"malformed replay recipe: {message}")
92
+
93
+
94
+ # --------------------------------------------------------------------------- build
95
+
96
+ def _put(store, tensor, sha256, label):
97
+ """Store one tensor; its payload digest must be the one the checkpoint recorded."""
98
+ stored = store.put_tensor(tensor)
99
+ if stored["sha256"] != sha256:
100
+ raise _malformed(f"{label} digest {sha256[:12]} does not match the tensor held for it")
101
+ return tensor_pointer(stored["ref"], sha256=stored["sha256"], shape=stored["shape"],
102
+ dtype=stored["dtype"])
103
+
104
+
105
+ def _edit(manifest, tensors, store):
106
+ """A checkpoint edit manifest as a recipe edit; its tensors go to ``store``."""
107
+ described = manifest["value"]
108
+ if described["kind"] == "scalar":
109
+ value = {"kind": "scalar", "value": num(described["value"], "supplied")}
110
+ else:
111
+ sha = described["sha256"]
112
+ if sha not in tensors:
113
+ raise _malformed(f"edit value {sha[:12]} at {manifest['port']} is not held")
114
+ value = _put(store, tensors[sha], sha, f"edit value at {manifest['port']}")
115
+ out = {"port": manifest["port"], "op": manifest["op"], "value": value}
116
+ if "selection" in manifest:
117
+ out["selection"] = manifest["selection"]
118
+ if "cell" in manifest:
119
+ out["cell"] = dict(manifest["cell"])
120
+ if "dose" in manifest:
121
+ out["dose"] = num(manifest["dose"], "supplied")
122
+ if "origin" in manifest:
123
+ out["origin"] = dict(manifest["origin"])
124
+ if "mask_sha256" in manifest:
125
+ sha = manifest["mask_sha256"]
126
+ if sha not in tensors:
127
+ raise _malformed(f"edit mask {sha[:12]} at {manifest['port']} is not held")
128
+ out["mask"] = _put(store, tensors[sha], sha, f"edit mask at {manifest['port']}")
129
+ out["mask_count"] = int(manifest["mask_count"])
130
+ return out
131
+
132
+
133
+ def from_checkpoint(checkpoint, *, tokens, layers, tensors, store):
134
+ """Seal the recipe of a ``Run.checkpoint()``.
135
+
136
+ ``tokens`` are the run's token ids, ``layers`` the model's layer count, ``tensors`` maps the
137
+ payload sha256 of every edit value and mask the checkpoint names to its tensor
138
+ (``Run.edit_tensors()``), ``store`` the project ``LocalStore`` the tensors are written to.
139
+ Raises ``RecordError`` when the recipe would hold an array or exceed 64 KiB.
140
+ """
141
+ if checkpoint.get("schema") != CHECKPOINT_SCHEMA:
142
+ raise _malformed("not an mdb engine checkpoint")
143
+ tokens = [int(t) for t in tokens]
144
+ if digest(tokens) != checkpoint["prompt_sha256"]:
145
+ raise _malformed("the token ids are not the checkpoint's prompt")
146
+ prefill = checkpoint.get("prefill", len(tokens) - 1)
147
+ if type(prefill) is not int or not 0 <= prefill < len(tokens):
148
+ raise _malformed(f"prefill {prefill!r} is not a row count in 0..{len(tokens) - 1}")
149
+ if len(tokens) > MAX_INLINE_ITEMS:
150
+ import numpy as np
151
+
152
+ stored = store.put_tensor(np.asarray(tokens, dtype=np.int64))
153
+ tokens = tensor_pointer(stored["ref"], sha256=stored["sha256"], shape=stored["shape"],
154
+ dtype=stored["dtype"])
155
+ body = {
156
+ "schema": SCHEMA,
157
+ "name": checkpoint.get("name"),
158
+ "model_identity": checkpoint["model_identity"],
159
+ "layers": int(layers),
160
+ "tokens": tokens,
161
+ "prompt_sha256": checkpoint["prompt_sha256"],
162
+ "prefill": prefill,
163
+ "numeric_scope": dict(checkpoint.get("numeric_scope") or {}),
164
+ "lookahead": checkpoint["lookahead"],
165
+ "transitions": [{"transition": int(entry["transition"]), "layer": int(entry["layer"]),
166
+ "edits": [_edit(m, tensors, store) for m in entry["edits"]]}
167
+ for entry in checkpoint["path_edits"]],
168
+ "staged": [_edit(m, tensors, store) for m in checkpoint["edits"]],
169
+ "target": {"where": checkpoint["where"], "transitions": int(checkpoint["transitions"]),
170
+ "port": checkpoint["port"]},
171
+ "cut": checkpoint["cut"],
172
+ }
173
+ return seal(body)
174
+
175
+
176
+ def seal(body):
177
+ """Bound and seal a recipe body (``fingerprint`` is recomputed); raises ``RecordError``."""
178
+ body = check_bounded({k: v for k, v in dict(body).items() if k != "fingerprint"},
179
+ "replay recipe", max_bytes=MAX_RECORD_BYTES)
180
+ return verify({**body, "fingerprint": index.recipe_fingerprint(body)})
181
+
182
+
183
+ # --------------------------------------------------------------------------- read
184
+
185
+ def _check_edit(edit, label):
186
+ if not isinstance(edit, Mapping) or not {"port", "op", "value"} <= set(edit) <= _EDIT_KEYS:
187
+ raise _malformed(f"{label} is {{port, op, value, mask?, mask_count?, selection?, cell?, "
188
+ "dose?, origin?}")
189
+ if "cell" in edit and (not isinstance(edit["cell"], Mapping)
190
+ or set(edit["cell"]) != _CELL_KEYS):
191
+ raise _malformed(f"{label} cell is {{{', '.join(sorted(_CELL_KEYS))}}}")
192
+ if "dose" in edit and "cell" not in edit:
193
+ raise _malformed(f"{label}: a dose belongs to a state-cell edit")
194
+ if "dose" in edit and check_num(edit["dose"], f"{label} dose")["authority"] != "supplied":
195
+ raise _malformed(f"{label} dose is a supplied number")
196
+ if "origin" in edit and not isinstance(edit["origin"], Mapping):
197
+ raise _malformed(f"{label} origin is an object")
198
+ value = edit["value"]
199
+ if isinstance(value, Mapping) and value.get("kind") == "scalar":
200
+ if set(value) != {"kind", "value"}:
201
+ raise _malformed(f"{label} scalar is {{kind, value}}")
202
+ claim = check_num(value["value"], f"{label} value")
203
+ if claim["authority"] != "supplied":
204
+ raise _malformed(f"{label} scalar is a supplied number")
205
+ else:
206
+ validate_tensor_pointer(value)
207
+ if ("mask" in edit) != ("mask_count" in edit):
208
+ raise _malformed(f"{label} carries a mask and its count together")
209
+ if "mask" in edit:
210
+ validate_tensor_pointer(edit["mask"])
211
+ if edit["mask"]["dtype"] != "bool":
212
+ raise _malformed(f"{label} mask is a bool tensor")
213
+
214
+
215
+ def verify(recipe):
216
+ """Check a recipe's fields, bounds, seal and edits; returns it or raises ``RecipeError``."""
217
+ if not isinstance(recipe, Mapping) or not (
218
+ set(FIELDS) - set(_OPTIONAL) <= set(recipe) <= set(FIELDS)):
219
+ raise _malformed("fields are " + ", ".join(FIELDS))
220
+ if recipe["schema"] != SCHEMA:
221
+ raise _malformed(f"schema must be {SCHEMA!r}")
222
+ if "prefill" in recipe and (type(recipe["prefill"]) is not int or recipe["prefill"] < 0):
223
+ raise _malformed("prefill is a nonnegative row count")
224
+ try:
225
+ bounded = check_bounded(dict(recipe), "replay recipe", max_bytes=MAX_RECORD_BYTES)
226
+ body = {k: v for k, v in bounded.items() if k != "fingerprint"}
227
+ if recipe["fingerprint"] != index.recipe_fingerprint(body):
228
+ raise _malformed("its seal differs from its content")
229
+ if not isinstance(recipe["tokens"], list):
230
+ validate_tensor_pointer(recipe["tokens"])
231
+ if not isinstance(recipe["transitions"], list) or not isinstance(recipe["staged"], list):
232
+ raise _malformed("transitions and staged are lists")
233
+ for n, entry in enumerate(recipe["transitions"]):
234
+ if set(entry) != {"transition", "layer", "edits"}:
235
+ raise _malformed("a transition is {transition, layer, edits}")
236
+ for i, edit in enumerate(entry["edits"]):
237
+ _check_edit(edit, f"transitions[{n}].edits[{i}]")
238
+ for i, edit in enumerate(recipe["staged"]):
239
+ _check_edit(edit, f"staged[{i}]")
240
+ if set(recipe["target"]) != {"where", "transitions", "port"}:
241
+ raise _malformed("target is {where, transitions, port}")
242
+ except RecordError as error:
243
+ raise _malformed(str(error)) from error
244
+ return dict(recipe)
245
+
246
+
247
+ def _manifest(edit):
248
+ """A recipe edit as the checkpoint edit manifest it came from."""
249
+ value = edit["value"]
250
+ if value["kind"] == "scalar":
251
+ described = {"kind": "scalar", "value": value["value"]["value"]}
252
+ else:
253
+ described = {"kind": "tensor", "sha256": value["sha256"], "shape": list(value["shape"]),
254
+ "dtype": "torch." + value["dtype"]}
255
+ out = {"port": edit["port"], "op": edit["op"], "value": described}
256
+ if "cell" in edit:
257
+ out["cell"] = dict(edit["cell"])
258
+ if "dose" in edit:
259
+ out["dose"] = edit["dose"]["value"]
260
+ if "selection" in edit:
261
+ out["selection"] = edit["selection"]
262
+ if "origin" in edit:
263
+ out["origin"] = dict(edit["origin"])
264
+ if "mask" in edit:
265
+ out.update(mask_sha256=edit["mask"]["sha256"], mask_count=edit["mask_count"],
266
+ mask_shape=list(edit["mask"]["shape"]))
267
+ return out
268
+
269
+
270
+ def to_checkpoint(recipe):
271
+ """The ``Run.checkpoint()`` dict the recipe was sealed from (``Run.restore`` input)."""
272
+ recipe = verify(recipe)
273
+ target = recipe["target"]
274
+ out = {
275
+ "schema": CHECKPOINT_SCHEMA, "name": recipe["name"],
276
+ "model_identity": recipe["model_identity"], "prompt_sha256": recipe["prompt_sha256"],
277
+ "where": target["where"], "cut": recipe["cut"], "transitions": target["transitions"],
278
+ "port": target["port"], "lookahead": recipe["lookahead"],
279
+ "numeric_scope": dict(recipe["numeric_scope"]),
280
+ "edits": [_manifest(e) for e in recipe["staged"]],
281
+ "path_edits": [{"transition": t["transition"], "layer": t["layer"],
282
+ "edits": [_manifest(e) for e in t["edits"]]}
283
+ for t in recipe["transitions"]],
284
+ }
285
+ if "prefill" in recipe: # absent: an older recipe, the default split
286
+ out["prefill"] = recipe["prefill"]
287
+ return out
288
+
289
+
290
+ def tensor_pointers(recipe):
291
+ """Every tensor pointer of the recipe's edits (values and masks), in recipe order."""
292
+ edits = [e for t in recipe["transitions"] for e in t["edits"]] + list(recipe["staged"])
293
+ out = []
294
+ for edit in edits:
295
+ if edit["value"]["kind"] == "tensor":
296
+ out.append(edit["value"])
297
+ if "mask" in edit:
298
+ out.append(edit["mask"])
299
+ return out
300
+
301
+
302
+ def _load(pointer, store, label):
303
+ try:
304
+ return resolve_tensor(pointer, store=store, framework="torch")
305
+ except Unresolved as error:
306
+ code = "corrupt-blob" if error.refused else "missing-blob"
307
+ raise RecipeError(code, f"{label} blob {pointer['ref']} (payload sha256 "
308
+ f"{pointer['sha256'][:12]}): {error.reason}") from error
309
+
310
+
311
+ def load_tensors(recipe, store):
312
+ """``{payload sha256: torch tensor}`` of every edit value and mask, each verified against
313
+ the store's file digest and the recipe's payload digest. A missing blob is
314
+ ``RecipeError("missing-blob")``, a corrupt one ``RecipeError("corrupt-blob")``, each naming
315
+ the blob."""
316
+ return {p["sha256"]: _load(p, store, "edit tensor") for p in tensor_pointers(recipe)}
317
+
318
+
319
+ def load_tokens(recipe, store):
320
+ """The recipe's token ids (read from the store when held by pointer), digest-checked."""
321
+ tokens = recipe["tokens"]
322
+ if not isinstance(tokens, list):
323
+ tokens = [int(t) for t in _load(tokens, store, "token ids").reshape(-1).tolist()]
324
+ if digest(tokens) != recipe["prompt_sha256"]:
325
+ raise _malformed("its token ids differ from its prompt_sha256")
326
+ return tokens
327
+
328
+
329
+ def check_binding(recipe, *, model_identity, numeric_scope):
330
+ """Refuse a replay on another model identity or under another numeric scope (a cut binds
331
+ both, so the replay could not reproduce the recorded fingerprint)."""
332
+ if _canonical(recipe["model_identity"]) != _canonical(model_identity):
333
+ raise RecipeError("model-identity",
334
+ f"recipe {recipe['fingerprint'][:12]} was recorded on model identity "
335
+ f"{str(recipe['model_identity'])[:16]}; the attached model is "
336
+ f"{str(model_identity)[:16]} (wrong model identity)")
337
+ recorded, mine = dict(recipe["numeric_scope"]), dict(numeric_scope or {})
338
+ differing = sorted(k for k in set(recorded) | set(mine) if recorded.get(k) != mine.get(k))
339
+ if differing:
340
+ detail = ", ".join(f"{k}: recipe {recorded.get(k)!r}, this process {mine.get(k)!r}"
341
+ for k in differing)
342
+ raise RecipeError("numeric-scope",
343
+ f"recipe {recipe['fingerprint'][:12]} was recorded under another "
344
+ f"numeric scope ({detail}); set the same scope and re-attach")
345
+
346
+
347
+ def fingerprint_mismatch(recipe, expected, reached):
348
+ """The refusal for a replay of ``recipe`` that reached cut ``reached``, not ``expected``."""
349
+ return RecipeError("fingerprint",
350
+ f"replaying recipe {recipe['fingerprint'][:12]} reached cut {reached[:12]}, "
351
+ f"not the recorded {expected[:12]} (fingerprint mismatch)")
352
+
353
+
354
+ def edit_ref(manifest):
355
+ """The reference of one edit in an ``@cut+edit`` origin: the sha256 of its checkpoint
356
+ manifest (``Run.origin_of``'s ``edits`` items; port, op, the value or its payload digest,
357
+ mask, selection, cell, dose, origin) as canonical JSON. Any differing field gives another
358
+ reference. 64 hex characters, so it is a valid origin edit id."""
359
+ if not isinstance(manifest, Mapping) or not {"port", "op", "value"} <= set(manifest):
360
+ raise _malformed("an edit manifest is {port, op, value, ...}")
361
+ return digest(dict(manifest))
362
+
363
+
364
+ def occurrence_checkpoint(recipe, *, where, cut, event, port, edits=None):
365
+ """The ``Run.checkpoint()`` whose cursor sits on one occurrence of the recipe's history.
366
+
367
+ ``cut``/``event`` are the boundary cut and transition count the occurrence is read at or
368
+ computed from (``Run.origin_of``), ``port`` its port inside that layer (None for a boundary
369
+ value). The edits staged there are the recipe's edits of transition ``event`` (its staged
370
+ edits when ``event`` is the target's transition); the path is every recorded transition
371
+ before ``event``. Restoring it and reading at the cursor reproduces the occurrence.
372
+
373
+ ``edits``: the ordered edit references of an ``@cut+edit`` origin (``edit_ref``). When given,
374
+ the staged edits must have exactly those references, else ``RecipeError("origin-edits")``:
375
+ the recipe would compute the value under other edits than it was read under.
376
+ """
377
+ recipe = verify(recipe)
378
+ target = recipe["target"]["transitions"]
379
+ if event > target:
380
+ raise _malformed(f"event {event} is past the recipe target (transition {target})")
381
+ layer = (recipe["staged"] if event == target else next(
382
+ (t["edits"] for t in recipe["transitions"] if t["transition"] == event), []))
383
+ out = to_checkpoint(recipe)
384
+ out.update(name=None, where=where, cut=cut, transitions=event, port=port,
385
+ edits=[_manifest(e) for e in layer] if port is not None else [],
386
+ path_edits=[p for p in out["path_edits"] if p["transition"] < event])
387
+ if edits is not None:
388
+ mine = [edit_ref(m) for m in out["edits"]]
389
+ if mine != list(edits):
390
+ raise RecipeError(
391
+ "origin-edits",
392
+ f"recipe {recipe['fingerprint'][:12]} applies {len(mine)} edit(s) at transition "
393
+ f"{event} ({', '.join(r[:12] for r in mine) or 'none'}); the address origin "
394
+ f"names {len(edits)} ({', '.join(str(r)[:12] for r in edits) or 'none'}) (the "
395
+ "edits differ: tampered, or another recipe)")
396
+ return out
397
+
398
+
399
+ # --------------------------------------------------------------------------- project
400
+
401
+ CHECKPOINT = declare_kind("checkpoint", required=("name", "recipe", "where", "cut", "port"),
402
+ plain_numeric=("transitions", "serial"))
403
+
404
+
405
+ def save(project, session_id, recipe):
406
+ """Verify and index a recipe in the project; returns its id (its fingerprint)."""
407
+ return index.put_recipe(project, session_id, verify(recipe))
408
+
409
+
410
+ def load(project, recipe_id):
411
+ """A recipe from the project index, seal and content verified."""
412
+ return verify(index.get_recipe(project, recipe_id))
413
+
414
+
415
+ def checkpoints(project, session_id):
416
+ """The session's checkpoint records (verified v2 records), oldest first."""
417
+ rows = index.list_records(project, session_id, kind=CHECKPOINT.name, strict=True)
418
+ return sorted(rows, key=lambda r: r["body"]["serial"])
419
+
420
+
421
+ def record_checkpoint(project, session_id, recipe, *, run=None):
422
+ """Index a named checkpoint of a saved recipe and move the session cursor to it.
423
+
424
+ The record (kind ``checkpoint``) holds the name, the recipe id, the target and a serial
425
+ number, so re-saving a name later is a newer record even when the content repeats.
426
+ """
427
+ row = project.session(session_id)
428
+ target = recipe["target"]
429
+ record = seal_record(
430
+ session_id=session_id, kind=CHECKPOINT.name, model_identity=json.loads(row["identity"]),
431
+ execution=json.loads(row["execution"]), authority="measured",
432
+ body={"name": recipe["name"], "recipe": recipe["fingerprint"], "where": target["where"],
433
+ "cut": recipe["cut"], "transitions": target["transitions"], "port": target["port"],
434
+ "serial": len(checkpoints(project, session_id))}, run=run)
435
+ identifier = index.put_record(project, record)
436
+ index.set_cursor(project, session_id, identifier)
437
+ return record
438
+
439
+
440
+ def find_checkpoint(project, name, *, session_id=None):
441
+ """The newest checkpoint record named ``name``: in ``session_id`` first, else in exactly one
442
+ other session of the project. None when no session has it; ``Refused`` when several other
443
+ sessions do (name the session to choose)."""
444
+ def newest(sid):
445
+ named = [r for r in checkpoints(project, sid) if r["body"]["name"] == name]
446
+ return named[-1] if named else None
447
+
448
+ if session_id is not None:
449
+ found = newest(session_id)
450
+ if found is not None:
451
+ return found
452
+ others = [r["session_id"] for r in project.sessions() if r["session_id"] != session_id]
453
+ found = [record for record in map(newest, others) if record is not None]
454
+ if len(found) > 1:
455
+ raise Refused(f"checkpoint {name!r} exists in sessions "
456
+ + ", ".join(r["session_id"] for r in found) + "; attach with session=")
457
+ return found[0] if found else None