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,377 @@
1
+ """Where checkpoint bytes live: a local project, a directory or an S3-compatible bucket.
2
+
3
+ A checkpoint (``mdb.engine.checkpoint``) is a sealed ``checkpoint-state`` record plus blobs: its
4
+ document and every tensor part, each a saturn tensor blob addressed by the sha256 of its
5
+ bytes. A store holds both under one layout::
6
+
7
+ <root>/tensors/<sha256>.safetensors the blob bytes, exactly as a project store holds them
8
+ <root>/records/<record id>.json the sealed record
9
+
10
+ Backends: ``ProjectStore`` (a project's own store and record index), ``DirectoryStore`` (a
11
+ plain directory, ``file:///path``) and ``S3Store`` (``s3://bucket/prefix``; boto3, the
12
+ ``model-debugger[s3]`` extra; MinIO through ``endpoint``). Credentials come from the environment
13
+ only (boto3's chain: ``AWS_ACCESS_KEY_ID``, ``AWS_SECRET_ACCESS_KEY``); a store's ``uri`` names
14
+ no credential and is what a record says.
15
+
16
+ ``copy`` moves a checkpoint between two stores: blobs the target already has are not sent
17
+ again (dedup across jobs), and every blob read is checked against its sha256 before it is
18
+ written anywhere.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ import json
25
+ import os
26
+ from pathlib import Path
27
+ from typing import Any
28
+ from urllib.parse import urlparse
29
+
30
+ _HEX = set("0123456789abcdef")
31
+
32
+
33
+ def _sha(text: str) -> str:
34
+ if len(text) != 64 or not set(text) <= _HEX:
35
+ raise ValueError(f"{text!r} is not a sha256")
36
+ return text
37
+
38
+
39
+ def _blob_key(sha: str) -> str:
40
+ return f"tensors/{_sha(sha)}.safetensors"
41
+
42
+
43
+ def _record_key(record_id: str) -> str:
44
+ return f"records/{record_id}.json"
45
+
46
+
47
+ class MissingBlob(ValueError):
48
+ """A blob the store does not hold (``sha256`` names it)."""
49
+
50
+ def __init__(self, sha256: str, uri: str):
51
+ self.sha256 = sha256
52
+ super().__init__(f"checkpoint blob {sha256} is missing from {uri}")
53
+
54
+
55
+ class Store:
56
+ """Blobs and records by key. Backends implement ``_get`` (None when absent), ``_put``,
57
+ ``_has`` and ``_keys``; the sha256 checks are here, once."""
58
+
59
+ uri = ""
60
+
61
+ def _get(self, key: str) -> bytes | None:
62
+ raise NotImplementedError
63
+
64
+ def _put(self, key: str, data: bytes) -> None:
65
+ raise NotImplementedError
66
+
67
+ def _has(self, key: str) -> bool:
68
+ return self._get(key) is not None
69
+
70
+ def _keys(self, prefix: str) -> list[str]:
71
+ raise NotImplementedError
72
+
73
+ # blobs --------------------------------------------------------------------------------
74
+
75
+ def has(self, sha: str) -> bool:
76
+ return self._has(_blob_key(sha))
77
+
78
+ def get(self, sha: str) -> bytes:
79
+ """The blob ``sha``, checked: ``MissingBlob`` when absent, ``ValueError`` when its
80
+ bytes differ from their sha256."""
81
+ data = self._get(_blob_key(sha))
82
+ if data is None:
83
+ raise MissingBlob(sha, self.uri)
84
+ if hashlib.sha256(data).hexdigest() != sha:
85
+ raise ValueError(f"checkpoint blob {sha} in {self.uri} differs from its sha256")
86
+ return data
87
+
88
+ def put(self, sha: str, data: bytes) -> None:
89
+ if hashlib.sha256(data).hexdigest() != sha:
90
+ raise ValueError(f"blob bytes differ from their sha256 {sha}")
91
+ self._put(_blob_key(sha), data)
92
+
93
+ # records ------------------------------------------------------------------------------
94
+
95
+ def put_record(self, record: dict[str, Any]) -> None:
96
+ self._put(_record_key(record["id"]), json.dumps(record, sort_keys=True).encode())
97
+
98
+ def find_record(self, ref: str) -> dict[str, Any] | None:
99
+ """The verified record whose id starts with ``ref`` (None when there is none)."""
100
+ from mdb.core.kinds import CHECKPOINT_STATE # noqa: F401 (declares the kind)
101
+ from mdb.core.records import verify_record
102
+
103
+ ids = sorted({k.rsplit("/", 1)[-1].removesuffix(".json")
104
+ for k in self._keys(f"records/{ref}")})
105
+ if not ids:
106
+ return None
107
+ if len(ids) > 1:
108
+ raise ValueError(f"checkpoint record prefix {ref} is ambiguous in {self.uri}; give "
109
+ "more digits")
110
+ data = self._get(_record_key(ids[0]))
111
+ if data is None:
112
+ return None
113
+ record = verify_record(json.loads(data))
114
+ if record["id"] != ids[0]:
115
+ raise ValueError(f"record {ids[0]} in {self.uri} holds record {record['id']}")
116
+ return record
117
+
118
+ def __repr__(self) -> str:
119
+ return f"{type(self).__name__}({self.uri!r})"
120
+
121
+
122
+ class DirectoryStore(Store):
123
+ """A plain directory (local disk, a mounted share)."""
124
+
125
+ def __init__(self, root: str | Path):
126
+ self.root = Path(root).expanduser().absolute()
127
+ self.uri = self.root.as_uri()
128
+
129
+ def _path(self, key: str) -> Path:
130
+ return self.root / key
131
+
132
+ def _get(self, key: str) -> bytes | None:
133
+ try:
134
+ return self._path(key).read_bytes()
135
+ except FileNotFoundError:
136
+ return None
137
+
138
+ def _has(self, key: str) -> bool:
139
+ return self._path(key).is_file()
140
+
141
+ def _put(self, key: str, data: bytes) -> None:
142
+ path = self._path(key)
143
+ path.parent.mkdir(parents=True, exist_ok=True)
144
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
145
+ temporary.write_bytes(data)
146
+ os.replace(temporary, path)
147
+
148
+ def _keys(self, prefix: str) -> list[str]:
149
+ folder, _, stem = prefix.rpartition("/")
150
+ directory = self.root / folder
151
+ if not directory.is_dir():
152
+ return []
153
+ return [f"{folder}/{p.name}" for p in directory.iterdir() if p.name.startswith(stem)]
154
+
155
+
156
+ class S3Store(Store):
157
+ """An S3-compatible bucket (MinIO: give ``endpoint``, else ``AWS_ENDPOINT_URL``). Needs
158
+ boto3 (``pip install 'model-debugger[s3]'``)."""
159
+
160
+ def __init__(self, uri: str, *, endpoint: str | None = None, client: Any = None):
161
+ parsed = urlparse(uri)
162
+ if parsed.scheme != "s3" or not parsed.netloc:
163
+ raise ValueError(f"{uri!r} is not an s3://bucket/prefix URI")
164
+ if parsed.username or parsed.password:
165
+ raise ValueError("an s3 URI names no credentials: they come from the environment")
166
+ self.bucket = parsed.netloc
167
+ self.prefix = parsed.path.strip("/")
168
+ self.uri = f"s3://{self.bucket}/{self.prefix}".rstrip("/")
169
+ self.endpoint = endpoint or os.environ.get("AWS_ENDPOINT_URL") or None
170
+ self._client = client
171
+
172
+ @property
173
+ def client(self) -> Any:
174
+ if self._client is None:
175
+ try:
176
+ import boto3
177
+ from botocore.config import Config
178
+ except ImportError as error:
179
+ raise ImportError("an s3:// checkpoint store needs boto3: pip install "
180
+ "'model-debugger[s3]'") from error
181
+ self._client = boto3.client(
182
+ "s3", endpoint_url=self.endpoint,
183
+ region_name=os.environ.get("AWS_DEFAULT_REGION") or "us-east-1",
184
+ config=Config(s3={"addressing_style": "path"}))
185
+ return self._client
186
+
187
+ def _key(self, key: str) -> str:
188
+ return f"{self.prefix}/{key}" if self.prefix else key
189
+
190
+ @staticmethod
191
+ def _absent(error: Exception) -> bool:
192
+ code = str(getattr(error, "response", {}).get("Error", {}).get("Code", ""))
193
+ return code in ("404", "NoSuchKey", "NotFound")
194
+
195
+ def _get(self, key: str) -> bytes | None:
196
+ try:
197
+ return self.client.get_object(Bucket=self.bucket, Key=self._key(key))["Body"].read()
198
+ except Exception as error: # botocore.exceptions.ClientError (boto3 is optional)
199
+ if self._absent(error):
200
+ return None
201
+ raise
202
+
203
+ def _has(self, key: str) -> bool:
204
+ try:
205
+ self.client.head_object(Bucket=self.bucket, Key=self._key(key))
206
+ return True
207
+ except Exception as error:
208
+ if self._absent(error):
209
+ return False
210
+ raise
211
+
212
+ def _put(self, key: str, data: bytes) -> None:
213
+ self.client.put_object(Bucket=self.bucket, Key=self._key(key), Body=data)
214
+
215
+ def _keys(self, prefix: str) -> list[str]:
216
+ out, cut = [], len(self._key(""))
217
+ pages = self.client.get_paginator("list_objects_v2").paginate(
218
+ Bucket=self.bucket, Prefix=self._key(prefix))
219
+ for page in pages:
220
+ out += [item["Key"][cut:] for item in page.get("Contents", [])]
221
+ return out
222
+
223
+
224
+ class ProjectStore(Store):
225
+ """A project's own store (``store/tensors``) and record index: the local end of ``copy``."""
226
+
227
+ def __init__(self, project: Any):
228
+ self.project = project
229
+ self.uri = f"project:{project.root}"
230
+
231
+ def _path(self, sha: str) -> Path:
232
+ return self.project.store.root / _blob_key(sha)
233
+
234
+ def has(self, sha: str) -> bool:
235
+ return self._path(sha).is_file()
236
+
237
+ def get(self, sha: str) -> bytes:
238
+ try:
239
+ data = self._path(sha).read_bytes()
240
+ except FileNotFoundError:
241
+ raise MissingBlob(sha, self.uri) from None
242
+ if hashlib.sha256(data).hexdigest() != sha:
243
+ raise ValueError(f"checkpoint blob {sha} in {self.uri} differs from its sha256")
244
+ return data
245
+
246
+ def put(self, sha: str, data: bytes) -> None:
247
+ from saturn.store import _publish
248
+
249
+ if hashlib.sha256(data).hexdigest() != sha:
250
+ raise ValueError(f"blob bytes differ from their sha256 {sha}")
251
+ _publish(self._path(sha), data)
252
+
253
+ def put_record(self, record: dict[str, Any]) -> None:
254
+ from mdb.core import index
255
+
256
+ self.project.open_session(record["session_id"], model_identity=record["model_identity"],
257
+ execution=record["execution"])
258
+ index.put_record(self.project, record)
259
+
260
+ def find_record(self, ref: str) -> dict[str, Any] | None:
261
+ try:
262
+ return find_record(self.project, ref)
263
+ except ValueError as error:
264
+ if "no checkpoint record" in str(error):
265
+ return None
266
+ raise
267
+
268
+
269
+ def open_store(uri: Any, *, endpoint: str | None = None) -> Store:
270
+ """A store from ``uri``: a ``Store``, a ``Project``, ``s3://bucket/prefix``, ``file:///dir``
271
+ or a directory path."""
272
+ if isinstance(uri, Store):
273
+ return uri
274
+ if hasattr(uri, "store") and hasattr(uri, "sessions"):
275
+ return ProjectStore(uri)
276
+ text = str(uri)
277
+ if text.startswith("s3://"):
278
+ from mdb.core import settings
279
+
280
+ return S3Store(text, endpoint=endpoint or settings.value("storage.endpoint"))
281
+ if text.startswith("file://"):
282
+ return DirectoryStore(urlparse(text).path)
283
+ if "://" in text:
284
+ raise ValueError(f"unknown checkpoint store {text!r}: s3://bucket/prefix, file:///dir "
285
+ "or a directory")
286
+ return DirectoryStore(text)
287
+
288
+
289
+ def is_store_uri(value: Any) -> bool:
290
+ return isinstance(value, Store) or (isinstance(value, str)
291
+ and value.startswith(("s3://", "file://")))
292
+
293
+
294
+ def configured(given: Any = None) -> Store | None:
295
+ """The checkpoint store ``given`` names, else ``[storage] checkpoint_store``, else None."""
296
+ from mdb.core import settings
297
+
298
+ uri = settings.value("storage.checkpoint_store", given)
299
+ return None if uri is None else open_store(uri)
300
+
301
+
302
+ def cache_project() -> Any:
303
+ """The local project that holds checkpoints read from (or written to) a store when no
304
+ project is attached: ``[storage] checkpoint_cache``, default ``$XDG_CACHE_HOME/mdb/
305
+ checkpoints``."""
306
+ from mdb.core import settings
307
+ from mdb.core.project import Project
308
+
309
+ root = settings.value("storage.checkpoint_cache")
310
+ if root is None:
311
+ base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
312
+ root = Path(base) / "mdb" / "checkpoints"
313
+ return Project(root)
314
+
315
+
316
+ def blobs_of(record: dict[str, Any], doc: dict[str, Any]) -> list[str]:
317
+ """The blobs a checkpoint names: its document, then every part (sha256 of the blob)."""
318
+ refs = [record["body"]["document"]["ref"]]
319
+ refs += [p["ref"] for p in doc["parts"]]
320
+ return list(dict.fromkeys(refs))
321
+
322
+
323
+ def copy(record: dict[str, Any], doc: dict[str, Any] | None, source: Store, target: Store
324
+ ) -> dict[str, Any]:
325
+ """Copy checkpoint ``record`` (document ``doc``; None: read from ``source``) and its blobs
326
+ from ``source`` to ``target``, blobs first and the record last (a record never names
327
+ missing bytes). A blob ``target`` has is not sent again. Returns counts."""
328
+ sent = kept = size = 0
329
+ read: dict[str, bytes] = {}
330
+ if doc is None:
331
+ ref = record["body"]["document"]["ref"]
332
+ read[ref] = source.get(ref)
333
+ doc = _document(read[ref])
334
+ for sha in blobs_of(record, doc):
335
+ if target.has(sha):
336
+ kept += 1
337
+ continue
338
+ data = read.pop(sha, None) or source.get(sha)
339
+ target.put(sha, data)
340
+ sent += 1
341
+ size += len(data)
342
+ target.put_record(record)
343
+ return {"store": target.uri, "sent": sent, "present": kept, "bytes": size}
344
+
345
+
346
+ def _document(raw: bytes) -> dict[str, Any]:
347
+ """The JSON document inside a uint8 tensor blob (``bounded.put_json``); the reader checks
348
+ it against the record's sha256 (``checkpoint.load_record``)."""
349
+ size = int.from_bytes(raw[:8], "little")
350
+ return json.loads(raw[8 + size:])
351
+
352
+
353
+ __all__ = ["DirectoryStore", "MissingBlob", "ProjectStore", "S3Store", "Store", "blobs_of",
354
+ "cache_project", "configured", "copy", "is_store_uri", "open_store"]
355
+
356
+
357
+ def find_record(project: Any, ref: str) -> dict[str, Any]:
358
+ """The ``checkpoint-state`` record ``ref`` (an id or a unique prefix of >= 8 hex digits) of
359
+ any session of ``project``."""
360
+ from mdb.core import index
361
+ from mdb.core.kinds import CHECKPOINT_STATE # noqa: F401 (declares the kind)
362
+
363
+ ref = str(ref).strip().lower()
364
+ if len(ref) < 8 or any(c not in "0123456789abcdef" for c in ref):
365
+ raise ValueError(f"{ref!r} is not a record id (8 or more hex digits)")
366
+ found = []
367
+ for session in project.sessions():
368
+ for record in index.list_records(project, session["session_id"], kind="checkpoint-state"):
369
+ if record.get("verified") is False:
370
+ continue
371
+ if record["id"].startswith(ref):
372
+ found.append(record)
373
+ if not found:
374
+ raise ValueError(f"no checkpoint record {ref} in project {project.root}")
375
+ if len({r["id"] for r in found}) > 1:
376
+ raise ValueError(f"checkpoint record prefix {ref} is ambiguous; give more digits")
377
+ return found[0]
@@ -0,0 +1,117 @@
1
+ """Paging of a circuit's node tree: the record keeps the root and its first levels, and each group
2
+ that does not fit one page is a pointer to a child page (a sha256-checked JSON blob).
3
+
4
+ Torch-free (the recorded server reads pages with it). ``paginate`` works on node views (the JSON
5
+ a circuit record holds); ``find`` routes a node id to the page that holds it. A paged node keeps
6
+ its own numbers and gains ``paged``: its children WERE examined and are stored elsewhere, which
7
+ is not the same as ``unexamined`` (members dropped from a ``+N more`` group, never expanded).
8
+ Node ids are preorder numbers, so the ids below a paged node are the ``descendants`` that follow
9
+ its own.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+ from typing import Any
16
+
17
+ from .bounded import json_bytes
18
+ from .records import num
19
+
20
+ PAGE_SCHEMA = "mdb-circuit-page-v1"
21
+ # One page (the record's root page or a child page) holds at most this much canonical JSON and
22
+ # this many values. Measured at 40 layers (qwen3 tiny, top=8 depth=3): 371 nodes, 66 KiB, 3576
23
+ # values, ~178 bytes a node, so the record's own 64 KiB bound is what a large circuit hits first.
24
+ PAGE_BYTES = 32 * 1024
25
+ PAGE_VALUES = 1500
26
+
27
+
28
+ class PageError(ValueError):
29
+ """A circuit page cannot be made, found or read."""
30
+
31
+
32
+ def _values(x: Any) -> int:
33
+ if isinstance(x, dict):
34
+ return 1 + sum(_values(v) for v in x.values())
35
+ if isinstance(x, list):
36
+ return 1 + sum(_values(v) for v in x)
37
+ return 1
38
+
39
+
40
+ def fits(node: dict[str, Any]) -> bool:
41
+ return len(json_bytes(node)) <= PAGE_BYTES and _values(node) <= PAGE_VALUES
42
+
43
+
44
+ def total(node: dict[str, Any]) -> int:
45
+ """Nodes in ``node``'s subtree, itself included, counting the ones held in pages."""
46
+ paged = node.get("paged")
47
+ return (1 + sum(total(c) for c in node.get("children", ()))
48
+ + (int(paged["descendants"]["value"]) if paged else 0))
49
+
50
+
51
+ def _inline(node: dict[str, Any]) -> list[dict[str, Any]]:
52
+ """Descendants of ``node`` that still hold their children inline."""
53
+ out = []
54
+ for child in node.get("children", ()):
55
+ if child.get("children"):
56
+ out.append(child)
57
+ out += _inline(child)
58
+ return out
59
+
60
+
61
+ def paginate(node: dict[str, Any], put: Callable[[dict[str, Any]], dict[str, Any]],
62
+ meta: dict[str, Any]) -> None:
63
+ """Make ``node`` fit one page: the descendant with the largest subtree has its children
64
+ moved to a child page (``put`` stores it and returns its pointer) until it fits. A child page
65
+ is fitted the same way, so no page is over ``PAGE_BYTES`` / ``PAGE_VALUES``."""
66
+ while not fits(node):
67
+ candidates = _inline(node)
68
+ if not candidates:
69
+ raise PageError("a circuit node does not fit one page even with every child "
70
+ "paged; lower top")
71
+ child = max(candidates, key=lambda c: len(json_bytes(c)))
72
+ below, kids = total(child) - 1, len(child["children"])
73
+ subtree = dict(child)
74
+ paginate(subtree, put, meta)
75
+ pointer = put({"schema": PAGE_SCHEMA, **meta, "node": subtree})
76
+ del child["children"]
77
+ child["paged"] = {
78
+ "state": "paged",
79
+ "children": num(kids, "derived-exact"), "descendants": num(below, "derived-exact"),
80
+ "pointer": pointer,
81
+ "meaning": "the children of this node were examined; they are stored as a "
82
+ "sha256-checked page, not listed here (`circuit show ID node=ID`, or "
83
+ "the stored route with node=ID, reads it)"}
84
+
85
+
86
+ def find(node: dict[str, Any], wanted: str, load: Callable[[dict[str, Any]], dict[str, Any]]
87
+ ) -> dict[str, Any] | None:
88
+ """The page for node ``wanted`` below ``node`` (a node view of a root page or a child page):
89
+ its child page when it is paged, else its inline subtree as an ``inline`` page. ``load``
90
+ resolves a pointer to a checked page."""
91
+ number = int(wanted[1:])
92
+ for child in node.get("children", ()):
93
+ first = int(child["id"][1:])
94
+ if not first <= number < first + total(child):
95
+ continue
96
+ if child["id"] == wanted:
97
+ if "paged" in child:
98
+ return load(child["paged"]["pointer"])
99
+ return {"schema": PAGE_SCHEMA, "state": "inline", "node": child}
100
+ if "paged" in child:
101
+ return find(load(child["paged"]["pointer"])["node"], wanted, load)
102
+ return find(child, wanted, load)
103
+ return None
104
+
105
+
106
+ def locate(root: dict[str, Any], count: int, wanted: Any,
107
+ load: Callable[[dict[str, Any]], dict[str, Any]]) -> dict[str, Any]:
108
+ """``find`` from the record's root, with the id checked (``n1..n<count>``)."""
109
+ if not (isinstance(wanted, str) and wanted[:1] == "n" and wanted[1:].isdigit()
110
+ and 1 <= int(wanted[1:]) <= count):
111
+ raise PageError(f"no node {wanted!r} (ids n1..n{count})")
112
+ if wanted == root["id"]:
113
+ return {"schema": PAGE_SCHEMA, "state": "inline", "node": root}
114
+ found = find(root, wanted, load)
115
+ if found is None:
116
+ raise PageError(f"no node {wanted!r} (ids n1..n{count})")
117
+ return found