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/settings.py ADDED
@@ -0,0 +1,718 @@
1
+ """mdb settings: every user setting's default, config-file key and environment variable, in one
2
+ table, and how a value is resolved (standard library only; no model framework).
3
+
4
+ Precedence, highest first:
5
+
6
+ 1. the command line (``mdb engine --dtype fp32``);
7
+ 2. the environment (``MDB_MODEL_DTYPE=fp32``; older names such as ``MDB_RECORDS`` still work);
8
+ 3. the file named by ``MDB_CONFIG``;
9
+ 4. the project file: ``<project>/mdb.toml`` when a project is named (``--project DIR`` or
10
+ ``MDB_PROJECT_DIR``), else the first ``mdb.toml`` or ``pyproject.toml`` with a ``[tool.mdb]``
11
+ table found walking up from the working directory (stopping at the repository root);
12
+ 5. the user file ``$XDG_CONFIG_HOME/mdb/config.toml`` (default ``~/.config/mdb/config.toml``);
13
+ 6. the defaults in ``KEYS``.
14
+
15
+ A config file holds locations and machine defaults. Settings that change a verdict (floors,
16
+ ``recheck``, ``lookahead``, ``prefill``, ``retain_rows``, branch ``mode``/``batch``, a
17
+ preregistration, seeds) are refused by name: they stay in the call, where the script custody
18
+ hashes shows them. Unknown keys and wrong types are errors that name ``file:key``.
19
+
20
+ When a loaded file sets a key that reaches a record (``Key.recorded``), ``provenance()`` is the
21
+ block custody adds to every record: those files' paths, sha256 and recorded keys, and the
22
+ resolved values. With no such file nothing is added and record ids are unchanged. Python entry
23
+ points read ``value(name, given)``: an explicit argument wins, None takes the setting.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import os
30
+ import sys
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ SCHEMA = "mdb-config-v1"
36
+ PROVENANCE_SCHEMA = "mdb-config-provenance-v1"
37
+ FILE_NAME = "mdb.toml"
38
+
39
+ # The one copy of these lists in mdb: ``engine.models`` (torch) and every front end import them.
40
+ TINY_FAMILIES = ("qwen2", "qwen3", "llama", "mistral")
41
+ DTYPES = ("bf16", "fp32")
42
+ DEFAULT_DTYPE = "bf16"
43
+ DEFAULT_DEVICE = "cpu"
44
+ DEFAULT_SEED = 113
45
+ DEFAULT_HOST = "127.0.0.1"
46
+ DEFAULT_PORT = 8765
47
+ SAE_PORTS = ("h_out", "h")
48
+
49
+
50
+ class ConfigError(ValueError):
51
+ """A config file, environment variable or flag that cannot be used (names where)."""
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class Key:
56
+ """One setting. ``kind``: str, int, bool, path, paths, strs, aliases, defaults, sae."""
57
+
58
+ name: str
59
+ kind: str
60
+ default: Any = None
61
+ env: tuple[str, ...] = () # current name first, then older names still read
62
+ choices: tuple[str, ...] = ()
63
+ recorded: bool = False # it reaches a record: which model, dtype, device, session,
64
+ # SAE basis or custody label a record is about, or what
65
+ # REPL commands run before the script (init, defaults)
66
+ project: str = "yes" # in a project file: "yes"; "inside" (a path that must
67
+ # resolve inside the project file's directory); "no"
68
+ # (command line, environment, MDB_CONFIG or user file only)
69
+ help: str = ""
70
+
71
+
72
+ # why a key marked project="no" is refused in a project file (a cloned repository's mdb.toml)
73
+ USER_ONLY_WHY = {"records.plugins": "it would run plug-in code the project names",
74
+ "serve.allow_hosts": "it names hosts mdb serve trusts",
75
+ "repl.trusted_projects": "it says whose init files may run",
76
+ "repl.history": "it names a file mdb writes"}
77
+
78
+ KEYS: dict[str, Key] = {key.name: key for key in (
79
+ Key("model.roots", "paths", (), ("MDB_MODEL_ROOTS", "LLM_MODELS_EXTRA_ROOT"), recorded=True,
80
+ help="directories searched for checkpoints by name after the Hugging Face cache"),
81
+ Key("model.aliases", "aliases", {}, recorded=True,
82
+ help="short name -> checkpoint directory or cached model name"),
83
+ Key("model.dtype", "str", DEFAULT_DTYPE, ("MDB_MODEL_DTYPE",), DTYPES, recorded=True,
84
+ help="weights dtype of a model mdb loads (recorded in every record's execution)"),
85
+ Key("model.device", "str", DEFAULT_DEVICE, ("MDB_MODEL_DEVICE",), recorded=True,
86
+ help="torch device of a model mdb loads (recorded in every record's execution)"),
87
+ Key("project.dir", "path", None, ("MDB_PROJECT_DIR",), project="inside",
88
+ help="project attached when no --project is given"),
89
+ Key("project.session", "str", "auto", ("MDB_PROJECT_SESSION",), recorded=True,
90
+ help="session id in the project; auto = family + digest of model and execution"),
91
+ Key("records.sink", "str", None, ("MDB_RECORDS_SINK", "MDB_RECORDS"), project="inside",
92
+ help="record sink: a file, a directory, or a name with {run}"),
93
+ Key("records.append", "bool", False, ("MDB_RECORDS_APPEND",),
94
+ help="add to a sink file another run wrote"),
95
+ Key("records.payloads", "bool", True, ("MDB_RECORDS_PAYLOADS",),
96
+ help="also write large payloads to the sink"),
97
+ Key("records.plugins", "strs", (), ("MDB_RECORDS_PLUGINS",), project="no",
98
+ help="installed mdb.sinks entry points that receive every sealed record (names, or "
99
+ "all); none by default"),
100
+ Key("custody.kernel_path", "str", None, ("MDB_CUSTODY_KERNEL_PATH", "MDB_KERNEL_PATH"),
101
+ recorded=True, help="kernel path named in every record's custody block"),
102
+ Key("serve.host", "str", DEFAULT_HOST, ("MDB_SERVE_HOST",), help="mdb serve bind host"),
103
+ Key("serve.port", "int", DEFAULT_PORT, ("MDB_SERVE_PORT",), help="mdb serve port"),
104
+ Key("serve.allow_hosts", "strs", (), ("MDB_SERVE_ALLOW_HOSTS",), project="no",
105
+ help="extra Host headers mdb serve accepts (HOST or HOST:PORT)"),
106
+ Key("repl.init", "path", None, ("MDB_REPL_INIT",), recorded=True, project="inside",
107
+ help="command file run before --script or the prompt (a project file's runs only "
108
+ "from a trusted project directory)"),
109
+ Key("repl.trusted_projects", "paths", (), ("MDB_REPL_TRUSTED_PROJECTS",), project="no",
110
+ help="directories whose project files may run their repl.init"),
111
+ Key("repl.history", "path", None, ("MDB_REPL_HISTORY",), project="no",
112
+ help="file keeping interactive command history"),
113
+ Key("repl.defaults", "defaults", {}, recorded=True,
114
+ help="OP.ARG = value: display defaults (and the sweep cap) of REPL commands"),
115
+ Key("storage.shared_tensor_store", "path", None,
116
+ ("MDB_STORAGE_SHARED_TENSOR_STORE", "MDB_SHARED_TENSOR_STORE"), project="inside",
117
+ help="shared tensor pool (same filesystem as the projects using it)"),
118
+ Key("storage.checkpoint_store", "str", None,
119
+ ("MDB_STORAGE_CHECKPOINT_STORE", "MDB_CHECKPOINT_STORE"),
120
+ help="where project checkpoints are also published and record ids are fetched from: "
121
+ "s3://bucket/prefix, file:///dir or a directory (credentials: environment only)"),
122
+ Key("storage.endpoint", "str", None, ("MDB_STORAGE_ENDPOINT",),
123
+ help="S3 endpoint URL of an s3:// checkpoint store (MinIO); default AWS_ENDPOINT_URL"),
124
+ Key("storage.checkpoint_cache", "path", None, ("MDB_STORAGE_CHECKPOINT_CACHE",),
125
+ help="local project for store checkpoints when none is attached; default "
126
+ "$XDG_CACHE_HOME/mdb/checkpoints"),
127
+ Key("sae.sources", "sae", {}, recorded=True, help="NAME = {path, layers, k, port, cache, verify, layer}"),
128
+ )}
129
+ SECTIONS = tuple(dict.fromkeys(name.split(".")[0] for name in KEYS))
130
+ SAE_FIELDS = {"path": "path", "layers": "str", "k": "int", "port": "str", "cache": "int",
131
+ "verify": "bool", "layer": "int"}
132
+
133
+ _PER_CALL = ("it is written into the record body by the call that uses it, and a file the "
134
+ "record does not name must not move it")
135
+ REFUSED: dict[str, str] = {
136
+ **{name: "a floor decides whether a reading counts as a verdict; " + _PER_CALL
137
+ + ": pass it per call (margin_floor(spacings=...), the op argument)"
138
+ for name in ("floor", "floors", "floor_spacings", "margin_floor_spacings",
139
+ "stability_floor_spacings", "stable_k", "verdict")},
140
+ "recheck": "it decides which branch arms are re-measured; pass Branches.run(recheck=...)",
141
+ "lookahead": "it decides what a move inside a layer computes; pass it per run "
142
+ "(start lookahead=..., Debugger.run(lookahead=...))",
143
+ "prefill": "it decides which prompt rows are stepped ports; pass it per run "
144
+ "(start prefill=K, Debugger.run(prefill=K))",
145
+ "retain_rows": "it decides which cuts a run keeps for rewinds; pass it per run "
146
+ "(start retain_rows=N, Debugger.run(retain_rows=N))",
147
+ "mode": "branch modes decide how arms are measured; pass Branches.run(mode=...)",
148
+ "batch": "branch batching decides how arms are measured; pass Branches.run(batch=...)",
149
+ "branches": "branch settings decide how arms are measured; pass them to Branches.run",
150
+ "prereg": "a preregistration belongs to one run; pass --prereg, MDB_PREREG or "
151
+ "custody.declare(prereg=...)",
152
+ "script": "custody hashes the script that ran; pass --script or MDB_SCRIPT",
153
+ "seed": "a seed chooses the model or the samples; pass --seed per run",
154
+ "allow_remote": "binding mdb serve beyond loopback has no authentication; type "
155
+ "--allow-remote each time",
156
+ }
157
+
158
+ _TRUE, _FALSE = ("1", "true", "yes", "on"), ("0", "false", "no", "off", "")
159
+
160
+
161
+ @dataclass
162
+ class Layer:
163
+ """One source of values. ``kind``: cli, env, file, default."""
164
+
165
+ kind: str
166
+ label: str
167
+ values: dict[str, Any] = field(default_factory=dict)
168
+ path: Path | None = None
169
+ sha256: str | None = None
170
+ names: dict[str, str] = field(default_factory=dict) # key -> env var / flag that set it
171
+
172
+
173
+ def user_file(env: dict[str, str] | None = None) -> Path:
174
+ env = os.environ if env is None else env
175
+ base = env.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
176
+ return Path(base).expanduser() / "mdb" / "config.toml"
177
+
178
+
179
+ def _toml(path: Path) -> dict[str, Any]:
180
+ if sys.version_info >= (3, 11):
181
+ import tomllib
182
+ else: # pragma: no cover - the declared dependency on Python 3.10
183
+ import tomli as tomllib
184
+ try:
185
+ with path.open("rb") as handle:
186
+ return tomllib.load(handle)
187
+ except OSError as error:
188
+ raise ConfigError(f"{path}: cannot read: {error.strerror or error}") from None
189
+ except tomllib.TOMLDecodeError as error:
190
+ raise ConfigError(f"{path}: not valid TOML: {error}") from None
191
+
192
+
193
+ def _pyproject_table(path: Path) -> dict[str, Any] | None:
194
+ """``[tool.mdb]`` of a pyproject.toml, or None. An unparseable file with no ``[tool.mdb``
195
+ text is not mdb's and is skipped; one that has it is an error."""
196
+ try:
197
+ data = _toml(path)
198
+ except ConfigError:
199
+ try:
200
+ text = path.read_text(errors="replace")
201
+ except OSError:
202
+ return None
203
+ if "[tool.mdb" in text:
204
+ raise
205
+ return None
206
+ tool = data.get("tool")
207
+ table = tool.get("mdb") if isinstance(tool, dict) else None
208
+ return table if isinstance(table, dict) else None
209
+
210
+
211
+ def _refuse(where: str, name: str) -> None:
212
+ if name in REFUSED:
213
+ raise ConfigError(f"{where}: {name!r} cannot be set in a config file: {REFUSED[name]}")
214
+
215
+
216
+ def _check_value(where: str, key: Key, value: Any, base: Path | None) -> Any:
217
+ """``value`` (from a file) as the setting's type; paths relative to the file's directory."""
218
+ def bad(what: str) -> ConfigError:
219
+ return ConfigError(f"{where}: expected {what}, got {value!r}")
220
+
221
+ kind = key.kind
222
+ if kind == "bool":
223
+ if not isinstance(value, bool):
224
+ raise bad("true or false")
225
+ return value
226
+ if kind == "int":
227
+ if type(value) is not int:
228
+ raise bad("an integer")
229
+ if key.name == "serve.port" and not 1 <= value <= 65535:
230
+ raise bad("a port 1..65535")
231
+ return value
232
+ if kind == "str":
233
+ if key.choices and value not in key.choices:
234
+ raise bad("one of " + ", ".join(key.choices))
235
+ if not isinstance(value, str) or not value.strip():
236
+ raise bad("non-empty text")
237
+ if key.name == "records.sink" and base is not None:
238
+ return _relative(value, base)
239
+ return value
240
+ if kind == "path":
241
+ if not isinstance(value, str) or not value.strip():
242
+ raise bad("a path")
243
+ return _relative(value, base)
244
+ if kind in ("paths", "strs"):
245
+ if not isinstance(value, list) or any(not isinstance(v, str) or not v.strip()
246
+ for v in value):
247
+ raise bad("a list of " + ("paths" if kind == "paths" else "text"))
248
+ return tuple(_relative(v, base) if kind == "paths" else v for v in value)
249
+ if kind == "aliases":
250
+ if not isinstance(value, dict):
251
+ raise bad("a table of NAME = \"model\"")
252
+ for name, target in value.items():
253
+ if name.startswith(("tiny:", "http://", "https://")):
254
+ raise ConfigError(f"{where}.{name}: an alias may not shadow a tiny:FAMILY or "
255
+ "http(s):// target")
256
+ if not isinstance(target, str) or not target.strip():
257
+ raise ConfigError(f"{where}.{name}: expected a model name or path, got "
258
+ f"{target!r}")
259
+ return {name: _alias(target, base) for name, target in value.items()}
260
+ if kind == "defaults":
261
+ return _defaults(where, value)
262
+ if kind == "sae":
263
+ return _sae(where, value, base)
264
+ raise AssertionError(kind)
265
+
266
+
267
+ def _relative(text: str, base: Path | None) -> str:
268
+ """``~`` expanded; a relative path in a file is relative to the file's directory (a
269
+ trailing separator, meaning a directory, is kept)."""
270
+ expanded = os.path.expanduser(text)
271
+ if base is None or os.path.isabs(expanded):
272
+ return expanded
273
+ joined = str(base / expanded)
274
+ return joined + os.sep if text.endswith(("/", os.sep)) and not joined.endswith(os.sep) \
275
+ else joined
276
+
277
+
278
+ def _alias(target: str, base: Path | None) -> str:
279
+ """An alias to an existing relative directory is relative to the file; else a name."""
280
+ if base is not None and not os.path.isabs(os.path.expanduser(target)) and \
281
+ (base / target).is_dir():
282
+ return str(base / target)
283
+ return os.path.expanduser(target)
284
+
285
+
286
+ def _defaults(where: str, value: Any) -> dict[str, Any]:
287
+ """``repl.defaults``: ``{op = {arg = scalar}}`` or ``{"op.arg" = scalar}`` -> flat."""
288
+ if not isinstance(value, dict):
289
+ raise ConfigError(f"{where}: expected a table of OP.ARG = value")
290
+ out: dict[str, Any] = {}
291
+ for op, inner in value.items():
292
+ items = inner.items() if isinstance(inner, dict) else [(None, inner)]
293
+ for arg, scalar in items:
294
+ name = f"{op}.{arg}" if arg is not None else op
295
+ if "." not in name or name.count(".") != 1:
296
+ raise ConfigError(f"{where}.{name}: write OP.ARG (print.top = 5)")
297
+ _refuse(f"{where}.{name}", name.split(".")[1])
298
+ if isinstance(scalar, (dict, list)) or isinstance(scalar, str):
299
+ raise ConfigError(f"{where}.{name}: expected a number or true/false, got "
300
+ f"{scalar!r}")
301
+ out[name] = scalar
302
+ return out
303
+
304
+
305
+ def _sae(where: str, value: Any, base: Path | None) -> dict[str, dict[str, Any]]:
306
+ if not isinstance(value, dict):
307
+ raise ConfigError(f"{where}: expected a table of NAME = {{path = ...}}")
308
+ out = {}
309
+ for name, entry in value.items():
310
+ here = f"{where}.{name}"
311
+ if not isinstance(entry, dict):
312
+ raise ConfigError(f"{here}: expected a table with path = ...")
313
+ unknown = sorted(set(entry) - set(SAE_FIELDS))
314
+ for item in unknown:
315
+ _refuse(f"{here}.{item}", item)
316
+ if unknown:
317
+ raise ConfigError(f"{here}.{unknown[0]}: unknown key (known: "
318
+ f"{', '.join(SAE_FIELDS)})")
319
+ if "path" not in entry:
320
+ raise ConfigError(f"{here}: missing path")
321
+ fields: dict[str, Any] = {}
322
+ for item, kind in SAE_FIELDS.items():
323
+ if item not in entry:
324
+ continue
325
+ spec = Key(f"sae.{item}", kind, choices=SAE_PORTS if item == "port" else ())
326
+ fields[item] = _check_value(f"{here}.{item}", spec, entry[item], base)
327
+ out[name] = fields
328
+ return out
329
+
330
+
331
+ def _inside(value: str, base: Path) -> bool:
332
+ target = Path(str(value).replace("{run}", "run")).expanduser()
333
+ target = (base / target) if not target.is_absolute() else target
334
+ try:
335
+ Path(os.path.realpath(target)).relative_to(os.path.realpath(base))
336
+ return True
337
+ except ValueError:
338
+ return False
339
+
340
+
341
+ def _file_layer(path: Path, label: str, table: dict[str, Any] | None = None) -> Layer:
342
+ """A config file's values, validated: unknown keys, refused keys and types are errors. A
343
+ project file (``label == "project"``: found from the project or by walking up, so possibly
344
+ from a cloned repository) may not set the keys marked ``project="no"``, and the paths marked
345
+ ``"inside"`` must resolve inside its directory."""
346
+ raw = path.read_bytes() if path.is_file() else None
347
+ if raw is None:
348
+ raise ConfigError(f"{path}: no such config file")
349
+ data = _toml(path) if table is None else table
350
+ where = f"{path}" if table is None else f"{path}:[tool.mdb]"
351
+ base = path.parent.resolve()
352
+ values: dict[str, Any] = {}
353
+ for section, body in data.items():
354
+ if section == "schema":
355
+ if body != SCHEMA:
356
+ raise ConfigError(f"{where}:schema: expected {SCHEMA!r}, got {body!r}")
357
+ continue
358
+ _refuse(f"{where}:{section}", section)
359
+ if section not in SECTIONS:
360
+ raise ConfigError(f"{where}:{section}: unknown key (sections: "
361
+ f"{', '.join(SECTIONS)}; see docs/CONFIG.md)")
362
+ if not isinstance(body, dict):
363
+ raise ConfigError(f"{where}:{section}: expected a [{section}] table")
364
+ for name, value in body.items():
365
+ _refuse(f"{where}:{section}.{name}", name)
366
+ key = KEYS.get(f"{section}.{name}")
367
+ if key is None:
368
+ known = ", ".join(k.split(".", 1)[1] for k in KEYS if k.startswith(section + "."))
369
+ raise ConfigError(f"{where}:{section}.{name}: unknown key (in [{section}]: "
370
+ f"{known})")
371
+ checked = _check_value(f"{where}:{key.name}", key, value, base)
372
+ if label == "project" and key.project == "no":
373
+ why = USER_ONLY_WHY.get(key.name, "it names a file mdb writes")
374
+ raise ConfigError(f"{where}:{key.name}: a project file may not set this ({why}); "
375
+ "set it on the command line, in the environment or in the user "
376
+ "file")
377
+ if label == "project" and key.project == "inside" and not _inside(checked, base):
378
+ raise ConfigError(f"{where}:{key.name}: {value!r} is outside the project "
379
+ f"directory {base}; a project file names paths inside its "
380
+ "own tree (set others on the command line, in the environment "
381
+ "or in the user file)")
382
+ values[key.name] = checked
383
+ return Layer("file", label, values, path=path.resolve(),
384
+ sha256=hashlib.sha256(raw).hexdigest())
385
+
386
+
387
+ def _env_value(key: Key, name: str, text: str) -> Any:
388
+ def bad(what: str) -> ConfigError:
389
+ return ConfigError(f"environment {name}={text!r}: expected {what} ({key.name})")
390
+
391
+ if key.kind == "bool":
392
+ lowered = text.strip().lower()
393
+ if lowered in _TRUE:
394
+ return True
395
+ if lowered in _FALSE:
396
+ return False
397
+ raise bad("1/true/yes or 0/false/no")
398
+ if key.kind == "int":
399
+ try:
400
+ value = int(text)
401
+ except ValueError:
402
+ raise bad("an integer") from None
403
+ if key.name == "serve.port" and not 1 <= value <= 65535:
404
+ raise bad("a port 1..65535")
405
+ return value
406
+ if key.kind == "paths":
407
+ return tuple(os.path.expanduser(p) for p in text.split(os.pathsep) if p.strip())
408
+ if key.kind == "strs":
409
+ return tuple(p.strip() for p in text.split(",") if p.strip())
410
+ if key.kind == "path":
411
+ return os.path.expanduser(text)
412
+ if key.choices and text not in key.choices:
413
+ raise bad("one of " + ", ".join(key.choices))
414
+ return text
415
+
416
+
417
+ def _env_layer(env: dict[str, str]) -> Layer:
418
+ layer = Layer("env", "environment")
419
+ for key in KEYS.values():
420
+ found = [(name, env[name]) for name in key.env if env.get(name, "").strip()]
421
+ if not found:
422
+ continue
423
+ values = {name: _env_value(key, name, text) for name, text in found}
424
+ if len(set(map(repr, values.values()))) > 1:
425
+ listed = ", ".join(f"{name}={text!r}" for name, text in found)
426
+ raise ConfigError(f"environment sets {key.name} twice with different values: "
427
+ f"{listed}; unset the older name")
428
+ name = found[0][0]
429
+ layer.values[key.name] = values[name]
430
+ layer.names[key.name] = name
431
+ return layer
432
+
433
+
434
+ def _repository_root(start: Path) -> Path | None:
435
+ for directory in (start, *start.parents):
436
+ if (directory / ".git").exists():
437
+ return directory
438
+ return None
439
+
440
+
441
+ SKIPPED: list[str] = [] # files discovery passed over (not the user's); config check prints them
442
+
443
+
444
+ def _owned(path: Path) -> bool:
445
+ """Whether the current user owns ``path`` (as git's safe.directory: a file another user
446
+ wrote is not read)."""
447
+ getuid = getattr(os, "getuid", None)
448
+ return getuid is None or path.stat().st_uid == getuid()
449
+
450
+
451
+ def find_project_file(start: Path) -> tuple[Path, dict[str, Any] | None] | None:
452
+ """The first ``mdb.toml`` (table None) or ``pyproject.toml`` with ``[tool.mdb]`` walking up
453
+ from ``start``, stopping at the repository root or the home directory. With neither above
454
+ ``start`` (a scratch directory under /tmp), only ``start`` itself is looked at. A file the
455
+ current user does not own is skipped (listed in ``SKIPPED``)."""
456
+ start = start.resolve()
457
+ stop = _repository_root(start)
458
+ home = Path.home().resolve()
459
+ if stop is None and home not in (start, *start.parents):
460
+ stop = start
461
+ for directory in (start, *start.parents):
462
+ candidate = directory / FILE_NAME
463
+ if candidate.is_file():
464
+ if _owned(candidate):
465
+ return candidate, None
466
+ SKIPPED.append(f"{candidate}: not owned by the current user; not read")
467
+ pyproject = directory / "pyproject.toml"
468
+ if pyproject.is_file():
469
+ if not _owned(pyproject):
470
+ SKIPPED.append(f"{pyproject}: not owned by the current user; not read")
471
+ else:
472
+ table = _pyproject_table(pyproject)
473
+ if table is not None:
474
+ return pyproject, table
475
+ if directory == stop or directory == home:
476
+ return None
477
+ return None
478
+
479
+
480
+ class Settings:
481
+ """Resolved settings: ``get(key)``, ``origin(key)``, ``explain(key)``, ``provenance()``."""
482
+
483
+ def __init__(self, layers: list[Layer], args: dict[str, Any]):
484
+ self.layers = layers # highest precedence first; the last is defaults
485
+ self._args = args
486
+
487
+ def _winner(self, name: str) -> Layer:
488
+ if name not in KEYS:
489
+ raise ConfigError(f"unknown setting {name!r} (settings: {', '.join(KEYS)})")
490
+ for layer in self.layers:
491
+ if name in layer.values:
492
+ return layer
493
+ raise AssertionError(name)
494
+
495
+ def get(self, name: str) -> Any:
496
+ return self._winner(name).values[name]
497
+
498
+ def layer_of(self, name: str) -> Layer:
499
+ return self._winner(name)
500
+
501
+ def init_file(self) -> tuple[str | None, str | None]:
502
+ """``(path, None)`` of the init file to run, or ``(None, reason)`` when a project
503
+ file's ``repl.init`` is not trusted (its directory is not under a
504
+ ``repl.trusted_projects`` entry): gdb's auto-load safe-path rule."""
505
+ path = self.get("repl.init")
506
+ layer = self._winner("repl.init")
507
+ if path is None or layer.kind != "file" or layer.label != "project":
508
+ return path, None
509
+ here = os.path.realpath(layer.path.parent)
510
+ for trusted in self.get("repl.trusted_projects"):
511
+ root = os.path.realpath(os.path.expanduser(trusted))
512
+ if here == root or here.startswith(root.rstrip(os.sep) + os.sep):
513
+ return path, None
514
+ return None, (f"not running the init file {path} named by the project file "
515
+ f"{layer.path}: add {layer.path.parent} to [repl] trusted_projects in the "
516
+ "user file, or pass --init FILE")
517
+
518
+ def origin(self, name: str) -> str:
519
+ return describe(self._winner(name), name)
520
+
521
+ def explain(self, name: str) -> list[dict[str, Any]]:
522
+ """Every layer that sets ``name``, highest first; the first one wins."""
523
+ winner = self._winner(name)
524
+ return [{"source": describe(layer, name), "value": layer.values[name],
525
+ "wins": layer is winner}
526
+ for layer in self.layers if name in layer.values]
527
+
528
+ @property
529
+ def files(self) -> list[Layer]:
530
+ return [layer for layer in self.layers if layer.kind == "file"]
531
+
532
+ def as_dict(self) -> dict[str, Any]:
533
+ return {name: self.get(name) for name in KEYS}
534
+
535
+ def provenance(self) -> dict[str, Any] | None:
536
+ """The block custody records, or None. Only files that set a key reaching a record
537
+ (``Key.recorded``: model roots, aliases, dtype, device, session, kernel path, SAE
538
+ sources, REPL init and defaults) count: each such file's path, sha256 and the recorded
539
+ keys it sets, then the winning value and source of each of those keys. Values are JSON
540
+ text (``"\"fp32\""``), so numbers in a setting are never read as measured claims. A file of locations only (serve, repl,
541
+ records, storage, project dir) adds nothing, so record ids stay as without it."""
542
+ sources, keys = [], []
543
+ for layer in self.files:
544
+ mine = {name: _text(value) for name, value in layer.values.items()
545
+ if KEYS[name].recorded}
546
+ if mine:
547
+ sources.append({"path": str(layer.path), "sha256": layer.sha256,
548
+ "layer": layer.label, "settings": mine})
549
+ keys += [name for name in mine if name not in keys]
550
+ if not sources:
551
+ return None
552
+ keys = [name for name in KEYS if name in keys]
553
+ out = {"schema": PROVENANCE_SCHEMA, "sources": sources,
554
+ "resolved": {name: _text(self.get(name)) for name in keys},
555
+ "origins": {name: self.origin(name) for name in keys}}
556
+ given = {name: sorted(values, key=repr) for name, values in EXPLICIT.items()
557
+ if name in keys}
558
+ if given: # a call argument overrode the setting (the record's execution says what ran)
559
+ out["call_arguments"] = {name: [_text(v) for v in values]
560
+ for name, values in given.items()}
561
+ return out
562
+
563
+
564
+ def _jsonable(value: Any) -> Any:
565
+ if isinstance(value, dict):
566
+ return {key: _jsonable(item) for key, item in value.items()}
567
+ return list(value) if isinstance(value, tuple) else value
568
+
569
+
570
+ def _text(value: Any) -> str:
571
+ """A setting's value as canonical JSON text: a record holds no bare numbers outside
572
+ labelled claims, and a config value is a supplied setting, not a measurement."""
573
+ import json
574
+
575
+ return json.dumps(_jsonable(value), sort_keys=True, separators=(",", ":"))
576
+
577
+
578
+ def describe(layer: Layer, name: str) -> str:
579
+ if layer.kind == "file":
580
+ return f"{layer.label} file {layer.path}"
581
+ if layer.kind in ("env", "cli"):
582
+ flag = layer.names.get(name)
583
+ older = layer.kind == "env" and flag is not None and flag != KEYS[name].env[0]
584
+ suffix = f" (older name of {KEYS[name].env[0]})" if older else ""
585
+ return f"{'environment' if layer.kind == 'env' else 'command line'} {flag}{suffix}" \
586
+ if flag else layer.label
587
+ return "default"
588
+
589
+
590
+ def resolve(cli: dict[str, Any] | None = None, *, flags: dict[str, str] | None = None,
591
+ project: str | Path | None = None, cwd: str | Path | None = None,
592
+ env: dict[str, str] | None = None) -> Settings:
593
+ """Resolve every setting. ``cli`` maps setting names to command-line values (``None``
594
+ means not given); ``flags`` maps them to the flag spelled (for ``explain``); ``project`` is
595
+ the project directory the command named (its ``mdb.toml`` is the project file)."""
596
+ env = dict(os.environ if env is None else env)
597
+ cwd = Path.cwd() if cwd is None else Path(cwd)
598
+ cli_layer = Layer("cli", "command line",
599
+ {k: v for k, v in (cli or {}).items() if v is not None},
600
+ names={k: (flags or {}).get(k, k) for k in (cli or {})})
601
+ for name in cli_layer.values:
602
+ if name not in KEYS:
603
+ raise ConfigError(f"unknown setting {name!r}")
604
+ env_layer = _env_layer(env)
605
+ files: list[Layer] = []
606
+ named = env.get("MDB_CONFIG", "").strip()
607
+ if named:
608
+ files.append(_file_layer(Path(named).expanduser(), "MDB_CONFIG"))
609
+ project_dir = project or cli_layer.values.get("project.dir") or \
610
+ env_layer.values.get("project.dir")
611
+ if project_dir is not None:
612
+ candidate = Path(project_dir).expanduser() / FILE_NAME
613
+ if candidate.is_file():
614
+ files.append(_file_layer(candidate, "project"))
615
+ else:
616
+ found = find_project_file(cwd)
617
+ if found is not None:
618
+ path, table = found
619
+ files.append(_file_layer(path, "project", table))
620
+ user = user_file(env)
621
+ if user.is_file():
622
+ files.append(_file_layer(user, "user"))
623
+ defaults = Layer("default", "default", {name: key.default for name, key in KEYS.items()})
624
+ return Settings([cli_layer, env_layer, *files, defaults],
625
+ {"cli": cli, "flags": flags, "project": project, "cwd": cwd, "env": None})
626
+
627
+
628
+ # --------------------------------------------------------------------------- the process's
629
+
630
+ _ACTIVE: list[Settings] = []
631
+ _STORE_SET: list[bool] = [] # this module named the saturn shared store
632
+
633
+
634
+ def _apply_store(root: str | None) -> None:
635
+ """Hand ``storage.shared_tensor_store`` to saturn (``set_shared_store``); with no
636
+ store, clear one this module set before (the environment and ``.mdb-storage.json`` then
637
+ apply as saturn reads them)."""
638
+ if root is None and not _STORE_SET:
639
+ return
640
+ from saturn import shared_store
641
+
642
+ setter = getattr(shared_store, "set_shared_store", None)
643
+ if setter is None:
644
+ if root is None:
645
+ return
646
+ raise ConfigError("storage.shared_tensor_store needs a model-runtime with "
647
+ "shared_store.set_shared_store (install model-runtime from the same "
648
+ "checkout as mdb)")
649
+ try:
650
+ setter(root)
651
+ except ValueError as error:
652
+ raise ConfigError(f"storage.shared_tensor_store = {root!r}: {error}") from None
653
+ _STORE_SET[:] = [True] if root is not None else []
654
+
655
+
656
+ def activate(settings: Settings) -> Settings:
657
+ """Make ``settings`` this process's (custody, sinks, model lookup, the Python entry points'
658
+ defaults, SAE sources and the shared tensor store read it)."""
659
+ store = settings.get("storage.shared_tensor_store")
660
+ _apply_store(None if store is None else str(Path(store).expanduser().absolute()))
661
+ _ACTIVE[:] = [settings]
662
+ return settings
663
+
664
+
665
+ def current() -> Settings:
666
+ """This process's settings, resolved from the environment and files on first use."""
667
+ if not _ACTIVE:
668
+ activate(resolve())
669
+ return _ACTIVE[0]
670
+
671
+
672
+ EXPLICIT: dict[str, set] = {} # setting -> values Python calls passed explicitly instead
673
+
674
+
675
+ def value(name: str, given: Any = None) -> Any:
676
+ """``given`` when not None (an explicit argument wins), else the resolved setting. An
677
+ explicit value that differs from the setting is remembered, so the custody config block
678
+ shows that a call overrode it (``call_arguments``)."""
679
+ resolved = current().get(name)
680
+ if given is None:
681
+ return resolved
682
+ if isinstance(given, (str, int, float, bool)) and given != resolved:
683
+ EXPLICIT.setdefault(name, set()).add(given)
684
+ return given
685
+
686
+
687
+ def refresh() -> Settings:
688
+ """Re-resolve with the same command line (the environment or files changed)."""
689
+ if not _ACTIVE:
690
+ return current()
691
+ args = dict(_ACTIVE[0]._args)
692
+ args.pop("env", None)
693
+ return activate(resolve(**args))
694
+
695
+
696
+ def reset() -> None:
697
+ """Forget the process's settings and clear a store this module set (tests)."""
698
+ _ACTIVE.clear()
699
+ EXPLICIT.clear()
700
+ SKIPPED.clear()
701
+ _apply_store(None)
702
+
703
+
704
+ def legacy_storage_file(start: str | Path) -> Path | None:
705
+ """The nearest ``.mdb-storage.json`` above ``start`` (still read by saturn; the
706
+ ``[storage]`` section replaces it)."""
707
+ path = Path(start).expanduser().resolve()
708
+ for directory in (path, *path.parents):
709
+ candidate = directory / ".mdb-storage.json"
710
+ if candidate.is_file():
711
+ return candidate
712
+ return None
713
+
714
+
715
+ __all__ = ["ConfigError", "DEFAULT_DEVICE", "DEFAULT_DTYPE", "DEFAULT_HOST", "DEFAULT_PORT",
716
+ "DEFAULT_SEED", "DTYPES", "KEYS", "Key", "REFUSED", "SCHEMA", "Settings",
717
+ "TINY_FAMILIES", "activate", "current", "find_project_file", "refresh", "reset",
718
+ "resolve", "user_file", "value"]