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,306 @@
1
+ """Core files, now checkpoints (``engine.checkpoint``).
2
+
3
+ ``dump(run, path, ...)`` writes a checkpoint file (``mdb-checkpoint-file-v2``): the state at the
4
+ cut as content-addressed tensors, rehydrated with no prefix recompute, exact at any cursor
5
+ (a cut inside a row included). ``load(path)`` reads both that and the legacy core file
6
+ (``mdb-core-file-v1``: the K/V of rows ``0..K-1`` at ``t<K>.start``, captured values and a sealed
7
+ ``core-file`` record), which this module keeps reading:
8
+
9
+ * ``load`` checks the record seal and every tensor digest (refusing a changed file).
10
+ * ``CoreFile.run(adapter)`` seeds a ``Session`` of ``adapter`` with that state and returns a
11
+ ``Run`` rooted there. A v1 file did not record the cut's parent, so its root is a foreign
12
+ lineage (``run.lineage["root"] == "checkpoint"``): its fingerprints are not those of the
13
+ source run. On another dtype or weights it is a replica, refused unless ``replica=True``.
14
+ * ``CoreFile.null_check(adapter)``: runs the replica to each captured address and records
15
+ ``argmax_equal`` (logits) and ``max_abs_diff`` against the captured values (measured).
16
+ * ``dump_v1`` writes the legacy format (kept for compatibility tests).
17
+
18
+ Structural refusals: another family, layer count, KV heads, head_dim or vocabulary than the dump's.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ import torch
28
+
29
+ from .ports import tensor_digest
30
+
31
+ SCHEMA = "mdb-core-file-v1"
32
+
33
+
34
+ def _shape_of(adapter: Any) -> dict[str, Any]:
35
+ return {"family": adapter.spec.model_type, "layers": int(adapter.layers),
36
+ "kv_heads": int(adapter.num_kv_heads), "head_dim": int(adapter.head_dim),
37
+ "vocab": int(adapter.vocab_size)}
38
+
39
+
40
+ def dump(run: Any, path: str | Path, *, row: int | None = None, at: str | None = None,
41
+ capture: tuple[str, ...] | None = None, session_id: str | None = None,
42
+ history: str = "row") -> dict[str, Any]:
43
+ """Write a checkpoint file of ``run`` (``engine.checkpoint.save``; default: at the cursor)
44
+ and return its sealed record."""
45
+ from . import checkpoint
46
+
47
+ return checkpoint.save(run, path, row=row, at=at, capture=capture, session_id=session_id,
48
+ history=history)
49
+
50
+
51
+ def dump_v1(run: Any, path: str | Path, *, row: int | None = None,
52
+ capture: tuple[str, ...] | None = None, session_id: str | None = None
53
+ ) -> dict[str, Any]:
54
+ """Write a legacy ``mdb-core-file-v1`` core file of ``run`` split at ``t<row>.start``
55
+ (default: the run's first stepped row) and return its sealed record (module docstring)."""
56
+ from mdb.core.custody import custody
57
+ from mdb.core.kinds import CORE_FILE # noqa: F401 (declares the kind)
58
+ from mdb.core.records import num, seal_record
59
+
60
+ row = run.first_row if row is None else int(row)
61
+ found = [i for i, m in enumerate(run._trail) if m.row == row and m.label == "start"]
62
+ if not found:
63
+ raise ValueError(f"the run holds no t{row}.start boundary (first stepped row "
64
+ f"t{run.first_row}, cursor {run.where}); dump at a row it has started")
65
+ index = found[-1]
66
+ payload = run._cut_of(index).payload
67
+ keys = [k.detach().to("cpu") for k in payload["keys"]]
68
+ values = [v.detach().to("cpu") for v in payload["values"]]
69
+ tokens = [int(t) for t in payload["tokens"][0].tolist()]
70
+ last = len(run.tokens) - 1
71
+ # edits/cells the run committed AFTER the split are not in the stored cache: a captured
72
+ # value that includes them would fail the replica's null check and blame the replica
73
+ post = [m for m in run._trail[index:-1] if m.edits or m.cells]
74
+ if capture is None:
75
+ capture = (f"t{last}.logits",) if not post and run.parse(f"t{last}.logits") \
76
+ <= run.parse(run.where) else ()
77
+ elif post and capture:
78
+ raise ValueError(
79
+ f"the run committed edits after t{row}.start ({len(post)} transitions): a captured "
80
+ "value would include them but the core file replays only the prefix; dump with "
81
+ "capture=() or dump before editing")
82
+ captured = {address: run.read(address).detach().to("cpu") for address in capture}
83
+ tensors = {f"keys.{i}": k for i, k in enumerate(keys)}
84
+ tensors.update({f"values.{i}": v for i, v in enumerate(values)})
85
+ tensors.update({f"captured.{a}": t for a, t in captured.items()})
86
+ manifest = {name: {"sha256": tensor_digest(t), "shape": list(t.shape),
87
+ "dtype": str(t.dtype).removeprefix("torch.")}
88
+ for name, t in tensors.items()}
89
+ adapter = run.adapter
90
+ body = {
91
+ "schema": SCHEMA, "split": {"row": row, "tokens": len(tokens),
92
+ "tokens_sha256": hashlib.sha256(str(tokens).encode()).hexdigest()},
93
+ "prompt": {"tokens": list(run.tokens)[:64], "length": len(run.tokens),
94
+ "sha256": hashlib.sha256(str(list(run.tokens)).encode()).hexdigest()},
95
+ "shape": _shape_of(adapter),
96
+ "source": {"dtype": str(adapter.dtype).removeprefix("torch."),
97
+ "device": str(adapter.device), "where": run.where,
98
+ "cut": run._trail[index].fingerprint},
99
+ "procedure": {"prefill": int(run.prefill), "first_row": int(run.first_row),
100
+ "prompt_rows": len(run.tokens)},
101
+ "path_edits": [{"transition": e["transition"], "layer": e["layer"],
102
+ "count": len(e["edits"])} for e in run._path_manifest(index)][:64],
103
+ "edited": bool(run._path_manifest(index)),
104
+ "post_split_edits": len(post),
105
+ "captured": sorted(captured)[:64],
106
+ "tensors": {"count": len(manifest),
107
+ "sha256": hashlib.sha256(str(sorted((k, v["sha256"]) for k, v in
108
+ manifest.items())).encode()).hexdigest()},
109
+ "bytes": num(float(sum(t.numel() * t.element_size() for t in tensors.values())),
110
+ "measured"),
111
+ "custody": custody("mdb-stepped"),
112
+ }
113
+ from saturn.values import digest
114
+
115
+ from mdb.core.pointers import seal_digest
116
+
117
+ session = session_id or "mdb-run:" + seal_digest({"model": adapter.model_identity,
118
+ "prompt": digest(run.tokens)})[:32]
119
+ record = seal_record(session_id=session, kind="core-file",
120
+ model_identity=adapter.model_identity,
121
+ execution=dict(adapter.execution), authority="measured", body=body)
122
+ import json
123
+
124
+ # the record and manifest as JSON text: plain data only, so ``weights_only`` loading works
125
+ torch.save({"schema": SCHEMA, "record": json.dumps(record), "manifest": json.dumps(manifest),
126
+ "prompt": list(run.tokens), "tokens": tokens,
127
+ "keys": keys, "values": values, "captured": captured}, str(path))
128
+ return record
129
+
130
+
131
+ class CoreFile:
132
+ """A loaded, digest-checked core file (``load``)."""
133
+
134
+ def __init__(self, data: dict[str, Any], path: str | None = None):
135
+ self.path = path
136
+ self.record = data["record"]
137
+ self.manifest = data["manifest"]
138
+ self.prompt = [int(t) for t in data["prompt"]]
139
+ self.tokens = [int(t) for t in data["tokens"]]
140
+ self.keys, self.values = data["keys"], data["values"]
141
+ self.captured = data["captured"]
142
+ self.split = int(self.record["body"]["split"]["row"])
143
+
144
+ @property
145
+ def id(self) -> str:
146
+ return self.record["id"]
147
+
148
+ def _check(self, adapter: Any) -> None:
149
+ want, have = self.record["body"]["shape"], _shape_of(adapter)
150
+ differ = [k for k in want if want[k] != have[k]]
151
+ if differ:
152
+ raise ValueError("core file of another model shape: " + ", ".join(
153
+ f"{k} {want[k]} vs {have[k]}" for k in differ))
154
+
155
+ def session(self, adapter: Any) -> Any:
156
+ """A ``Session`` of ``adapter`` at the split, the stored K/V moved once to the adapter's
157
+ device and dtype."""
158
+ from saturn.core import Session
159
+
160
+ self._check(adapter)
161
+ device, dtype = adapter.device, adapter.dtype
162
+
163
+ def move(t: torch.Tensor) -> torch.Tensor:
164
+ return t.to(device=device, dtype=dtype) if (t.dtype != dtype or str(t.device)
165
+ != str(torch.device(device))) else t.clone()
166
+
167
+ state = {"tokens": torch.tensor([self.tokens], dtype=torch.long, device=device),
168
+ "keys": [move(k) for k in self.keys], "values": [move(v) for v in self.values],
169
+ "layer": 0, "phase": "embed", "hidden": None, "logits": None,
170
+ "sampled_token": None}
171
+ if self.split < len(self.prompt) - 1:
172
+ state["prompt"] = torch.tensor([self.prompt], dtype=torch.long, device=device)
173
+ return Session(adapter, state)
174
+
175
+ def run(self, adapter: Any, *, lookahead: str | None = None, check: bool = True,
176
+ name: str | None = None, replica: bool = False, verify: bool | str = False,
177
+ root: Any = None) -> Any:
178
+ """A ``Run`` of ``adapter`` rooted at the split (module docstring); ``run.core`` names the
179
+ file and ``run.core_check`` holds the null check (``check``). Another dtype or weights
180
+ is a replica, refused unless ``replica=True``. A v1 file holds no recipe, so its path
181
+ is never verified: ``verify=True`` raises, ``verify="report"`` records why."""
182
+ from .checkpoint import CheckpointUnverified
183
+ from .run import Run
184
+
185
+ unverifiable = {"ok": False, "state": "unresolved", "checkpoint": self.id,
186
+ "reason": "a v1 core file holds no recipe to replay"}
187
+ if verify is True:
188
+ raise CheckpointUnverified(unverifiable)
189
+
190
+ lookahead = "none" if lookahead is None else lookahead
191
+ source_dtype = self.record["body"]["source"]["dtype"]
192
+ dtype = str(adapter.dtype).removeprefix("torch.")
193
+ same_identity = adapter.model_identity == self.record["model_identity"]
194
+ # a replica is another dtype OR other weights (same shape, e.g. Base vs Instruct)
195
+ is_replica = dtype != source_dtype or not same_identity
196
+ self._check(adapter)
197
+ if is_replica and not replica:
198
+ what = "another model (model identity differs)" if not same_identity else (
199
+ f"another dtype ({source_dtype} dumped, {dtype} here)")
200
+ raise ValueError(f"core file of {what}; load it as a labelled replica with "
201
+ "replica=True")
202
+ cut = self.session(adapter).capture(retain=False)
203
+ run = Run(adapter, self.prompt, root=cut, prefill=self.split, lookahead=lookahead)
204
+ run.name = name or f"core@{self.id[:12]}"
205
+ run.lineage = {"root": "checkpoint", "checkpoint": self.id, "legacy": SCHEMA,
206
+ "cut": cut.fingerprint, "replica": is_replica,
207
+ "checkpoints": [self.id]}
208
+ run._origin = self
209
+ run.core = {"record": self.id, "path": self.path, "split": self.split,
210
+ "where": run.where, "cut": cut.fingerprint, "history": "cursor",
211
+ "exact": False, "lineage": dict(run.lineage),
212
+ "source_dtype": source_dtype, "dtype": dtype,
213
+ "same_identity": same_identity, "replica": is_replica,
214
+ "holds": [], "holds_dropped": []}
215
+ run.from_checkpoint = {"checkpoint": self.id, "path": "unverified"}
216
+ if is_replica:
217
+ run.from_checkpoint["replica"] = True
218
+ if verify == "report":
219
+ run.core["verified"] = unverifiable
220
+ run.core_check = self.null_check(adapter, lookahead=lookahead) if check else None
221
+ if is_replica:
222
+ ok = (run.core_check or {}).get("ok")
223
+ run.from_checkpoint["null_check"] = None if ok is None else bool(ok)
224
+ return run
225
+
226
+ def null_check(self, adapter: Any, *, lookahead: str = "none") -> dict[str, Any]:
227
+ """Run a fresh replica to every captured address and compare (measured): per address
228
+ ``max_abs_diff`` (float64) and, for logits, ``argmax_equal``; ``ok`` when every argmax
229
+ agrees (and every difference is 0 on the same dtype and identity)."""
230
+ if not self.captured:
231
+ return {"state": "unresolved", "reason": "the core file captured no value"}
232
+ from .run import Run
233
+
234
+ cut = self.session(adapter).capture(retain=False)
235
+ replica = Run(adapter, self.prompt, root=cut, prefill=self.split, lookahead=lookahead)
236
+ out: dict[str, Any] = {"checks": {}, "authority": "measured"}
237
+ same = (str(adapter.dtype).removeprefix("torch.") == self.record["body"]["source"]["dtype"]
238
+ and adapter.model_identity == self.record["model_identity"])
239
+ ok = True
240
+ for address in sorted(self.captured, key=replica.parse):
241
+ replica.until(address)
242
+ got = replica.read(address).detach().to("cpu")
243
+ want = self.captured[address]
244
+ diff = float((got.to(torch.float64) - want.to(torch.float64)).abs().max())
245
+ entry: dict[str, Any] = {"max_abs_diff": diff}
246
+ if address.endswith("logits"):
247
+ entry["argmax_equal"] = int(got.reshape(-1).argmax()) == int(want.reshape(-1).argmax())
248
+ entry["argmax"] = [int(want.reshape(-1).argmax()), int(got.reshape(-1).argmax())]
249
+ ok = ok and entry["argmax_equal"]
250
+ if same:
251
+ ok = ok and diff == 0.0
252
+ out["checks"][address] = entry
253
+ out.update(ok=ok, same_dtype_and_identity=same,
254
+ rule="argmax equal at every captured logits" + (
255
+ " and bit-identical values (same dtype and identity)" if same else ""))
256
+ return out
257
+
258
+
259
+ def load(path: str | Path) -> Any:
260
+ """Read a checkpoint file (``engine.checkpoint``) or a legacy v1 core file, verifying the
261
+ record seal and every tensor's sha256."""
262
+ from .checkpoint import load_file
263
+
264
+ return load_file(path)
265
+
266
+
267
+ def load_v1(data: dict[str, Any], path: str | Path) -> CoreFile:
268
+ """A legacy v1 core file from its ``torch.load``-ed dict (``load``), checked."""
269
+ import json
270
+
271
+ from mdb.core.kinds import CORE_FILE # noqa: F401 (declares the kind)
272
+ from mdb.core.records import verify_record
273
+
274
+ if data.get("schema") != SCHEMA:
275
+ raise ValueError(f"{path} is not an mdb core file")
276
+ data["record"], data["manifest"] = json.loads(data["record"]), json.loads(data["manifest"])
277
+ verify_record(data["record"])
278
+ manifest = data["manifest"]
279
+ tensors = {f"keys.{i}": k for i, k in enumerate(data["keys"])}
280
+ tensors.update({f"values.{i}": v for i, v in enumerate(data["values"])})
281
+ tensors.update({f"captured.{a}": t for a, t in data["captured"].items()})
282
+ if set(tensors) != set(manifest):
283
+ raise ValueError("core file tensors differ from its manifest")
284
+ for name, tensor in tensors.items():
285
+ if tensor_digest(tensor) != manifest[name]["sha256"]:
286
+ raise ValueError(f"core file tensor {name} differs from its sha256")
287
+ summary = hashlib.sha256(str(sorted((k, v["sha256"]) for k, v in manifest.items()))
288
+ .encode()).hexdigest()
289
+ if summary != data["record"]["body"]["tensors"]["sha256"]:
290
+ raise ValueError("core file manifest differs from its sealed record")
291
+ body = data["record"]["body"]
292
+ prompt = [int(t) for t in data["prompt"]]
293
+ tokens = [int(t) for t in data["tokens"]]
294
+ if hashlib.sha256(str(prompt).encode()).hexdigest() != body["prompt"]["sha256"] \
295
+ or len(prompt) != body["prompt"]["length"]:
296
+ raise ValueError("core file prompt differs from its sealed prompt sha256")
297
+ split = body["split"]
298
+ if len(tokens) != split["tokens"] or tokens != prompt[:len(tokens)] or (
299
+ "tokens_sha256" in split
300
+ and hashlib.sha256(str(tokens).encode()).hexdigest() != split["tokens_sha256"]):
301
+ raise ValueError("core file tokens differ from its sealed split (or are not a prompt "
302
+ "prefix)")
303
+ return CoreFile(data, str(path))
304
+
305
+
306
+ __all__ = ["CoreFile", "SCHEMA", "dump", "dump_v1", "load", "load_v1"]
mdb/engine/edits.py ADDED
@@ -0,0 +1,323 @@
1
+ """State-cell edits: a write into the key/value cache that the native decoder layers read.
2
+
3
+ An occurrence and a state cell are different things. ``t18.L20.v`` is the value row 18 wrote
4
+ when it ran layer 20 (edited at that occurrence with ``Run.set``). ``cache.L20.v[kv0,row=18]``
5
+ is the cell as later rows read it: ``Run.set_cell`` edits it at any cursor after the write, and
6
+ the edit takes effect for every read of the cell that has not happened yet. Reads that already
7
+ happened are not recomputed.
8
+
9
+ Realisation is native. A ``CellEdit`` rides on the next layer transition (``PortController``
10
+ ``cells=``): its write lands in the ``DynamicCache`` object that transition hands the native
11
+ layer, by copy-on-write of that layer's key or value tensor (the cut a checkpoint holds keeps
12
+ the unedited tensor). ``timing`` says when, inside that transition:
13
+
14
+ * ``before``: at the layer's entry, before its attention reads the cache;
15
+ * ``after``: at the layer's exit, after its attention read. Used when the cursor sits in the
16
+ cell's own layer at or past the read boundary (``CELL_BOUNDARY``): ``kr`` for a key cell
17
+ (the key argument of the eager call holds the cached keys), ``p`` for a value cell (a stop at
18
+ ``p`` computes the value mix natively).
19
+
20
+ Operators (``CELL_OPS``): ``replace``, ``add``, ``scale`` as for ports (the operand cast to the
21
+ cell dtype, one rounded op), and ``mix DOSE`` toward a value: ``cell + DOSE * (value - cell)``
22
+ computed in float64 from the native bits of the cell and the value, rounded once to the cell
23
+ dtype (on the cell's device; on the host for a device without float64); ``mix 1`` is the exact
24
+ copy of the value's words and ``mix 0`` leaves the cell's words as they are.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from collections.abc import Sequence
30
+ from dataclasses import dataclass
31
+ from typing import Any
32
+
33
+ import torch
34
+
35
+ from .ports import changed_fraction, max_abs, tensor_digest, with_labels
36
+
37
+ CELL_OPS = ("replace", "add", "scale", "mix")
38
+ CELL_BOUNDARY = {"k": "kr", "v": "p"}
39
+ CELL_READ = {"k": "kr", "v": "A"}
40
+ TIMINGS = ("before", "after")
41
+ CELL_AXES = ("batch", "kv_head", "row", "head_dim")
42
+
43
+
44
+ def _picks(items: Sequence[int] | None, name: str) -> tuple[int, ...] | None:
45
+ if items is None:
46
+ return None
47
+ out = tuple(int(i) for i in items)
48
+ if not out:
49
+ raise ValueError(f"cell {name} selection names no element")
50
+ if any(i < 0 for i in out) or len(set(out)) != len(out):
51
+ raise ValueError(f"cell {name} indices must be distinct nonnegative integers")
52
+ return out
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class CellEdit:
57
+ """One staged write into ``cache.L<layer>.<tensor>``.
58
+
59
+ ``rows`` (required), ``kv`` and ``d`` (None: the whole axis) pick the elements. ``value`` is a
60
+ finite number or a floating tensor of the picked block's shape ``(1, kv, rows, d)``. ``dose``
61
+ is required for ``mix`` and refused otherwise. ``staged_at`` is the transition count of the
62
+ boundary the cursor stood on when the edit was staged (which stops ``reverse`` re-stages it
63
+ at). ``selection`` is the selector text and ``origin`` the pointer of a value taken from
64
+ another run (``{origin, via, address, sha256, where, cut, recipe}``), both recorded verbatim.
65
+ """
66
+
67
+ layer: int
68
+ tensor: str
69
+ rows: tuple[int, ...]
70
+ value: Any
71
+ op: str = "replace"
72
+ kv: tuple[int, ...] | None = None
73
+ d: tuple[int, ...] | None = None
74
+ dose: float | None = None
75
+ timing: str = "before"
76
+ staged_at: int = 0
77
+ selection: str | None = None
78
+ origin: dict[str, Any] | None = None
79
+
80
+ def __post_init__(self) -> None:
81
+ if type(self.layer) is not int or self.layer < 0:
82
+ raise ValueError("cell layer must be a nonnegative integer")
83
+ if self.tensor not in ("k", "v"):
84
+ raise ValueError("a cache cell is k or v")
85
+ if self.op not in CELL_OPS:
86
+ raise ValueError(f"cell op must be one of {', '.join(CELL_OPS)}")
87
+ if self.timing not in TIMINGS:
88
+ raise ValueError(f"cell timing must be one of {', '.join(TIMINGS)}")
89
+ object.__setattr__(self, "rows", _picks(self.rows, "row"))
90
+ object.__setattr__(self, "kv", _picks(self.kv, "kv"))
91
+ object.__setattr__(self, "d", _picks(self.d, "d"))
92
+ if (self.op == "mix") != (self.dose is not None):
93
+ raise ValueError("mix needs a dose, and only mix takes one")
94
+ if self.dose is not None:
95
+ dose = float(self.dose)
96
+ if dose != dose or dose in (float("inf"), float("-inf")):
97
+ raise ValueError("a mix dose must be finite")
98
+ object.__setattr__(self, "dose", dose)
99
+ value = self.value
100
+ if isinstance(value, torch.Tensor):
101
+ if not value.is_floating_point():
102
+ raise ValueError("cell edit tensors must be floating point")
103
+ if value.dim() != 4 or value.shape[0] != 1 or value.shape[2] != len(self.rows):
104
+ raise ValueError(f"a cell value tensor has the block shape (1, kv, rows, d); got "
105
+ f"{list(value.shape)} for {len(self.rows)} row(s)")
106
+ if not bool(torch.isfinite(value).all()):
107
+ raise ValueError("cell edit values must be finite")
108
+ object.__setattr__(self, "value", value.detach().to("cpu", copy=True))
109
+ elif type(value) in (int, float):
110
+ if value != value or value in (float("inf"), float("-inf")):
111
+ raise ValueError("edit scalars must be finite")
112
+ object.__setattr__(self, "value", float(value))
113
+ else:
114
+ raise ValueError("cell edit value must be a tensor or a finite number")
115
+ if type(self.staged_at) is not int or self.staged_at < 0:
116
+ raise ValueError("staged_at must be a nonnegative transition count")
117
+
118
+ # --- what the edit names ------------------------------------------------------------
119
+
120
+ @property
121
+ def port(self) -> str:
122
+ """The cell's name without a selector: ``cache.L<layer>.<tensor>``."""
123
+ return f"cache.L{self.layer}.{self.tensor}"
124
+
125
+ @property
126
+ def text(self) -> str:
127
+ """The cell address with its selector, as the user wrote it (canonical picks)."""
128
+ return self.port + f"[{self.selection}]" if self.selection else self.port
129
+
130
+ def block_shape(self, kv_heads: int, head_dim: int) -> tuple[int, int, int, int]:
131
+ return (1, len(self.kv) if self.kv else kv_heads, len(self.rows),
132
+ len(self.d) if self.d else head_dim)
133
+
134
+ def check(self, shape: Sequence[int]) -> None:
135
+ """Refuse an edit that does not fit a cache tensor of ``shape`` ``(1, KV, T, d_h)``."""
136
+ _, kv_heads, length, head_dim = (int(s) for s in shape)
137
+ if max(self.rows) >= length:
138
+ raise ValueError(f"{self.port} holds rows 0..{length - 1} here; row {max(self.rows)} "
139
+ "is not written yet")
140
+ if self.kv is not None and max(self.kv) >= kv_heads:
141
+ raise ValueError(f"kv {max(self.kv)} is out of range ({kv_heads} kv heads)")
142
+ if self.d is not None and max(self.d) >= head_dim:
143
+ raise ValueError(f"d {max(self.d)} is out of range (head_dim {head_dim})")
144
+ if isinstance(self.value, torch.Tensor):
145
+ want = self.block_shape(kv_heads, head_dim)
146
+ if tuple(self.value.shape) != want:
147
+ raise ValueError(f"the value has shape {list(self.value.shape)}; the selected "
148
+ f"cell block has shape {list(want)}")
149
+
150
+ def index(self, shape: Sequence[int], device: Any = "cpu") -> tuple[Any, ...]:
151
+ """Advanced index of the picked block in a cache tensor of ``shape``."""
152
+ _, kv_heads, _, head_dim = (int(s) for s in shape)
153
+ kv = torch.tensor(self.kv if self.kv else range(kv_heads), device=device)
154
+ rows = torch.tensor(self.rows, device=device)
155
+ d = torch.tensor(self.d if self.d else range(head_dim), device=device)
156
+ return (0, kv.view(-1, 1, 1), rows.view(1, -1, 1), d.view(1, 1, -1))
157
+
158
+ def mask(self, shape: Sequence[int]) -> torch.Tensor:
159
+ """The picked elements as a bool mask over a cache tensor of ``shape``."""
160
+ out = torch.zeros(tuple(int(s) for s in shape), dtype=torch.bool)
161
+ out[self.index(shape)] = True
162
+ return out
163
+
164
+ @property
165
+ def exact_copy(self) -> bool:
166
+ """Whether every picked element becomes the cast of the supplied value (replace, mix 1)."""
167
+ return self.op == "replace" or (self.op == "mix" and self.dose == 1.0)
168
+
169
+ # --- realisation ----------------------------------------------------------------------
170
+
171
+ def _requested(self) -> torch.Tensor:
172
+ """The request in float64 on the host, where the value is stored (an exact widening)."""
173
+ if isinstance(self.value, torch.Tensor):
174
+ return self.value[0].to(torch.float64)
175
+ return torch.tensor(self.value, dtype=torch.float64)
176
+
177
+ def _cast(self, dtype: torch.dtype) -> torch.Tensor:
178
+ """The operand of ``replace``, ``add``, ``scale`` and ``mix 1``: the value cast once to
179
+ the cell dtype, on the host where the value is stored."""
180
+ if isinstance(self.value, torch.Tensor):
181
+ return self.value[0].to(dtype)
182
+ return torch.tensor(self.value, dtype=torch.float64).to(dtype)
183
+
184
+ def _exact(self, x: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
185
+ """The float64 request on float64 ``x`` with the float64 operand ``v`` (same device)."""
186
+ if self.exact_copy:
187
+ return v.expand(x.shape).clone()
188
+ if self.op == "add":
189
+ return x + v
190
+ if self.op == "scale":
191
+ return x * v
192
+ return x + self.dose * (v - x)
193
+
194
+ def ideal(self, block: torch.Tensor) -> torch.Tensor:
195
+ """The exact float64 result on the picked block ``block`` (the request, unrounded)."""
196
+ x = block.detach().to("cpu", torch.float64)
197
+ return self._exact(x, self._requested().expand(x.shape))
198
+
199
+ def apply_block(self, block: torch.Tensor) -> torch.Tensor:
200
+ """The written block: the native arithmetic of the operator on the picked block."""
201
+ return self._apply(block, None if self.op == "mix" and not self.exact_copy else
202
+ self._cast(block.dtype).to(block.device))
203
+
204
+ def _apply(
205
+ self, block: torch.Tensor, cast: torch.Tensor | None, host: torch.Tensor | None = None
206
+ ) -> torch.Tensor:
207
+ """``apply_block`` given the cast operand on the block's device (None for ``mix``, which
208
+ casts nothing: ``mix DOSE`` widens both sides to float64 and rounds the result once).
209
+ ``host``: the block already on the host, used where float64 needs the host."""
210
+ if self.exact_copy:
211
+ return cast.expand(block.shape).clone()
212
+ if self.op == "add":
213
+ return block + cast
214
+ if self.op == "scale":
215
+ return block * cast
216
+ if self.dose == 0.0:
217
+ return block.clone() # exactly the identity (x + 0 * d would turn -0.0 into +0.0)
218
+ device = block.device if block.device.type != "mps" else torch.device("cpu")
219
+ x = (host if host is not None and device.type == "cpu" else block).to(device, torch.float64)
220
+ mixed = self._exact(x, self._requested().to(device))
221
+ return mixed.to(block.device, block.dtype)
222
+
223
+ def realise(self, cache: torch.Tensor) -> tuple[torch.Tensor, dict[str, Any]]:
224
+ """``(new cache tensor, record)``: a copy of ``cache`` with the block written (the input
225
+ is never modified). The record: ``realised_sha256`` of the written block, its dtype,
226
+ ``cast_*`` (the requested operand against its cast to the cell dtype; absent for ``mix``
227
+ below 1, which casts no operand), ``realised_*`` (the written block against the exact
228
+ float64 request), ``changed_fraction`` and ``count``.
229
+
230
+ The operand is computed once and each tensor crosses to the host once: the picked block
231
+ and the written block, for the record (the value is stored on the host already).
232
+ """
233
+ self.check(cache.shape)
234
+ index = self.index(cache.shape, cache.device)
235
+ block = cache[index]
236
+ cast = None if self.op == "mix" and not self.exact_copy else self._cast(block.dtype)
237
+ before = block.detach().to("cpu")
238
+ written = self._apply(block, None if cast is None else cast.to(block.device), before)
239
+ out = cache.clone()
240
+ out[index] = written
241
+ after = written.detach().to("cpu")
242
+ requested = self._requested()
243
+ x = before.to(torch.float64)
244
+ effect = max_abs((after.to(torch.float64) - self._exact(x, requested.expand(x.shape))).abs())
245
+ record: dict[str, Any] = {
246
+ "realised_dtype": str(written.dtype),
247
+ "realised_sha256": tensor_digest(after),
248
+ }
249
+ if cast is not None:
250
+ cast_error = max_abs((cast.to(torch.float64) - requested).abs())
251
+ record["cast_exact"] = cast_error == 0.0
252
+ record["cast_max_abs_error"] = cast_error
253
+ record.update({
254
+ "realised_exact": effect == 0.0,
255
+ "realised_max_abs_error": effect,
256
+ "changed_fraction": changed_fraction(before, after),
257
+ "count": int(block.numel()),
258
+ })
259
+ return out, with_labels(record)
260
+
261
+ # --- records ----------------------------------------------------------------------------
262
+
263
+ def manifest(self) -> dict[str, Any]:
264
+ """Plain JSON of the request (tensors by payload sha256): what checkpoints and replay
265
+ recipes hold. ``port`` is ``cache.L<l>.<k|v>``, so an edit list stays one list."""
266
+ value = self.value
267
+ if isinstance(value, torch.Tensor):
268
+ described: dict[str, Any] = {"kind": "tensor", "sha256": tensor_digest(value),
269
+ "shape": list(value.shape), "dtype": str(value.dtype)}
270
+ else:
271
+ described = {"kind": "scalar", "value": value}
272
+ cell = {"layer": self.layer, "tensor": self.tensor, "rows": list(self.rows),
273
+ "kv": None if self.kv is None else list(self.kv),
274
+ "d": None if self.d is None else list(self.d), "timing": self.timing,
275
+ "staged_at": self.staged_at}
276
+ entry: dict[str, Any] = {"port": self.port, "op": self.op, "value": described,
277
+ "cell": cell}
278
+ if self.dose is not None:
279
+ entry["dose"] = self.dose
280
+ if self.selection is not None:
281
+ entry["selection"] = self.selection
282
+ if self.origin is not None:
283
+ entry["origin"] = dict(self.origin)
284
+ return entry
285
+
286
+ @property
287
+ def key(self) -> str:
288
+ described = self.manifest()["value"]
289
+ return described["sha256"] if described["kind"] == "tensor" else f"scalar:{described['value']}"
290
+
291
+ @classmethod
292
+ def from_manifest(cls, manifest: dict[str, Any], value: Any) -> CellEdit:
293
+ """The edit a ``manifest()`` describes, with ``value`` (the tensor it names, or None for a
294
+ scalar)."""
295
+ cell = manifest["cell"]
296
+ described = manifest["value"]
297
+ return cls(
298
+ int(cell["layer"]), cell["tensor"], tuple(cell["rows"]),
299
+ described["value"] if described["kind"] == "scalar" else value,
300
+ manifest["op"], kv=cell.get("kv"), d=cell.get("d"), dose=manifest.get("dose"),
301
+ timing=cell.get("timing", "before"), staged_at=int(cell.get("staged_at", 0)),
302
+ selection=manifest.get("selection"), origin=manifest.get("origin"),
303
+ )
304
+
305
+
306
+ def is_cell(manifest: dict[str, Any]) -> bool:
307
+ """Whether an edit manifest (checkpoint or recipe edit) is a state-cell edit."""
308
+ return "cell" in manifest
309
+
310
+
311
+ def overlay(cache: torch.Tensor, cells: Sequence[CellEdit], layer: int, tensor: str
312
+ ) -> torch.Tensor:
313
+ """``cache`` (one layer's key or value tensor) with the ``before`` edits of ``cells`` that
314
+ address it written in order, as the next native read of it will see them."""
315
+ out = cache
316
+ for edit in cells:
317
+ if edit.layer == layer and edit.tensor == tensor and edit.timing == "before":
318
+ out = edit.realise(out)[0]
319
+ return out
320
+
321
+
322
+ __all__ = ["CELL_AXES", "CELL_BOUNDARY", "CELL_OPS", "CELL_READ", "CellEdit", "TIMINGS",
323
+ "is_cell", "overlay"]