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,1265 @@
1
+ """Checkpoints: a run's state at a cut as content-addressed pointers to its tensors.
2
+
3
+ One checkpoint object serves ``Run.checkpoint(durable=...)``, ``Run.dump`` / ``Debugger.run_from``
4
+ (the core files of mdb 0.2.2) and ``Debugger.checkpoint`` / ``restart`` (a project):
5
+
6
+ * **What is stored.** The native ``StateCut`` of every trail mark kept (``history``), slot by
7
+ slot: per layer the key/value cache, the hidden carrier of a row in flight (a cut inside a row
8
+ is a layer boundary ``t<r>.L<i>.h_out``), logits, the sampled token, the stepped-prompt slot,
9
+ plus the cut's boundary, execution point, surface and **parent fingerprint**. Each tensor is
10
+ stored as parts (the block form the engine already holds: the prefix cache once, then one
11
+ part per appended row), each part addressed by the sha256 of its bytes; identical parts are
12
+ stored once. The cursor (a port inside the pending layer and the edits staged there), the
13
+ committed edits of every transition kept, the edit and mask tensors (including those of the
14
+ path before the first kept mark), the active holds (described, not re-armed), the run's
15
+ recipe (``Run.checkpoint()``: provenance and the input of ``verify``) and optional captured
16
+ values complete it.
17
+ * **Where.** A self-contained file (``torch.save`` of plain data, so ``weights_only`` loading
18
+ works) or a project (``mdb.core.project.Project``): every part a tensor blob of its store, the
19
+ document a JSON blob, the record indexed under the session. A checkpoint is addressed by its
20
+ file path or by its record id (a unique prefix of at least 8 hex digits).
21
+ * **Record.** A sealed ``checkpoint-state`` record (schema ``mdb-record-v3``) holding the
22
+ document's sha256, every part's sha256, the cut fingerprints, the prompt digest, the
23
+ procedure, the lineage (``root``: ``prompt`` when the cut's fingerprints chain back to a run
24
+ of the prompt; ``checkpoint`` when they chain back to a foreign root, a replica or a legacy
25
+ core file) and custody.
26
+ * **Rehydration** (``Checkpoint.run``) rebuilds every kept cut from its parts, recomputes its
27
+ fingerprint from the content and refuses one that differs from the record; the run's trail is
28
+ the kept marks with their committed edits and the cursor is put back (port, staged edits).
29
+ Nothing before the cursor is recomputed; moving to a port inside the pending layer is one
30
+ probe of that layer, exactly as on the source run. The fingerprints are the source run's,
31
+ so checkpoints transfer between the source and the reloaded run in both directions.
32
+ * **Honest identity.** A cut's fingerprint is the sha256 of the model identity, the execution
33
+ contract (dtype, device, numeric scope, library versions), the state content, the execution
34
+ point and the parent fingerprint. Rehydration recomputes it from the stored content and the
35
+ recorded parent, so a changed tensor, another model or another execution never verifies. The
36
+ parent is recorded, not re-derived: ``verify`` (``run(..., verify=True)``) replays the recipe
37
+ from the lineage root (the prompt) and checks it reaches the same fingerprint (measured).
38
+ * **Replicas.** Another dtype, device or weights of the same shape is refused unless
39
+ ``replica=True``: then the cursor's state (cast once to the target dtype) roots a new lineage,
40
+ labelled a replica, and ``run.core_check`` compares the captured values (``null_check``).
41
+
42
+ Structural refusals: another family, layer count, KV heads, head_dim or vocabulary.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import hashlib
48
+ import json
49
+ import time
50
+ from collections.abc import Mapping
51
+ from pathlib import Path
52
+ from typing import Any
53
+
54
+ import torch
55
+
56
+ # the state document, a self-contained file, the record kind; their JSON Schemas:
57
+ # mdb.core.checkpoint_schema (docs/CHECKPOINT-SCHEMA.md)
58
+ from mdb.core.checkpoint_schema import DOCUMENT as SCHEMA
59
+ from mdb.core.checkpoint_schema import FILE as FILE_SCHEMA
60
+ from mdb.core.checkpoint_schema import FILE_KEYS, KIND
61
+ from mdb.core.checkpoint_store import find_record # (lives in core: stores use it)
62
+
63
+ from .ports import tensor_digest
64
+
65
+ HISTORIES = ("cursor", "row", "root")
66
+ _FILE_KEYS = set(FILE_KEYS)
67
+ _SHAS_PER_TEXT = 60 # packed sha256 hex per record string (<= 4 KiB)
68
+ _MAX_INLINE_SHAS = 60 * _SHAS_PER_TEXT # beyond: the record holds their digest only (the
69
+ # sealed document lists them)
70
+
71
+
72
+ def shape_of(adapter: Any) -> dict[str, Any]:
73
+ return {"family": adapter.spec.model_type, "layers": int(adapter.layers),
74
+ "kv_heads": int(adapter.num_kv_heads), "head_dim": int(adapter.head_dim),
75
+ "vocab": int(adapter.vocab_size)}
76
+
77
+
78
+ def check_shape(want: Mapping[str, Any], adapter: Any, what: str = "checkpoint") -> None:
79
+ have = shape_of(adapter)
80
+ differ = [k for k in want if want[k] != have.get(k)]
81
+ if differ:
82
+ raise ValueError(f"{what} of another model shape: " + ", ".join(
83
+ f"{k} {want[k]} vs {have.get(k)}" for k in differ))
84
+
85
+
86
+ def _canonical(value: Any) -> str:
87
+ return json.dumps(value, sort_keys=True, separators=(",", ":"))
88
+
89
+
90
+ def _sha_text(text: str) -> str:
91
+ return hashlib.sha256(text.encode()).hexdigest()
92
+
93
+
94
+ def _dtype_name(t: torch.Tensor) -> str:
95
+ return str(t.dtype).removeprefix("torch.")
96
+
97
+
98
+ def _plain(value: Any, what: str) -> Any:
99
+ """``value`` as plain JSON data (a JSON round trip), refusing anything that is not."""
100
+ try:
101
+ return json.loads(json.dumps(value))
102
+ except (TypeError, ValueError) as error:
103
+ raise ValueError(f"{what} is not plain data: {error}") from error
104
+
105
+
106
+ def aligned_blocks(length: int) -> list[tuple[int, int]]:
107
+ """``[start, end)`` row blocks of ``0..length``: power-of-two sizes, largest first, each
108
+ aligned to its size (``length`` 100 is 64 + 32 + 4): at most ``log2(length) + 1`` blocks,
109
+ and a longer run of the same rows shares every block but the last few."""
110
+ out, start = [], 0
111
+ size = 1 << max(length.bit_length() - 1, 0)
112
+ while start < length:
113
+ while start + size > length:
114
+ size >>= 1
115
+ out.append((start, start + size))
116
+ start += size
117
+ return out
118
+
119
+
120
+ class _Writer:
121
+ """Collects the parts (content-addressed) and the tensor descriptors of one checkpoint."""
122
+
123
+ def __init__(self, store: Any = None):
124
+ self.store = store
125
+ self.parts: list[dict[str, Any]] = []
126
+ self.blobs: dict[str, torch.Tensor] = {}
127
+ self._part_index: dict[str, int] = {}
128
+ self._part_seen: dict[int, tuple[Any, int]] = {}
129
+ self.tensors: list[dict[str, Any]] = []
130
+ self._seen: dict[Any, tuple[Any, int]] = {}
131
+ self._keep: list[Any] = [] # chunks named by part memo keys stay alive meanwhile
132
+ self.bytes = 0
133
+
134
+ def part(self, t: torch.Tensor, memo: Any = None) -> int:
135
+ key0 = memo if memo is not None else id(t)
136
+ seen = self._part_seen.get(key0)
137
+ if seen is not None and (memo is not None or seen[0] is t):
138
+ return seen[1]
139
+ flat = t.detach().to("cpu").contiguous()
140
+ sha = tensor_digest(flat)
141
+ key = part_key(sha, _dtype_name(flat), list(flat.shape))
142
+ index = self._part_index.get(key)
143
+ if index is None:
144
+ pointer: dict[str, Any] = {"sha256": sha, "shape": list(flat.shape),
145
+ "dtype": _dtype_name(flat)}
146
+ if self.store is not None:
147
+ pointer["ref"] = self.store.put_tensor(flat)["ref"]
148
+ else:
149
+ # a compact copy: torch.save of a view would write its whole storage
150
+ self.blobs[key] = flat.clone(memory_format=torch.contiguous_format)
151
+ self.bytes += flat.numel() * flat.element_size()
152
+ self.parts.append(pointer)
153
+ index = self._part_index[key] = len(self.parts) - 1
154
+ self._part_seen[key0] = (t, index)
155
+ return index
156
+
157
+ def tensor(self, value: Any) -> int:
158
+ """The descriptor index of a tensor or ``saturn.core.Blocks`` (one per held
159
+ tensor: the same chunks give the same index)."""
160
+ from saturn.core import Blocks
161
+
162
+ if not isinstance(value, Blocks):
163
+ value = Blocks((value,), None, tuple(value.shape), tuple(value.stride()),
164
+ value.dtype)
165
+ key = (value.dim, tuple(id(c) for c in value.chunks))
166
+ seen = self._seen.get(key)
167
+ if seen is not None:
168
+ return seen[1]
169
+ chunks, axis = value.chunks, value.dim
170
+ if axis is None:
171
+ parts = [self.part(chunks[0])]
172
+ else:
173
+ parts = self._aligned(chunks, axis, int(value.shape[axis]))
174
+ descriptor = {"dtype": str(value.dtype).removeprefix("torch."),
175
+ "shape": list(value.shape), "stride": list(value.stride), "axis": axis,
176
+ "parts": parts}
177
+ self.tensors.append(descriptor)
178
+ index = len(self.tensors) - 1
179
+ self._seen[key] = (value, index) # keeps the chunks alive while ids are keys
180
+ return index
181
+
182
+ def _aligned(self, chunks: tuple[torch.Tensor, ...], axis: int, length: int) -> list[int]:
183
+ """Parts of the rows ``0..length`` held as ``chunks`` along ``axis``: the first chunk
184
+ whole (the prefix cache every cut of the run shares; for a rehydrated run, the part it
185
+ was rehydrated from), then the rows after it in ``aligned_blocks`` blocks counted from
186
+ its end, so a cut one row later shares every part but the last few. A block inside one
187
+ chunk is hashed once per chunk."""
188
+ offsets, at = [], 0
189
+ for chunk in chunks:
190
+ offsets.append(at)
191
+ at += int(chunk.shape[axis])
192
+ base = int(chunks[0].shape[axis])
193
+ blocks = ([(0, base)] if base else []) + [
194
+ (base + a, base + b) for a, b in aligned_blocks(length - base)]
195
+ out = []
196
+ for start, end in blocks:
197
+ inside = [(c, o) for c, o in zip(chunks, offsets)
198
+ if o <= start and end <= o + int(c.shape[axis])]
199
+ if inside:
200
+ chunk, offset = inside[0]
201
+ piece = chunk.narrow(axis, start - offset, end - start)
202
+ out.append(self.part(piece, memo=(id(chunk), start - offset, end - start)))
203
+ self._keep.append(chunk)
204
+ continue
205
+ pieces = [c.narrow(axis, max(start, o) - o, min(end, o + int(c.shape[axis]))
206
+ - max(start, o))
207
+ for c, o in zip(chunks, offsets)
208
+ if o < end and start < o + int(c.shape[axis])]
209
+ out.append(self.part(torch.cat(pieces, dim=axis)))
210
+ return out
211
+
212
+ def encode(self, value: Any) -> Any:
213
+ from saturn.core import Blocks
214
+
215
+ if isinstance(value, (torch.Tensor, Blocks)):
216
+ return {"kind": "tensor", "t": self.tensor(value)}
217
+ if isinstance(value, Mapping):
218
+ if any(not isinstance(k, str) for k in value):
219
+ raise ValueError("a checkpoint state mapping needs string keys")
220
+ return {"kind": "mapping", "items": {k: self.encode(v) for k, v in value.items()}}
221
+ if isinstance(value, tuple):
222
+ return {"kind": "tuple", "items": [self.encode(v) for v in value]}
223
+ if isinstance(value, list):
224
+ return {"kind": "list", "items": [self.encode(v) for v in value]}
225
+ if value is None or type(value) in (bool, int, float, str):
226
+ return {"kind": "scalar", "value": value}
227
+ raise ValueError(f"unsupported checkpoint state value: {type(value).__name__}")
228
+
229
+
230
+ def part_key(sha: str, dtype: str, shape: list[int]) -> str:
231
+ return f"{sha}.{dtype}.{'x'.join(str(int(s)) for s in shape) or 'scalar'}"
232
+
233
+
234
+ def _packed(shas: list[str]) -> list[str]:
235
+ return ["".join(shas[i:i + _SHAS_PER_TEXT]) for i in range(0, len(shas), _SHAS_PER_TEXT)]
236
+
237
+
238
+ def _unpacked(texts: list[str]) -> list[str]:
239
+ return [t[i:i + 64] for t in texts for i in range(0, len(t), 64)]
240
+
241
+
242
+ # --------------------------------------------------------------------------- write
243
+
244
+ def _mark_address(run: Any, index: int) -> str:
245
+ return run.address(run._mark_key(run._trail[index]))
246
+
247
+
248
+ def _recipe_at(run: Any, index: int) -> dict[str, Any]:
249
+ """``Run.checkpoint()`` of trail mark ``index`` (the cursor's own when it is the last)."""
250
+ from saturn.values import digest
251
+
252
+ from .run import CHECKPOINT_SCHEMA
253
+
254
+ if index == len(run._trail) - 1:
255
+ return run.checkpoint(pin=False)
256
+ mark = run._trail[index]
257
+ body = {"schema": CHECKPOINT_SCHEMA, "name": None,
258
+ "model_identity": run.adapter.model_identity, "prompt_sha256": digest(run.tokens),
259
+ "prefill": run.prefill, "where": _mark_address(run, index), "cut": mark.fingerprint,
260
+ "transitions": mark.transitions, "port": None, "lookahead": run.lookahead,
261
+ "numeric_scope": run._numeric_scope(), "edits": [],
262
+ "path_edits": run._path_manifest(index)}
263
+ supplied = [[m.transitions, m.supplied] for m in [*run._ancestry, *run._trail[:index]]
264
+ if m.supplied is not None]
265
+ if supplied:
266
+ body["supplied"] = supplied
267
+ return body
268
+
269
+
270
+ def _mark_entry(mark: Any, committed: bool) -> dict[str, Any]:
271
+ """A trail mark as plain data: its fingerprint and place and, when the transition after it
272
+ was committed (``committed``), that transition's edits, cells, records and fed token."""
273
+ entry: dict[str, Any] = {
274
+ "fingerprint": mark.fingerprint, "transitions": mark.transitions, "row": mark.row,
275
+ "label": mark.label, "phase": mark.phase, "layer": mark.layer,
276
+ "supplied": mark.supplied if committed else None, "cut": None,
277
+ "edits": [], "cells": [], "fired": [], "cell_fired": []}
278
+ if committed:
279
+ entry["edits"] = [e.manifest() for e in mark.edits]
280
+ entry["cells"] = [c.manifest() for c in mark.cells]
281
+ entry["fired"] = _plain(list(mark.fired), "a fired edit record")
282
+ entry["cell_fired"] = _plain(list(mark.cell_fired), "a cell realisation record")
283
+ return entry
284
+
285
+
286
+ def _target_index(run: Any, at: str | None, row: int | None) -> int:
287
+ if at is not None and row is not None:
288
+ raise ValueError("give at= or row=, not both")
289
+ if row is not None:
290
+ at = f"t{int(row)}.start"
291
+ if at is None:
292
+ return len(run._trail) - 1
293
+ key = run.parse(at)
294
+ found = [i for i, m in enumerate(run._trail) if run._mark_key(m) == key]
295
+ if not found:
296
+ if key == run._key():
297
+ return len(run._trail) - 1
298
+ where = run.address(key)
299
+ if key < run._mark_key(run._trail[0]):
300
+ raise ValueError(f"the run holds no {where} boundary: it is before the run root "
301
+ f"{run.root}; save at a stop the run has reached")
302
+ raise ValueError(f"the run holds no {where} boundary (first stepped row "
303
+ f"t{run.first_row}, cursor {run.where}); save at the cursor or at a "
304
+ "boundary the run has passed (a row start, a layer boundary)")
305
+ return found[-1]
306
+
307
+
308
+ def _later_edits(run: Any, index: int) -> list[str]:
309
+ """What the run changed after trail mark ``index`` that a checkpoint there would not hold."""
310
+ out = [f"{run.address(run._mark_key(m))} ({len(m.edits) + len(m.cells)} committed)"
311
+ for m in run._trail[index:-1] if m.edits or m.cells]
312
+ if index != len(run._trail) - 1 and (run._edits or run._cells):
313
+ out.append(f"{run.where} ({len(run._edits) + len(run._cells)} staged)")
314
+ return out
315
+
316
+
317
+ def _first_kept(run: Any, index: int, history: str) -> int:
318
+ if history == "cursor":
319
+ return index
320
+ if history == "root":
321
+ return 0
322
+ row = run._trail[index].row
323
+ return min(i for i in range(index + 1) if run._trail[i].row == row)
324
+
325
+
326
+ def _holds(run: Any, writer: Any, from_row: int, holds: str) -> list[dict[str, Any]]:
327
+ """The active holds, each with the source values it reads from ``from_row`` on (tensor
328
+ indices), its source's cursor and cut, so a reloaded run re-arms it exactly; ``holds``
329
+ ``"drop"``: described and marked dropped (the reloaded run continues free)."""
330
+ from .holds import source_addresses
331
+ from .refs import run_label
332
+
333
+ out = []
334
+ for hold in run.hold_objects():
335
+ entry = {**hold.describe(), "cells": [dict(c) for c in hold.cells],
336
+ "dropped": holds == "drop"}
337
+ if holds == "rearm":
338
+ values = {}
339
+ for address in source_addresses(run, hold, from_row):
340
+ try:
341
+ value = hold.source.read(address)
342
+ except ValueError:
343
+ continue # not computed by the source (yet): refused on reach
344
+ values[address] = writer.tensor(value.detach().contiguous())
345
+ entry["snapshot"] = {"source": run_label(hold.source), "where": hold.source.where,
346
+ "cut": hold.source.checkpoint(pin=False)["cut"],
347
+ "tokens": list(hold.source.tokens), "values": values}
348
+ out.append(entry)
349
+ return out
350
+
351
+
352
+ def build(run: Any, *, store: Any = None, name: str | None = None, at: str | None = None,
353
+ row: int | None = None, history: str = "row",
354
+ capture: tuple[str, ...] | None = None, holds: str = "rearm"
355
+ ) -> tuple[dict[str, Any], _Writer, dict]:
356
+ """The state document of ``run`` at ``at`` (default: the cursor) and its writer (parts put
357
+ in ``store`` when given, else held for a file), plus the record body facts."""
358
+ if history not in HISTORIES:
359
+ raise ValueError(f"history is one of {', '.join(HISTORIES)}")
360
+ index = _target_index(run, at, row)
361
+ where = run.where if index == len(run._trail) - 1 else _mark_address(run, index)
362
+ later = _later_edits(run, index)
363
+ cursor_is_cut = index == len(run._trail) - 1
364
+ last = len(run.tokens) - 1
365
+ if capture is None:
366
+ computed = run.parse(f"t{last}.logits") <= run._key()
367
+ capture = (f"t{last}.logits",) if computed and not later else ()
368
+ elif later and capture:
369
+ raise ValueError(
370
+ f"the run changed its state after {where}: {', '.join(later)}; a captured value "
371
+ "would include those edits but the checkpoint holds the state at "
372
+ f"{where}; save at the cursor (at=None) or with capture=()")
373
+ if later and not cursor_is_cut:
374
+ raise ValueError(
375
+ f"the run edited after {where}: {', '.join(later)}; a checkpoint at {where} would "
376
+ "not hold those edits; save at the cursor (at=None, the default: a cut inside a "
377
+ "row is kept exactly) or before editing")
378
+ first = _first_kept(run, index, history)
379
+ stored = {first, index}
380
+ stored.update(i for i in range(first, index + 1)
381
+ if run._trail[i].label == "start" or run._trail[i].row == run._trail[index].row)
382
+ from saturn.core import cut_blocks
383
+
384
+ writer = _Writer(store)
385
+ ancestry = [_mark_entry(m, True) for m in [*run._ancestry, *run._trail[:first]]
386
+ if m.edits or m.cells or m.supplied is not None]
387
+ marks = []
388
+ for i in range(first, index + 1):
389
+ mark = run._trail[i]
390
+ entry = _mark_entry(mark, i < index)
391
+ if i in stored:
392
+ cut = run._cut_of(i)
393
+ if cut.fingerprint != mark.fingerprint:
394
+ raise RuntimeError(f"the cut of {_mark_address(run, i)} differs from its mark")
395
+ entry["cut"] = {
396
+ "boundary": cut.boundary, "parent": cut.parent,
397
+ "execution_point": _plain(dict(cut.execution_point or {}), "an execution point")
398
+ if cut.execution_point is not None else None,
399
+ "surface": _plain(dict(cut.surface), "a state surface")
400
+ if cut.surface is not None else None,
401
+ "payload": writer.encode(cut_blocks(cut))}
402
+ marks.append(entry)
403
+ tensors = run.edit_tensors()
404
+ edit_index = {sha: writer.tensor(t) for sha, t in sorted(tensors.items())}
405
+ captured = {}
406
+ for address in capture:
407
+ value = run.read(address).detach().to("cpu").contiguous().clone()
408
+ captured[address] = writer.tensor(value)
409
+ if holds not in ("rearm", "drop"):
410
+ raise ValueError("holds is 'rearm' (default) or 'drop'")
411
+ if run.hold_objects() and not cursor_is_cut and holds == "rearm":
412
+ raise ValueError(f"the run holds ports ({', '.join(h.name for h in run.hold_objects())})"
413
+ f" now, not necessarily at {where}: save at the cursor to re-arm them, "
414
+ "or pass holds='drop' (recorded)")
415
+ held = _holds(run, writer, run._trail[index].row, holds)
416
+ staged_edits = [e.manifest() for e in run._edits] if cursor_is_cut else []
417
+ staged_cells = [c.manifest() for c in run._cells] if cursor_is_cut else []
418
+ adapter = run.adapter
419
+ doc = {
420
+ "schema": SCHEMA, "name": name,
421
+ "model_identity": _plain(adapter.model_identity, "the model identity"),
422
+ "execution": _plain(dict(adapter.execution), "the execution contract"),
423
+ "shape": shape_of(adapter),
424
+ "prompt": list(run.tokens), "prefill": int(run.prefill), "lookahead": run.lookahead,
425
+ "history": history, "where": where,
426
+ "cursor": {"port": run._port if cursor_is_cut else None,
427
+ "edits": staged_edits, "cells": staged_cells},
428
+ "ancestry": ancestry,
429
+ "marks": marks,
430
+ "edit_tensors": edit_index,
431
+ "captured": captured,
432
+ "holds": held,
433
+ "recipe": _recipe_at(run, index),
434
+ "lineage": dict(run.lineage),
435
+ "parts": writer.parts, "tensors": writer.tensors,
436
+ }
437
+ doc = _plain(doc, "the checkpoint document")
438
+ facts = {"index": index, "first": first, "where": where, "stored": len(stored)}
439
+ return doc, writer, facts
440
+
441
+
442
+ def _body(run: Any, doc: dict[str, Any], writer: _Writer, facts: dict[str, Any],
443
+ document: dict[str, Any]) -> dict[str, Any]:
444
+ from saturn.values import digest
445
+
446
+ from mdb.core.custody import custody
447
+ from mdb.core.kinds import procedure
448
+ from mdb.core.records import num
449
+
450
+ cut_mark = doc["marks"][-1]
451
+ root_mark = doc["marks"][0]
452
+ shas = sorted({p["sha256"] for p in doc["parts"]})
453
+ recipe = doc["recipe"]
454
+ adapter = run.adapter
455
+ body = {
456
+ "schema": SCHEMA, "name": doc["name"], "where": doc["where"],
457
+ "port": doc["cursor"]["port"],
458
+ "cut": {"fingerprint": cut_mark["fingerprint"], "transitions": cut_mark["transitions"],
459
+ "row": cut_mark["row"], "label": cut_mark["label"]},
460
+ "root": {"fingerprint": root_mark["fingerprint"], "transitions": root_mark["transitions"],
461
+ "row": root_mark["row"], "label": root_mark["label"]},
462
+ "history": doc["history"], "marks": len(doc["marks"]), "stored_cuts": facts["stored"],
463
+ "prompt": {"tokens": list(run.tokens)[:64], "length": len(run.tokens),
464
+ "sha256": digest(list(run.tokens))},
465
+ "procedure": procedure(run),
466
+ "shape": doc["shape"],
467
+ "source": {"dtype": _dtype_name_of(adapter), "device": str(adapter.device)},
468
+ "lineage": doc["lineage"],
469
+ "recipe": {"sha256": _sha_text(_canonical(recipe)),
470
+ "path_edits": len(recipe["path_edits"]), "staged": len(recipe["edits"])},
471
+ "edited": bool(recipe["path_edits"] or recipe["edits"]),
472
+ "holds": [{"name": h["name"], "address": h["address"], "dropped": h["dropped"]}
473
+ for h in doc["holds"]][:64],
474
+ "captured": sorted(doc["captured"])[:64],
475
+ "document": document,
476
+ "tensors": {"count": len(shas),
477
+ "sha256": _packed(shas) if len(shas) <= _MAX_INLINE_SHAS else None,
478
+ "parts_sha256": _sha_text(_canonical(shas))},
479
+ "bytes": num(float(writer.bytes), "measured"),
480
+ "custody": custody("mdb-stepped"),
481
+ }
482
+ return body
483
+
484
+
485
+ def _dtype_name_of(adapter: Any) -> str:
486
+ return str(adapter.dtype).removeprefix("torch.")
487
+
488
+
489
+ def _session_id(run: Any) -> str:
490
+ from saturn.values import digest
491
+
492
+ from mdb.core.pointers import seal_digest
493
+
494
+ return "mdb-run:" + seal_digest({"model": run.adapter.model_identity,
495
+ "prompt": digest(run.tokens)})[:32]
496
+
497
+
498
+ def _seal(run: Any, body: dict[str, Any], session_id: str, execution: Any = None
499
+ ) -> dict[str, Any]:
500
+ from mdb.core.kinds import CHECKPOINT_STATE # noqa: F401 (declares the kind)
501
+ from mdb.core.records import seal_record
502
+
503
+ return seal_record(session_id=session_id, kind=KIND,
504
+ model_identity=run.adapter.model_identity,
505
+ execution=dict(run.adapter.execution if execution is None else execution),
506
+ authority="measured", body=body, run=run)
507
+
508
+
509
+ def save(run: Any, target: Any = None, *, project: Any = None, session_id: str | None = None,
510
+ name: str | None = None, at: str | None = None, row: int | None = None,
511
+ history: str = "row", capture: tuple[str, ...] | None = None,
512
+ holds: str = "rearm", store: Any = None) -> dict[str, Any]:
513
+ """Write a checkpoint of ``run`` at ``at`` (default: the cursor; ``row=K`` is
514
+ ``at="t<K>.start"``) and return its sealed record. ``target`` a path: a self-contained file;
515
+ ``project``: the project's store and index (``session_id``: the record's session, default
516
+ the project's session bound to this model when there is exactly one). ``store`` (or
517
+ ``[storage] checkpoint_store``; ``mdb.core.checkpoint_store``): a project checkpoint is
518
+ also published there (blobs the store has are not sent again; the record names the
519
+ store's URI); ``target`` a store URI (``s3://bucket/prefix``, ``file:///dir``) or a
520
+ ``Store``: written to the local cache project and published there. ``history``:
521
+ ``cursor`` (only the cut), ``row`` (default: every boundary of the cut's row before it, so
522
+ the reloaded run rewinds inside that row) or ``root`` (back to the run's root: row starts
523
+ as cuts, the boundaries between them replayed on demand). ``capture``: addresses whose
524
+ values are stored for a replica's ``null_check`` (default: the last prompt row's logits when
525
+ the run computed them). ``holds``: ``rearm`` (default) keeps each active hold with the
526
+ source values it reads from the checkpoint's row on, so the reloaded run continues held,
527
+ bit for bit; ``drop`` records the holds as dropped and the reloaded run continues free."""
528
+ from mdb.core import checkpoint_store as stores
529
+
530
+ if stores.is_store_uri(target):
531
+ if project is not None:
532
+ raise ValueError("save to a store or to a project, one of them")
533
+ store, target = target, None
534
+ project = stores.cache_project()
535
+ if session_id is None and not _bound_sessions(project, run):
536
+ session_id = _session_id(run)
537
+ project.open_session(session_id, model_identity=run.adapter.model_identity,
538
+ execution=dict(run.adapter.execution))
539
+ if (target is None) == (project is None):
540
+ raise ValueError("save to a path or to a project, one of them")
541
+ if target is not None and store is not None:
542
+ raise ValueError("a checkpoint file holds its own tensors: publish to a store from a "
543
+ "project (project=..., store=...)")
544
+ from mdb.core.bounded import put_json
545
+
546
+ started = time.perf_counter()
547
+ remote = stores.configured(store) if project is not None else None
548
+ local = project.store if project is not None else None
549
+ doc, writer, facts = build(run, store=local, name=name, at=at, row=row, history=history,
550
+ capture=capture, holds=holds)
551
+ text = _canonical(doc)
552
+ published = None
553
+ if project is not None:
554
+ session = session_id or _project_session(project, run)
555
+ document = put_json(doc, store=local)
556
+ document = {k: document[k] for k in ("state", "ref", "bytes", "sha256", "tensor")}
557
+ if document["sha256"] != _sha_text(text):
558
+ raise RuntimeError("the stored document differs from its canonical text")
559
+ row_ = project.session(session)
560
+ body = _body(run, doc, writer, facts, document)
561
+ if remote is not None:
562
+ body["store"] = {"uri": remote.uri} # where the blobs live (no credentials)
563
+ record = _seal(run, body, session, execution=json.loads(row_["execution"]))
564
+ from mdb.core import index
565
+
566
+ index.put_record(project, record)
567
+ if remote is not None:
568
+ published = stores.copy(record, doc, stores.ProjectStore(project), remote)
569
+ else:
570
+ document = {"state": "file", "bytes": len(text.encode()), "sha256": _sha_text(text)}
571
+ record = _seal(run, _body(run, doc, writer, facts, document),
572
+ session_id or _session_id(run))
573
+ torch.save({"schema": FILE_SCHEMA, "record": json.dumps(record), "document": text,
574
+ "tensors": writer.blobs}, str(target))
575
+ from mdb.core import custody
576
+
577
+ custody.emit_file(record, target)
578
+ record_seconds = time.perf_counter() - started
579
+ _LAST_WRITE.update(seconds=record_seconds, bytes=writer.bytes, parts=len(writer.parts),
580
+ published=published)
581
+ return record
582
+
583
+
584
+ _LAST_WRITE: dict[str, Any] = {}
585
+
586
+
587
+ def _bound_sessions(project: Any, run: Any) -> list[dict[str, Any]]:
588
+ return [s for s in project.sessions()
589
+ if s["model_identity"] == _plain(run.adapter.model_identity, "identity")
590
+ and _canonical(s["execution"]) == _canonical(_plain(dict(run.adapter.execution),
591
+ "execution"))]
592
+
593
+
594
+ def _project_session(project: Any, run: Any) -> str:
595
+ sessions = _bound_sessions(project, run)
596
+ if len(sessions) != 1:
597
+ raise ValueError(f"the project has {len(sessions)} sessions bound to this model and "
598
+ "execution; name one (session_id=)")
599
+ return sessions[0]["session_id"]
600
+
601
+
602
+ # --------------------------------------------------------------------------- read
603
+
604
+ class Checkpoint:
605
+ """A checkpoint read back (``load``): its record, document and parts, checked; tensors are
606
+ read and verified when first needed (``run``), and kept, so many runs share them."""
607
+
608
+ def __init__(self, record: dict[str, Any], doc: dict[str, Any], *, path: str | None = None,
609
+ blobs: dict[str, torch.Tensor] | None = None, store: Any = None):
610
+ self.record, self.doc, self.path = record, doc, path
611
+ self._blobs, self._store = blobs, store
612
+ self._parts: dict[int, torch.Tensor] = {}
613
+ self._blocks: dict[tuple[int, str], Any] = {}
614
+ self._cuts: dict[tuple[str, int], Any] = {}
615
+ self.prompt = [int(t) for t in doc["prompt"]]
616
+ self.split = int(doc["marks"][-1]["row"])
617
+ self.timings: dict[str, float] = {}
618
+
619
+ # identity ----------------------------------------------------------------------------
620
+
621
+ @property
622
+ def id(self) -> str:
623
+ return self.record["id"]
624
+
625
+ @property
626
+ def where(self) -> str:
627
+ return self.doc["where"]
628
+
629
+ @property
630
+ def fingerprint(self) -> str:
631
+ return self.doc["marks"][-1]["fingerprint"]
632
+
633
+ @property
634
+ def recipe(self) -> dict[str, Any]:
635
+ return dict(self.doc["recipe"])
636
+
637
+ @property
638
+ def lineage(self) -> dict[str, Any]:
639
+ return dict(self.doc["lineage"])
640
+
641
+ def describe(self) -> dict[str, Any]:
642
+ body = self.record["body"]
643
+ return {"record": self.id, "path": self.path, "where": self.where,
644
+ "cut": self.fingerprint, "history": self.doc["history"],
645
+ "marks": len(self.doc["marks"]), "parts": len(self.doc["parts"]),
646
+ "bytes": body["bytes"]["value"], "lineage": self.lineage}
647
+
648
+ # tensors -----------------------------------------------------------------------------
649
+
650
+ def _part(self, index: int) -> torch.Tensor:
651
+ found = self._parts.get(index)
652
+ if found is not None:
653
+ return found
654
+ pointer = self.doc["parts"][index]
655
+ if self._store is not None:
656
+ from mdb.core.pointers import Unresolved, resolve_tensor, tensor_pointer
657
+
658
+ try:
659
+ value = resolve_tensor(tensor_pointer(pointer["ref"], sha256=pointer["sha256"],
660
+ shape=pointer["shape"],
661
+ dtype=pointer["dtype"]),
662
+ store=self._store, framework="torch")
663
+ except Unresolved as error:
664
+ raise ValueError(f"checkpoint part {pointer['sha256'][:12]}: {error}") from error
665
+ else:
666
+ value = self._blobs[part_key(pointer["sha256"], pointer["dtype"], pointer["shape"])]
667
+ if (tensor_digest(value) != pointer["sha256"] or list(value.shape) != pointer["shape"]
668
+ or _dtype_name(value) != pointer["dtype"]):
669
+ raise ValueError(f"checkpoint tensor {pointer['sha256'][:12]} differs from its "
670
+ "sha256")
671
+ self._parts[index] = value
672
+ return value
673
+
674
+ def blocks(self, index: int, device: Any = "cpu") -> Any:
675
+ """Tensor ``index`` of the document as ``saturn.core.Blocks`` of its parts (on
676
+ ``device``; cached, so every cut that holds the tensor shares one object)."""
677
+ from saturn.core import Blocks
678
+
679
+ key = (index, str(device))
680
+ found = self._blocks.get(key)
681
+ if found is not None:
682
+ return found
683
+ desc = self.doc["tensors"][index]
684
+ parts = [self._part(i) for i in desc["parts"]]
685
+ if str(device) != "cpu":
686
+ parts = [p.to(device) for p in parts]
687
+ dtype = getattr(torch, desc["dtype"])
688
+ if any(p.dtype != dtype for p in parts):
689
+ raise ValueError("checkpoint tensor parts differ from its dtype")
690
+ if desc["axis"] is None and len(parts) != 1:
691
+ raise ValueError("a checkpoint tensor without an axis has one part")
692
+ found = self._blocks[key] = Blocks(tuple(parts), desc["axis"], tuple(desc["shape"]),
693
+ tuple(desc["stride"]), dtype)
694
+ return found
695
+
696
+ def tensor(self, index: int) -> torch.Tensor:
697
+ """Tensor ``index`` of the document, rebuilt from its parts (CPU)."""
698
+ try:
699
+ return self.blocks(index).tensor()
700
+ except ValueError as error:
701
+ raise ValueError(f"checkpoint tensor {index}: {error}") from error
702
+
703
+ def _decode(self, value: Any, device: Any, *, blocks: bool = False) -> Any:
704
+ kind = value["kind"]
705
+ if kind == "tensor":
706
+ if blocks:
707
+ return self.blocks(value["t"], device)
708
+ t = self.tensor(value["t"])
709
+ return t if str(t.device) == str(device) else t.to(device)
710
+ if kind == "mapping":
711
+ return {k: self._decode(v, device, blocks=blocks) for k, v in value["items"].items()}
712
+ if kind == "list":
713
+ return [self._decode(v, device, blocks=blocks) for v in value["items"]]
714
+ if kind == "tuple":
715
+ return tuple(self._decode(v, device, blocks=blocks) for v in value["items"])
716
+ if kind == "scalar":
717
+ return value["value"]
718
+ raise ValueError(f"unknown checkpoint value kind {kind!r}")
719
+
720
+ # binding -----------------------------------------------------------------------------
721
+
722
+ def binding(self, adapter: Any) -> dict[str, Any]:
723
+ """How ``adapter`` relates to the source: same identity, same execution (exact), dtype."""
724
+ check_shape(self.doc["shape"], adapter)
725
+ same_identity = _plain(adapter.model_identity, "identity") == self.doc["model_identity"]
726
+ same_execution = _canonical(_plain(dict(adapter.execution), "execution")) == \
727
+ _canonical(self.doc["execution"])
728
+ return {"same_identity": same_identity, "same_execution": same_execution,
729
+ "exact": same_identity and same_execution,
730
+ "source_dtype": self.doc["execution"].get("dtype", "").removeprefix("torch."),
731
+ "dtype": _dtype_name_of(adapter)}
732
+
733
+ def _refuse(self, adapter: Any, replica: bool) -> dict[str, Any]:
734
+ bound = self.binding(adapter)
735
+ if bound["exact"] or replica:
736
+ return bound
737
+ if not bound["same_identity"]:
738
+ raise ValueError("checkpoint of another model (model identity differs); load it as "
739
+ "a labelled replica with replica=True")
740
+ mine = _flatten(_plain(dict(adapter.execution), "execution"))
741
+ theirs = _flatten(self.doc["execution"])
742
+ differ = sorted(k for k in set(mine) | set(theirs) if mine.get(k) != theirs.get(k))
743
+ raise ValueError("checkpoint of another execution (" + "; ".join(
744
+ f"{k}: checkpoint {theirs.get(k, 'missing')!r}, here {mine.get(k, 'missing')!r}"
745
+ for k in differ[:6]) + "); load it as a labelled replica with replica=True")
746
+
747
+ def cut(self, adapter: Any, index: int) -> Any:
748
+ """The ``StateCut`` of kept mark ``index`` (exact binding), fingerprint verified."""
749
+ from saturn.core import StateCut
750
+
751
+ key = (str(adapter.device), index)
752
+ found = self._cuts.get(key)
753
+ if found is not None:
754
+ return found
755
+ mark = self.doc["marks"][index]
756
+ stored = mark["cut"]
757
+ if stored is None:
758
+ raise ValueError(f"mark {index} of the checkpoint keeps no cut")
759
+ payload = self._decode(stored["payload"], adapter.device, blocks=True)
760
+ try:
761
+ cut = StateCut.from_blocks(adapter.model_identity, adapter.execution,
762
+ stored["boundary"], stored["parent"], payload,
763
+ execution_point=stored["execution_point"],
764
+ surface=stored["surface"])
765
+ except ValueError as error:
766
+ raise ValueError(f"checkpoint state at mark {index}: {error}") from error
767
+ if cut.fingerprint != mark["fingerprint"]:
768
+ raise ValueError(f"checkpoint state at mark {index} differs from its fingerprint "
769
+ f"{mark['fingerprint'][:12]} (changed tensors or metadata)")
770
+ self._cuts[key] = cut
771
+ return cut
772
+
773
+ def _rearm(self, run: Any) -> None:
774
+ """Re-arm the holds the source had active (``save(holds="rearm")``), each reading the
775
+ source values the checkpoint kept (``holds.Snapshot``)."""
776
+ from .holds import Hold, Snapshot
777
+
778
+ for h in self.doc["holds"]:
779
+ if h["dropped"]:
780
+ continue
781
+ snap = h["snapshot"]
782
+ values = {a: self.tensor(i) for a, i in snap["values"].items()}
783
+ source = Snapshot(snap["source"], snap["where"], snap["cut"], values, snap["tokens"])
784
+ run._holds.append(Hold(h["name"], h["port"], tuple(h["layers"]),
785
+ None if h["rows"] is None else tuple(h["rows"]), source,
786
+ h["address"], cells=[dict(c) for c in h["cells"]]))
787
+ run._hold_key = None
788
+
789
+ def _held(self) -> dict[str, torch.Tensor]:
790
+ out = {}
791
+ for sha, index in self.doc["edit_tensors"].items():
792
+ value = self.tensor(index)
793
+ if tensor_digest(value) != sha:
794
+ raise ValueError(f"checkpoint edit tensor {sha[:12]} differs from its sha256")
795
+ out[sha] = value
796
+ return out
797
+
798
+ # runs --------------------------------------------------------------------------------
799
+
800
+ def run(self, adapter: Any, *, lookahead: str | None = None, name: str | None = None,
801
+ replica: bool = False, check: bool = True, verify: bool | str = False,
802
+ root: Any = None) -> Any:
803
+ """A ``Run`` of ``adapter`` at the checkpoint's cursor (module docstring). ``replica``:
804
+ allow another dtype, device or weights (a new lineage at the cursor). ``check``: the
805
+ replica null check (``run.core_check``; values were captured), else the result says
806
+ there was no null check. The run is labelled ``from checkpoint <id>, path unverified``
807
+ (``run.from_checkpoint``) until its path is verified. ``verify=True``: replay the
808
+ recipe from the lineage root (``root`` for a foreign one) first and raise
809
+ ``CheckpointUnverified`` unless it reaches the checkpoint's fingerprint (the run is then
810
+ ``path verified``); ``verify="report"``: record the result as ``run.core["verified"]``
811
+ and never raise."""
812
+ if verify not in (False, True, "report"):
813
+ raise ValueError(f"verify is False, True or 'report', not {verify!r}")
814
+ if verify is True:
815
+ result = self.verify(adapter, root=root)
816
+ started = time.perf_counter()
817
+ bound = self._refuse(adapter, replica)
818
+ lookahead = self.doc["lookahead"] if lookahead is None else lookahead
819
+ if bound["exact"]:
820
+ run = self._exact(adapter, lookahead)
821
+ else:
822
+ run = self._replica(adapter, lookahead)
823
+ seconds = time.perf_counter() - started
824
+ run.name = name or f"core@{self.id[:12]}"
825
+ run.core = {"record": self.id, "path": self.path, "split": self.split,
826
+ "where": self.where, "cut": self.fingerprint,
827
+ "history": self.doc["history"], "exact": bound["exact"],
828
+ "replica": not bound["exact"], "lineage": dict(run.lineage),
829
+ "source_dtype": bound["source_dtype"], "dtype": bound["dtype"],
830
+ "same_identity": bound["same_identity"],
831
+ "holds": [h["name"] for h in self.doc["holds"] if not h["dropped"]],
832
+ "holds_dropped": [h["name"] for h in self.doc["holds"] if h["dropped"]],
833
+ "load_seconds": seconds}
834
+ run.from_checkpoint = {"checkpoint": self.id, "path": "unverified"}
835
+ if not bound["exact"]:
836
+ run.from_checkpoint["replica"] = True
837
+ run.core_check = None
838
+ if check and self.doc["captured"]:
839
+ run.core_check = self.null_check(adapter, lookahead=lookahead, replica=replica)
840
+ elif check and not bound["exact"]:
841
+ run.core_check = {"state": "unresolved", "ok": None,
842
+ "reason": "no null check: the checkpoint captured no value to "
843
+ "compare the replica with (save it with capture=)"}
844
+ if not bound["exact"]:
845
+ ok = (run.core_check or {}).get("ok")
846
+ run.from_checkpoint["null_check"] = None if ok is None else bool(ok)
847
+ if verify is True:
848
+ run.core["verified"] = result
849
+ elif verify == "report":
850
+ run.core["verified"] = self.verify(adapter, root=root, report=True)
851
+ if run.core.get("verified", {}).get("ok"):
852
+ run.from_checkpoint["path"] = "verified"
853
+ return run
854
+
855
+ def _exact(self, adapter: Any, lookahead: str) -> Any:
856
+ from saturn.core import Session
857
+
858
+ from .run import Run
859
+
860
+ marks = self.doc["marks"]
861
+ for i in range(1, len(marks)):
862
+ # the kept marks are consecutive trail marks: each cut chains to the one before
863
+ stored = marks[i]["cut"]
864
+ if stored is not None and stored["parent"] != marks[i - 1]["fingerprint"]:
865
+ raise ValueError(f"checkpoint mark {i} ({marks[i]['label']}) has parent "
866
+ f"{str(stored['parent'])[:12]}, not the previous mark "
867
+ f"{marks[i - 1]['fingerprint'][:12]} (a broken chain)")
868
+ cuts = {i: self.cut(adapter, i) for i, m in enumerate(marks) if m["cut"] is not None}
869
+ # the cuts hold the parts (block form) or the tensors themselves: the concatenated
870
+ # copies are not needed any more (rebuilt from the parts if ever asked for again)
871
+ self._blocks.clear()
872
+ run = Run(adapter, self.prompt, root=cuts[0], root_transitions=marks[0]["transitions"],
873
+ prefill=self.doc["prefill"], lookahead=lookahead)
874
+ if run._trail[0].fingerprint != marks[0]["fingerprint"]:
875
+ raise ValueError("the rehydrated root differs from the checkpoint's fingerprint")
876
+ run.hold(self._held())
877
+ self._rearm(run)
878
+ run._ancestry = [self._mark(run, m, None, ancestor=True) for m in self.doc["ancestry"]]
879
+ run.lineage = self._lineage()
880
+ run._origin = self
881
+ trail = [run._trail[0]]
882
+ trail += [self._mark(run, m, cuts.get(i)) for i, m in enumerate(marks[1:], 1)]
883
+ self._fill(run, trail[0], marks[0])
884
+ run._trail = trail
885
+ if len(marks) > 1:
886
+ run.session = Session.from_cut(adapter, cuts[len(marks) - 1])
887
+ self._cursor(run)
888
+ return run
889
+
890
+ @staticmethod
891
+ def _fill(run: Any, mark: Any, m: dict[str, Any]) -> Any:
892
+ mark.edits = tuple(run._edit_from(e) for e in m["edits"])
893
+ mark.cells = tuple(run._edit_from(c) for c in m["cells"])
894
+ mark.fired = tuple(dict(x) for x in m["fired"])
895
+ mark.cell_fired = tuple(dict(x) for x in m["cell_fired"])
896
+ mark.supplied = m["supplied"]
897
+ return mark
898
+
899
+ def _mark(self, run: Any, m: dict[str, Any], cut: Any, *, ancestor: bool = False) -> Any:
900
+ from .run import _Mark
901
+
902
+ mark = _Mark(m["fingerprint"], cut, m["row"], m["label"], m["phase"], m["layer"],
903
+ m["transitions"], ancestor=ancestor)
904
+ return self._fill(run, mark, m)
905
+
906
+ def _cursor(self, run: Any) -> None:
907
+ from .edits import CellEdit
908
+ from .ports import PortEdit
909
+
910
+ cursor = self.doc["cursor"]
911
+ staged = [run._edit_from(m) for m in [*cursor["edits"], *cursor["cells"]]]
912
+ run._edits = [e for e in staged if isinstance(e, PortEdit)]
913
+ run._cells = [e for e in staged if isinstance(e, CellEdit)]
914
+ run._cache, run._port = None, None
915
+ if cursor["port"] is not None:
916
+ port = run.program.spec(cursor["port"]).name
917
+ run._ensure_cache(port)
918
+ run._port = port
919
+ if run.where != self.where:
920
+ raise RuntimeError(f"the rehydrated cursor is at {run.where}, not {self.where}")
921
+
922
+ def _lineage(self) -> dict[str, Any]:
923
+ lineage = dict(self.doc["lineage"])
924
+ lineage.setdefault("checkpoints", [])
925
+ lineage["checkpoints"] = [*lineage["checkpoints"], self.id][-8:]
926
+ return lineage
927
+
928
+ def _replica(self, adapter: Any, lookahead: str) -> Any:
929
+ from saturn.core import Session
930
+
931
+ from .run import Run
932
+
933
+ marks = self.doc["marks"]
934
+ stored = marks[-1]["cut"]
935
+ state = self._decode(stored["payload"], "cpu")
936
+ state.pop("__saturn_external__", None)
937
+ device, dtype = adapter.device, adapter.dtype
938
+
939
+ def move(t: Any) -> Any:
940
+ if isinstance(t, Mapping):
941
+ return {k: move(v) for k, v in t.items()}
942
+ if isinstance(t, (list, tuple)):
943
+ return type(t)(move(x) for x in t)
944
+ if not isinstance(t, torch.Tensor):
945
+ return t
946
+ if t.is_floating_point():
947
+ return t.to(device=device, dtype=dtype)
948
+ return t.to(device=device)
949
+
950
+ state = move(state)
951
+ root = Session(adapter, state).capture(retain=False)
952
+ run = Run(adapter, self.prompt, root=root, root_transitions=marks[-1]["transitions"],
953
+ prefill=self.doc["prefill"], lookahead=lookahead)
954
+ run.hold(self._held())
955
+ self._rearm(run)
956
+ run._ancestry = [self._mark(run, m, None, ancestor=True)
957
+ for m in [*self.doc["ancestry"], *marks[:-1]]
958
+ if m["edits"] or m["cells"] or m["supplied"] is not None]
959
+ run.lineage = {"root": "checkpoint", "checkpoint": self.id, "replica": True,
960
+ "cut": root.fingerprint, "source_cut": self.fingerprint,
961
+ "checkpoints": [self.id]}
962
+ run._origin = self
963
+ self._cursor(run)
964
+ return run
965
+
966
+ def null_check(self, adapter: Any, *, lookahead: str = "none",
967
+ replica: bool = True) -> dict[str, Any]:
968
+ """Run a fresh run of this checkpoint to every captured address and compare (measured):
969
+ per address ``max_abs_diff`` (float64) and, for logits, ``argmax_equal``; ``ok`` when
970
+ every argmax agrees (and every difference is 0 on the same dtype and identity)."""
971
+ if not self.doc["captured"]:
972
+ return {"state": "unresolved", "reason": "the checkpoint captured no value"}
973
+ bound = self._refuse(adapter, replica)
974
+ twin = self._exact(adapter, lookahead) if bound["exact"] else self._replica(adapter,
975
+ lookahead)
976
+ out: dict[str, Any] = {"checks": {}, "authority": "measured"}
977
+ same = bound["exact"]
978
+ ok = True
979
+ for address in sorted(self.doc["captured"], key=twin.parse):
980
+ if twin.parse(address) > twin._key():
981
+ twin.until(address)
982
+ got = twin.read(address).detach().to("cpu")
983
+ want = self.tensor(self.doc["captured"][address])
984
+ diff = float((got.to(torch.float64) - want.to(torch.float64)).abs().max())
985
+ entry: dict[str, Any] = {"max_abs_diff": diff}
986
+ if address.endswith("logits"):
987
+ entry["argmax_equal"] = int(got.reshape(-1).argmax()) == int(
988
+ want.reshape(-1).argmax())
989
+ entry["argmax"] = [int(want.reshape(-1).argmax()), int(got.reshape(-1).argmax())]
990
+ ok = ok and entry["argmax_equal"]
991
+ if same:
992
+ ok = ok and diff == 0.0
993
+ out["checks"][address] = entry
994
+ out.update(ok=ok, same_dtype_and_identity=same,
995
+ rule="argmax equal at every captured logits" + (
996
+ " and bit-identical values (same dtype and identity)" if same else ""))
997
+ return out
998
+
999
+ def verify(self, adapter: Any, *, root: Any = None, report: bool = False) -> dict[str, Any]:
1000
+ """Verify by recompute (measured): replay the recipe from the lineage root (a run of the
1001
+ prompt; ``root``, a ``Run`` or ``Checkpoint``, for a foreign lineage) with the stored
1002
+ edit tensors and compare the cut it reaches with the checkpoint's fingerprint. Raises
1003
+ ``CheckpointUnverified`` unless it does (also when it cannot be checked: another model
1004
+ or execution, or a foreign root and no ``root=``); ``report``: return the result
1005
+ (``ok``, ``state``) instead of raising."""
1006
+ result = self._verify(adapter, root)
1007
+ if not result["ok"] and not report:
1008
+ raise CheckpointUnverified(result)
1009
+ return result
1010
+
1011
+ def _verify(self, adapter: Any, root: Any) -> dict[str, Any]:
1012
+ from .run import ReplayMismatch, Run
1013
+
1014
+ started = time.perf_counter()
1015
+ lineage = self.doc["lineage"]
1016
+ if self.binding(adapter)["exact"] is False:
1017
+ return {"ok": False, "state": "unresolved", "checkpoint": self.id,
1018
+ "reason": "verify needs the source's model and execution"}
1019
+ if lineage.get("root") != "prompt" and root is None:
1020
+ return {"ok": False, "state": "unresolved", "checkpoint": self.id,
1021
+ "reason": "the lineage root is a foreign checkpoint "
1022
+ f"({lineage.get('checkpoint')}); pass root= to verify from it"}
1023
+ recipe = self.recipe
1024
+ if root is None:
1025
+ replay = Run(adapter, self.prompt, prefill=recipe["prefill"],
1026
+ lookahead=recipe["lookahead"])
1027
+ elif isinstance(root, Checkpoint):
1028
+ replay = root.run(adapter, check=False)
1029
+ elif isinstance(root, (str, Path)):
1030
+ replay = load(root).run(adapter, check=False)
1031
+ else:
1032
+ replay = root.fresh()
1033
+ replay.hold(self._held())
1034
+ try:
1035
+ replay.restore(recipe)
1036
+ reached = replay._trail[-1].fingerprint
1037
+ except ReplayMismatch as error:
1038
+ reached = error.reached
1039
+ ok = reached == self.fingerprint
1040
+ return {"ok": ok, "state": "resolved", "checkpoint": self.id, "expected": self.fingerprint, "reached": reached,
1041
+ "authority": "measured", "seconds": time.perf_counter() - started,
1042
+ "native_calls": dict(replay.calls),
1043
+ "rule": "the recipe replayed from the lineage root reaches the checkpoint's cut "
1044
+ "fingerprint (state content, execution contract and ancestry)"}
1045
+
1046
+
1047
+ class CheckpointUnverified(ValueError):
1048
+ """A checkpoint whose path did not verify by recompute (``result`` says why)."""
1049
+
1050
+ def __init__(self, result: dict[str, Any]):
1051
+ self.result = result
1052
+ if result.get("state") == "resolved":
1053
+ text = (f"checkpoint {str(result.get('checkpoint'))[:16]} did not verify: the recipe "
1054
+ f"replayed from its lineage root reaches {str(result['reached'])[:12]}, not "
1055
+ f"{str(result['expected'])[:12]}")
1056
+ else:
1057
+ text = (f"checkpoint {str(result.get('checkpoint'))[:16]} cannot be verified: "
1058
+ f"{result['reason']}")
1059
+ super().__init__(text + " (verify='report' returns the result instead)")
1060
+
1061
+
1062
+ def _flatten(value: Any, prefix: str = "") -> dict[str, Any]:
1063
+ if isinstance(value, Mapping):
1064
+ out: dict[str, Any] = {}
1065
+ for k, v in value.items():
1066
+ out.update(_flatten(v, f"{prefix}{k}."))
1067
+ return out
1068
+ return {prefix.rstrip("."): value}
1069
+
1070
+
1071
+ def _verify_document(record: dict[str, Any], text: str) -> dict[str, Any]:
1072
+ body = record["body"]
1073
+ if body.get("schema") != SCHEMA:
1074
+ raise ValueError(f"not an {SCHEMA} checkpoint record")
1075
+ if _sha_text(text) != body["document"]["sha256"]:
1076
+ raise ValueError("checkpoint document differs from its sealed sha256")
1077
+ doc = json.loads(text)
1078
+ if doc.get("schema") != SCHEMA:
1079
+ raise ValueError("checkpoint document has another schema")
1080
+ shas = sorted({p["sha256"] for p in doc["parts"]})
1081
+ listed = body["tensors"]["sha256"]
1082
+ if (listed is not None and _unpacked(listed) != shas) or body["tensors"]["count"] != len(
1083
+ shas) or body["tensors"]["parts_sha256"] != _sha_text(_canonical(shas)):
1084
+ raise ValueError("checkpoint parts differ from the sha256s in its record")
1085
+ from saturn.values import digest
1086
+
1087
+ if digest(doc["prompt"]) != body["prompt"]["sha256"] or len(doc["prompt"]) != \
1088
+ body["prompt"]["length"]:
1089
+ raise ValueError("checkpoint prompt differs from its sealed prompt sha256")
1090
+ if doc["marks"][-1]["fingerprint"] != body["cut"]["fingerprint"] or \
1091
+ doc["marks"][0]["fingerprint"] != body["root"]["fingerprint"]:
1092
+ raise ValueError("checkpoint marks differ from the fingerprints in its record")
1093
+ if _sha_text(_canonical(doc["recipe"])) != body["recipe"]["sha256"]:
1094
+ raise ValueError("checkpoint recipe differs from its sealed sha256")
1095
+ if _plain(record["model_identity"], "identity") != doc["model_identity"]:
1096
+ raise ValueError("checkpoint document belongs to another model than its record")
1097
+ return doc
1098
+
1099
+
1100
+ def load_file(path: str | Path) -> Any:
1101
+ """A checkpoint file (this schema, or a legacy ``mdb-core-file-v1`` core file)."""
1102
+ from mdb.core.kinds import CHECKPOINT_STATE # noqa: F401 (declares the kind)
1103
+ from mdb.core.records import verify_record
1104
+
1105
+ data = torch.load(str(path), map_location="cpu", weights_only=True)
1106
+ if not isinstance(data, dict):
1107
+ raise ValueError(f"{path} is not an mdb checkpoint")
1108
+ from . import core_file
1109
+
1110
+ if data.get("schema") == core_file.SCHEMA:
1111
+ return core_file.load_v1(data, path)
1112
+ if data.get("schema") != FILE_SCHEMA:
1113
+ raise ValueError(f"{path} is not an mdb checkpoint")
1114
+ if set(data) != _FILE_KEYS:
1115
+ raise ValueError("checkpoint file holds other entries than its schema")
1116
+ record = verify_record(json.loads(data["record"]))
1117
+ doc = _verify_document(record, data["document"])
1118
+ keys = {part_key(p["sha256"], p["dtype"], p["shape"]) for p in doc["parts"]}
1119
+ if set(data["tensors"]) != keys:
1120
+ raise ValueError("checkpoint file tensors differ from its document")
1121
+ checkpoint = Checkpoint(record, doc, path=str(path), blobs=data["tensors"])
1122
+ for index in range(len(doc["parts"])):
1123
+ checkpoint._part(index) # every part's sha256, before anything is used
1124
+ return checkpoint
1125
+
1126
+
1127
+ def load_record(project: Any, record: dict[str, Any], *, store: Any = None) -> Checkpoint:
1128
+ """The checkpoint of ``record``, indexed in ``project``. Blobs the project lacks are copied
1129
+ from ``store`` (else ``[storage] checkpoint_store``, else the store the record names),
1130
+ each checked against its sha256."""
1131
+ from mdb.core import checkpoint_store as stores
1132
+ from mdb.core.bounded import load_json
1133
+
1134
+ pointer = record["body"]["document"]
1135
+ local = stores.ProjectStore(project)
1136
+ if not local.has(pointer["ref"]):
1137
+ _complete(project, record, None, store)
1138
+ doc = load_json(pointer, store=project.store)
1139
+ text = _canonical(doc)
1140
+ doc = _verify_document(record, text)
1141
+ if any(not local.has(p["ref"]) for p in doc["parts"]):
1142
+ _complete(project, record, doc, store)
1143
+ return Checkpoint(record, doc, store=project.store)
1144
+
1145
+
1146
+ def _remote_for(record: dict[str, Any], store: Any) -> Any:
1147
+ from mdb.core import checkpoint_store as stores
1148
+
1149
+ remote = stores.configured(store)
1150
+ if remote is None and isinstance(record["body"].get("store"), Mapping):
1151
+ remote = stores.open_store(record["body"]["store"]["uri"])
1152
+ return remote
1153
+
1154
+
1155
+ def _complete(project: Any, record: dict[str, Any], doc: dict[str, Any] | None,
1156
+ store: Any) -> None:
1157
+ """Copy the blobs of ``record`` the project lacks from its store (``MissingBlob`` names
1158
+ a blob neither holds)."""
1159
+ from mdb.core import checkpoint_store as stores
1160
+
1161
+ remote = _remote_for(record, store)
1162
+ if remote is None:
1163
+ missing = [record["body"]["document"]["ref"]] if doc is None else [
1164
+ p["ref"] for p in doc["parts"] if not stores.ProjectStore(project).has(p["ref"])]
1165
+ raise stores.MissingBlob(missing[0], f"project {project.root} (and no checkpoint store "
1166
+ "is configured: [storage] checkpoint_store)")
1167
+ stores.copy(record, doc, remote, stores.ProjectStore(project))
1168
+
1169
+
1170
+ def fetch(project: Any, ref: str, store: Any) -> dict[str, Any]:
1171
+ """Copy checkpoint record ``ref`` (an id or unique prefix) and its blobs from ``store`` into
1172
+ ``project``; returns the record as the project indexes it."""
1173
+ from mdb.core import checkpoint_store as stores
1174
+ from mdb.core.kinds import CHECKPOINT_STATE # noqa: F401 (declares the kind)
1175
+
1176
+ remote = stores.open_store(store)
1177
+ record = remote.find_record(str(ref).strip().lower())
1178
+ if record is None:
1179
+ raise ValueError(f"no checkpoint record {ref} in project {project.root} or in store "
1180
+ f"{remote.uri}")
1181
+ if record["kind"] != KIND:
1182
+ raise ValueError(f"record {record['id'][:16]} in {remote.uri} is a {record['kind']}, "
1183
+ "not a checkpoint")
1184
+ stores.copy(record, None, remote, stores.ProjectStore(project))
1185
+ return find_record(project, record["id"])
1186
+
1187
+
1188
+ def find_named(project: Any, name: str | None, *, session_id: str | None = None,
1189
+ cut: str | None = None) -> dict[str, Any] | None:
1190
+ """The newest ``checkpoint-state`` record named ``name`` (None: any name; optionally at cut
1191
+ ``cut``), in ``session_id`` first, else in any session."""
1192
+ from mdb.core import index
1193
+ from mdb.core.kinds import CHECKPOINT_STATE # noqa: F401 (declares the kind)
1194
+
1195
+ sessions = [s["session_id"] for s in project.sessions()]
1196
+ if session_id in sessions:
1197
+ sessions = [session_id] + [s for s in sessions if s != session_id]
1198
+ for sid in sessions:
1199
+ named = [r for r in index.list_records(project, sid, kind=KIND)
1200
+ if r.get("verified") is not False
1201
+ and (name is None or r["body"].get("name") == name)
1202
+ and (cut is None or r["body"]["cut"]["fingerprint"] == cut)]
1203
+ if named:
1204
+ return named[-1]
1205
+ return None
1206
+
1207
+
1208
+ def load(ref: Any, *, project: Any = None, store: Any = None) -> Any:
1209
+ """A checkpoint from a path, a bundle directory (``engine.bundle``: imported first), a record
1210
+ id or checkpoint name (with ``project``: the newest ``checkpoint-state`` of that name) or a
1211
+ loaded object. A record id
1212
+ the project does not hold is fetched from ``store`` (else ``[storage]
1213
+ checkpoint_store``) into the project, or into the local cache project when none is
1214
+ attached (``mdb.core.checkpoint_store.cache_project``)."""
1215
+ from mdb.core import checkpoint_store as stores
1216
+
1217
+ from . import core_file
1218
+
1219
+ if isinstance(ref, (Checkpoint, core_file.CoreFile)):
1220
+ return ref
1221
+ from .bundle import is_bundle, read
1222
+
1223
+ if is_bundle(ref): # an exported bundle: imported into the project (or the cache project)
1224
+ target = project if project is not None else stores.cache_project()
1225
+ return load_record(target, read(target, ref))
1226
+ remote = stores.configured(store)
1227
+ if isinstance(ref, Mapping) and "id" in ref and ref.get("kind") == KIND:
1228
+ ref = ref["id"]
1229
+ if project is None and remote is None:
1230
+ raise ValueError("a checkpoint record needs the project that holds it")
1231
+ if isinstance(ref, Mapping) and isinstance(ref.get("durable"), Mapping):
1232
+ durable = ref["durable"]
1233
+ ref = durable.get("path") or durable["record"]
1234
+ if remote is None and durable.get("store"):
1235
+ remote = stores.open_store(durable["store"])
1236
+ is_file = isinstance(ref, Path) or (isinstance(ref, str) and Path(ref).expanduser().is_file())
1237
+ if isinstance(ref, str) and not is_file and project is None and remote is not None:
1238
+ project = stores.cache_project()
1239
+ record = None
1240
+ if isinstance(ref, str) and project is not None:
1241
+ try:
1242
+ record = find_record(project, ref)
1243
+ except ValueError as error:
1244
+ if not is_file: # a checkpoint name of the project (`dbg.checkpoint(run, NAME)`)
1245
+ record = find_named(project, ref.strip())
1246
+ if record is None and remote is not None and "no checkpoint record" in str(error):
1247
+ record = fetch(project, ref, remote)
1248
+ elif record is None and not is_file:
1249
+ raise ValueError(f"{error}, nor a checkpoint name of the project (the REPL's "
1250
+ "`checkpoints` lists names and record ids)") from error
1251
+ if is_file and record is not None:
1252
+ raise ValueError(f"{ref!r} names both a file and checkpoint record {record['id'][:16]} "
1253
+ "of the project: pass Path(...) for the file, or the record itself (the dict "
1254
+ "states.find_record returns) for the record")
1255
+ if is_file:
1256
+ return load_file(Path(ref).expanduser())
1257
+ if record is not None:
1258
+ return load_record(project, record, store=remote)
1259
+ raise ValueError(f"no checkpoint at {ref!r}: give a file path, or a record id with a "
1260
+ "project attached or a checkpoint store configured")
1261
+
1262
+
1263
+ __all__ = ["Checkpoint", "CheckpointUnverified", "FILE_SCHEMA", "HISTORIES", "KIND", "SCHEMA",
1264
+ "build", "fetch", "find_named", "find_record", "load", "load_file", "load_record",
1265
+ "save", "shape_of"]