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.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/ops/debugger.py
ADDED
|
@@ -0,0 +1,926 @@
|
|
|
1
|
+
"""The embedding API: attach to an already-loaded Hugging Face causal LM and step it.
|
|
2
|
+
|
|
3
|
+
dbg = mdb.attach(model, tokenizer) # eager attention, eval mode, one sequence
|
|
4
|
+
run = dbg.run("Weather: freezing") # a port-level Run, cursor at t<last>.L0.h
|
|
5
|
+
run.until("L1.p"); dbg.repl(run) # or: ctx = dbg.ops(run); dispatch(ctx, ...)
|
|
6
|
+
|
|
7
|
+
With ``project=`` the debugger is durable: ``attach(model, tok, project="runs/t")`` creates or
|
|
8
|
+
reopens an ``mdb.core.project.Project`` and a session bound to the model identity and
|
|
9
|
+
execution; ``dbg.checkpoint(run, "pre")`` stores the replay recipe, the edit tensors and the
|
|
10
|
+
boundary cut; ``dbg.restart("pre")`` (any later process) rebuilds that cursor with the same cut
|
|
11
|
+
fingerprint; ``dbg.export(run, "t3.L1.u")`` returns an occurrence pointer ``mdb.resolve``
|
|
12
|
+
turns back into the tensor.
|
|
13
|
+
|
|
14
|
+
Named runs: ``dbg.run(prompt, name="boiling")`` keeps one live run per name (``runs``; the
|
|
15
|
+
default name is ``main``). A state-cell edit of one run can take its value from another:
|
|
16
|
+
``cell_value("boiling:cache.L1.v[kv0,row=2]", run=target)`` (or ``boiling:t2.L1.v[kv0]``, the
|
|
17
|
+
value row 2 wrote at ``v``; ``kr`` works too) resolves the origin as a live named run, else as a
|
|
18
|
+
project session id or durable checkpoint name (restored from its stored cut, else replayed
|
|
19
|
+
from the token ids), refuses another model identity, another numeric scope or a row the donor
|
|
20
|
+
has not computed, and returns the selected block ``(1, kv, rows, d)`` with its pointer (names
|
|
21
|
+
and digests, never the array). A port edit takes ``ORIGIN:ADDR`` the same way (``set
|
|
22
|
+
L0.A[h1] = clean:L0.A[h1]``, the clean-to-corrupted activation patch): both go through
|
|
23
|
+
``origin_value``.
|
|
24
|
+
|
|
25
|
+
This module lives in ``mdb.ops`` (the lowest layer that may know the operation registry);
|
|
26
|
+
``mdb.attach`` / ``mdb.open_tiny`` / ``mdb.Debugger`` resolve here lazily.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from collections.abc import Sequence
|
|
32
|
+
from dataclasses import replace
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from saturn.values import digest
|
|
36
|
+
|
|
37
|
+
from mdb.core import index
|
|
38
|
+
from mdb.core import recipe as recipes
|
|
39
|
+
from mdb.core.address import (
|
|
40
|
+
DEFAULT_GLOBALS,
|
|
41
|
+
AddressError,
|
|
42
|
+
Occurrence,
|
|
43
|
+
Origin,
|
|
44
|
+
StateCell,
|
|
45
|
+
format_address,
|
|
46
|
+
parse,
|
|
47
|
+
)
|
|
48
|
+
from mdb.core.errors import Refused
|
|
49
|
+
from mdb.core.pointers import RecordError, Unresolved, occurrence_pointer
|
|
50
|
+
from mdb.core.settings import DEFAULT_SEED
|
|
51
|
+
from mdb.engine.edits import CELL_AXES
|
|
52
|
+
from mdb.engine.ports import PROGRAMS, config_refusal, program_for, tensor_digest
|
|
53
|
+
from mdb.engine.run import ReplayMismatch, Run
|
|
54
|
+
|
|
55
|
+
from .context import Context
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Debugger:
|
|
59
|
+
"""One attached model: its saturn operation-granularity adapter and tokenizer, and with
|
|
60
|
+
a project, the durable session (``project``, ``session_id``). ``live`` is the run this
|
|
61
|
+
debugger made or restarted last (the resolver's ``live`` tier reads its port cache)."""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self, model: Any, tokenizer: Any, adapter: Any, *, project: Any = None,
|
|
65
|
+
session_id: str | None = None,
|
|
66
|
+
):
|
|
67
|
+
self.model = model
|
|
68
|
+
self.tokenizer = tokenizer
|
|
69
|
+
self.adapter = adapter
|
|
70
|
+
self.program = program_for(adapter)
|
|
71
|
+
self.project = project
|
|
72
|
+
self.session_id = session_id
|
|
73
|
+
self.live: Run | None = None
|
|
74
|
+
self.runs: dict[str, Run] = {}
|
|
75
|
+
self.run_checkpoints: dict[str, dict[str, Any]] = {} # in-memory, of runs not shown
|
|
76
|
+
self.carried_circuits: dict[int, Any] = {} # id -> circuit, built by an earlier run
|
|
77
|
+
self.imports: dict[str, Imported] = {} # foreign values (TransformerLens, nnsight, ...)
|
|
78
|
+
|
|
79
|
+
# --- foreign values -------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
def import_values(self, name: str, values: dict[str, Any], *, tokens: Sequence[int],
|
|
82
|
+
provenance: dict[str, Any] | None = None,
|
|
83
|
+
model_identity: str | None = None) -> Imported:
|
|
84
|
+
"""Register values computed outside mdb (a TransformerLens cache, nnsight saves) as the
|
|
85
|
+
origin ``name``: ``name:cache.L22.v[kv1,row=11]`` and ``name:t11.L22.v[kv1]`` then
|
|
86
|
+
resolve from them for state-cell edits, and ``name:t17.L22.A`` for port edits.
|
|
87
|
+
|
|
88
|
+
``values`` maps occurrence addresses ``t<r>.L<l>.<port>`` to tensors in mdb's layout
|
|
89
|
+
for one row (``mdb.interop`` converts tool layouts). Values are ``supplied``: another
|
|
90
|
+
program computed them (another kernel order, batch shape or weight basis), so mdb never
|
|
91
|
+
labels them ``measured``. ``model_identity`` (when the caller knows it) must equal this
|
|
92
|
+
model's; ``provenance`` (tool, version, hook names, processing) is copied into every
|
|
93
|
+
pointer made from the import.
|
|
94
|
+
"""
|
|
95
|
+
name = run_name(name)
|
|
96
|
+
if name in self.runs:
|
|
97
|
+
raise Refused(f"{name!r} names a live run; pick another import name")
|
|
98
|
+
if model_identity is not None and model_identity != self.adapter.model_identity:
|
|
99
|
+
raise Refused(f"{name}: values of another model (identity {str(model_identity)[:16]},"
|
|
100
|
+
f" attached {str(self.adapter.model_identity)[:16]})")
|
|
101
|
+
imported = Imported(name, self.adapter, self.program, values, list(tokens),
|
|
102
|
+
dict(provenance or {}))
|
|
103
|
+
self.imports[name] = imported
|
|
104
|
+
return imported
|
|
105
|
+
|
|
106
|
+
def port_value(self, text: str, *, run: Run) -> tuple[Any, dict[str, Any]]:
|
|
107
|
+
"""The value ``IMPORT:t<r>.L<l>.<port>`` names, whole port (selectors on the value are
|
|
108
|
+
refused: the target's selector picks the elements), checked against the port shape of
|
|
109
|
+
``run``. Only imports carry port values across runs."""
|
|
110
|
+
try:
|
|
111
|
+
address = parse(text, ports=self.program.names, global_ports=DEFAULT_GLOBALS)
|
|
112
|
+
except AddressError as error:
|
|
113
|
+
raise Refused(f"bad value address {text!r}: {error}") from None
|
|
114
|
+
origin = address.origin
|
|
115
|
+
if origin is None or origin.branch not in self.imports:
|
|
116
|
+
raise Refused(f"{text}: a port value from another origin must name an import "
|
|
117
|
+
f"(have: {', '.join(sorted(self.imports)) or 'none'}); a value from "
|
|
118
|
+
"another run goes into a state cell (cache.L<i>.k|v)")
|
|
119
|
+
if not isinstance(address, Occurrence) or address.layer is None:
|
|
120
|
+
raise Refused(f"{text}: a port value is an occurrence t<r>.L<l>.<port>")
|
|
121
|
+
if address.selector.keys or address.selector.tokens:
|
|
122
|
+
raise Refused(f"{text}: name the whole port; the target's selector picks elements")
|
|
123
|
+
imported = self.imports[origin.branch]
|
|
124
|
+
target = f"t{address.token}.L{address.layer}.{address.port}"
|
|
125
|
+
value = imported.read(target)
|
|
126
|
+
want = tuple(run.port_shape(address.port))
|
|
127
|
+
if tuple(value.shape) != want:
|
|
128
|
+
raise Refused(f"{text} has shape {list(value.shape)}; the port has {list(want)}")
|
|
129
|
+
return value.to(run.adapter.dtype), imported.pointer(target, value)
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def family(self) -> str:
|
|
133
|
+
return self.program.family
|
|
134
|
+
|
|
135
|
+
def tokens(self, prompt: str | Sequence[int] | Any) -> list[int]:
|
|
136
|
+
"""Token ids of one sequence; text needs the tokenizer, batches are refused."""
|
|
137
|
+
if isinstance(prompt, str):
|
|
138
|
+
if self.tokenizer is None:
|
|
139
|
+
raise Refused("text prompts need a tokenizer; attach(model, tokenizer) or pass "
|
|
140
|
+
"token ids")
|
|
141
|
+
ids = self.tokenizer(prompt)["input_ids"]
|
|
142
|
+
elif hasattr(prompt, "tolist"):
|
|
143
|
+
if getattr(prompt, "ndim", 1) == 2:
|
|
144
|
+
if prompt.shape[0] != 1:
|
|
145
|
+
raise Refused(f"mdb steps one sequence (batch 1), got batch {prompt.shape[0]}")
|
|
146
|
+
prompt = prompt[0]
|
|
147
|
+
elif getattr(prompt, "ndim", 1) != 1:
|
|
148
|
+
raise Refused("token ids must be one sequence")
|
|
149
|
+
ids = prompt.tolist()
|
|
150
|
+
else:
|
|
151
|
+
ids = list(prompt)
|
|
152
|
+
if ids and isinstance(ids[0], (list, tuple)):
|
|
153
|
+
if len(ids) != 1:
|
|
154
|
+
raise Refused(f"mdb steps one sequence (batch 1), got batch {len(ids)}")
|
|
155
|
+
ids = list(ids[0])
|
|
156
|
+
if not ids:
|
|
157
|
+
raise Refused("the prompt has no tokens")
|
|
158
|
+
if any(isinstance(t, bool) or not isinstance(t, int) or t < 0 for t in ids):
|
|
159
|
+
raise Refused("token ids must be nonnegative integers")
|
|
160
|
+
if max(ids) >= self.adapter.vocab_size:
|
|
161
|
+
raise Refused(f"token id {max(ids)} is outside the vocabulary "
|
|
162
|
+
f"({self.adapter.vocab_size})")
|
|
163
|
+
if len(ids) > self.adapter.max_positions:
|
|
164
|
+
raise Refused(f"{len(ids)} tokens exceed max_position_embeddings "
|
|
165
|
+
f"{self.adapter.max_positions}")
|
|
166
|
+
return [int(t) for t in ids]
|
|
167
|
+
|
|
168
|
+
def run(
|
|
169
|
+
self,
|
|
170
|
+
prompt: str | Sequence[int],
|
|
171
|
+
*,
|
|
172
|
+
retain_rows: int | None = None,
|
|
173
|
+
lookahead: str | None = None,
|
|
174
|
+
name: str | None = None,
|
|
175
|
+
prefill: int | None = None,
|
|
176
|
+
) -> Run:
|
|
177
|
+
"""Prefill all but the last token (``prefill=K``: the first ``K``; the later prompt
|
|
178
|
+
rows are stepped with their tokens forced); the cursor starts where the ``start`` op
|
|
179
|
+
leaves it, at ``t<first stepped row>.L0.<first port>`` (this is the one implementation
|
|
180
|
+
of ``start``). The session is built once, under that split.
|
|
181
|
+
|
|
182
|
+
``lookahead`` (``"none"``, the engine default, ``"layer"`` or ``"auto"``) is passed to
|
|
183
|
+
``Run``.
|
|
184
|
+
``name`` (a branch name, default ``main``) keeps the run in ``runs`` under that name,
|
|
185
|
+
replacing an earlier run of the same name; other values can then name it as an origin.
|
|
186
|
+
"""
|
|
187
|
+
name = run_name(name)
|
|
188
|
+
options: dict[str, Any] = {"retain_rows": retain_rows, "prefill": prefill}
|
|
189
|
+
if lookahead is not None:
|
|
190
|
+
options["lookahead"] = lookahead
|
|
191
|
+
run = Run(self.adapter, self.tokens(prompt), **options)
|
|
192
|
+
run.until(f"L0.{run.program.names[0]}")
|
|
193
|
+
run.name = name
|
|
194
|
+
self._carry_circuits(run)
|
|
195
|
+
self.runs[name] = run
|
|
196
|
+
self.live = run
|
|
197
|
+
return run
|
|
198
|
+
|
|
199
|
+
# --- values from another run ----------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
def _donor(self, branch: str, *, replay: bool = False) -> tuple[Run, str, str | None]:
|
|
202
|
+
"""``(run, via, recipe id)`` standing for origin ``branch``: the live run of that name
|
|
203
|
+
(``via`` ``live``), else the project's latest recipe for that session id or checkpoint
|
|
204
|
+
name, rehydrated from its ``checkpoint-state`` (``checkpoint``), restored from a stored
|
|
205
|
+
boundary cut (``cut``, projects written before checkpoint states) or replayed from the
|
|
206
|
+
token ids (``replay``; always with ``replay=True``: a replayed run holds the
|
|
207
|
+
transitions before its cursor, a rehydrated one those its checkpoint kept)."""
|
|
208
|
+
if branch in self.runs and not replay:
|
|
209
|
+
return self.runs[branch], "live", None
|
|
210
|
+
if self.project is None:
|
|
211
|
+
raise Refused(f"unknown origin {branch!r}: no run of that name (info runs) and no "
|
|
212
|
+
"project to look a session or checkpoint up in")
|
|
213
|
+
from mdb.core.resolve import recipes_for
|
|
214
|
+
|
|
215
|
+
found = recipes_for(self.project, branch, self.session_id)
|
|
216
|
+
if not found:
|
|
217
|
+
raise Refused(f"unknown origin {branch!r}: no run of that name (info runs) and the "
|
|
218
|
+
"project holds no session or checkpoint of that name")
|
|
219
|
+
recipe = recipes.load(self.project, found[-1])
|
|
220
|
+
recipes.check_binding(recipe, model_identity=self.adapter.model_identity,
|
|
221
|
+
numeric_scope=self._numeric_scope())
|
|
222
|
+
checkpoint = recipes.to_checkpoint(recipe)
|
|
223
|
+
if not replay:
|
|
224
|
+
from mdb.engine import checkpoint as states
|
|
225
|
+
|
|
226
|
+
state = states.find_named(self.project, None, session_id=self.session_id,
|
|
227
|
+
cut=recipe["cut"])
|
|
228
|
+
if state is not None:
|
|
229
|
+
recipes.load_tensors(recipe, self.project.store)
|
|
230
|
+
run = states.load_record(self.project, state).run(self.adapter, check=False)
|
|
231
|
+
run.name = None
|
|
232
|
+
return run, "checkpoint", recipe["fingerprint"]
|
|
233
|
+
for session in () if replay else self.project.sessions():
|
|
234
|
+
sid = session["session_id"]
|
|
235
|
+
if recipe["cut"] in self.project.cut_ids(sid):
|
|
236
|
+
root = self.project.load_cut(sid, recipe["cut"])
|
|
237
|
+
return (self._restored(checkpoint, recipe, self.project.store, root), "cut",
|
|
238
|
+
recipe["fingerprint"])
|
|
239
|
+
return (self._restored(checkpoint, recipe, self.project.store), "replay",
|
|
240
|
+
recipe["fingerprint"])
|
|
241
|
+
|
|
242
|
+
def cell_value(self, text: str, *, run: Run) -> tuple[Any, dict[str, Any]]:
|
|
243
|
+
"""The value ``ORIGIN:ADDR`` names, for a state-cell edit of ``run``: the selected
|
|
244
|
+
block ``(1, kv, rows, d)`` of a cache cell or of a ``v``/``kr`` occurrence of the run
|
|
245
|
+
``ORIGIN`` stands for, and its pointer ``{origin, via, address, sha256, shape, dtype,
|
|
246
|
+
where, cut, recipe}``. Refuses (``Refused``) an unknown origin, another model identity
|
|
247
|
+
or numeric scope than ``run``'s, and a row the donor has not computed."""
|
|
248
|
+
try:
|
|
249
|
+
address = parse(text, ports=self.program.names, global_ports=DEFAULT_GLOBALS)
|
|
250
|
+
except AddressError as error:
|
|
251
|
+
raise Refused(f"bad value address {text!r}: {error}") from None
|
|
252
|
+
origin = address.origin
|
|
253
|
+
if origin is None or origin.branch is None:
|
|
254
|
+
raise Refused(f"{text!r} names no run: write ORIGIN:ADDR (a run name, a session id "
|
|
255
|
+
"or a checkpoint name)")
|
|
256
|
+
if origin.edits:
|
|
257
|
+
raise Refused("an origin with edits (@cut+edit) is not a run; name a run")
|
|
258
|
+
if origin.branch in self.imports:
|
|
259
|
+
imported = self.imports[origin.branch]
|
|
260
|
+
block = cell_block(imported, address, label=origin.branch)
|
|
261
|
+
return block, imported.pointer(format_address(address), block)
|
|
262
|
+
return self.origin_value(origin.branch, format_address(address), run=run,
|
|
263
|
+
pick=lambda donor: cell_block(donor, address,
|
|
264
|
+
label=origin.branch))
|
|
265
|
+
|
|
266
|
+
def origin_value(self, branch: str, address: str, *, run: Run, pick: Any
|
|
267
|
+
) -> tuple[Any, dict[str, Any]]:
|
|
268
|
+
"""The one fetch of a value from another run (cell and port edits both use it):
|
|
269
|
+
``pick(donor)`` reads the selected tensor from the run origin ``branch`` stands for
|
|
270
|
+
(``_donor``: a live named run, else a project session or checkpoint restored from its
|
|
271
|
+
cut or replayed), after refusing another model identity or numeric scope than ``run``'s.
|
|
272
|
+
Reading leaves the donor's cursor and state as they were. Returns the tensor and its
|
|
273
|
+
pointer ``{origin, via, address, sha256, shape, dtype, where, cut, recipe}``."""
|
|
274
|
+
donor, via, recipe = self._donor(branch)
|
|
275
|
+
_same_binding(donor, run, branch)
|
|
276
|
+
try:
|
|
277
|
+
block = pick(donor)
|
|
278
|
+
except NotHeld:
|
|
279
|
+
if via not in ("cut", "checkpoint"):
|
|
280
|
+
raise
|
|
281
|
+
# restored from its cut, the donor starts at its cursor: replay it from the token
|
|
282
|
+
# ids, which computes the transitions before the cursor too
|
|
283
|
+
donor, via, recipe = self._donor(branch, replay=True)
|
|
284
|
+
block = pick(donor)
|
|
285
|
+
pointer = {"origin": branch, "via": via, "address": address,
|
|
286
|
+
"sha256": tensor_digest(block), "shape": list(block.shape),
|
|
287
|
+
"dtype": str(block.dtype).removeprefix("torch."), "where": donor.where,
|
|
288
|
+
"cut": donor.checkpoint(pin=False)["cut"], "recipe": recipe}
|
|
289
|
+
return block, pointer
|
|
290
|
+
|
|
291
|
+
# --- durable checkpoints (project=) ---------------------------------------------------
|
|
292
|
+
|
|
293
|
+
def _project(self, what: str) -> Any:
|
|
294
|
+
if self.project is None:
|
|
295
|
+
raise Refused(f"{what} needs a project: attach(model, tokenizer, project=PATH) "
|
|
296
|
+
"(run.checkpoint() keeps an in-memory checkpoint)")
|
|
297
|
+
if self.project.read_only:
|
|
298
|
+
raise Refused(f"{what} needs a writable project")
|
|
299
|
+
return self.project
|
|
300
|
+
|
|
301
|
+
def _numeric_scope(self) -> dict[str, Any]:
|
|
302
|
+
return dict(self.adapter.execution.get("numeric_scope") or {})
|
|
303
|
+
|
|
304
|
+
def _save_recipe(self, run: Run, name: str | None, *, cut: bool = True) -> dict[str, Any]:
|
|
305
|
+
"""Store the recipe of ``run``'s cursor (edit tensors as blobs) and, with ``cut``, its
|
|
306
|
+
boundary cut (a whole native cut: ``checkpoint`` stores the state as a
|
|
307
|
+
``checkpoint-state`` instead, so K/V is not stored twice)."""
|
|
308
|
+
project = self._project("a durable checkpoint")
|
|
309
|
+
if run.adapter is not self.adapter:
|
|
310
|
+
raise Refused("the run belongs to another attached model")
|
|
311
|
+
checkpoint = run.checkpoint(name)
|
|
312
|
+
boundary = run.session.capture(retain=False)
|
|
313
|
+
if boundary.fingerprint != checkpoint["cut"]:
|
|
314
|
+
raise Refused("the run's session is not at its cursor's boundary cut")
|
|
315
|
+
try:
|
|
316
|
+
recipe = recipes.from_checkpoint(checkpoint, tokens=run.tokens,
|
|
317
|
+
layers=self.adapter.layers,
|
|
318
|
+
tensors=run.edit_tensors(), store=project.store)
|
|
319
|
+
except RecordError as error:
|
|
320
|
+
raise Refused(f"the checkpoint does not fit one replay recipe: {error}") from error
|
|
321
|
+
recipes.save(project, self.session_id, recipe)
|
|
322
|
+
if cut:
|
|
323
|
+
project.save_cut(self.session_id, boundary)
|
|
324
|
+
return recipe
|
|
325
|
+
|
|
326
|
+
def checkpoint(self, run: Run, name: str, *, history: str = "row",
|
|
327
|
+
holds: str = "rearm") -> dict[str, Any]:
|
|
328
|
+
"""Make ``run``'s cursor durable under ``name``: the replay recipe, its edit tensors and
|
|
329
|
+
masks (store blobs), a ``checkpoint`` record and the session cursor, and the state
|
|
330
|
+
itself as a ``checkpoint-state`` record whose tensors are store blobs
|
|
331
|
+
(``engine.checkpoint``; ``state`` in the result is its record id): ``restart`` and
|
|
332
|
+
``run_from`` rehydrate it with no prefix recompute. No whole native cut is stored
|
|
333
|
+
(projects that hold one from before are still read: ``cut_ids``, ``load_cut``)."""
|
|
334
|
+
if not isinstance(name, str) or not name.strip():
|
|
335
|
+
raise Refused("a durable checkpoint needs a name")
|
|
336
|
+
if holds not in ("rearm", "drop"):
|
|
337
|
+
raise Refused("holds is 'rearm' (default) or 'drop'")
|
|
338
|
+
recipe = self._save_recipe(run, name, cut=False)
|
|
339
|
+
record = recipes.record_checkpoint(self.project, self.session_id, recipe, run=run)
|
|
340
|
+
from mdb.engine import checkpoint as states
|
|
341
|
+
|
|
342
|
+
state = states.save(run, project=self.project, session_id=self.session_id, name=name,
|
|
343
|
+
history=history, holds=holds)
|
|
344
|
+
return {"name": name, "where": recipe["target"]["where"], "cut": recipe["cut"],
|
|
345
|
+
"recipe": recipe["fingerprint"], "record": record["id"],
|
|
346
|
+
"blobs": len(recipes.tensor_pointers(recipe)), "state": state["id"]}
|
|
347
|
+
|
|
348
|
+
def checkpoints(self) -> list[dict[str, Any]]:
|
|
349
|
+
"""This session's durable checkpoints, oldest first: name, where, cut, recipe and
|
|
350
|
+
``state``, the record id ``run_from`` takes (None for a checkpoint stored before
|
|
351
|
+
checkpoints held state: ``restart`` replays it)."""
|
|
352
|
+
project = self._project("listing durable checkpoints")
|
|
353
|
+
from mdb.engine import checkpoint as states
|
|
354
|
+
|
|
355
|
+
def state(body):
|
|
356
|
+
found = states.find_named(project, body["name"], session_id=self.session_id,
|
|
357
|
+
cut=body["cut"])
|
|
358
|
+
return None if found is None else found["id"]
|
|
359
|
+
|
|
360
|
+
return [{"name": r["body"]["name"], "where": r["body"]["where"], "cut": r["body"]["cut"],
|
|
361
|
+
"recipe": r["body"]["recipe"], "state": state(r["body"])}
|
|
362
|
+
for r in recipes.checkpoints(project, self.session_id)]
|
|
363
|
+
|
|
364
|
+
def restart(self, name: str, *, replay: bool = False, verify: bool | str = False) -> Run:
|
|
365
|
+
"""A new run at the durable checkpoint ``name`` (this session's, else the one other
|
|
366
|
+
session that has it): rehydrated from its stored state when the project holds it (no
|
|
367
|
+
prefix recompute; labelled ``from checkpoint <id>, path unverified``; ``verify=True``
|
|
368
|
+
replays the recipe first and raises ``CheckpointUnverified`` unless it reaches the
|
|
369
|
+
checkpoint, ``verify="report"`` records the result as ``run.core["verified"]``), else
|
|
370
|
+
(or with ``replay``) replayed from the token ids. Same cut fingerprint, same edits,
|
|
371
|
+
either way."""
|
|
372
|
+
project = self._project("restart")
|
|
373
|
+
found = recipes.find_checkpoint(project, name, session_id=self.session_id)
|
|
374
|
+
if found is None:
|
|
375
|
+
raise Refused(f"no durable checkpoint {name!r} in this project "
|
|
376
|
+
f"(session {self.session_id})")
|
|
377
|
+
from mdb.engine import checkpoint as states
|
|
378
|
+
|
|
379
|
+
recipe = recipes.load(project, found["body"]["recipe"])
|
|
380
|
+
state = states.find_named(project, name, session_id=found["session_id"],
|
|
381
|
+
cut=found["body"]["cut"])
|
|
382
|
+
if state is not None and not replay:
|
|
383
|
+
# the recipe's refusals first (model identity, numeric scope, its edit blobs), so a
|
|
384
|
+
# rehydrated restart refuses exactly as a replayed one
|
|
385
|
+
recipes.check_binding(recipe, model_identity=self.adapter.model_identity,
|
|
386
|
+
numeric_scope=self._numeric_scope())
|
|
387
|
+
recipes.load_tensors(recipe, project.store)
|
|
388
|
+
run = states.load_record(project, state).run(self.adapter, check=False,
|
|
389
|
+
verify=verify)
|
|
390
|
+
run.name = None # as a replayed restart: not a named run of this debugger
|
|
391
|
+
else:
|
|
392
|
+
run = self.replay(recipe)
|
|
393
|
+
self._carry_circuits(run)
|
|
394
|
+
self.live = run
|
|
395
|
+
return run
|
|
396
|
+
|
|
397
|
+
def _carry_circuits(self, run: Run) -> None:
|
|
398
|
+
"""Keep the circuit ledger across a new run: the circuits of the run this one replaces
|
|
399
|
+
(the live one) join ``run``'s ledger, so ``circuit show ID`` still reads them and new
|
|
400
|
+
ids continue after them; ``carried_circuits`` holds the ones that belong to an earlier
|
|
401
|
+
run (a circuit record is sealed and independent of the run that built it)."""
|
|
402
|
+
from mdb.analysis.circuits import build as circuits
|
|
403
|
+
|
|
404
|
+
if self.live is None or self.live is run:
|
|
405
|
+
return
|
|
406
|
+
earlier = circuits.ledger(self.live)
|
|
407
|
+
circuits.ledger(run).update(earlier)
|
|
408
|
+
self.carried_circuits.update(earlier)
|
|
409
|
+
|
|
410
|
+
def replay(self, recipe: dict[str, Any]) -> Run:
|
|
411
|
+
"""A new run restored to a replay recipe of this project (``RecipeError`` refusals:
|
|
412
|
+
model identity, numeric scope, missing or corrupt blob, fingerprint mismatch)."""
|
|
413
|
+
return self._restored(recipes.to_checkpoint(recipe), recipe, self._project("replay").store)
|
|
414
|
+
|
|
415
|
+
def _restored(self, checkpoint: dict[str, Any], recipe: dict[str, Any], store: Any,
|
|
416
|
+
root: Any = None) -> Run:
|
|
417
|
+
recipes.check_binding(recipe, model_identity=self.adapter.model_identity,
|
|
418
|
+
numeric_scope=self._numeric_scope())
|
|
419
|
+
tensors = recipes.load_tensors(recipe, store)
|
|
420
|
+
tokens = recipes.load_tokens(recipe, store)
|
|
421
|
+
transitions = checkpoint["transitions"] if root is not None else 0
|
|
422
|
+
run = Run(self.adapter, tokens, lookahead=recipe["lookahead"] if root is None else "none",
|
|
423
|
+
root=root, root_transitions=transitions)
|
|
424
|
+
run.hold(tensors)
|
|
425
|
+
try:
|
|
426
|
+
run.restore(checkpoint)
|
|
427
|
+
except ReplayMismatch as error:
|
|
428
|
+
raise recipes.fingerprint_mismatch(recipe, error.expected, error.reached) from error
|
|
429
|
+
return run
|
|
430
|
+
|
|
431
|
+
# --- occurrence pointers --------------------------------------------------------------
|
|
432
|
+
|
|
433
|
+
def export(self, run: Run, target: str, *, keep: bool = False) -> dict[str, Any]:
|
|
434
|
+
"""An occurrence pointer to the value at ``target`` (a computed address of ``run``).
|
|
435
|
+
|
|
436
|
+
The pointer names the address (origin: this session), the stored recipe of ``run``'s
|
|
437
|
+
cursor, the transition and the boundary cut the value comes from, and the value's
|
|
438
|
+
shape, dtype, payload sha256 and authority (``Run.read_info``). With ``keep`` the value
|
|
439
|
+
is also stored as a blob and indexed, so ``mdb.resolve`` answers without a model.
|
|
440
|
+
"""
|
|
441
|
+
project = self._project("export")
|
|
442
|
+
try:
|
|
443
|
+
where = run.address(run.parse(target))
|
|
444
|
+
origin = run.origin_of(target)
|
|
445
|
+
address = parse(where, ports=self.program.names)
|
|
446
|
+
except (ValueError, AddressError) as error:
|
|
447
|
+
raise Refused(f"cannot export {target!r}: {error}") from error
|
|
448
|
+
info = run.read_info(target)
|
|
449
|
+
if info["state"] != "resolved":
|
|
450
|
+
raise Refused(f"the value at {where} is {info['state']}: {info['reason']}")
|
|
451
|
+
value = run.read(target)
|
|
452
|
+
recipe = self._save_recipe(run, None)
|
|
453
|
+
address = replace(address, origin=Origin(branch=self.session_id))
|
|
454
|
+
pointer = occurrence_pointer(
|
|
455
|
+
address, program="stepped", shape=list(value.shape),
|
|
456
|
+
dtype=str(value.dtype).removeprefix("torch."), sha256=tensor_digest(value),
|
|
457
|
+
recipe=recipe["fingerprint"], event=origin["transitions"], cut=origin["cut"],
|
|
458
|
+
authority=info["authority"])
|
|
459
|
+
if keep:
|
|
460
|
+
blob = project.store.put_tensor(value)["ref"]
|
|
461
|
+
try:
|
|
462
|
+
index.index_occurrence(project, self.session_id, pointer["address"],
|
|
463
|
+
layers=self.adapter.layers, recipe_id=recipe["fingerprint"],
|
|
464
|
+
event_id=origin["transitions"], cut_id=origin["cut"],
|
|
465
|
+
blob_id=blob)
|
|
466
|
+
except RecordError as error:
|
|
467
|
+
raise Refused(f"cannot index {where}: {error}") from error
|
|
468
|
+
return pointer
|
|
469
|
+
|
|
470
|
+
def live_occurrence(self, checkpoint: dict[str, Any]) -> tuple[Any, str | None]:
|
|
471
|
+
"""The resolver's ``live`` tier: the value at ``checkpoint["where"]`` from the live run's
|
|
472
|
+
port cache (nothing is computed), when that run reached it from the same cut with the
|
|
473
|
+
same layer edits. ``Unresolved`` otherwise."""
|
|
474
|
+
run, where = self.live, checkpoint["where"]
|
|
475
|
+
if run is None:
|
|
476
|
+
raise Unresolved("no live run")
|
|
477
|
+
if digest(run.tokens) != checkpoint["prompt_sha256"]:
|
|
478
|
+
raise Unresolved("the live run has another prompt")
|
|
479
|
+
try:
|
|
480
|
+
origin = run.origin_of(where)
|
|
481
|
+
except ValueError as error:
|
|
482
|
+
raise Unresolved(f"the live run has not computed {where}: {error}") from error
|
|
483
|
+
same = (origin["cut"], origin["transitions"], origin["port"]) == (
|
|
484
|
+
checkpoint["cut"], checkpoint["transitions"], checkpoint["port"])
|
|
485
|
+
if not same or (origin["port"] is not None and origin["edits"] != checkpoint["edits"]):
|
|
486
|
+
raise Unresolved("the live run reached this address from another state")
|
|
487
|
+
row, label = where.split(".", 1)
|
|
488
|
+
value = (run.row_captures(int(row[1:])) or {}).get(label)
|
|
489
|
+
if value is None:
|
|
490
|
+
raise Unresolved(f"{where} is not in the live run's port cache")
|
|
491
|
+
return value, run.read_info(where)["authority"]
|
|
492
|
+
|
|
493
|
+
def compute_occurrence(
|
|
494
|
+
self, checkpoint: dict[str, Any], recipe: dict[str, Any], store: Any, *, root: Any = None,
|
|
495
|
+
) -> tuple[Any, str | None]:
|
|
496
|
+
"""The resolver's ``cut`` (``root`` a stored boundary cut: one read-only probe) and
|
|
497
|
+
``replay`` (``root`` None: replay from the token ids) tiers: the value at the cursor of
|
|
498
|
+
``checkpoint`` (``mdb.core.recipe.occurrence_checkpoint``) and its authority."""
|
|
499
|
+
try:
|
|
500
|
+
run = self._restored(checkpoint, recipe, store, root)
|
|
501
|
+
except Refused:
|
|
502
|
+
raise
|
|
503
|
+
except ValueError as error: # another execution, an address with no stop, ...
|
|
504
|
+
raise Unresolved(str(error)) from error
|
|
505
|
+
return run.read(), run.read_info()["authority"]
|
|
506
|
+
|
|
507
|
+
def ops(self, run: Run | None = None):
|
|
508
|
+
"""A context for ``mdb.ops.dispatch`` bound to this model (and ``run``, if given)."""
|
|
509
|
+
return Context(self, run)
|
|
510
|
+
|
|
511
|
+
def each(self, prompts: Any, line: str, *, at: str | None = None, keep: bool = False,
|
|
512
|
+
ctx: Context | None = None, prefill: int | str | None = None,
|
|
513
|
+
shard: str | None = None, core: Any = None) -> Any:
|
|
514
|
+
"""Run one op line on every prompt of a set (``mdb.ops.sets``): ``prompts`` is the name
|
|
515
|
+
of a loaded set, a JSONL path (a ``str`` ending in ``.jsonl``) or a list of item dicts
|
|
516
|
+
(kept as the set ``inline``). ``prefill``: each item's split (``K`` or ``"@ROLE"``,
|
|
517
|
+
bound per item); ``shard``: ``"K/N"``, the K-th of N contiguous parts of the set.
|
|
518
|
+
``core``: a checkpoint (path, record id, loaded) the items with no ``core`` (item key,
|
|
519
|
+
alias ``from``), ``prompt`` or ``tokens`` of their own are rehydrated from instead of
|
|
520
|
+
started; an item with its own prompt starts from it, and a pair donor is never
|
|
521
|
+
rehydrated from the set's ``core``. Returns
|
|
522
|
+
``EachResult(summary, results, statistics)``; the live run
|
|
523
|
+
and its cursor are left as they were."""
|
|
524
|
+
from .sets import define, load, run_each
|
|
525
|
+
|
|
526
|
+
if isinstance(prompts, str) and prompts.endswith(".jsonl"):
|
|
527
|
+
prompts = load(self, "file", prompts).name
|
|
528
|
+
elif not isinstance(prompts, str):
|
|
529
|
+
rows = list(prompts)
|
|
530
|
+
if core is not None: # an item with no prompt of its own runs from ``core``
|
|
531
|
+
rows = [dict(r, core=core) if isinstance(r, dict) and not (
|
|
532
|
+
{"prompt", "tokens", "core", "from"} & set(r)) else r for r in rows]
|
|
533
|
+
prompts = define(self, "inline", rows).name
|
|
534
|
+
return run_each(ctx if ctx is not None else self.ops(self.live), prompts, line, at=at,
|
|
535
|
+
keep=keep, prefill=None if prefill is None else str(prefill),
|
|
536
|
+
shard=shard, core=core)
|
|
537
|
+
|
|
538
|
+
# --- debugger objects: branches, pools, custody --------------------------------------
|
|
539
|
+
|
|
540
|
+
def branches(self, run: Run, consumer: Any, **options: Any) -> Any:
|
|
541
|
+
"""Named native branches of ``run`` from one checkpoint (``analysis.measure.branches``)."""
|
|
542
|
+
from mdb.analysis.measure.branches import Branches
|
|
543
|
+
|
|
544
|
+
return Branches(run, consumer, **options)
|
|
545
|
+
|
|
546
|
+
def pool(self, items: Sequence[dict[str, Any]], address: str, **options: Any) -> Any:
|
|
547
|
+
"""A value pool collected at ``address`` over ``items``
|
|
548
|
+
(``analysis.measure.pools.collect``)."""
|
|
549
|
+
from mdb.analysis.measure.pools import collect
|
|
550
|
+
|
|
551
|
+
return collect(self, items, address, **options)
|
|
552
|
+
|
|
553
|
+
def run_from(self, core: Any, *, name: str | None = None, check: bool = True,
|
|
554
|
+
lookahead: str | None = None, replica: bool = False,
|
|
555
|
+
verify: bool | str = False, root: Any = None, store: Any = None) -> Run:
|
|
556
|
+
"""A run of this debugger's model from a checkpoint (``engine.checkpoint``): ``core`` is
|
|
557
|
+
a file path, a record id (or unique prefix) of this debugger's project or of the
|
|
558
|
+
checkpoint store (``store``, else ``[storage] checkpoint_store``: fetched into the
|
|
559
|
+
project, or the local cache project when none is attached), a durable
|
|
560
|
+
``Run.checkpoint(durable=...)`` result or a loaded checkpoint; a legacy v1 core file
|
|
561
|
+
loads too. The state at the checkpoint's cursor is rehydrated (no prefix recompute),
|
|
562
|
+
bit-identical on the same model and execution; another dtype, device or weights is
|
|
563
|
+
refused unless ``replica=True`` (a labelled replica, null-checked as
|
|
564
|
+
``run.core_check``). Every value and record of the run says ``from checkpoint <id>,
|
|
565
|
+
path unverified`` until ``run.verify()``. ``verify=True``: replay the recipe from the
|
|
566
|
+
lineage root first (``root``: a run or checkpoint, for a lineage rooted at another
|
|
567
|
+
checkpoint) and raise ``CheckpointUnverified`` unless it reaches the checkpoint's
|
|
568
|
+
fingerprint; ``verify="report"``: record the result as ``run.core["verified"]``
|
|
569
|
+
(measured) and never raise."""
|
|
570
|
+
loaded = self.load_checkpoint(core, store=store)
|
|
571
|
+
run = loaded.run(self.adapter, lookahead=lookahead, check=check,
|
|
572
|
+
name=run_name(name or "core"), replica=replica, verify=verify,
|
|
573
|
+
root=root)
|
|
574
|
+
self._carry_circuits(run)
|
|
575
|
+
self.runs[run.name] = run
|
|
576
|
+
self.live = run
|
|
577
|
+
return run
|
|
578
|
+
|
|
579
|
+
def export_bundle(self, name: str, path: Any) -> dict[str, Any]:
|
|
580
|
+
"""Write durable checkpoint ``name`` and the records that reference it to the directory
|
|
581
|
+
``path`` (``engine.bundle``); another project imports it with ``import_bundle`` or
|
|
582
|
+
``start from=PATH``. Returns the manifest."""
|
|
583
|
+
from mdb.engine import bundle
|
|
584
|
+
|
|
585
|
+
try:
|
|
586
|
+
return bundle.write(self._project("export"), name, path, session_id=self.session_id)
|
|
587
|
+
except ValueError as error:
|
|
588
|
+
raise Refused(str(error)) from error
|
|
589
|
+
|
|
590
|
+
def import_bundle(self, path: Any) -> dict[str, Any]:
|
|
591
|
+
"""Import the bundle at ``path`` into this debugger's project; returns its
|
|
592
|
+
checkpoint-state record (``start from=NAME`` and ``restart NAME`` then find it)."""
|
|
593
|
+
from mdb.engine import bundle
|
|
594
|
+
|
|
595
|
+
try:
|
|
596
|
+
return bundle.read(self._project("import"), path)
|
|
597
|
+
except ValueError as error:
|
|
598
|
+
raise Refused(str(error)) from error
|
|
599
|
+
|
|
600
|
+
def load_checkpoint(self, ref: Any, *, store: Any = None) -> Any:
|
|
601
|
+
"""The checkpoint ``ref`` names (``run_from``), read and checked, not yet run; a record
|
|
602
|
+
id this project lacks comes from ``store`` (else ``[storage] checkpoint_store``)."""
|
|
603
|
+
from mdb.engine import checkpoint as states
|
|
604
|
+
|
|
605
|
+
try:
|
|
606
|
+
return states.load(ref, project=self.project, store=store)
|
|
607
|
+
except FileNotFoundError as error:
|
|
608
|
+
raise Refused(f"no checkpoint file {ref}") from error
|
|
609
|
+
|
|
610
|
+
@staticmethod
|
|
611
|
+
def custody(*, script: Any = None, prereg: Any = None, kernel_path: str | None = None,
|
|
612
|
+
note: str | None = None) -> dict[str, Any]:
|
|
613
|
+
"""Declare record custody for this process (``core.custody.declare``): every record
|
|
614
|
+
sealed from now on carries the script and prereg sha256, library versions and kernel
|
|
615
|
+
path."""
|
|
616
|
+
from mdb.core import custody
|
|
617
|
+
|
|
618
|
+
return custody.declare(script=script, prereg=prereg, kernel_path=kernel_path, note=note)
|
|
619
|
+
|
|
620
|
+
@staticmethod
|
|
621
|
+
def records_to(path: Any = None, *, append: bool | None = None,
|
|
622
|
+
payloads: bool | None = None) -> Any:
|
|
623
|
+
"""Append every record sealed from now on to ``path`` (JSONL; ``core.custody.Sink``):
|
|
624
|
+
records persist with no project attached. No path, a directory (existing, a trailing
|
|
625
|
+
``/``, or a suffix-less name) or ``{run}`` in the name gives a unique per-process/job file; an existing file another run wrote needs
|
|
626
|
+
``append=True``. Pointer payloads with no store (compact ``Branches`` arms) are written
|
|
627
|
+
to the sink too (``Sink.load_json``). Arguments left as None take ``[records]`` of the
|
|
628
|
+
config (``core.custody.records_to``)."""
|
|
629
|
+
from mdb.core import custody
|
|
630
|
+
|
|
631
|
+
return custody.records_to(path, append=append, payloads=payloads)
|
|
632
|
+
|
|
633
|
+
def repl(self, run: Run | None = None, **options: Any) -> int:
|
|
634
|
+
"""Interactive gdb-style REPL on this model; returns when the user quits."""
|
|
635
|
+
from mdb.repl.shell import Shell # sanctioned upward import: Debugger.repl convenience
|
|
636
|
+
|
|
637
|
+
return Shell(self.ops(run), **options).loop()
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
class NotHeld(Refused):
|
|
641
|
+
"""A value the donor run does not hold at its cursor (not computed yet, or before the
|
|
642
|
+
transitions it holds); ``Debugger.origin_value`` retries a donor restored from its cut by
|
|
643
|
+
replay before refusing."""
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
class _ImportAdapter:
|
|
647
|
+
"""The dimensions ``cell_block`` needs, from the attached model's adapter."""
|
|
648
|
+
|
|
649
|
+
def __init__(self, adapter: Any):
|
|
650
|
+
self.head_dim = adapter.head_dim
|
|
651
|
+
self.layers = adapter.layers
|
|
652
|
+
self.num_kv_heads = adapter.num_kv_heads
|
|
653
|
+
self.model_identity = adapter.model_identity
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
# ports whose values do not depend on TransformerLens weight processing (fold_ln, centring,
|
|
657
|
+
# value-bias folding): only the attention weights. Every other port is in another basis.
|
|
658
|
+
BASIS_FREE_PORTS = ("p",)
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
class Imported:
|
|
662
|
+
"""Values computed by another tool, standing in for a donor run (``cell_block`` reads it
|
|
663
|
+
like a ``Run``: ``read``, ``read_cache``, ``adapter``, ``where``). Keys are occurrence
|
|
664
|
+
addresses ``t<r>.L<l>.<port>`` in mdb's single-row layout; ``kr`` of row ``r`` holds the
|
|
665
|
+
rotated keys of rows ``0..r`` (as mdb's ``kr`` does)."""
|
|
666
|
+
|
|
667
|
+
def __init__(self, name: str, adapter: Any, program: Any, values: dict[str, Any],
|
|
668
|
+
tokens: list[int], provenance: dict[str, Any]):
|
|
669
|
+
self.name = name
|
|
670
|
+
self.adapter = _ImportAdapter(adapter)
|
|
671
|
+
self.tokens = tokens
|
|
672
|
+
# records hold no bare numbers: provenance is descriptive text and flags
|
|
673
|
+
self.provenance = {str(k): v if isinstance(v, (bool, str)) or v is None else str(v)
|
|
674
|
+
for k, v in provenance.items()}
|
|
675
|
+
processed = bool(provenance.get("processed"))
|
|
676
|
+
self.values: dict[str, Any] = {}
|
|
677
|
+
for key, value in values.items():
|
|
678
|
+
try:
|
|
679
|
+
address = parse(key, ports=program.names, global_ports=DEFAULT_GLOBALS)
|
|
680
|
+
except AddressError as error:
|
|
681
|
+
raise Refused(f"import {name}: bad address {key!r}: {error}") from None
|
|
682
|
+
if not isinstance(address, Occurrence) or address.layer is None or address.origin:
|
|
683
|
+
raise Refused(f"import {name}: {key!r} is not t<r>.L<l>.<port>")
|
|
684
|
+
if processed and address.port not in BASIS_FREE_PORTS:
|
|
685
|
+
raise Refused(
|
|
686
|
+
f"import {name}: {key} comes from weight-processed TransformerLens "
|
|
687
|
+
"(fold_ln / centring / value-bias folding put it in another basis); import "
|
|
688
|
+
"values from an unprocessed bridge (boot_transformers without "
|
|
689
|
+
"enable_compatibility_mode, or no_processing=True)")
|
|
690
|
+
if not 0 <= address.layer < self.adapter.layers:
|
|
691
|
+
raise Refused(f"import {name}: no layer {address.layer}")
|
|
692
|
+
self.values[f"t{address.token}.L{address.layer}.{address.port}"] = value.detach()
|
|
693
|
+
self.where = f"import {name} ({len(self.values)} values)"
|
|
694
|
+
|
|
695
|
+
def read(self, target: str) -> Any:
|
|
696
|
+
try:
|
|
697
|
+
return self.values[target]
|
|
698
|
+
except KeyError:
|
|
699
|
+
raise ValueError(f"import {self.name} holds no {target}") from None
|
|
700
|
+
|
|
701
|
+
def read_cache(self, layer: int, kind: str) -> Any:
|
|
702
|
+
"""The cache of ``layer`` as the import's last row would read it: value rows stacked
|
|
703
|
+
from ``t<r>.L<l>.v``; keys from the last row's ``kr`` (rotated, rows 0..last)."""
|
|
704
|
+
import torch
|
|
705
|
+
|
|
706
|
+
kv, head_dim = self.adapter.num_kv_heads, self.adapter.head_dim
|
|
707
|
+
if kind == "k":
|
|
708
|
+
rows = sorted(int(k[1:].split(".")[0]) for k in self.values
|
|
709
|
+
if k.endswith(f".L{layer}.kr"))
|
|
710
|
+
if not rows:
|
|
711
|
+
raise Refused(f"import {self.name} holds no kr of layer {layer}")
|
|
712
|
+
return self.values[f"t{rows[-1]}.L{layer}.kr"]
|
|
713
|
+
rows = sorted(int(k[1:].split(".")[0]) for k in self.values
|
|
714
|
+
if k.endswith(f".L{layer}.v"))
|
|
715
|
+
if not rows or rows != list(range(len(rows))):
|
|
716
|
+
raise Refused(f"import {self.name} needs v of rows 0..n of layer {layer} for a "
|
|
717
|
+
f"cache cell (has rows {rows[:8]})")
|
|
718
|
+
return torch.cat([self.values[f"t{r}.L{layer}.v"].reshape(1, 1, kv, head_dim)
|
|
719
|
+
.transpose(1, 2) for r in rows], dim=2)
|
|
720
|
+
|
|
721
|
+
def pointer(self, address: str, value: Any) -> dict[str, Any]:
|
|
722
|
+
return {"origin": self.name, "via": "import", "address": address,
|
|
723
|
+
"sha256": tensor_digest(value), "shape": list(value.shape),
|
|
724
|
+
"dtype": str(value.dtype).removeprefix("torch."), "where": self.where,
|
|
725
|
+
"cut": None, "recipe": None, "authority": "supplied",
|
|
726
|
+
"provenance": dict(self.provenance)}
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def run_name(name: str | None) -> str:
|
|
730
|
+
"""A run name (default ``main``): a branch name, so ``NAME:ADDR`` can name a value of it."""
|
|
731
|
+
if name is None:
|
|
732
|
+
return "main"
|
|
733
|
+
try:
|
|
734
|
+
Origin(branch=name)
|
|
735
|
+
except AddressError as error:
|
|
736
|
+
raise Refused(f"run name {name!r} is not a branch name: {error}") from None
|
|
737
|
+
return name
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def _same_binding(donor: Run, run: Run, label: str) -> None:
|
|
741
|
+
"""Refuse a donor run of another model identity or numeric scope, naming what differs."""
|
|
742
|
+
if donor.adapter.model_identity != run.adapter.model_identity:
|
|
743
|
+
raise Refused(f"{label}: another model (identity {str(donor.adapter.model_identity)[:16]}"
|
|
744
|
+
f", this run {str(run.adapter.model_identity)[:16]})")
|
|
745
|
+
mine, theirs = run._numeric_scope(), donor._numeric_scope()
|
|
746
|
+
differing = sorted(k for k in set(mine) | set(theirs) if mine.get(k) != theirs.get(k))
|
|
747
|
+
if differing:
|
|
748
|
+
detail = ", ".join(f"{k}: {label} {theirs.get(k)!r}, this run {mine.get(k)!r}"
|
|
749
|
+
for k in differing)
|
|
750
|
+
raise Refused(f"{label}: another numeric scope ({detail})")
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def cell_block(run: Run, address: Any, *, label: str | None = None) -> Any:
|
|
754
|
+
"""The block ``(1, kv, rows, d)`` an address of ``run`` selects, for a state-cell value:
|
|
755
|
+
a cache cell ``cache.L<l>.k|v[kv,row,d]`` as the next read sees it, or the key (``kr``) or
|
|
756
|
+
value (``v``) row ``t<r>.L<l>`` wrote (one row; ``k`` is before RoPE and is refused)."""
|
|
757
|
+
from mdb.engine import breakpoints as bp
|
|
758
|
+
|
|
759
|
+
label = label or "this run"
|
|
760
|
+
head_dim = run.adapter.head_dim
|
|
761
|
+
if isinstance(address, StateCell):
|
|
762
|
+
if not 0 <= address.layer < run.adapter.layers:
|
|
763
|
+
raise Refused(f"{label}: no layer {address.layer}")
|
|
764
|
+
value = run.read_cache(address.layer, address.tensor)
|
|
765
|
+
row = None
|
|
766
|
+
keys = dict(address.selector.keys)
|
|
767
|
+
wanted = keys.get("row")
|
|
768
|
+
length = int(value.shape[2])
|
|
769
|
+
top = (wanted.stop - 1 if hasattr(wanted, "stop") else max(wanted.values)
|
|
770
|
+
if hasattr(wanted, "values") else wanted)
|
|
771
|
+
if top is not None and top >= length:
|
|
772
|
+
raise Refused(f"{label} has not computed row {top} of cache.L{address.layer}."
|
|
773
|
+
f"{address.tensor} (it holds rows 0..{length - 1} at {run.where})")
|
|
774
|
+
elif isinstance(address, Occurrence) and address.layer is not None:
|
|
775
|
+
if address.port not in ("v", "kr"):
|
|
776
|
+
raise Refused(f"a cell value comes from a cache cell or a v/kr occurrence, not "
|
|
777
|
+
f"{address.port}" + (" (k is before RoPE; the cache holds kr)"
|
|
778
|
+
if address.port in ("k", "kn") else ""))
|
|
779
|
+
target = f"t{address.token}.L{address.layer}.{address.port}"
|
|
780
|
+
try:
|
|
781
|
+
found = run.read(target)
|
|
782
|
+
except ValueError as error:
|
|
783
|
+
raise NotHeld(f"{label} has not computed {target}: {error}") from None
|
|
784
|
+
kv_heads = run.adapter.num_kv_heads
|
|
785
|
+
if address.port == "v":
|
|
786
|
+
value = found.reshape(1, 1, kv_heads, head_dim).transpose(1, 2)
|
|
787
|
+
else:
|
|
788
|
+
value = found[:, :, address.token:address.token + 1, :]
|
|
789
|
+
row = address.token
|
|
790
|
+
else:
|
|
791
|
+
raise Refused(f"a cell value is a cache cell or a v/kr occurrence, not "
|
|
792
|
+
f"{format_address(address)}")
|
|
793
|
+
try:
|
|
794
|
+
picks = bp.plan(CELL_AXES, list(value.shape), address.selector, head_dim=head_dim,
|
|
795
|
+
row=row)
|
|
796
|
+
except (bp.SelectionError, bp.SelectionRange) as error:
|
|
797
|
+
raise Refused(f"{label}: {error}") from None
|
|
798
|
+
import torch
|
|
799
|
+
|
|
800
|
+
out = value
|
|
801
|
+
for axis, pick in enumerate(picks):
|
|
802
|
+
if pick is not None:
|
|
803
|
+
out = out.index_select(axis, torch.tensor(list(pick), dtype=torch.long,
|
|
804
|
+
device=out.device))
|
|
805
|
+
return out.detach().clone()
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def attach(
|
|
809
|
+
model: Any, tokenizer: Any = None, *, project: Any = None, session: str | None = None
|
|
810
|
+
) -> Debugger:
|
|
811
|
+
"""Attach to a loaded Hugging Face causal LM (a family of ``engine.ports.FAMILIES``: Qwen2,
|
|
812
|
+
Qwen3, Llama, Mistral; eager attention, eval mode).
|
|
813
|
+
|
|
814
|
+
``project`` (a path, or an ``mdb.core.project.Project``) makes the debugger durable: the
|
|
815
|
+
project is created or reopened and the session ``session`` is opened, bound to the model
|
|
816
|
+
identity and execution. The default session id is the family plus a digest of both, so a
|
|
817
|
+
later process attaching the same model under the same numeric scope reopens it.
|
|
818
|
+
|
|
819
|
+
``project`` None: the configured ``[project] dir`` (``mdb.core.settings``), if any;
|
|
820
|
+
``project=False``: no project whatever the config says. ``session`` None: the configured
|
|
821
|
+
``[project] session`` when a project is attached (``auto`` = the default id).
|
|
822
|
+
"""
|
|
823
|
+
config = getattr(model, "config", None)
|
|
824
|
+
if config is None or not hasattr(model, "parameters"):
|
|
825
|
+
raise Refused("attach needs a loaded Hugging Face causal LM (a model with .config)")
|
|
826
|
+
family = getattr(config, "model_type", None)
|
|
827
|
+
if family not in PROGRAMS:
|
|
828
|
+
raise Refused(
|
|
829
|
+
f"no port program for model_type {family!r}; supported: {', '.join(sorted(PROGRAMS))}"
|
|
830
|
+
)
|
|
831
|
+
refusal = config_refusal(family, config)
|
|
832
|
+
if refusal is not None:
|
|
833
|
+
raise Refused(f"cannot attach: {refusal}")
|
|
834
|
+
implementation = getattr(config, "_attn_implementation", None)
|
|
835
|
+
if implementation != "eager":
|
|
836
|
+
raise Refused(
|
|
837
|
+
f"attention implementation is {implementation!r}; port stepping needs eager "
|
|
838
|
+
"attention: load with from_pretrained(..., attn_implementation='eager')"
|
|
839
|
+
)
|
|
840
|
+
wrapped = [name for name, _ in model.named_modules() if name.endswith("_original_component")]
|
|
841
|
+
if wrapped:
|
|
842
|
+
raise Refused(
|
|
843
|
+
f"the module tree was rewritten by a TransformerLens bridge ({len(wrapped)} wrapped "
|
|
844
|
+
f"modules, e.g. {wrapped[0]!r}); port hooks would not see native attention. Attach "
|
|
845
|
+
"before bridging, or bridge mdb.interop.tl.shared_clone(model) (same weights)")
|
|
846
|
+
patched = [name for name, module in model.named_modules() if _rewritten_forward(module)]
|
|
847
|
+
if patched:
|
|
848
|
+
raise Refused(
|
|
849
|
+
f"{len(patched)} module(s) run a rewritten forward (e.g. {patched[0]!r}), as "
|
|
850
|
+
"nnsight's .source leaves behind; mdb's attention interceptor would not run there. "
|
|
851
|
+
"Hand the tool mdb.interop.clone.shared_clone(model) (same weights)")
|
|
852
|
+
training = [name or "<model>" for name, module in model.named_modules() if module.training]
|
|
853
|
+
if training:
|
|
854
|
+
raise Refused(
|
|
855
|
+
f"{len(training)} sub-module(s) are in training mode (dropout), e.g. "
|
|
856
|
+
f"{training[0]!r}; call model.eval() first (attach never changes your model)"
|
|
857
|
+
)
|
|
858
|
+
from saturn.adapters.decoder import DecoderAdapter
|
|
859
|
+
|
|
860
|
+
from mdb.core import settings
|
|
861
|
+
|
|
862
|
+
if project is False:
|
|
863
|
+
project = None
|
|
864
|
+
elif project is None:
|
|
865
|
+
project = settings.value("project.dir")
|
|
866
|
+
if project is not None and session is None:
|
|
867
|
+
configured = settings.value("project.session")
|
|
868
|
+
session = None if configured == "auto" else configured
|
|
869
|
+
try:
|
|
870
|
+
adapter = DecoderAdapter(model, granularity="operation")
|
|
871
|
+
except ValueError as error:
|
|
872
|
+
raise Refused(f"cannot attach: {error}") from error
|
|
873
|
+
if project is None:
|
|
874
|
+
if session is not None:
|
|
875
|
+
raise Refused("session= names a session of a project; pass project= too")
|
|
876
|
+
return Debugger(model, tokenizer, adapter)
|
|
877
|
+
return _durable(model, tokenizer, adapter, project, session)
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
def _rewritten_forward(module: Any) -> bool:
|
|
881
|
+
"""``engine.ports.rewritten_forward`` (one rule for attach and for every layer step)."""
|
|
882
|
+
from mdb.engine.ports import rewritten_forward
|
|
883
|
+
|
|
884
|
+
return rewritten_forward(module)
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def _durable(model: Any, tokenizer: Any, adapter: Any, project: Any, session: str | None):
|
|
888
|
+
"""The debugger of ``attach(..., project=)``: open the project and the session."""
|
|
889
|
+
from mdb.core.project import Project, ProjectError
|
|
890
|
+
|
|
891
|
+
if session is None:
|
|
892
|
+
binding = {"model_identity": adapter.model_identity, "execution": adapter.execution}
|
|
893
|
+
session = f"{program_for(adapter).family}-{digest(binding)[:12]}"
|
|
894
|
+
try:
|
|
895
|
+
Origin(branch=session) # a session id is an address origin: a branch name
|
|
896
|
+
except AddressError as error:
|
|
897
|
+
raise Refused(f"session id {session!r} is not a branch name: {error}") from error
|
|
898
|
+
try:
|
|
899
|
+
opened = project if isinstance(project, Project) else Project(project)
|
|
900
|
+
opened.open_session(session, model_identity=adapter.model_identity,
|
|
901
|
+
execution=adapter.execution)
|
|
902
|
+
except (ProjectError, OSError) as error:
|
|
903
|
+
raise Refused(f"cannot open project {project}: {error}") from error
|
|
904
|
+
return Debugger(model, tokenizer, adapter, project=opened, session_id=session)
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def open_tiny(family: str = "qwen2", dtype: str | None = None, *, seed: int = DEFAULT_SEED,
|
|
908
|
+
project: Any = None, session: str | None = None,
|
|
909
|
+
device: str | None = None) -> Debugger:
|
|
910
|
+
"""A random tiny eager model (no tokenizer) for demos and tests, built on the CPU and moved
|
|
911
|
+
to ``device`` (the device is recorded in every record's execution). ``dtype``, ``device``,
|
|
912
|
+
``project`` and ``session`` left as None take the configured values (``attach``)."""
|
|
913
|
+
return attach(_tiny(family, dtype, seed, device), project=project, session=session)
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
def _tiny(family: str, dtype: str | None, seed: int, device: str | None = None) -> Any:
|
|
917
|
+
from mdb.core import settings
|
|
918
|
+
from mdb.engine.models import tiny_model
|
|
919
|
+
|
|
920
|
+
device = settings.value("model.device", device)
|
|
921
|
+
model = tiny_model(family, settings.value("model.dtype", dtype), seed=seed)
|
|
922
|
+
if str(device) != "cpu":
|
|
923
|
+
from mdb.engine.models import check_device
|
|
924
|
+
|
|
925
|
+
model = model.to(check_device(device))
|
|
926
|
+
return model
|