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/engine/selfcheck.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""Exactness, probe-consistency and rewind checks for port stepping, with per-operation timings.
|
|
2
|
+
|
|
3
|
+
python -m mdb.engine.selfcheck --tiny qwen2|qwen3|llama|mistral [--dtype bf16|fp32] \
|
|
4
|
+
--generate N --out OUT
|
|
5
|
+
python -m mdb.engine.selfcheck --model PATH|NAME [--dtype bf16|fp32] [--device cpu|cuda] \
|
|
6
|
+
[--prompt TEXT | --token-ids 1,2,3] --generate N --out OUT
|
|
7
|
+
|
|
8
|
+
``--generate`` and ``--out`` were ``--tokens`` and ``--json``; the old names still work (with a
|
|
9
|
+
notice), so existing job scripts keep running.
|
|
10
|
+
|
|
11
|
+
Works on any checkpoint of a family in ``ports.FAMILIES``; nothing assumes tiny sizes. Numbers are
|
|
12
|
+
measured in this process unless the report's ``labels`` map says otherwise (the expected layer
|
|
13
|
+
count is derived-exact from the layer count and token count; ``generated`` and
|
|
14
|
+
``prompt_tokens`` are supplied).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import platform
|
|
22
|
+
import statistics
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import torch
|
|
29
|
+
|
|
30
|
+
from .models import DTYPES, TINY_FAMILIES, load_local, tiny_model # noqa: E402,F401
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _sync(device: torch.device) -> None:
|
|
34
|
+
if device.type == "cuda":
|
|
35
|
+
torch.cuda.synchronize(device)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _timed(samples: dict[str, list[float]], name: str, device: torch.device, fn, *args):
|
|
39
|
+
_sync(device)
|
|
40
|
+
start = time.perf_counter()
|
|
41
|
+
result = fn(*args)
|
|
42
|
+
_sync(device)
|
|
43
|
+
samples.setdefault(name, []).append(time.perf_counter() - start)
|
|
44
|
+
return result
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _summary(samples: dict[str, list[float]]) -> dict[str, Any]:
|
|
48
|
+
return {
|
|
49
|
+
name: {
|
|
50
|
+
"count": len(values),
|
|
51
|
+
"median_ms": statistics.median(values) * 1e3,
|
|
52
|
+
"min_ms": min(values) * 1e3,
|
|
53
|
+
"max_ms": max(values) * 1e3,
|
|
54
|
+
"total_ms": sum(values) * 1e3,
|
|
55
|
+
}
|
|
56
|
+
for name, values in samples.items()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _digest(value: torch.Tensor) -> str:
|
|
61
|
+
from .ports import tensor_digest
|
|
62
|
+
|
|
63
|
+
return tensor_digest(value)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def check_exactness(adapter: Any, tokens: list[int], count: int, samples: dict) -> dict:
|
|
67
|
+
"""Same Session program with an observe-all controller vs none: receipts and cuts equal."""
|
|
68
|
+
from .ports import PortController, program_for
|
|
69
|
+
|
|
70
|
+
program = program_for(adapter)
|
|
71
|
+
plain = adapter.session(tokens)
|
|
72
|
+
observed = adapter.session(tokens)
|
|
73
|
+
controller = PortController(program, None)
|
|
74
|
+
logits_equal, cuts_equal, transitions = True, True, 0
|
|
75
|
+
while plain.read("tokens").shape[1] < len(tokens) + count:
|
|
76
|
+
_timed(samples, "transition_plain", adapter.device, plain.continue_)
|
|
77
|
+
_timed(
|
|
78
|
+
samples,
|
|
79
|
+
"transition_observed",
|
|
80
|
+
adapter.device,
|
|
81
|
+
lambda: observed.continue_(1, ports=controller),
|
|
82
|
+
)
|
|
83
|
+
transitions += 1
|
|
84
|
+
left, right = plain.capture(retain=False), observed.capture(retain=False)
|
|
85
|
+
cuts_equal &= left.fingerprint == right.fingerprint
|
|
86
|
+
if left.payload["logits"] is not None:
|
|
87
|
+
logits_equal &= bool(
|
|
88
|
+
torch.equal(
|
|
89
|
+
left.payload["logits"].view(torch.uint8),
|
|
90
|
+
right.payload["logits"].view(torch.uint8),
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
receipts_equal = [r._body for r in plain.receipts] == [r._body for r in observed.receipts]
|
|
94
|
+
generated = plain.read("tokens")[0].tolist()
|
|
95
|
+
native = adapter.native_logits(generated[:-1])
|
|
96
|
+
stepped = plain.read("logits")
|
|
97
|
+
return {
|
|
98
|
+
"transitions": transitions,
|
|
99
|
+
"observed_layer_calls": controller.installs,
|
|
100
|
+
"expected_layer_calls": adapter.layers * count,
|
|
101
|
+
"receipts_byte_identical": receipts_equal,
|
|
102
|
+
"cut_fingerprints_identical": cuts_equal,
|
|
103
|
+
"logits_byte_identical": logits_equal,
|
|
104
|
+
"stepped_vs_hf_full_forward_max_abs_logit_diff": float(
|
|
105
|
+
(stepped.float() - native.float()).abs().max()
|
|
106
|
+
),
|
|
107
|
+
"generated_tokens": generated[len(tokens) :],
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def check_probes(adapter: Any, tokens: list[int], samples: dict) -> dict:
|
|
112
|
+
"""Every port of every layer of the first row: stop-probe equals the one-pass capture."""
|
|
113
|
+
from .ports import PortController, program_for
|
|
114
|
+
|
|
115
|
+
program = program_for(adapter)
|
|
116
|
+
session = adapter.session(tokens)
|
|
117
|
+
session.continue_() # embed
|
|
118
|
+
mismatches, probes, s_checks, mix_checks, state_changes = [], 0, [], [], 0
|
|
119
|
+
full_installs = 0
|
|
120
|
+
for layer in range(adapter.layers):
|
|
121
|
+
before = session.capture(retain=False)
|
|
122
|
+
kv = [t.clone() for t in before.payload["keys"] + before.payload["values"]]
|
|
123
|
+
full = PortController(program, layer)
|
|
124
|
+
_timed(samples, "probe_full_layer", adapter.device, session.probe, full)
|
|
125
|
+
full_installs += full.installs
|
|
126
|
+
s_checks.append(full.checks.get("s"))
|
|
127
|
+
mix_checks.append(full.checks.get("mix_replica"))
|
|
128
|
+
for port in program.names:
|
|
129
|
+
if port == "h_out":
|
|
130
|
+
continue
|
|
131
|
+
stop = PortController(program, layer, stop=port, capture=(port,))
|
|
132
|
+
result = _timed(samples, "probe_stop", adapter.device, session.probe, stop)
|
|
133
|
+
probes += 1
|
|
134
|
+
if not result["stopped"] or not torch.equal(stop.captures[port], full.captures[port]):
|
|
135
|
+
mismatches.append(f"L{layer}.{port}")
|
|
136
|
+
after = session.capture(retain=False)
|
|
137
|
+
state_changes += after.fingerprint != before.fingerprint
|
|
138
|
+
payload = after.payload
|
|
139
|
+
state_changes += not all(
|
|
140
|
+
torch.equal(a, b) for a, b in zip(kv, payload["keys"] + payload["values"])
|
|
141
|
+
)
|
|
142
|
+
_timed(samples, "layer_commit_plain", adapter.device, session.continue_)
|
|
143
|
+
return {
|
|
144
|
+
"stop_probes": probes,
|
|
145
|
+
"mismatches": mismatches,
|
|
146
|
+
"state_changed_by_probe": state_changes,
|
|
147
|
+
"receipts_after": len(session.receipts),
|
|
148
|
+
"attempts_after": len(session.attempts),
|
|
149
|
+
"history_after": len(session.history),
|
|
150
|
+
"full_probe_installs": full_installs,
|
|
151
|
+
"s_replica": s_checks,
|
|
152
|
+
"mix_replica": mix_checks,
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def check_rewind(adapter: Any, tokens: list[int], samples: dict) -> dict:
|
|
157
|
+
"""Checkpoint mid-layer, step 7 ports, restore, step 7 again; also across a token edge."""
|
|
158
|
+
from .run import Run
|
|
159
|
+
|
|
160
|
+
run = Run(adapter, tokens)
|
|
161
|
+
names = run.program.names
|
|
162
|
+
results = {}
|
|
163
|
+
last = adapter.layers - 1
|
|
164
|
+
for case, target in (
|
|
165
|
+
("mid_layer", f"L0.{names[len(names) // 2]}"),
|
|
166
|
+
("token_boundary", f"L{last}.{names[-3]}"),
|
|
167
|
+
):
|
|
168
|
+
_timed(samples, "until", adapter.device, run.until, target)
|
|
169
|
+
checkpoint = _timed(samples, "checkpoint", adapter.device, run.checkpoint, case)
|
|
170
|
+
first, second = [], []
|
|
171
|
+
for trace in (first, second):
|
|
172
|
+
for _ in range(7):
|
|
173
|
+
_timed(samples, "port_step", adapter.device, run.step, "port")
|
|
174
|
+
trace.append((run.where, _digest(run.read())))
|
|
175
|
+
if trace is first:
|
|
176
|
+
_timed(samples, "restore", adapter.device, run.restore, checkpoint)
|
|
177
|
+
results[case] = {
|
|
178
|
+
"checkpoint_where": checkpoint["where"],
|
|
179
|
+
"checkpoint_bytes": len(json.dumps(checkpoint)),
|
|
180
|
+
"path": [where for where, _ in first],
|
|
181
|
+
"identical": first == second,
|
|
182
|
+
}
|
|
183
|
+
run.step("token")
|
|
184
|
+
reverse = []
|
|
185
|
+
for _ in range(3):
|
|
186
|
+
_timed(samples, "reverse_port_step", adapter.device, run.reverse_step, "port")
|
|
187
|
+
reverse.append(run.where)
|
|
188
|
+
results["reverse_steps"] = reverse
|
|
189
|
+
return results
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def time_token(adapter: Any, tokens: list[int], samples: dict) -> None:
|
|
193
|
+
from .run import Run
|
|
194
|
+
|
|
195
|
+
run = Run(adapter, tokens)
|
|
196
|
+
for _ in range(2):
|
|
197
|
+
_timed(samples, "token_step_run", adapter.device, run.step, "token")
|
|
198
|
+
session = adapter.session(tokens)
|
|
199
|
+
_timed(samples, "token_generate_plain", adapter.device, adapter.generate, session, 1)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def environment(adapter: Any) -> dict[str, Any]:
|
|
203
|
+
import transformers
|
|
204
|
+
|
|
205
|
+
return {
|
|
206
|
+
"torch": torch.__version__,
|
|
207
|
+
"transformers": transformers.__version__,
|
|
208
|
+
"python": platform.python_version(),
|
|
209
|
+
"platform": platform.platform(),
|
|
210
|
+
"device": str(adapter.device),
|
|
211
|
+
"dtype": str(adapter.dtype),
|
|
212
|
+
"attention_implementation": adapter.model.config._attn_implementation,
|
|
213
|
+
"family": adapter.spec.model_type,
|
|
214
|
+
"layers": adapter.layers,
|
|
215
|
+
"hidden_size": adapter.hidden_size,
|
|
216
|
+
"heads": adapter.num_heads,
|
|
217
|
+
"kv_heads": adapter.num_kv_heads,
|
|
218
|
+
"torch_num_threads": torch.get_num_threads(),
|
|
219
|
+
"model_identity": adapter.model_identity,
|
|
220
|
+
"cuda": torch.cuda.get_device_name(adapter.device)
|
|
221
|
+
if adapter.device.type == "cuda"
|
|
222
|
+
else None,
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# older flag -> current flag; the older ones still work, with a notice on stderr
|
|
227
|
+
RENAMED = {"--tokens": "--generate", "--json": "--out"}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _renamed(argv: list[str]) -> list[str]:
|
|
231
|
+
"""``--tokens N`` / ``--json PATH`` (older names: ``mdb engine`` uses ``--tokens`` for prompt
|
|
232
|
+
ids and ``--json`` as a switch) rewritten to ``--generate`` / ``--out``."""
|
|
233
|
+
out = []
|
|
234
|
+
for word in argv:
|
|
235
|
+
flag, eq, value = word.partition("=")
|
|
236
|
+
if flag in RENAMED:
|
|
237
|
+
print(f"selfcheck: {flag} is now {RENAMED[flag]} (the old name still works)",
|
|
238
|
+
file=sys.stderr)
|
|
239
|
+
word = RENAMED[flag] + eq + value
|
|
240
|
+
out.append(word)
|
|
241
|
+
return out
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def main(argv: list[str] | None = None) -> int:
|
|
245
|
+
from mdb.core import settings
|
|
246
|
+
from mdb.core.locate import locate_model
|
|
247
|
+
|
|
248
|
+
parser = argparse.ArgumentParser(prog="python -m mdb.engine.selfcheck")
|
|
249
|
+
source = parser.add_mutually_exclusive_group(required=True)
|
|
250
|
+
source.add_argument("--tiny", choices=TINY_FAMILIES)
|
|
251
|
+
source.add_argument("--model", help="checkpoint directory, cached model name or alias")
|
|
252
|
+
parser.add_argument("--dtype", choices=tuple(DTYPES),
|
|
253
|
+
help=f"default {settings.DEFAULT_DTYPE} ([model] dtype)")
|
|
254
|
+
parser.add_argument("--device", help=f"default {settings.DEFAULT_DEVICE} ([model] device)")
|
|
255
|
+
parser.add_argument("--generate", type=int, default=2, metavar="N",
|
|
256
|
+
help="tokens to generate (older name: --tokens)")
|
|
257
|
+
parser.add_argument("--prompt", help="prompt text (needs the checkpoint tokenizer)")
|
|
258
|
+
parser.add_argument("--token-ids", help="comma-separated prompt token ids")
|
|
259
|
+
parser.add_argument("--out", required=True, metavar="PATH",
|
|
260
|
+
help="report path (older name: --json)")
|
|
261
|
+
args = parser.parse_args(_renamed(list(sys.argv[1:] if argv is None else argv)))
|
|
262
|
+
if args.generate < 1:
|
|
263
|
+
parser.error("--generate must be positive")
|
|
264
|
+
config = settings.activate(settings.resolve(
|
|
265
|
+
{"model.dtype": args.dtype, "model.device": args.device},
|
|
266
|
+
flags={"model.dtype": "--dtype", "model.device": "--device"}))
|
|
267
|
+
dtype, device = config.get("model.dtype"), config.get("model.device")
|
|
268
|
+
from saturn.adapters.decoder import DecoderAdapter
|
|
269
|
+
|
|
270
|
+
started = time.perf_counter()
|
|
271
|
+
if args.tiny:
|
|
272
|
+
model = tiny_model(args.tiny, dtype=dtype).to(torch.device(device))
|
|
273
|
+
adapter = DecoderAdapter(model, granularity="operation", device=torch.device(device))
|
|
274
|
+
else:
|
|
275
|
+
args.model = str(locate_model(args.model))
|
|
276
|
+
model = load_local(args.model, dtype=dtype, device=device)
|
|
277
|
+
adapter = DecoderAdapter(model, granularity="operation", device=torch.device(device))
|
|
278
|
+
load_seconds = time.perf_counter() - started
|
|
279
|
+
prompt_encoding = "token ids"
|
|
280
|
+
if args.token_ids:
|
|
281
|
+
tokens = [int(item) for item in args.token_ids.split(",")]
|
|
282
|
+
elif args.prompt and args.model:
|
|
283
|
+
from transformers import AutoTokenizer
|
|
284
|
+
|
|
285
|
+
tokenizer = AutoTokenizer.from_pretrained(args.model, local_files_only=True)
|
|
286
|
+
tokens = tokenizer(args.prompt)["input_ids"]
|
|
287
|
+
prompt_encoding = "checkpoint tokenizer"
|
|
288
|
+
elif args.prompt:
|
|
289
|
+
# a tiny random model has no tokenizer: byte values folded into its vocabulary
|
|
290
|
+
tokens = [byte % adapter.vocab_size for byte in args.prompt.encode("utf-8")]
|
|
291
|
+
prompt_encoding = "utf-8 bytes modulo vocab_size (tiny model has no tokenizer)"
|
|
292
|
+
else:
|
|
293
|
+
tokens = [1, 2, 3, 4, 5]
|
|
294
|
+
prompt_encoding = "default ids"
|
|
295
|
+
samples: dict[str, list[float]] = {}
|
|
296
|
+
report: dict[str, Any] = {
|
|
297
|
+
"schema": "mdb-engine-selfcheck-v1",
|
|
298
|
+
"source": args.tiny and f"tiny:{args.tiny}" or "checkpoint",
|
|
299
|
+
"prompt_tokens": len(tokens),
|
|
300
|
+
"prompt_encoding": prompt_encoding,
|
|
301
|
+
"generated": args.generate,
|
|
302
|
+
"environment": environment(adapter),
|
|
303
|
+
"load_seconds": load_seconds,
|
|
304
|
+
"labels": {
|
|
305
|
+
"default": "measured",
|
|
306
|
+
"exactness.expected_layer_calls": "derived-exact",
|
|
307
|
+
"generated": "supplied",
|
|
308
|
+
"prompt_tokens": "supplied",
|
|
309
|
+
},
|
|
310
|
+
}
|
|
311
|
+
report["exactness"] = check_exactness(adapter, tokens, args.generate, samples)
|
|
312
|
+
report["probe_consistency"] = check_probes(adapter, tokens, samples)
|
|
313
|
+
report["rewind"] = check_rewind(adapter, tokens, samples)
|
|
314
|
+
time_token(adapter, tokens, samples)
|
|
315
|
+
report["timings"] = _summary(samples)
|
|
316
|
+
report["passed"] = passed(report)
|
|
317
|
+
Path(args.out).write_text(json.dumps(report, indent=2, sort_keys=True))
|
|
318
|
+
print(json.dumps({"passed": report["passed"], "json": args.out}))
|
|
319
|
+
return 0 if report["passed"] else 1
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def passed(report: dict[str, Any]) -> bool:
|
|
323
|
+
"""Every check holds, every replica check passed, and the controller really installed."""
|
|
324
|
+
exact = report["exactness"]
|
|
325
|
+
probes = report["probe_consistency"]
|
|
326
|
+
rewind = report["rewind"]
|
|
327
|
+
layers = report["environment"]["layers"]
|
|
328
|
+
replicas = probes["s_replica"] + probes["mix_replica"]
|
|
329
|
+
return bool(
|
|
330
|
+
exact["receipts_byte_identical"]
|
|
331
|
+
and exact["cut_fingerprints_identical"]
|
|
332
|
+
and exact["logits_byte_identical"]
|
|
333
|
+
and not probes["mismatches"]
|
|
334
|
+
and not probes["state_changed_by_probe"]
|
|
335
|
+
and probes["attempts_after"] == 0
|
|
336
|
+
and probes["history_after"] == 0
|
|
337
|
+
and all(item["identical"] for key, item in rewind.items() if key != "reverse_steps")
|
|
338
|
+
and exact["transitions"] > 0
|
|
339
|
+
and exact["observed_layer_calls"] == exact["expected_layer_calls"]
|
|
340
|
+
and probes["full_probe_installs"] == layers
|
|
341
|
+
and len(replicas) == 2 * layers
|
|
342
|
+
and all(item == {"equal": True} for item in replicas)
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
if __name__ == "__main__":
|
|
347
|
+
sys.exit(main())
|