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/repl/shell.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""A gdb-style line REPL: every command is one ``mdb.ops.dispatch`` call, then ``render``.
|
|
2
|
+
|
|
3
|
+
Conventions: an empty line repeats the last motion command (interactive only); unique
|
|
4
|
+
prefixes resolve (``fin`` -> ``finish``); aliases ``s n c b p bt u d i l r q h rs rn rc``
|
|
5
|
+
(``u`` is until, ``d`` delete, as in gdb); ``help [verb]`` reads the registry. Local
|
|
6
|
+
commands: ``help``, ``source [-k] FILE``, ``record [append] FILE|stop``, ``quit``.
|
|
7
|
+
|
|
8
|
+
No traceback ever reaches the user: an unexpected exception is an ``internal`` error (the
|
|
9
|
+
registry converts it), Ctrl-C during a command prints ``interrupted at <where>`` and the
|
|
10
|
+
session carries on. ``source`` stops at its first error (as gdb) unless ``-k``, and nests at
|
|
11
|
+
most ``MAX_SOURCE_DEPTH`` deep. ``record`` is refused while sourcing (``--script`` and init
|
|
12
|
+
files too), refuses an existing file unless ``append``, and creates files with mode 0600.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, TextIO
|
|
22
|
+
|
|
23
|
+
from mdb.ops import OpError, dispatch, registry
|
|
24
|
+
from mdb.ops.errors import BadArgs, internal
|
|
25
|
+
from mdb.ops.lines import ( # noqa: F401 - the parser moved to mdb.ops.lines; re-exported
|
|
26
|
+
_INT,
|
|
27
|
+
_KEYWORD,
|
|
28
|
+
ALIASES,
|
|
29
|
+
SPECIAL,
|
|
30
|
+
WHY,
|
|
31
|
+
_after,
|
|
32
|
+
_break_args,
|
|
33
|
+
_compare_args,
|
|
34
|
+
_condition_args,
|
|
35
|
+
_consumer_option,
|
|
36
|
+
_convert,
|
|
37
|
+
_each_args,
|
|
38
|
+
_equals_outside_brackets,
|
|
39
|
+
_generic,
|
|
40
|
+
_prompt_args,
|
|
41
|
+
_set_args,
|
|
42
|
+
_symbol_args,
|
|
43
|
+
_up_args,
|
|
44
|
+
_watch_args,
|
|
45
|
+
_whatif_args,
|
|
46
|
+
_with_consumer,
|
|
47
|
+
parse,
|
|
48
|
+
resolve_verb,
|
|
49
|
+
route,
|
|
50
|
+
split,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
from .render import render, render_error
|
|
54
|
+
|
|
55
|
+
LOCAL = ("help", "source", "record", "quit")
|
|
56
|
+
MAX_SOURCE_DEPTH = 16
|
|
57
|
+
# Arguments an init file may not pass: they change what is measured, and an init file is not the
|
|
58
|
+
# script custody hashes (``mdb.core.settings.REFUSED`` minus ``mode``, which ``watch`` uses for
|
|
59
|
+
# its trigger kind).
|
|
60
|
+
INIT_REFUSED = ("lookahead", "prefill", "retain_rows", "recheck", "batch", "seed", "floor",
|
|
61
|
+
"floors", "floor_spacings", "margin_floor_spacings", "stability_floor_spacings",
|
|
62
|
+
"stable_k")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# --------------------------------------------------------------------------- shell
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Shell:
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
ctx: Any,
|
|
72
|
+
*,
|
|
73
|
+
json_mode: bool = False,
|
|
74
|
+
out: TextIO | None = None,
|
|
75
|
+
prompt: str = "(mdb) ",
|
|
76
|
+
defaults: dict[str, Any] | None = None,
|
|
77
|
+
history: str | Path | None = None,
|
|
78
|
+
):
|
|
79
|
+
self.ctx = ctx
|
|
80
|
+
self.defaults: dict[str, dict[str, Any]] = {}
|
|
81
|
+
self.history = Path(history).expanduser() if history else None
|
|
82
|
+
if defaults:
|
|
83
|
+
self.set_defaults(defaults)
|
|
84
|
+
self.json_mode = json_mode
|
|
85
|
+
self.out = out if out is not None else sys.stdout
|
|
86
|
+
self.prompt = prompt
|
|
87
|
+
self.last_motion: str | None = None
|
|
88
|
+
self.record_to: Path | None = None
|
|
89
|
+
self.errors = 0
|
|
90
|
+
self.depth = 0 # nesting of `source`
|
|
91
|
+
self._interrupted = False # Ctrl-C seen: a running script stops
|
|
92
|
+
self._failed = False # the last command (or a nested non -k source) failed
|
|
93
|
+
self._init = False # sourcing an init file (INIT_REFUSED arguments refused)
|
|
94
|
+
if not json_mode and hasattr(ctx, "notice"):
|
|
95
|
+
ctx.notice = self._notice # an op's line before its result (sweep's plan)
|
|
96
|
+
|
|
97
|
+
def set_defaults(self, defaults: dict[str, Any], source: str = "repl.defaults") -> None:
|
|
98
|
+
"""``{"OP.ARG": value}``: display defaults and the sweep cap (``Arg.configurable``) used
|
|
99
|
+
when a command line does not give the argument. A non-configurable argument, an unknown
|
|
100
|
+
op or a bad value raises ``BadArgs`` naming ``source``."""
|
|
101
|
+
from mdb.ops.registry import check_default
|
|
102
|
+
|
|
103
|
+
for name, value in defaults.items():
|
|
104
|
+
try:
|
|
105
|
+
op_name, arg_name, checked = check_default(name, value)
|
|
106
|
+
except OpError as error:
|
|
107
|
+
raise BadArgs(f"{source}.{name}: {error.message}") from None
|
|
108
|
+
self.defaults.setdefault(op_name, {})[arg_name] = checked
|
|
109
|
+
|
|
110
|
+
def _notice(self, text: str) -> None:
|
|
111
|
+
self.write(text)
|
|
112
|
+
flush = getattr(self.out, "flush", None)
|
|
113
|
+
if flush is not None:
|
|
114
|
+
flush()
|
|
115
|
+
|
|
116
|
+
def write(self, text: str) -> None:
|
|
117
|
+
self.out.write(text + "\n")
|
|
118
|
+
|
|
119
|
+
def resolve(self, word: str) -> str:
|
|
120
|
+
return resolve_verb(word, LOCAL)
|
|
121
|
+
|
|
122
|
+
def _error(self, error: OpError) -> None:
|
|
123
|
+
self.errors += 1
|
|
124
|
+
self._failed = True
|
|
125
|
+
if self.json_mode:
|
|
126
|
+
self.write(json.dumps({"error": error.to_json(), "state": error.state,
|
|
127
|
+
"reason": error.message}, sort_keys=True))
|
|
128
|
+
else:
|
|
129
|
+
self.write(render_error(error))
|
|
130
|
+
|
|
131
|
+
def _where(self) -> str:
|
|
132
|
+
run = getattr(self.ctx, "run", None)
|
|
133
|
+
try:
|
|
134
|
+
return run.where if run is not None else "no run"
|
|
135
|
+
except Exception: # noqa: BLE001 - reporting the cursor must never fail
|
|
136
|
+
return "an unknown position"
|
|
137
|
+
|
|
138
|
+
def execute(self, line: str, *, repeat: bool = False) -> bool:
|
|
139
|
+
"""Run one command line; False means quit. Never raises: errors are printed (an
|
|
140
|
+
unexpected one as ``internal``), Ctrl-C prints ``interrupted at <where>``."""
|
|
141
|
+
text = line.strip()
|
|
142
|
+
if self.depth == 0:
|
|
143
|
+
self._interrupted = False
|
|
144
|
+
if not text:
|
|
145
|
+
if not repeat or self.last_motion is None:
|
|
146
|
+
return True
|
|
147
|
+
text = self.last_motion
|
|
148
|
+
if text.startswith("#"):
|
|
149
|
+
return True
|
|
150
|
+
verb, _, rest = text.partition(" ")
|
|
151
|
+
try:
|
|
152
|
+
name = self.resolve(verb)
|
|
153
|
+
if name == "quit":
|
|
154
|
+
return False
|
|
155
|
+
if name in LOCAL:
|
|
156
|
+
self._local(name, rest.strip())
|
|
157
|
+
if name != "record":
|
|
158
|
+
self._record(text, name)
|
|
159
|
+
return True
|
|
160
|
+
name, rest = route(name, rest)
|
|
161
|
+
args = parse(name, rest)
|
|
162
|
+
for arg_name, value in self.defaults.get(name, {}).items():
|
|
163
|
+
if args.get(arg_name) is None:
|
|
164
|
+
args[arg_name] = value
|
|
165
|
+
if self._init:
|
|
166
|
+
banned = sorted(k for k, v in args.items() if k in INIT_REFUSED and v is not None)
|
|
167
|
+
if banned:
|
|
168
|
+
names = ", ".join(f"{b}=" for b in banned)
|
|
169
|
+
raise BadArgs(f"an init file may not pass {names}: it changes what is "
|
|
170
|
+
"measured; put it in the script (--script) or the command "
|
|
171
|
+
"line")
|
|
172
|
+
result = dispatch(self.ctx, name, args)
|
|
173
|
+
except OpError as error:
|
|
174
|
+
self._error(error)
|
|
175
|
+
return True
|
|
176
|
+
except KeyboardInterrupt:
|
|
177
|
+
self.errors += 1
|
|
178
|
+
self._failed = True
|
|
179
|
+
self._interrupted = True
|
|
180
|
+
where = self._where()
|
|
181
|
+
if self.json_mode:
|
|
182
|
+
self.write(json.dumps({"interrupted": where, "state": "unresolved",
|
|
183
|
+
"reason": f"interrupted at {where}"}, sort_keys=True))
|
|
184
|
+
else:
|
|
185
|
+
self.write(f"interrupted at {where}")
|
|
186
|
+
return True
|
|
187
|
+
except Exception as error: # noqa: BLE001 - the shell never shows a traceback
|
|
188
|
+
self._error(internal(error))
|
|
189
|
+
return True
|
|
190
|
+
self.write(json.dumps(result, sort_keys=True) if self.json_mode else render(result))
|
|
191
|
+
if registry()[name].motion:
|
|
192
|
+
self.last_motion = text
|
|
193
|
+
self._record(text, name)
|
|
194
|
+
return True
|
|
195
|
+
|
|
196
|
+
def _record(self, text: str, name: str) -> None:
|
|
197
|
+
if self.record_to is not None and name != "record":
|
|
198
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
|
|
199
|
+
fd = os.open(self.record_to, flags, 0o600)
|
|
200
|
+
with os.fdopen(fd, "a") as handle:
|
|
201
|
+
handle.write(text + "\n")
|
|
202
|
+
|
|
203
|
+
def _start_recording(self, rest: str) -> None:
|
|
204
|
+
append = False
|
|
205
|
+
words = rest.split(None, 1)
|
|
206
|
+
if words and words[0] == "append":
|
|
207
|
+
append, rest = True, (words[1] if len(words) > 1 else "")
|
|
208
|
+
if self.depth:
|
|
209
|
+
raise BadArgs("record is not available from a script (--script, an init file or "
|
|
210
|
+
"`source`): type it at the prompt")
|
|
211
|
+
if not rest:
|
|
212
|
+
raise BadArgs("record [append] FILE | record stop")
|
|
213
|
+
path = Path(rest).expanduser()
|
|
214
|
+
if path.exists() and not append:
|
|
215
|
+
raise BadArgs(f"{path} exists; use `record append {rest}` to add to it")
|
|
216
|
+
os.close(os.open(path, os.O_WRONLY | os.O_CREAT | (os.O_APPEND if append else os.O_EXCL),
|
|
217
|
+
0o600))
|
|
218
|
+
self.record_to = path
|
|
219
|
+
self._say_record(path, append)
|
|
220
|
+
|
|
221
|
+
def _say_record(self, path: Path | None, append: bool) -> None:
|
|
222
|
+
"""``record`` is JSON in ``--json`` mode like every other op."""
|
|
223
|
+
if self.json_mode:
|
|
224
|
+
self.write(json.dumps({"op": "record", "state": "resolved",
|
|
225
|
+
"recording": None if path is None else str(path),
|
|
226
|
+
"append": append}, sort_keys=True))
|
|
227
|
+
elif path is None:
|
|
228
|
+
self.write("recording stopped")
|
|
229
|
+
else:
|
|
230
|
+
self.write(f"recording commands to {path}" + (" (append)" if append else ""))
|
|
231
|
+
|
|
232
|
+
def _local(self, name: str, rest: str) -> None:
|
|
233
|
+
if name == "help":
|
|
234
|
+
text = self.help(rest or None)
|
|
235
|
+
self.write(json.dumps({"op": "help", "state": "resolved", "text": text},
|
|
236
|
+
sort_keys=True) if self.json_mode else text)
|
|
237
|
+
elif name == "source":
|
|
238
|
+
keep = False
|
|
239
|
+
if rest.startswith("-k "):
|
|
240
|
+
keep, rest = True, rest[3:].strip()
|
|
241
|
+
if not rest:
|
|
242
|
+
raise BadArgs("source [-k] FILE")
|
|
243
|
+
try:
|
|
244
|
+
self.source(rest, keep_going=keep)
|
|
245
|
+
except OSError as error:
|
|
246
|
+
raise BadArgs(f"cannot read {rest}: {error.strerror or error}") from None
|
|
247
|
+
elif name == "record":
|
|
248
|
+
if rest in ("", "stop"):
|
|
249
|
+
self.record_to = None
|
|
250
|
+
self._say_record(None, False)
|
|
251
|
+
else:
|
|
252
|
+
self._start_recording(rest)
|
|
253
|
+
|
|
254
|
+
def help(self, verb: str | None = None) -> str:
|
|
255
|
+
ops = registry()
|
|
256
|
+
if verb is None:
|
|
257
|
+
lines = []
|
|
258
|
+
for effect in ("native", "navigate", "read", "mutate"):
|
|
259
|
+
lines.append(f"{effect}:")
|
|
260
|
+
for name in sorted(ops):
|
|
261
|
+
item = ops[name]
|
|
262
|
+
if item.effect == effect and item.milestone is None:
|
|
263
|
+
usage = item.usage or name
|
|
264
|
+
if len(usage) > 42:
|
|
265
|
+
lines.append(f" {usage}")
|
|
266
|
+
usage = ""
|
|
267
|
+
lines.append(f" {usage:<44}{item.summary}")
|
|
268
|
+
slots = sorted(name for name, item in ops.items() if item.milestone is not None)
|
|
269
|
+
if slots:
|
|
270
|
+
lines.append("not built yet: " + "; ".join(
|
|
271
|
+
f"{name}: {ops[name].milestone}" for name in slots))
|
|
272
|
+
lines.append("local: help [VERB] | source [-k] FILE | record [append] FILE|stop "
|
|
273
|
+
"| quit")
|
|
274
|
+
lines.append("aliases: " + " ".join(f"{k}={v}" for k, v in sorted(ALIASES.items())
|
|
275
|
+
if k != v))
|
|
276
|
+
return "\n".join(lines)
|
|
277
|
+
if verb == "why":
|
|
278
|
+
return WHY
|
|
279
|
+
name = self.resolve(verb)
|
|
280
|
+
if name in LOCAL:
|
|
281
|
+
return {"help": "help [VERB]: list commands or describe one",
|
|
282
|
+
"source": "source [-k] FILE: run commands from a file; stops at the first "
|
|
283
|
+
"error unless -k (keep going); nests at most "
|
|
284
|
+
f"{MAX_SOURCE_DEPTH} deep",
|
|
285
|
+
"record": "record [append] FILE|stop: write executed commands to FILE "
|
|
286
|
+
"(refuses an existing file unless `append`; mode 0600); "
|
|
287
|
+
"interactive only: refused inside --script, an init file or "
|
|
288
|
+
"`source`",
|
|
289
|
+
"quit": "quit: leave the debugger"}[name]
|
|
290
|
+
item = ops[name].to_json()
|
|
291
|
+
lines = [f"{item['usage']}", f" {item['summary']}",
|
|
292
|
+
f" effect {item['effect']}, needs a live run: "
|
|
293
|
+
f"{'yes' if item['needs_live'] else 'no'}"]
|
|
294
|
+
if "refused_until" in item:
|
|
295
|
+
lines.append(f" not built yet: {item['refused_until']}")
|
|
296
|
+
for arg in item["args"]:
|
|
297
|
+
extra = []
|
|
298
|
+
if arg.get("choices"):
|
|
299
|
+
extra.append("|".join(arg["choices"]))
|
|
300
|
+
if "default" in arg:
|
|
301
|
+
extra.append(f"default {arg['default']}")
|
|
302
|
+
if arg["required"]:
|
|
303
|
+
extra.append("required")
|
|
304
|
+
text = f" {arg['name']} ({arg['type']}{', ' + ', '.join(extra) if extra else ''})"
|
|
305
|
+
if arg.get("help"):
|
|
306
|
+
text += f": {arg['help']}"
|
|
307
|
+
lines.append(text)
|
|
308
|
+
return "\n".join(lines)
|
|
309
|
+
|
|
310
|
+
def source_init(self, path: str, *, echo: bool = True) -> int:
|
|
311
|
+
"""Run an init file (``[repl] init``, ``--init``): hashed into custody first
|
|
312
|
+
(``custody.ran_init``), and its commands may not pass ``INIT_REFUSED`` arguments
|
|
313
|
+
(nested ``source`` included). Returns the number of errors."""
|
|
314
|
+
from mdb.core import custody
|
|
315
|
+
|
|
316
|
+
custody.ran_init(path)
|
|
317
|
+
self._init = True
|
|
318
|
+
try:
|
|
319
|
+
return self.source(path, echo=echo)
|
|
320
|
+
finally:
|
|
321
|
+
self._init = False
|
|
322
|
+
|
|
323
|
+
def source(self, path: str, *, echo: bool = True, keep_going: bool = False) -> int:
|
|
324
|
+
"""Run a command file. It stops at the first error (as gdb) unless ``keep_going``
|
|
325
|
+
(``source -k``); nested ``source`` stops too, and at most ``MAX_SOURCE_DEPTH`` deep.
|
|
326
|
+
Returns the number of errors."""
|
|
327
|
+
if self.depth >= MAX_SOURCE_DEPTH:
|
|
328
|
+
raise BadArgs(f"source nests more than {MAX_SOURCE_DEPTH} deep (a script that "
|
|
329
|
+
f"sources itself?): {path}")
|
|
330
|
+
before = self.errors
|
|
331
|
+
self.depth += 1
|
|
332
|
+
try:
|
|
333
|
+
for number, raw in enumerate(Path(path).expanduser().read_text().splitlines(), 1):
|
|
334
|
+
line = raw.strip()
|
|
335
|
+
if not line or line.startswith("#"):
|
|
336
|
+
continue
|
|
337
|
+
if echo and not self.json_mode: # json mode: stdout is JSON lines only
|
|
338
|
+
self.write(f"{self.prompt}{line}")
|
|
339
|
+
self._failed = False
|
|
340
|
+
if not self.execute(line):
|
|
341
|
+
break
|
|
342
|
+
if self._interrupted:
|
|
343
|
+
break
|
|
344
|
+
if self._failed and not keep_going:
|
|
345
|
+
if self.depth == 1:
|
|
346
|
+
reason = (f"stopped sourcing {path} at line {number} "
|
|
347
|
+
"(use `source -k FILE` to keep going)")
|
|
348
|
+
self.write(json.dumps({"op": "source", "state": "refused",
|
|
349
|
+
"reason": reason}, sort_keys=True)
|
|
350
|
+
if self.json_mode else f"error: {reason}")
|
|
351
|
+
break
|
|
352
|
+
finally:
|
|
353
|
+
self.depth -= 1
|
|
354
|
+
if keep_going:
|
|
355
|
+
self._failed = False # source -k: its errors do not fail the calling line
|
|
356
|
+
return self.errors - before
|
|
357
|
+
|
|
358
|
+
def loop(self, stream: TextIO | None = None) -> int:
|
|
359
|
+
stream = stream if stream is not None else sys.stdin
|
|
360
|
+
interactive = stream is sys.stdin and stream.isatty()
|
|
361
|
+
readline = None
|
|
362
|
+
if interactive:
|
|
363
|
+
try:
|
|
364
|
+
import readline # enables line editing and history for input()
|
|
365
|
+
except ImportError:
|
|
366
|
+
readline = None
|
|
367
|
+
if readline is not None and self.history is not None:
|
|
368
|
+
try:
|
|
369
|
+
readline.read_history_file(str(self.history))
|
|
370
|
+
except OSError:
|
|
371
|
+
if self.history.exists() and self.history.stat().st_size > 0:
|
|
372
|
+
# not a history file (or unreadable): never write over it
|
|
373
|
+
self.write(f"warning: {self.history} is not a readline history file; "
|
|
374
|
+
"history is off for this session")
|
|
375
|
+
self.history = None
|
|
376
|
+
try:
|
|
377
|
+
return self._loop(stream, interactive)
|
|
378
|
+
finally:
|
|
379
|
+
if readline is not None and self.history is not None:
|
|
380
|
+
try:
|
|
381
|
+
self.history.parent.mkdir(parents=True, exist_ok=True)
|
|
382
|
+
readline.write_history_file(str(self.history))
|
|
383
|
+
except OSError as error:
|
|
384
|
+
self.write(f"warning: cannot write history {self.history}: "
|
|
385
|
+
f"{error.strerror or error}")
|
|
386
|
+
|
|
387
|
+
def _loop(self, stream: TextIO, interactive: bool) -> int:
|
|
388
|
+
while True:
|
|
389
|
+
try:
|
|
390
|
+
if interactive:
|
|
391
|
+
line = input(self.prompt)
|
|
392
|
+
else:
|
|
393
|
+
line = stream.readline()
|
|
394
|
+
if not line:
|
|
395
|
+
break
|
|
396
|
+
line = line.rstrip("\n")
|
|
397
|
+
if line.strip() and not line.strip().startswith("#"):
|
|
398
|
+
self.write(f"{self.prompt}{line.strip()}")
|
|
399
|
+
except EOFError:
|
|
400
|
+
break
|
|
401
|
+
except KeyboardInterrupt:
|
|
402
|
+
self.write("")
|
|
403
|
+
continue
|
|
404
|
+
try:
|
|
405
|
+
if not self.execute(line, repeat=interactive):
|
|
406
|
+
break
|
|
407
|
+
except KeyboardInterrupt: # between commands (execute handles its own)
|
|
408
|
+
self.write(f"interrupted at {self._where()}")
|
|
409
|
+
return 0 if self.errors == 0 else 1
|
mdb/serve/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""``mdb serve``: a read-only HTTP view over a recorded MDB project.
|
|
2
|
+
|
|
3
|
+
The server has no runtime of its own. Views are pure functions over project reads; tensors leave
|
|
4
|
+
the server only as bounded reductions (``reduce``). Importing this package loads neither a model
|
|
5
|
+
framework nor FastAPI; ``create_app`` imports FastAPI when called.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
__all__ = ["create_app"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def __getattr__(name):
|
|
13
|
+
if name == "create_app":
|
|
14
|
+
from .app import create_app
|
|
15
|
+
|
|
16
|
+
return create_app
|
|
17
|
+
raise AttributeError(name)
|
mdb/serve/__main__.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""``python -m mdb.serve --project PATH [--tiny FAMILY | --model PATH|NAME] [--port N]
|
|
2
|
+
[--host 127.0.0.1] [--allow-remote --allow-host HOST[:PORT] ...]``.
|
|
3
|
+
|
|
4
|
+
``--model`` takes the same forms as ``mdb engine MODEL`` (a directory, a cached name, an alias
|
|
5
|
+
from the config, ``tiny:FAMILY``). Defaults (project, host, port, allowed hosts, dtype, device)
|
|
6
|
+
may come from a config file or ``MDB_*`` variables (``mdb.core.settings``); a flag wins.
|
|
7
|
+
``--allow-remote`` is never read from a config file, ``serve.allow_hosts`` never from a project
|
|
8
|
+
file, and only ``--allow-host`` typed on the command line satisfies ``--allow-remote``.
|
|
9
|
+
|
|
10
|
+
Without ``--tiny``/``--model`` the server is a read-only viewer of the recorded project. With
|
|
11
|
+
one of them it also holds a live debugger attached with ``--project`` (``mdb serve --project
|
|
12
|
+
runs/t --tiny qwen2``): the web app steps it through the op registry, and checkpoints made
|
|
13
|
+
there are stored in the project. Live mode executes model code and accepts edits.
|
|
14
|
+
|
|
15
|
+
Binds loopback by default. There is no authentication, which is acceptable only on loopback:
|
|
16
|
+
a non-loopback host is refused unless ``--allow-remote`` is given, and then a warning is printed.
|
|
17
|
+
Every request must carry a ``Host`` (and ``Origin``, when sent) naming this server: the loopback
|
|
18
|
+
names with the bound port, or an explicit ``--allow-host``. ``--allow-remote`` requires at least
|
|
19
|
+
one ``--allow-host``, because without it no remote client's ``Host`` would be accepted.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import ipaddress
|
|
25
|
+
import sys
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from ..core.settings import TINY_FAMILIES # noqa: F401 - the one list (core.settings)
|
|
29
|
+
|
|
30
|
+
# setting name -> the flag that sets it (``mdb config explain`` names the flag)
|
|
31
|
+
FLAGS = {"project.dir": "--project", "project.session": "--session", "serve.host": "--host",
|
|
32
|
+
"serve.port": "--port", "serve.allow_hosts": "--allow-host", "model.dtype": "--dtype",
|
|
33
|
+
"model.device": "--device"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def is_loopback(host: str) -> bool:
|
|
37
|
+
if host == "localhost":
|
|
38
|
+
return True
|
|
39
|
+
try:
|
|
40
|
+
return ipaddress.ip_address(host).is_loopback
|
|
41
|
+
except ValueError:
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv=None):
|
|
46
|
+
from ..core import settings
|
|
47
|
+
from ..core.errors import BadArgs
|
|
48
|
+
from ..core.locate import parse_target
|
|
49
|
+
|
|
50
|
+
parser = argparse.ArgumentParser(
|
|
51
|
+
prog="mdb serve",
|
|
52
|
+
description="Web viewer of a recorded project. With --tiny or --model it also holds a "
|
|
53
|
+
"live debugger that the web app steps (live mode executes model code and "
|
|
54
|
+
"accepts edits). Binds loopback only unless --allow-remote is given; "
|
|
55
|
+
"there is no authentication.",
|
|
56
|
+
epilog="Defaults come from mdb.toml / ~/.config/mdb/config.toml and MDB_* variables "
|
|
57
|
+
"(mdb config show; docs/CONFIG.md).")
|
|
58
|
+
parser.add_argument("--project", type=Path,
|
|
59
|
+
help="the project to serve (required unless [project] dir is set)")
|
|
60
|
+
parser.add_argument("--session", metavar="NAME",
|
|
61
|
+
help="live session id in the project (default: family + model digest)")
|
|
62
|
+
parser.add_argument("--host", help=f"bind host (default {settings.DEFAULT_HOST})")
|
|
63
|
+
parser.add_argument("--port", type=int, help=f"port (default {settings.DEFAULT_PORT})")
|
|
64
|
+
parser.add_argument("--allow-remote", action="store_true",
|
|
65
|
+
help="bind a non-loopback host (no authentication!)")
|
|
66
|
+
parser.add_argument("--allow-host", action="append", default=None, metavar="HOST[:PORT]",
|
|
67
|
+
help="also accept this Host header (repeatable); HOST alone means "
|
|
68
|
+
"HOST:<port>. Required with --allow-remote")
|
|
69
|
+
source = parser.add_mutually_exclusive_group()
|
|
70
|
+
source.add_argument("--tiny", choices=TINY_FAMILIES,
|
|
71
|
+
help="live mode on a random tiny model (tests, demos)")
|
|
72
|
+
source.add_argument("--model", metavar="PATH|NAME",
|
|
73
|
+
help="live mode on a checkpoint directory, cached model name, model "
|
|
74
|
+
"alias or tiny:FAMILY (never downloads)")
|
|
75
|
+
parser.add_argument("--dtype", choices=settings.DTYPES,
|
|
76
|
+
help=f"weights dtype (default {settings.DEFAULT_DTYPE})")
|
|
77
|
+
parser.add_argument("--device", help=f"torch device (default {settings.DEFAULT_DEVICE})")
|
|
78
|
+
parser.add_argument("--seed", type=int, default=settings.DEFAULT_SEED,
|
|
79
|
+
help="tiny model seed")
|
|
80
|
+
parser.add_argument("--heartbeat", type=float, default=10.0, help=argparse.SUPPRESS)
|
|
81
|
+
args = parser.parse_args(argv)
|
|
82
|
+
cli = {"project.dir": args.project, "project.session": args.session,
|
|
83
|
+
"serve.host": args.host, "serve.port": args.port,
|
|
84
|
+
"serve.allow_hosts": tuple(args.allow_host) if args.allow_host else None,
|
|
85
|
+
"model.dtype": args.dtype, "model.device": args.device}
|
|
86
|
+
try:
|
|
87
|
+
if args.port is not None and not 1 <= args.port <= 65535:
|
|
88
|
+
raise settings.ConfigError("--port must be 1..65535 (the Host guard needs the "
|
|
89
|
+
"bound port)")
|
|
90
|
+
config = settings.activate(settings.resolve(cli, flags=FLAGS, project=args.project))
|
|
91
|
+
if args.model:
|
|
92
|
+
kind, value = parse_target(args.model)
|
|
93
|
+
from ..repl.__main__ import _say_alias
|
|
94
|
+
|
|
95
|
+
_say_alias("mdb serve", config, args.model)
|
|
96
|
+
if kind == "connect":
|
|
97
|
+
raise BadArgs("--model names a model to load here, not a server address")
|
|
98
|
+
if kind == "tiny":
|
|
99
|
+
args.model, args.tiny = None, value
|
|
100
|
+
else:
|
|
101
|
+
args.model = value # open_debugger resolves it (locate_model)
|
|
102
|
+
except (settings.ConfigError, BadArgs) as error:
|
|
103
|
+
print(f"mdb serve: {getattr(error, 'message', error)}", file=sys.stderr)
|
|
104
|
+
return 2
|
|
105
|
+
if config.get("project.dir") is None:
|
|
106
|
+
parser.error("name the project: --project DIR (or [project] dir in a config file)")
|
|
107
|
+
args.project = Path(config.get("project.dir"))
|
|
108
|
+
args.host, args.port = config.get("serve.host"), config.get("serve.port")
|
|
109
|
+
typed_hosts = list(args.allow_host or []) # --allow-remote needs these typed
|
|
110
|
+
args.allow_host = list(config.get("serve.allow_hosts"))
|
|
111
|
+
args.dtype, args.device = config.get("model.dtype"), config.get("model.device")
|
|
112
|
+
session = config.get("project.session")
|
|
113
|
+
args.session = None if session == "auto" else session
|
|
114
|
+
live_mode = bool(args.tiny or args.model)
|
|
115
|
+
if args.allow_remote and not typed_hosts:
|
|
116
|
+
print("mdb serve: --allow-remote needs --allow-host HOST[:PORT] naming how clients will "
|
|
117
|
+
"reach this server (a request whose Host is not listed is refused)",
|
|
118
|
+
file=sys.stderr)
|
|
119
|
+
return 2
|
|
120
|
+
if not is_loopback(args.host):
|
|
121
|
+
if not args.allow_remote:
|
|
122
|
+
print(f"mdb serve: refusing non-loopback host {args.host!r}: the server has no "
|
|
123
|
+
"authentication. Pass --allow-remote to bind it anyway.", file=sys.stderr)
|
|
124
|
+
return 2
|
|
125
|
+
print(f"mdb serve: WARNING: serving {args.project} on {args.host} without "
|
|
126
|
+
"authentication; anyone who can reach this port can read the project.",
|
|
127
|
+
file=sys.stderr)
|
|
128
|
+
if live_mode:
|
|
129
|
+
print("mdb serve: WARNING: LIVE MODE on a non-loopback host: anyone who can reach "
|
|
130
|
+
"this port can run the model, stage edits and write checkpoints into "
|
|
131
|
+
f"{args.project}.", file=sys.stderr)
|
|
132
|
+
try:
|
|
133
|
+
import uvicorn
|
|
134
|
+
except ImportError:
|
|
135
|
+
print("mdb serve: needs the serve extra (pip install 'model-debugger[serve]')",
|
|
136
|
+
file=sys.stderr)
|
|
137
|
+
return 2
|
|
138
|
+
from .app import create_app
|
|
139
|
+
|
|
140
|
+
live = None
|
|
141
|
+
if live_mode:
|
|
142
|
+
from ..core.errors import OpError
|
|
143
|
+
from .live import LiveSession, open_debugger
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
debugger = open_debugger(args.project, tiny=args.tiny, model=args.model,
|
|
147
|
+
dtype=args.dtype, device=args.device, seed=args.seed,
|
|
148
|
+
session=args.session)
|
|
149
|
+
except (OpError, ValueError, OSError) as error:
|
|
150
|
+
print(f"mdb serve: cannot attach the live model: "
|
|
151
|
+
f"{getattr(error, 'message', error)}", file=sys.stderr)
|
|
152
|
+
return 1
|
|
153
|
+
live = LiveSession(debugger)
|
|
154
|
+
try:
|
|
155
|
+
app = create_app(args.project, heartbeat=args.heartbeat, port=args.port,
|
|
156
|
+
allow_hosts=args.allow_host, live=live)
|
|
157
|
+
except (ValueError, OSError) as error:
|
|
158
|
+
print(f"mdb serve: {error}", file=sys.stderr)
|
|
159
|
+
return 1
|
|
160
|
+
from .app import STATIC
|
|
161
|
+
|
|
162
|
+
if not (STATIC / "index.html").is_file():
|
|
163
|
+
print(f"mdb serve: web build absent at {STATIC}; a pip install from Git has none: run "
|
|
164
|
+
"`npm run build` in packages/mdb/web of a checkout and install from it "
|
|
165
|
+
"(docs/INSTALL.md; the API at /api/v1 is served without it)", file=sys.stderr)
|
|
166
|
+
mode = f"live session {live.sid}" if live else "read-only"
|
|
167
|
+
print(f"mdb serve: http://{args.host}:{args.port}/ (project {args.project}; {mode})",
|
|
168
|
+
file=sys.stderr)
|
|
169
|
+
try: # one SIGTERM/SIGINT ends it: app.py's lifespan closes the event sockets first
|
|
170
|
+
uvicorn.run(app, host=args.host, port=args.port, log_level="warning",
|
|
171
|
+
timeout_graceful_shutdown=5)
|
|
172
|
+
finally:
|
|
173
|
+
if live is not None:
|
|
174
|
+
live.interrupt()
|
|
175
|
+
live.close()
|
|
176
|
+
return 0
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
if __name__ == "__main__":
|
|
180
|
+
raise SystemExit(main())
|