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/locate.py ADDED
@@ -0,0 +1,161 @@
1
+ """Find a model checkpoint on this machine by name (standard library only; never downloads).
2
+
3
+ ``locate_model("qwen2.5-1.5b")`` returns the directory of a local Hugging Face checkpoint:
4
+ a directory path as given, or a snapshot in the local Hugging Face cache whose repository id
5
+ matches the name. Matching is case-insensitive and tried in order: the full id
6
+ (``Qwen/Qwen2.5-1.5B-Instruct``), the id without its organisation, then a substring that
7
+ only one cached repository contains. A name that matches none, or several, is refused with the
8
+ candidates listed, so a short name never silently picks a model.
9
+
10
+ Settings (``mdb.core.settings``): ``[model] aliases`` maps a short name to a directory or a
11
+ cached name (tried first); ``[model] roots`` (or ``MDB_MODEL_ROOTS``) lists directories whose
12
+ checkpoints (``ROOT/NAME`` or ``ROOT/ORG/NAME`` with a config.json) are searched with the cache,
13
+ the cache winning a tie on the same id.
14
+
15
+ ``parse_target`` is the one reading of "which model" every front end uses: ``tiny:FAMILY``,
16
+ an ``http(s)://`` address of a running ``mdb serve``, or a directory or name for
17
+ ``locate_model``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ from pathlib import Path
24
+
25
+ from .errors import BadArgs
26
+ from .settings import TINY_FAMILIES
27
+
28
+
29
+ def parse_target(text: str) -> tuple[str, str]:
30
+ """``("tiny", FAMILY)``, ``("connect", URL)`` or ``("model", NAME_OR_DIR)``; a configured
31
+ alias is replaced by its target first (so an alias may name ``tiny:qwen2``)."""
32
+ from . import settings
33
+
34
+ text = str(text).strip()
35
+ text = settings.current().get("model.aliases").get(text, text)
36
+ if text.startswith(("http://", "https://")):
37
+ return "connect", text
38
+ if text.startswith("tiny:"):
39
+ family = text[len("tiny:"):]
40
+ if family not in TINY_FAMILIES:
41
+ raise BadArgs("tiny models are " + ", ".join(f"tiny:{name}" for name in TINY_FAMILIES))
42
+ return "tiny", family
43
+ return "model", text
44
+
45
+
46
+ def cache_dirs() -> list[Path]:
47
+ """The Hugging Face hub cache directories that exist, in lookup order."""
48
+ found = []
49
+ if os.environ.get("HF_HUB_CACHE"):
50
+ found.append(Path(os.environ["HF_HUB_CACHE"]))
51
+ if os.environ.get("HF_HOME"):
52
+ found.append(Path(os.environ["HF_HOME"]) / "hub")
53
+ found.append(Path.home() / ".cache" / "huggingface" / "hub")
54
+ seen, out = set(), []
55
+ for path in found:
56
+ path = path.expanduser()
57
+ if path not in seen and path.is_dir():
58
+ seen.add(path)
59
+ out.append(path)
60
+ return out
61
+
62
+
63
+ def _snapshot(repo: Path) -> Path | None:
64
+ """The snapshot ``refs/main`` names, else the newest one; only one that has a config."""
65
+ snapshots = repo / "snapshots"
66
+ if not snapshots.is_dir():
67
+ return None
68
+ ref = repo / "refs" / "main"
69
+ if ref.is_file():
70
+ named = snapshots / ref.read_text().strip()
71
+ if (named / "config.json").is_file():
72
+ return named
73
+ usable = [path for path in snapshots.iterdir() if (path / "config.json").is_file()]
74
+ return max(usable, key=lambda path: path.stat().st_mtime) if usable else None
75
+
76
+
77
+ def cached_models() -> dict[str, Path]:
78
+ """``repository id -> snapshot directory`` of every cached model that has a config."""
79
+ out: dict[str, Path] = {}
80
+ for cache in cache_dirs():
81
+ for repo in sorted(cache.glob("models--*")):
82
+ identifier = repo.name[len("models--"):].replace("--", "/")
83
+ snapshot = _snapshot(repo)
84
+ if snapshot is not None:
85
+ out.setdefault(identifier, snapshot)
86
+ return out
87
+
88
+
89
+ def model_roots() -> list[Path]:
90
+ """The configured model roots that exist (``[model] roots``, ``MDB_MODEL_ROOTS``)."""
91
+ from . import settings
92
+
93
+ return [Path(root).expanduser() for root in settings.current().get("model.roots")
94
+ if Path(root).expanduser().is_dir()]
95
+
96
+
97
+ def root_models() -> dict[str, Path]:
98
+ """``NAME`` or ``ORG/NAME`` -> directory of every checkpoint (with a config.json) one or
99
+ two levels under a model root."""
100
+ out: dict[str, Path] = {}
101
+ for root in model_roots():
102
+ for config in sorted([*root.glob("*/config.json"), *root.glob("*/*/config.json")]):
103
+ out.setdefault(config.parent.relative_to(root).as_posix(), config.parent)
104
+ return out
105
+
106
+
107
+ def known_models() -> dict[str, Path]:
108
+ """The cached models, then the model roots' (the cache wins a tie on one id)."""
109
+ out = cached_models()
110
+ for identifier, path in root_models().items():
111
+ out.setdefault(identifier, path)
112
+ return out
113
+
114
+
115
+ def locate_model(name: str) -> Path:
116
+ """The checkpoint directory for ``name`` (a directory, or a cached repository's name)."""
117
+ text = str(name).strip()
118
+ if not text:
119
+ raise BadArgs("no model given: pass a checkpoint directory or a cached model's name")
120
+ from . import settings
121
+
122
+ aliases = settings.current().get("model.aliases")
123
+ if text in aliases and aliases[text] != text:
124
+ target = aliases[text]
125
+ if target in aliases:
126
+ raise BadArgs(f"model alias {text!r} names another alias {target!r}; aliases are "
127
+ "one step (a directory or a model name)")
128
+ return locate_model(target)
129
+ path = Path(text).expanduser()
130
+ if path.is_dir():
131
+ if not (path / "config.json").is_file():
132
+ raise BadArgs(f"{path} is not a Hugging Face checkpoint directory "
133
+ "(config.json missing)")
134
+ return _weighted(path.resolve(), text)
135
+ models = known_models()
136
+ wanted = text.lower()
137
+ tiers = (
138
+ [identifier for identifier in models if identifier.lower() == wanted],
139
+ [identifier for identifier in models if identifier.lower().split("/")[-1] == wanted],
140
+ [identifier for identifier in models if wanted in identifier.lower()],
141
+ )
142
+ for found in tiers:
143
+ if len(found) == 1:
144
+ return _weighted(models[found[0]], found[0])
145
+ if found:
146
+ raise BadArgs(f"model name {text!r} matches {len(found)} local models: "
147
+ f"{', '.join(sorted(found))}; give more of the name")
148
+ where = ", ".join(str(place) for place in [*cache_dirs(), *model_roots()]) or \
149
+ "no Hugging Face cache or model root found"
150
+ known = ", ".join(sorted(models)[:12]) + (" ..." if len(models) > 12 else "")
151
+ raise BadArgs(f"no directory and no cached model named {text!r} ({where}); nothing is "
152
+ f"downloaded. Cached: {known or 'none'}")
153
+
154
+
155
+ def _weighted(path: Path, name: str) -> Path:
156
+ """``path``, refused when it has a config but no weight files (a cache entry that holds
157
+ only what a config lookup fetched)."""
158
+ if any(path.glob("*.safetensors")) or any(path.glob("*.bin")):
159
+ return path
160
+ raise BadArgs(f"{name} at {path} has a config.json but no weight files (*.safetensors, "
161
+ "*.bin); nothing is downloaded: put the weights there or name another model")
mdb/core/migrate.py ADDED
@@ -0,0 +1,280 @@
1
+ """``mdb records migrate PATH``: write the schema-v3 twin of a JSONL file of v2 records.
2
+
3
+ A record file (a ``records_to`` sink, or any file whose every line is a stored record, an
4
+ ``mdb_payload`` line or an ``mdb_execution`` line) is migrated to a NEW file beside it
5
+ (``NAME.v3.jsonl``, or under ``--out``), never in place, with a map file ``NAME.v3.map.json``:
6
+ ``{old id: new id}`` plus the source and target sha256. Each v2 record is verified, re-sealed
7
+ as v3 with the same content (``records.migrate_record``) and the target file is then read back
8
+ and every record compared with its source, field by field (canonical JSON of every field but
9
+ ``schema``, ``id`` and ``digest``: every number bit-identical). Payload lines are copied byte
10
+ for byte; a v3 record already in the source is copied unchanged (its id maps to itself).
11
+
12
+ References inside a body to another record's id (a watch-hits record's ``trace``, a value's
13
+ ``origin.record``) are content and keep the v2 id; the map file resolves them, and the v2 file
14
+ stays readable. Legacy ``mdb-circuit-investigation-v1`` records, project indexes and core files
15
+ are not rewritten: readers accept their v2 records as they are.
16
+
17
+ Torch-free. ``verify_file`` checks a record file without writing anything.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import re
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from . import records as R
28
+ from .pointers import RecordError
29
+
30
+ MAP_SCHEMA = "mdb-record-migration-v1"
31
+ SUFFIX = ".v3.jsonl"
32
+
33
+
34
+ def _declare_kinds() -> None:
35
+ """Import the modules that declare record kinds a reader may meet (all torch-free)."""
36
+ from . import kinds # noqa: F401
37
+ try:
38
+ from . import recipe # noqa: F401 (``checkpoint``)
39
+ except ImportError: # pragma: no cover - saturn missing
40
+ pass
41
+
42
+
43
+ def _lines(path: Path) -> list[tuple[str, dict[str, Any]]]:
44
+ out = []
45
+ for number, text in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
46
+ if not text.strip():
47
+ continue
48
+ big = text.startswith('{"bytes":') and '"mdb_payload"' in text[:200]
49
+ value = R.parse_line(text, f"{path}:{number}", limit=None if big else R.MAX_LINE_BYTES)
50
+ if not isinstance(value, dict):
51
+ raise RecordError(f"{path}:{number}: not a record, payload or execution line")
52
+ out.append((text, value))
53
+ return out
54
+
55
+
56
+ def _kind_of(line: dict[str, Any]) -> str:
57
+ if "mdb_payload" in line:
58
+ return "payload"
59
+ if "mdb_execution" in line:
60
+ return "execution"
61
+ if line.get("schema") in R.SCHEMAS:
62
+ return "record"
63
+ return "other"
64
+
65
+
66
+ def is_record_file(path: str | Path) -> bool:
67
+ """Every non-empty line is a stored record, payload or execution line (and one record)."""
68
+ try:
69
+ kinds = [_kind_of(v) for _, v in _lines(Path(path))]
70
+ except (RecordError, OSError, UnicodeDecodeError):
71
+ return False
72
+ return "record" in kinds and "other" not in kinds
73
+
74
+
75
+ def _executions(lines: list[tuple[str, dict[str, Any]]]) -> dict[str, Any]:
76
+ from .custody import _executions as checked
77
+
78
+ return checked([line for _, line in lines])
79
+
80
+
81
+ def read_file(path: str | Path, *, verify: bool = True) -> list[dict[str, Any]]:
82
+ """The logical records of a record file (v3 and v2 lines), verified unless asked not to."""
83
+ _declare_kinds()
84
+ lines = _lines(Path(path))
85
+ if any(_kind_of(v) == "other" for _, v in lines):
86
+ raise RecordError(f"{path} holds lines that are not records, payloads or executions "
87
+ "(an unknown or altered schema)")
88
+ executions = _executions(lines)
89
+ return [R.load_record(v, executions=executions, verify=verify)
90
+ for _, v in lines if _kind_of(v) == "record"]
91
+
92
+
93
+ def verify_file(path: str | Path) -> dict[str, Any]:
94
+ """Verify every record of a file; returns counts by schema and kind."""
95
+ records = read_file(path)
96
+ by_schema: dict[str, int] = {}
97
+ by_kind: dict[str, int] = {}
98
+ for record in records:
99
+ by_schema[record["schema"]] = by_schema.get(record["schema"], 0) + 1
100
+ by_kind[record["kind"]] = by_kind.get(record["kind"], 0) + 1
101
+ return {"path": str(path), "records": len(records), "schemas": by_schema, "kinds": by_kind}
102
+
103
+
104
+ def _sha(path: Path) -> str:
105
+ return hashlib.sha256(path.read_bytes()).hexdigest()
106
+
107
+
108
+ def target_of(path: Path, out: Path | None = None, root: Path | None = None) -> Path:
109
+ name = path.name[:-len(".jsonl")] if path.name.endswith(".jsonl") else path.name
110
+ if out is None:
111
+ return path.with_name(name + SUFFIX)
112
+ relative = path.parent.relative_to(root) if root is not None else Path()
113
+ return out / relative / (name + SUFFIX)
114
+
115
+
116
+ def migrate_file(path: str | Path, target: str | Path | None = None, *,
117
+ force: bool = False) -> dict[str, Any]:
118
+ """Write the v3 twin of one record file and its map; returns the map (also written).
119
+
120
+ Nothing is written unless every record migrates and the written file reads back with the
121
+ same content; ``target`` (default ``NAME.v3.jsonl`` beside ``path``) must not exist unless
122
+ ``force``."""
123
+ _declare_kinds()
124
+ path = Path(path)
125
+ target = Path(target) if target is not None else target_of(path)
126
+ if not target.name.endswith(SUFFIX):
127
+ raise RecordError(f"the target {target} must end in {SUFFIX}")
128
+ if target.resolve() == path.resolve() or (target.exists() and path.exists()
129
+ and target.samefile(path)):
130
+ raise RecordError(f"the target {target} is the source; a migration never writes in place")
131
+ map_path = target.with_name(target.name[:-len(SUFFIX)] + ".v3.map.json")
132
+ if map_path.resolve() == path.resolve():
133
+ raise RecordError(f"the map {map_path} is the source")
134
+ if not force and target.exists():
135
+ raise FileExistsError(f"{target} exists; pass force=True to replace it")
136
+ lines = _lines(path)
137
+ if any(_kind_of(v) == "other" for _, v in lines):
138
+ raise RecordError(f"{path} holds lines that are not records, payloads or executions")
139
+ executions = _executions(lines)
140
+ out: list[str] = []
141
+ written: set[str] = set()
142
+ mapping: dict[str, str] = {}
143
+ sources: list[dict[str, Any]] = []
144
+ counts = {"records": 0, "migrated": 0, "already_v3": 0, "payloads": 0}
145
+ for text, line in lines:
146
+ kind = _kind_of(line)
147
+ if kind == "payload":
148
+ out.append(text)
149
+ counts["payloads"] += 1
150
+ continue
151
+ if kind == "execution":
152
+ continue # re-emitted before the first record that needs it
153
+ old = R.load_record(line, executions=executions)
154
+ new = R.migrate_record(old)
155
+ counts["records"] += 1
156
+ counts["migrated" if old["schema"] == R.SCHEMA_V2 else "already_v3"] += 1
157
+ if old["id"] in mapping and mapping[old["id"]] != new["id"]:
158
+ raise RecordError(f"record {old['id'][:12]} maps to two ids")
159
+ mapping[old["id"]] = new["id"]
160
+ sources.append(old)
161
+ stored = R.stored_record(new)
162
+ if stored["execution_sha256"] not in written:
163
+ out.append(R._canonical({"mdb_execution": R.EXECUTION_SCHEMA,
164
+ "sha256": stored["execution_sha256"],
165
+ "execution": new["execution"]}))
166
+ written.add(stored["execution_sha256"])
167
+ out.append(R._canonical(stored))
168
+ target.parent.mkdir(parents=True, exist_ok=True)
169
+ partial = target.with_name(target.name + ".partial")
170
+ partial.write_text("".join(t + "\n" for t in out), encoding="utf-8")
171
+ try:
172
+ back = read_file(partial)
173
+ if len(back) != len(sources):
174
+ raise RecordError(f"read back {len(back)} records, wrote {len(sources)}")
175
+ for old, new in zip(sources, back):
176
+ R.same_content(old, new)
177
+ if mapping[old["id"]] != new["id"] or new["schema"] != R.SCHEMA:
178
+ raise RecordError(f"record {old['id'][:12]} read back under another id")
179
+ before = {v["sha256"] for _, v in lines if _kind_of(v) == "payload"}
180
+ after = {v["sha256"] for _, v in _lines(partial) if _kind_of(v) == "payload"}
181
+ if before != after:
182
+ raise RecordError("payload lines differ after migration")
183
+ except BaseException:
184
+ partial.unlink(missing_ok=True)
185
+ raise
186
+ report = {"schema": MAP_SCHEMA, "source": str(path), "source_sha256": _sha(path),
187
+ "target": str(target), "target_sha256": _sha(partial), **counts,
188
+ "verified": len(back),
189
+ "check": "every record read back from the target equals its source in every "
190
+ "field but schema, id and digest (canonical JSON)",
191
+ "map": mapping}
192
+ # the map first (atomically), then the target: a crash between leaves a map and no target,
193
+ # which a rerun replaces; never a target without its map
194
+ map_partial = map_path.with_name(map_path.name + ".partial")
195
+ map_partial.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8")
196
+ map_partial.replace(map_path)
197
+ partial.replace(target)
198
+ report["map_path"] = str(map_path)
199
+ return report
200
+
201
+
202
+ _LOOKS = re.compile(r'"schema"\s*:\s*"mdb-record-|"mdb_execution"\s*:')
203
+
204
+
205
+ def looks_like_record_file(path: str | Path) -> bool:
206
+ """True when the file's text mentions a record schema or an execution line, even if it
207
+ is truncated, altered or unreadable (so a scan reports it instead of skipping it)."""
208
+ try:
209
+ return bool(_LOOKS.search(Path(path).read_text(encoding="utf-8", errors="replace")))
210
+ except OSError:
211
+ return True
212
+
213
+
214
+ def record_files(path: str | Path, *, include_targets: bool = False) -> list[Path]:
215
+ """Record files at ``path``: the file itself, or every ``*.jsonl`` under a directory that
216
+ looks like a record file (``looks_like_record_file``, so a damaged one is listed and then
217
+ refused by the reader), not a ``.v3.jsonl`` target unless ``include_targets``."""
218
+ path = Path(path)
219
+ if path.is_file():
220
+ return [path]
221
+ return sorted(p for p in path.rglob("*.jsonl")
222
+ if (include_targets or not p.name.endswith(SUFFIX)) and looks_like_record_file(p))
223
+
224
+
225
+ USAGE = ("usage: mdb records migrate PATH [PATH ...] [--out DIR] [--force]\n"
226
+ " mdb records verify PATH [PATH ...]\n"
227
+ " migrate write NAME.v3.jsonl and NAME.v3.map.json for every record file at PATH (a\n"
228
+ " JSONL file, or a directory searched for record files); never in place\n"
229
+ " verify read every record of the files at PATH and check its seal")
230
+
231
+
232
+ def main(argv: list[str]) -> int:
233
+ import sys
234
+
235
+ if not argv or argv[0] in ("-h", "--help") or argv[0] not in ("migrate", "verify"):
236
+ print(USAGE, file=sys.stderr if argv and argv[0] not in ("-h", "--help") else sys.stdout)
237
+ return 0 if argv and argv[0] in ("-h", "--help") else 2
238
+ verb, rest = argv[0], argv[1:]
239
+ if any(a in ("-h", "--help") for a in rest):
240
+ print(USAGE)
241
+ return 0
242
+ out = force = None
243
+ paths = []
244
+ i = 0
245
+ while i < len(rest):
246
+ if rest[i] == "--out" and i + 1 < len(rest):
247
+ out, i = Path(rest[i + 1]), i + 2
248
+ elif rest[i] == "--force":
249
+ force, i = True, i + 1
250
+ else:
251
+ paths.append(Path(rest[i]))
252
+ i += 1
253
+ if not paths:
254
+ print(USAGE, file=sys.stderr)
255
+ return 2
256
+ status = 0
257
+ for root in paths:
258
+ files = record_files(root, include_targets=verb == "verify")
259
+ if not files:
260
+ print(f"{root}: no record files", file=sys.stderr)
261
+ status = 1
262
+ for file in files:
263
+ try:
264
+ if verb == "verify":
265
+ report = verify_file(file)
266
+ print(f"{file}: {report['records']} records verified {report['schemas']}")
267
+ continue
268
+ target = target_of(file, out, root if root.is_dir() else file.parent)
269
+ report = migrate_file(file, target, force=bool(force))
270
+ print(f"{file} -> {report['target']}: {report['records']} records "
271
+ f"({report['migrated']} migrated, {report['already_v3']} already v3), "
272
+ f"{report['verified']} read back equal; map {report['map_path']}")
273
+ except (RecordError, OSError, ValueError) as error:
274
+ print(f"{file}: refused: {error}", file=sys.stderr)
275
+ status = 1
276
+ return status
277
+
278
+
279
+ __all__ = ["MAP_SCHEMA", "SUFFIX", "is_record_file", "looks_like_record_file", "main", "migrate_file", "read_file",
280
+ "record_files", "target_of", "verify_file"]
@@ -0,0 +1,116 @@
1
+ """Offline Neuronpedia identities, without importing SAELens code or model frameworks.
2
+
3
+ Explicit mappings override basis metadata, then the installed SAELens registry.
4
+ All identities are supplied information, never a measured correspondence.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import re
10
+ from functools import lru_cache
11
+ from importlib.metadata import PackageNotFoundError, distribution
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ _PART = re.compile(r"[A-Za-z0-9_.-]+\Z")
16
+
17
+
18
+ def _identity(value: Any) -> tuple[str, str] | None:
19
+ if isinstance(value, str):
20
+ parts = value.split("/")
21
+ elif isinstance(value, dict):
22
+ parts = [value.get("model"), value.get("source")]
23
+ else:
24
+ return None
25
+ if len(parts) != 2 or not all(isinstance(p, str) and _PART.fullmatch(p)
26
+ and p not in (".", "..") for p in parts):
27
+ return None
28
+ return parts[0], parts[1]
29
+
30
+
31
+ def _registry_path() -> Path | None:
32
+ try:
33
+ dist = distribution("sae-lens")
34
+ except PackageNotFoundError:
35
+ return None
36
+ path = Path(dist.locate_file("sae_lens/pretrained_saes.yaml"))
37
+ return path if path.is_file() else None
38
+
39
+
40
+ @lru_cache(maxsize=4)
41
+ def _registry(path: str, mtime: int, size: int) -> tuple[dict, str]:
42
+ # File identity invalidates the cache after an installed registry is updated.
43
+ import yaml
44
+
45
+ raw = Path(path).read_bytes()
46
+ try:
47
+ data = yaml.safe_load(raw)
48
+ except yaml.YAMLError as error:
49
+ raise ValueError("invalid SAELens registry") from error
50
+ if not isinstance(data, dict):
51
+ raise ValueError("SAELens registry is not a mapping")
52
+ return data, hashlib.sha256(raw).hexdigest()
53
+
54
+
55
+ def feature_url(mapping: dict[str, Any] | None, release: str | None, sae_id: str | None,
56
+ feature: int, *, metadata: dict[str, Any] | None = None) -> dict[str, Any]:
57
+ """Resolve a feature from explicit ids, ``metadata.neuronpedia_id`` or SAELens.
58
+
59
+ Automatic links record their source (and registry digest). Existing explicit-map
60
+ results keep their serialized form. Missing/invalid metadata is a diagnostic,
61
+ never an obstacle to collecting numerical evidence. Nothing is downloaded.
62
+ """
63
+ key = f"{release}/{sae_id}"
64
+ origin = None
65
+ if mapping is not None and key in mapping:
66
+ value = mapping[key]
67
+ elif metadata is not None and metadata.get("neuronpedia_id") is not None:
68
+ value = metadata["neuronpedia_id"]
69
+ origin = {"kind": "sae-metadata"}
70
+ else:
71
+ value = None
72
+ repo = (metadata or {}).get("repo")
73
+ filename = (metadata or {}).get("file")
74
+ if (release and sae_id) or (repo and filename):
75
+ try:
76
+ path = _registry_path()
77
+ if path is not None:
78
+ stat = path.stat()
79
+ data, digest = _registry(str(path), stat.st_mtime_ns, stat.st_size)
80
+ matches = []
81
+ suites = [(release, data.get(release, {}))] if release and sae_id else data.items()
82
+ for name, suite in suites:
83
+ if not isinstance(suite, dict):
84
+ continue
85
+ if not (release and sae_id) and suite.get("repo_id") != repo:
86
+ continue
87
+ entries = suite.get("saes", [])
88
+ if not isinstance(entries, list):
89
+ raise ValueError("SAELens saes must be a list")
90
+ for entry in entries:
91
+ if not isinstance(entry, dict):
92
+ continue
93
+ if (entry.get("id") == sae_id if release and sae_id
94
+ else entry.get("path") == filename):
95
+ matches.append((name, entry))
96
+ if len(matches) == 1:
97
+ resolved_release, entry = matches[0]
98
+ value = entry.get("neuronpedia")
99
+ origin = {"kind": "saelens-registry", "sha256": digest,
100
+ "release": resolved_release, "sae_id": entry.get("id")}
101
+ except (ImportError, OSError, ValueError):
102
+ return {"state": "unresolved", "reason": "cannot read the local SAELens registry; "
103
+ "supply a Neuronpedia mapping or SAE metadata"}
104
+ if value is None:
105
+ return {"state": "unresolved", "reason": f"no Neuronpedia id for {key} in "
106
+ "explicit mappings, SAE metadata or the local SAELens registry; "
107
+ "supply model/source ids (SAELens ids are not Neuronpedia ids)"}
108
+ identity = _identity(value)
109
+ if identity is None or not isinstance(feature, int) or isinstance(feature, bool) or feature < 0:
110
+ return {"state": "unresolved", "reason": "invalid Neuronpedia identity or feature index"}
111
+ model, source = identity
112
+ out: dict[str, Any] = {
113
+ "url": f"https://www.neuronpedia.org/{model}/{source}/{feature}", "verified": "supplied"}
114
+ if origin is not None:
115
+ out["origin"] = origin
116
+ return out
mdb/core/plugins.py ADDED
@@ -0,0 +1,78 @@
1
+ """Plug-in lookup through entry points: how the engine reaches code it does not ship.
2
+
3
+ Standard library only (``importlib.metadata``); nothing is imported until a name is asked for.
4
+ Three groups are read:
5
+
6
+ * ``mdb.lanes`` (``VERB_GROUP``): command verbs. Each entry point is a callable
7
+ ``main(argv: list[str]) -> int`` that receives the verb itself followed by its arguments.
8
+ * ``mdb.lanes.exports`` (``EXPORT_GROUP``): attributes of the ``mdb`` package that the engine
9
+ does not define (``name = "module:attribute"``), resolved lazily by ``mdb.__getattr__``.
10
+ * ``mdb.sinks`` (``SINK_GROUP``): record sinks. Each entry point is a factory called with no
11
+ arguments; the object it returns has ``write(record: dict) -> None`` (and may have
12
+ ``close()``). ``core.custody`` hands it every sealed record while ``records.plugins``
13
+ (``MDB_RECORDS_PLUGINS``) names it; installed alone, a sink receives nothing.
14
+
15
+ The experiment lanes (distribution ``mdb-lanes``, in the saturn-lab research repository) declare
16
+ both groups. Distributions are found
17
+ on ``sys.path`` like any other installed metadata, so a source tree that carries a
18
+ ``*.dist-info`` directory next to its packages is found without being installed. The first
19
+ entry point of a name wins (``sys.path`` order); later duplicates are ignored.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from functools import lru_cache
24
+
25
+ VERB_GROUP = "mdb.lanes"
26
+ EXPORT_GROUP = "mdb.lanes.exports"
27
+ SINK_GROUP = "mdb.sinks"
28
+ PLUGIN_DIST = "mdb-lanes"
29
+ # What mdb-lanes declares, so that without it a lanes name is told apart from a typo.
30
+ LANES_VERBS = frozenset(
31
+ "analyze atlas attach bench bisect cache capabilities circuits cite claims compiled-state "
32
+ "context custody debug discovery doctor edit-search equations evidence family "
33
+ "flux-read-panels forecast forward-symbols graph help hyperion inspect jobs open ports "
34
+ "project public qwen-panels replay resume run script states storage symbol-producers "
35
+ "symbol-trace symbols verify view vm watch wsp xref".split())
36
+ LANES_EXPORTS = frozenset(
37
+ "ActionNode BenchError BenchSession CausalContextVM Evidence ExecutionBinding ForwardResult "
38
+ "GraphBinding GraphEdge GraphIntegrityError GraphNode GraphSnapshot GraphVerification "
39
+ "MambaStateVM ModelRunner NodeBinding OutputNode Project RunnerCapabilities "
40
+ "SaturnPubDebuggerAdapter SourceNode StateGraph StateGraphError StateNode "
41
+ "TransformerLensDebuggerAdapter TransformerLensRunner TransformersRunner available_backends "
42
+ "evidence register_backend".split())
43
+
44
+
45
+ @lru_cache(maxsize=None)
46
+ def entries(group: str) -> dict:
47
+ """``{name: EntryPoint}`` of one group (cached; ``clear()`` forgets it)."""
48
+ from importlib.metadata import entry_points
49
+
50
+ out = {}
51
+ for entry in entry_points(group=group):
52
+ out.setdefault(entry.name, entry)
53
+ return out
54
+
55
+
56
+ def clear() -> None:
57
+ entries.cache_clear()
58
+
59
+
60
+ def verbs() -> list[str]:
61
+ return sorted(entries(VERB_GROUP))
62
+
63
+
64
+ def verb(name: str):
65
+ """The callable registered for verb ``name``, or ``None`` when no plug-in provides it."""
66
+ entry = entries(VERB_GROUP).get(name)
67
+ return None if entry is None else entry.load()
68
+
69
+
70
+ def export(name: str):
71
+ """``(found, value)`` for attribute ``name`` of the ``mdb`` package."""
72
+ entry = entries(EXPORT_GROUP).get(name)
73
+ return (False, None) if entry is None else (True, entry.load())
74
+
75
+
76
+ def installed() -> bool:
77
+ """Whether any plug-in declares verbs or exports."""
78
+ return bool(entries(VERB_GROUP) or entries(EXPORT_GROUP))