model-debugger 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/core/project.py ADDED
@@ -0,0 +1,248 @@
1
+ """The engine's own durable project: a schema-3 ``project.sqlite`` plus a saturn ``store/``.
2
+
3
+ The directory is the one the lane ``mdb_lanes.project.Project`` writes and
4
+ ``mdb.core.project_read.ProjectReader`` (``mdb serve``) reads: the same seven schema-3 tables,
5
+ ``PRAGMA user_version = 3``, the same rollback-journal SQLite discipline (one connection per
6
+ operation, ``timeout=30``, ``BEGIN IMMEDIATE`` around read-modify-write) and the same session,
7
+ cut and store layout. Nothing here needs the lane package, a model or a framework.
8
+
9
+ * Creation is atomic: the database and ``store/`` are built in a hidden sibling directory and
10
+ renamed into place, so a crash leaves either no project or a whole one. When another process
11
+ wins the race the loser opens the winner's project.
12
+ * ``read_only=True`` opens SQLite with ``mode=ro`` and never creates a file or a directory, so a
13
+ read-only open (and every read through it) changes no byte of the tree.
14
+ * The index tables of ``mdb.core.index`` (records, cursor, recipes, occurrences) are additive
15
+ and created lazily by that module on its first write; this module creates only the schema-3
16
+ tables. ``db()``, ``json()``, ``read_only``, ``session()`` and ``store`` are what
17
+ ``mdb.core.index`` uses.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import shutil
24
+ import sqlite3
25
+ import tempfile
26
+ from contextlib import contextmanager
27
+ from pathlib import Path
28
+
29
+ from saturn.store import LocalStore
30
+ from saturn.values import canonical
31
+
32
+ SCHEMA_VERSION = 3
33
+ DATABASE = "project.sqlite"
34
+ STORE = "store"
35
+
36
+ # The lane project's schema-3 tables, verbatim, so either writer opens what the other made.
37
+ _SCHEMA = """
38
+ CREATE TABLE IF NOT EXISTS sessions (
39
+ id TEXT PRIMARY KEY, identity TEXT NOT NULL, execution TEXT NOT NULL,
40
+ selected TEXT NOT NULL, debug_info TEXT NOT NULL, revision INTEGER NOT NULL);
41
+ CREATE TABLE IF NOT EXISTS cuts (
42
+ session_id TEXT NOT NULL, id TEXT NOT NULL, manifest TEXT NOT NULL,
43
+ PRIMARY KEY (session_id, id));
44
+ CREATE TABLE IF NOT EXISTS receipts (
45
+ session_id TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL,
46
+ PRIMARY KEY (session_id, id));
47
+ CREATE TABLE IF NOT EXISTS imports (id TEXT PRIMARY KEY, body TEXT NOT NULL);
48
+ CREATE TABLE IF NOT EXISTS analyses (
49
+ id TEXT PRIMARY KEY, session_id TEXT NOT NULL, analyzer TEXT NOT NULL,
50
+ version TEXT NOT NULL, input_digest TEXT NOT NULL, body TEXT NOT NULL);
51
+ CREATE INDEX IF NOT EXISTS analysis_inputs
52
+ ON analyses(session_id, analyzer, version, input_digest);
53
+ CREATE TABLE IF NOT EXISTS symbols (
54
+ session_id TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL,
55
+ PRIMARY KEY(session_id, id));
56
+ CREATE TABLE IF NOT EXISTS slices (
57
+ id TEXT PRIMARY KEY, session_id TEXT NOT NULL, body TEXT NOT NULL);
58
+ PRAGMA user_version = 3;
59
+ """
60
+ _TABLES = ("sessions", "cuts", "receipts", "imports", "analyses", "symbols", "slices")
61
+
62
+
63
+ class ProjectError(ValueError):
64
+ """The directory is not a usable mdb project, or a write would break a session binding."""
65
+
66
+
67
+ def _connect(path, read_only):
68
+ if read_only:
69
+ return sqlite3.connect(Path(path).as_uri() + "?mode=ro", uri=True, timeout=30)
70
+ return sqlite3.connect(path, timeout=30)
71
+
72
+
73
+ def _fsync_tree(root):
74
+ for path in (root / DATABASE, root / STORE, root):
75
+ descriptor = os.open(path, os.O_RDONLY)
76
+ try:
77
+ os.fsync(descriptor)
78
+ except OSError: # some filesystems cannot fsync a directory; the files are flushed
79
+ pass
80
+ finally:
81
+ os.close(descriptor)
82
+
83
+
84
+ class Project:
85
+ """A durable mdb project directory, opened for writing (created when absent) or read-only."""
86
+
87
+ def __init__(self, root, *, read_only=False):
88
+ self.root = Path(root).expanduser().resolve()
89
+ self.read_only = bool(read_only)
90
+ database = self.root / DATABASE
91
+ if read_only:
92
+ if not database.is_file() or not (self.root / STORE).is_dir():
93
+ raise ProjectError(f"{self.root} is not an mdb project (read-only open needs "
94
+ f"{DATABASE} and {STORE}/)")
95
+ elif not database.is_file():
96
+ self._create()
97
+ self.store = LocalStore(self.root / STORE)
98
+ with self.db() as db:
99
+ version = db.execute("PRAGMA user_version").fetchone()[0]
100
+ if read_only and version != SCHEMA_VERSION:
101
+ raise ProjectError(f"read-only project requires schema {SCHEMA_VERSION}, found "
102
+ f"{version}; open a writable copy first")
103
+ if not read_only:
104
+ if version not in (0, 1, 2, SCHEMA_VERSION):
105
+ raise ProjectError(f"unsupported mdb project schema {version}")
106
+ present = {r[0] for r in db.execute(
107
+ "SELECT name FROM sqlite_master WHERE type='table'")}
108
+ if version != SCHEMA_VERSION or not set(_TABLES) <= present:
109
+ db.executescript(_SCHEMA) # the lane's own migration to schema 3
110
+ if not read_only:
111
+ (self.root / STORE).mkdir(exist_ok=True)
112
+
113
+ def _create(self):
114
+ """Build the project beside its final path and rename it into place (all or nothing)."""
115
+ if self.root.exists() and (not self.root.is_dir() or any(self.root.iterdir())):
116
+ raise ProjectError(f"{self.root} exists and is not an mdb project (no {DATABASE})")
117
+ self.root.parent.mkdir(parents=True, exist_ok=True)
118
+ staging = Path(tempfile.mkdtemp(prefix=f".{self.root.name}.", suffix=".creating",
119
+ dir=self.root.parent))
120
+ try:
121
+ (staging / STORE).mkdir()
122
+ db = sqlite3.connect(staging / DATABASE)
123
+ try:
124
+ db.executescript(_SCHEMA)
125
+ db.commit()
126
+ finally:
127
+ db.close()
128
+ _fsync_tree(staging)
129
+ try:
130
+ os.rename(staging, self.root) # replaces only an absent or empty directory
131
+ except OSError:
132
+ if not (self.root / DATABASE).is_file():
133
+ raise
134
+ # another process created the project first: open theirs
135
+ finally:
136
+ if staging.exists():
137
+ shutil.rmtree(staging)
138
+
139
+ @contextmanager
140
+ def db(self):
141
+ """One SQLite connection (``Row`` rows), committed on success; read-only when opened so."""
142
+ db = _connect(self.root / DATABASE, self.read_only)
143
+ db.row_factory = sqlite3.Row
144
+ try:
145
+ with db:
146
+ yield db
147
+ finally:
148
+ db.close()
149
+
150
+ @staticmethod
151
+ def json(value):
152
+ """The canonical JSON text every project row is stored as (the lane's ``_json``)."""
153
+ return canonical(value).decode("utf-8")
154
+
155
+ def _writable(self):
156
+ if self.read_only:
157
+ raise ProjectError("this project was opened read-only")
158
+
159
+ # ----------------------------------------------------------------------- sessions
160
+
161
+ def sessions(self):
162
+ """Every session: ``{session_id, model_identity, execution, selected_cut}`` by id."""
163
+ with self.db() as db:
164
+ rows = db.execute("SELECT * FROM sessions ORDER BY id").fetchall()
165
+ return [{"session_id": r["id"], "model_identity": json.loads(r["identity"]),
166
+ "execution": json.loads(r["execution"]), "selected_cut": r["selected"]}
167
+ for r in rows]
168
+
169
+ def session(self, session_id):
170
+ """The raw session row (``id, identity, execution, selected, debug_info, revision``)."""
171
+ with self.db() as db:
172
+ row = db.execute("SELECT * FROM sessions WHERE id=?", (session_id,)).fetchone()
173
+ if row is None:
174
+ raise ValueError(f"unknown project session: {session_id}")
175
+ return dict(row)
176
+
177
+ def open_session(self, session_id, *, model_identity, execution):
178
+ """Create the session bound to this model identity and execution, or reopen it.
179
+
180
+ A new session selects no cut yet (``selected`` is empty) and is at revision 0, the
181
+ revision the lane writer expects of a session it has not saved. Reopening a session
182
+ bound to another model identity or execution is refused.
183
+ """
184
+ self._writable()
185
+ if not isinstance(session_id, str) or not session_id.strip():
186
+ raise ProjectError("a project session needs a non-empty id")
187
+ identity, profile = self.json(model_identity), self.json(dict(execution))
188
+ with self.db() as db:
189
+ db.execute("BEGIN IMMEDIATE")
190
+ row = db.execute("SELECT * FROM sessions WHERE id=?", (session_id,)).fetchone()
191
+ if row is None:
192
+ db.execute("INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?)",
193
+ (session_id, identity, profile, "", self.json({}), 0))
194
+ elif row["identity"] != identity or row["execution"] != profile:
195
+ raise ProjectError(f"project session {session_id!r} is bound to another model "
196
+ "or execution")
197
+ return self.session(session_id)
198
+
199
+ def select(self, session_id, cut_id):
200
+ """Make an indexed cut the session's selected cut (one revision step)."""
201
+ self._writable()
202
+ with self.db() as db:
203
+ db.execute("BEGIN IMMEDIATE")
204
+ if db.execute("SELECT 1 FROM cuts WHERE session_id=? AND id=?",
205
+ (session_id, cut_id)).fetchone() is None:
206
+ raise ProjectError(f"cut {cut_id} is not retained in session {session_id!r}")
207
+ db.execute("UPDATE sessions SET selected=?, revision=revision+1 WHERE id=?",
208
+ (cut_id, session_id))
209
+
210
+ # ----------------------------------------------------------------------- cuts
211
+
212
+ def save_cut(self, session_id, cut):
213
+ """Publish a native cut to the store, then index it under the session (the lane order:
214
+ immutable bytes first, so an index row never names missing bytes). Returns its id."""
215
+ self._writable()
216
+ row = self.session(session_id)
217
+ if (self.json(cut.model_identity) != row["identity"]
218
+ or self.json(dict(cut.execution)) != row["execution"]):
219
+ raise ProjectError("the cut belongs to another model or execution than the session")
220
+ self.store.save(cut)
221
+ body = self.json(cut.manifest())
222
+ with self.db() as db:
223
+ db.execute("INSERT OR IGNORE INTO cuts VALUES (?, ?, ?)",
224
+ (session_id, cut.fingerprint, body))
225
+ stored = db.execute("SELECT manifest FROM cuts WHERE session_id=? AND id=?",
226
+ (session_id, cut.fingerprint)).fetchone()[0]
227
+ if stored != body:
228
+ raise ProjectError("project cut index identity collision")
229
+ return cut.fingerprint
230
+
231
+ def cut_ids(self, session_id):
232
+ """Cut ids indexed under the session, in insertion order."""
233
+ self.session(session_id)
234
+ with self.db() as db:
235
+ return [r[0] for r in db.execute(
236
+ "SELECT id FROM cuts WHERE session_id=? ORDER BY rowid", (session_id,))]
237
+
238
+ def load_cut(self, session_id, cut_id, *, device="cpu"):
239
+ """A retained native cut, checked against its index row and the session binding."""
240
+ with self.db() as db:
241
+ row = db.execute("SELECT manifest FROM cuts WHERE session_id=? AND id=?",
242
+ (session_id, cut_id)).fetchone()
243
+ if row is None:
244
+ raise ProjectError(f"cut {cut_id} is not retained in session {session_id!r}")
245
+ cut = self.store.load(cut_id, device=device)
246
+ if self.json(cut.manifest()) != row[0]:
247
+ raise ProjectError("project cut index differs from the native cut")
248
+ return cut