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/serve/live.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"""The live session of ``mdb serve --tiny|--model``: one attached debugger driven over HTTP.
|
|
2
|
+
|
|
3
|
+
Every action is ``mdb.ops.dispatch`` on the debugger's one ``Context`` (the registry the REPL
|
|
4
|
+
uses); the console runs a raw command line through the REPL's own ``Shell``. Nothing here
|
|
5
|
+
implements a verb.
|
|
6
|
+
|
|
7
|
+
One model, one thread. The model and the run are not thread-safe, so every job (op, console
|
|
8
|
+
line, live view, reduction) runs on ONE worker thread, in arrival order. At most ``QUEUE_LIMIT``
|
|
9
|
+
jobs wait behind the running one; a request that would make it ``QUEUE_LIMIT + 1`` is refused
|
|
10
|
+
with ``Busy`` (HTTP 409 ``busy``) and nothing runs. ``seq`` numbers ops and console lines in
|
|
11
|
+
execution order.
|
|
12
|
+
|
|
13
|
+
Interrupt. The REPL's Ctrl-C raises ``KeyboardInterrupt`` inside the running command; the engine
|
|
14
|
+
rolls a half-done cursor move back (``mdb.engine.run``) and the shell reports ``interrupted at
|
|
15
|
+
<where>``. The engine has no polled stop flag, so ``interrupt()`` delivers the same
|
|
16
|
+
``KeyboardInterrupt`` to the worker thread (``PyThreadState_SetAsyncExc``), once per job and
|
|
17
|
+
only while a job runs; a delivery that has not fired when the job ends is withdrawn.
|
|
18
|
+
|
|
19
|
+
Events. Each completed op or console line is published to every subscriber (the session's
|
|
20
|
+
WebSocket): ``{op, seq, source, where, stopped, state, stale}``; no tensor travels.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import asyncio
|
|
25
|
+
import ctypes
|
|
26
|
+
import io
|
|
27
|
+
import queue
|
|
28
|
+
import threading
|
|
29
|
+
import traceback
|
|
30
|
+
from concurrent.futures import Future
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from typing import Any
|
|
33
|
+
|
|
34
|
+
from mdb.core.settings import DEFAULT_SEED
|
|
35
|
+
|
|
36
|
+
QUEUE_LIMIT = 32
|
|
37
|
+
SUBSCRIBER_LIMIT = 256
|
|
38
|
+
_UNSET = object()
|
|
39
|
+
# The views a client re-fetches after an op of each effect.
|
|
40
|
+
STALE = {"read": [], "navigate": ["frame", "timeline"], "mutate": ["frame", "timeline", "tables"],
|
|
41
|
+
"native": ["frame", "timeline", "tables"]}
|
|
42
|
+
# Local REPL commands the web console refuses: they read or write files on the server, or end it.
|
|
43
|
+
CONSOLE_REFUSED = ("source", "record", "quit", "export")
|
|
44
|
+
EXPORT_REFUSED = ("`export` writes a directory on the server and is not available from the web; "
|
|
45
|
+
"run it in a local REPL or call Debugger.export_bundle")
|
|
46
|
+
# `promptset load` / `set load` read a file on the server (and its error text says whether the
|
|
47
|
+
# file exists): refused on the console and the op route; a set is sent inline (`promptset define`).
|
|
48
|
+
SET_LOAD_REFUSED = ("`promptset load` reads a file on the server and is not available from the "
|
|
49
|
+
"web; send the set inline: promptset define NAME ITEMS (items as JSON)")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Busy(Exception):
|
|
53
|
+
"""The worker's queue is full: the request was not queued."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class _Job:
|
|
58
|
+
fn: Any # () -> raw value; the only part a KeyboardInterrupt can end
|
|
59
|
+
interrupted: Any # () -> raw value reported when a KeyboardInterrupt ended ``fn``
|
|
60
|
+
finish: Any # raw value -> the request's value (runs after the job settled)
|
|
61
|
+
future: Future
|
|
62
|
+
interruptible: bool # an op or console line; never a view or a reduction
|
|
63
|
+
cancelled: bool = False # an interrupt arrived while it waited: it never runs
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Interrupted(Exception):
|
|
67
|
+
"""A read (a live view, a reduction) that an interrupt ended."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def error_json(error) -> dict[str, Any]:
|
|
71
|
+
"""An ``OpError`` as ``python -m mdb.repl --json`` prints it."""
|
|
72
|
+
return {"error": error.to_json(), "state": error.state, "reason": error.message}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def interrupted_json(where: str) -> dict[str, Any]:
|
|
76
|
+
"""An interrupted command as ``python -m mdb.repl --json`` prints it."""
|
|
77
|
+
return {"interrupted": where, "state": "unresolved", "reason": f"interrupted at {where}"}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def stopped_by(result: dict[str, Any]) -> str | None:
|
|
81
|
+
"""What ended a command: the run-to-hit ``reason`` of its result (breakpoint, watch, budget,
|
|
82
|
+
end-of-context, reached, error, ...), ``interrupted``, ``refused`` for an error, None for a
|
|
83
|
+
command that is not a run-to-hit."""
|
|
84
|
+
if "interrupted" in result:
|
|
85
|
+
return "interrupted"
|
|
86
|
+
if "error" in result:
|
|
87
|
+
return "refused"
|
|
88
|
+
reason = result.get("reason")
|
|
89
|
+
return reason if isinstance(reason, str) else None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _release_frames(error: BaseException) -> None:
|
|
93
|
+
"""Clear the locals of the finished frames in the tracebacks of ``error`` and of the
|
|
94
|
+
exceptions it chains, so a failed analysis (its row models, its float64 weights) is not
|
|
95
|
+
kept alive by the exception handed to the waiting request. The traceback's file and line
|
|
96
|
+
entries stay."""
|
|
97
|
+
todo, seen = [error], set()
|
|
98
|
+
while todo:
|
|
99
|
+
item = todo.pop()
|
|
100
|
+
if item is None or id(item) in seen:
|
|
101
|
+
continue
|
|
102
|
+
seen.add(id(item))
|
|
103
|
+
traceback.clear_frames(item.__traceback__)
|
|
104
|
+
todo += [item.__cause__, item.__context__]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class LiveSession:
|
|
108
|
+
"""One attached debugger (``mdb.attach(..., project=)``) and the worker that owns it."""
|
|
109
|
+
|
|
110
|
+
def __init__(self, debugger: Any, *, queue_limit: int = QUEUE_LIMIT):
|
|
111
|
+
from mdb.repl.shell import Shell
|
|
112
|
+
|
|
113
|
+
self.debugger = debugger
|
|
114
|
+
self.sid: str = debugger.session_id
|
|
115
|
+
self.ctx = debugger.ops()
|
|
116
|
+
self.shell = Shell(self.ctx, out=io.StringIO())
|
|
117
|
+
self.queue_limit = queue_limit
|
|
118
|
+
self._jobs: queue.Queue = queue.Queue(maxsize=queue_limit + 1)
|
|
119
|
+
self._lock = threading.Lock()
|
|
120
|
+
self._current: _Job | None = None
|
|
121
|
+
self._waiting: list[_Job] = [] # queued, not started (in order)
|
|
122
|
+
self._sent = False
|
|
123
|
+
self._pending = 0
|
|
124
|
+
self.seq = 0 # ops and console lines completed
|
|
125
|
+
self.running: str | None = None # name of the op or console line in flight
|
|
126
|
+
self._subscribers: set[tuple[Any, asyncio.Queue]] = set()
|
|
127
|
+
self._thread = threading.Thread(target=self._work, name="mdb-live", daemon=True)
|
|
128
|
+
self._thread.start()
|
|
129
|
+
|
|
130
|
+
# ------------------------------------------------------------------ worker
|
|
131
|
+
|
|
132
|
+
def submit(self, fn, interrupted, finish, *, interruptible=True) -> Future:
|
|
133
|
+
"""Queue ``fn()`` for the worker; ``Busy`` when ``queue_limit`` jobs already wait."""
|
|
134
|
+
job = _Job(fn, interrupted, finish, Future(), interruptible)
|
|
135
|
+
with self._lock:
|
|
136
|
+
waiting = self._pending - (1 if self._current is not None else 0)
|
|
137
|
+
if waiting >= self.queue_limit:
|
|
138
|
+
raise Busy(f"{waiting} requests are queued (limit {self.queue_limit})")
|
|
139
|
+
self._pending += 1
|
|
140
|
+
self._waiting.append(job)
|
|
141
|
+
self._jobs.put_nowait(job)
|
|
142
|
+
return job.future
|
|
143
|
+
|
|
144
|
+
def _work(self) -> None:
|
|
145
|
+
while True:
|
|
146
|
+
job = self._jobs.get()
|
|
147
|
+
if job is None:
|
|
148
|
+
return
|
|
149
|
+
value = self._attempt(job)
|
|
150
|
+
if not isinstance(value, BaseException):
|
|
151
|
+
try:
|
|
152
|
+
value = job.finish(value)
|
|
153
|
+
except Exception as error: # noqa: BLE001 - handed to the waiting request
|
|
154
|
+
value = error
|
|
155
|
+
with self._lock:
|
|
156
|
+
self._pending -= 1
|
|
157
|
+
if isinstance(value, BaseException):
|
|
158
|
+
_release_frames(value)
|
|
159
|
+
job.future.set_exception(value)
|
|
160
|
+
else:
|
|
161
|
+
job.future.set_result(value)
|
|
162
|
+
# the worker waits for the next job holding neither this one nor its result
|
|
163
|
+
del job, value
|
|
164
|
+
|
|
165
|
+
def _attempt(self, job: _Job):
|
|
166
|
+
"""Run one job's ``fn``. A ``KeyboardInterrupt`` that fires inside ``fn`` gives
|
|
167
|
+
``job.interrupted()``; one that fires after ``fn`` returned keeps its value. A job an
|
|
168
|
+
interrupt cancelled while it waited never runs and also gives ``job.interrupted()``. When
|
|
169
|
+
this returns no interrupt is pending, so ``finish`` cannot be cut short."""
|
|
170
|
+
value = _UNSET
|
|
171
|
+
try:
|
|
172
|
+
with self._lock:
|
|
173
|
+
self._waiting.remove(job)
|
|
174
|
+
if not job.cancelled:
|
|
175
|
+
self._current, self._sent = job, False
|
|
176
|
+
if not job.cancelled:
|
|
177
|
+
value = job.fn()
|
|
178
|
+
self._settle()
|
|
179
|
+
except KeyboardInterrupt:
|
|
180
|
+
self._settle()
|
|
181
|
+
except Exception as error: # noqa: BLE001 - handed to the waiting request
|
|
182
|
+
self._settle()
|
|
183
|
+
return error
|
|
184
|
+
if value is _UNSET:
|
|
185
|
+
try:
|
|
186
|
+
return job.interrupted()
|
|
187
|
+
except Exception as error: # noqa: BLE001
|
|
188
|
+
return error
|
|
189
|
+
return value
|
|
190
|
+
|
|
191
|
+
def _settle(self) -> None:
|
|
192
|
+
"""No job is current; withdraw an interrupt that was sent but has not fired. The sent
|
|
193
|
+
interrupt may fire inside this very call; it is then spent, and the call repeats."""
|
|
194
|
+
while True:
|
|
195
|
+
try:
|
|
196
|
+
with self._lock:
|
|
197
|
+
self._current = None
|
|
198
|
+
if self._sent:
|
|
199
|
+
ctypes.pythonapi.PyThreadState_SetAsyncExc(
|
|
200
|
+
ctypes.c_ulong(self._thread.ident), None)
|
|
201
|
+
self._sent = False
|
|
202
|
+
return
|
|
203
|
+
except KeyboardInterrupt:
|
|
204
|
+
continue
|
|
205
|
+
|
|
206
|
+
def interrupt(self) -> dict[str, Any]:
|
|
207
|
+
"""Deliver Ctrl-C to the running op or console line (once) and cancel every queued job
|
|
208
|
+
(each gets the interrupted result: an op or console line ``interrupted at <where>``, a
|
|
209
|
+
view or reduction ``Interrupted``). Says whether one was running and how many queued
|
|
210
|
+
jobs were cancelled. A running view or reduction is never interrupted."""
|
|
211
|
+
with self._lock:
|
|
212
|
+
cancelled = 0
|
|
213
|
+
for job in self._waiting:
|
|
214
|
+
if not job.cancelled:
|
|
215
|
+
job.cancelled = True
|
|
216
|
+
cancelled += 1
|
|
217
|
+
if self._current is None or not self._current.interruptible:
|
|
218
|
+
return {"interrupted": False, "running": None, "cancelled": cancelled,
|
|
219
|
+
"reason": "nothing is running" + (
|
|
220
|
+
f"; cancelled {cancelled} queued" if cancelled else "")}
|
|
221
|
+
if not self._sent:
|
|
222
|
+
ctypes.pythonapi.PyThreadState_SetAsyncExc(
|
|
223
|
+
ctypes.c_ulong(self._thread.ident), ctypes.py_object(KeyboardInterrupt))
|
|
224
|
+
self._sent = True
|
|
225
|
+
return {"interrupted": True, "running": self.running, "cancelled": cancelled,
|
|
226
|
+
"reason": None}
|
|
227
|
+
|
|
228
|
+
def cancel(self, future: Future) -> bool:
|
|
229
|
+
"""Cancel the one job behind ``future`` (its client went away): queued -> it never runs;
|
|
230
|
+
running and interruptible (an op or console line) -> Ctrl-C is delivered to it, as
|
|
231
|
+
``interrupt()`` does, so the state rolls back and the worker is free; a running view or
|
|
232
|
+
reduction is left to finish. Other jobs are untouched. True when something was done."""
|
|
233
|
+
with self._lock:
|
|
234
|
+
for job in self._waiting:
|
|
235
|
+
if job.future is future and not job.cancelled:
|
|
236
|
+
job.cancelled = True
|
|
237
|
+
return True
|
|
238
|
+
job = self._current
|
|
239
|
+
if job is None or job.future is not future or not job.interruptible or self._sent:
|
|
240
|
+
return False
|
|
241
|
+
ctypes.pythonapi.PyThreadState_SetAsyncExc(
|
|
242
|
+
ctypes.c_ulong(self._thread.ident), ctypes.py_object(KeyboardInterrupt))
|
|
243
|
+
self._sent = True
|
|
244
|
+
return True
|
|
245
|
+
|
|
246
|
+
def close(self) -> None:
|
|
247
|
+
"""Stop the worker after the jobs already queued."""
|
|
248
|
+
self._jobs.put(None)
|
|
249
|
+
self._thread.join(timeout=30)
|
|
250
|
+
|
|
251
|
+
# ------------------------------------------------------------------ commands
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def where(self) -> str | None:
|
|
255
|
+
run = self.ctx.run
|
|
256
|
+
try:
|
|
257
|
+
return run.where if run is not None else None
|
|
258
|
+
except Exception: # noqa: BLE001 - reporting the cursor must never fail
|
|
259
|
+
return None
|
|
260
|
+
|
|
261
|
+
def op(self, name: str, args: dict[str, Any]) -> Future:
|
|
262
|
+
"""Dispatch one registered op; the future's value is ``{seq, result, where}`` where
|
|
263
|
+
``result`` is exactly what ``python -m mdb.repl --json`` prints for it."""
|
|
264
|
+
from mdb.ops import OpError, Refused, dispatch, registry
|
|
265
|
+
|
|
266
|
+
effect = registry()[name].effect
|
|
267
|
+
|
|
268
|
+
def run():
|
|
269
|
+
self.running = name
|
|
270
|
+
if name == "promptset" and args.get("action") == "load":
|
|
271
|
+
return error_json(Refused(SET_LOAD_REFUSED))
|
|
272
|
+
if name == "export":
|
|
273
|
+
return error_json(Refused(EXPORT_REFUSED))
|
|
274
|
+
try:
|
|
275
|
+
return dispatch(self.ctx, name, args)
|
|
276
|
+
except OpError as error:
|
|
277
|
+
return error_json(error)
|
|
278
|
+
|
|
279
|
+
def interrupted():
|
|
280
|
+
return interrupted_json(self.where or "no run")
|
|
281
|
+
|
|
282
|
+
def finish(result):
|
|
283
|
+
body = self._done(name, effect, "op", stopped_by(result),
|
|
284
|
+
result.get("state", "resolved"))
|
|
285
|
+
body["result"] = result
|
|
286
|
+
return body
|
|
287
|
+
|
|
288
|
+
return self.submit(run, interrupted, finish)
|
|
289
|
+
|
|
290
|
+
def console(self, line: str) -> Future:
|
|
291
|
+
"""One command line through the REPL shell; the value is ``{seq, text, where}`` with the
|
|
292
|
+
text the REPL prints. ``source``, ``record`` and ``quit`` are refused here."""
|
|
293
|
+
from mdb.ops import OpError, registry
|
|
294
|
+
|
|
295
|
+
text = line.strip()
|
|
296
|
+
verb = text.partition(" ")[0]
|
|
297
|
+
try:
|
|
298
|
+
name = self.shell.resolve(verb) if verb else None
|
|
299
|
+
except OpError:
|
|
300
|
+
name = None # the shell prints the same error itself
|
|
301
|
+
label = name or verb or "console"
|
|
302
|
+
set_load = name in ("set", "promptset") and text.split()[1:2] == ["load"]
|
|
303
|
+
ops = registry()
|
|
304
|
+
effect = ops[name].effect if name in ops else "read"
|
|
305
|
+
before = []
|
|
306
|
+
|
|
307
|
+
def run():
|
|
308
|
+
self.running = label
|
|
309
|
+
if set_load:
|
|
310
|
+
return f"error: {SET_LOAD_REFUSED}"
|
|
311
|
+
if name in CONSOLE_REFUSED:
|
|
312
|
+
return (f"error: `{name}` is not available from the web console (it reads or "
|
|
313
|
+
"writes files on the server, or ends the session)")
|
|
314
|
+
before.append(self.ctx.table.last_stop)
|
|
315
|
+
self.shell.out = io.StringIO()
|
|
316
|
+
self.shell.execute(text)
|
|
317
|
+
return self.shell.out.getvalue().rstrip("\n")
|
|
318
|
+
|
|
319
|
+
def interrupted():
|
|
320
|
+
return f"interrupted at {self.where or 'no run'}"
|
|
321
|
+
|
|
322
|
+
def finish(out):
|
|
323
|
+
stopped = "interrupted" if out.startswith("interrupted at ") else None
|
|
324
|
+
stop = self.ctx.table.last_stop if before else None
|
|
325
|
+
if stopped is None and stop is not None and stop is not before[0] \
|
|
326
|
+
and stop["where"] == self.where:
|
|
327
|
+
kinds = {self.ctx.table.items[i].kind for i in stop["ids"]
|
|
328
|
+
if i in self.ctx.table.items}
|
|
329
|
+
stopped = ("watch+breakpoint" if "watch" in kinds and kinds - {"watch"} else
|
|
330
|
+
"watch" if kinds == {"watch"} else "breakpoint")
|
|
331
|
+
body = self._done(label, effect, "console", stopped,
|
|
332
|
+
"refused" if out.startswith("error") else "resolved")
|
|
333
|
+
body["text"] = out
|
|
334
|
+
return body
|
|
335
|
+
|
|
336
|
+
return self.submit(run, interrupted, finish)
|
|
337
|
+
|
|
338
|
+
def call(self, fn) -> Future:
|
|
339
|
+
"""Run a read (a live view, a reduction) on the worker: no event, no ``seq``; an
|
|
340
|
+
interrupt ends it with ``Interrupted``."""
|
|
341
|
+
|
|
342
|
+
def interrupted():
|
|
343
|
+
raise Interrupted("interrupted")
|
|
344
|
+
|
|
345
|
+
return self.submit(fn, interrupted, lambda value: value, interruptible=False)
|
|
346
|
+
|
|
347
|
+
def _done(self, name, effect, source, stopped, state) -> dict[str, Any]:
|
|
348
|
+
self.seq += 1
|
|
349
|
+
self.running = None
|
|
350
|
+
where = self.where
|
|
351
|
+
self.publish({"op": name, "seq": self.seq, "source": source, "where": where,
|
|
352
|
+
"stale": STALE.get(effect, STALE["native"]), "stopped": stopped,
|
|
353
|
+
"state": state})
|
|
354
|
+
return {"seq": self.seq, "where": where}
|
|
355
|
+
|
|
356
|
+
# ------------------------------------------------------------------ events
|
|
357
|
+
|
|
358
|
+
def subscribe(self) -> asyncio.Queue:
|
|
359
|
+
"""A queue that receives every event published from now on (call on the event loop)."""
|
|
360
|
+
events: asyncio.Queue = asyncio.Queue(maxsize=SUBSCRIBER_LIMIT)
|
|
361
|
+
with self._lock:
|
|
362
|
+
self._subscribers.add((asyncio.get_running_loop(), events))
|
|
363
|
+
return events
|
|
364
|
+
|
|
365
|
+
def unsubscribe(self, events: asyncio.Queue) -> None:
|
|
366
|
+
with self._lock:
|
|
367
|
+
self._subscribers = {s for s in self._subscribers if s[1] is not events}
|
|
368
|
+
|
|
369
|
+
def publish(self, event: dict[str, Any]) -> None:
|
|
370
|
+
"""Hand ``event`` to every subscriber's loop. A subscriber that fell
|
|
371
|
+
``SUBSCRIBER_LIMIT`` events behind loses the oldest (clients re-fetch on any event)."""
|
|
372
|
+
with self._lock:
|
|
373
|
+
targets = list(self._subscribers)
|
|
374
|
+
for loop, events in targets:
|
|
375
|
+
try:
|
|
376
|
+
loop.call_soon_threadsafe(_offer, events, dict(event))
|
|
377
|
+
except RuntimeError: # the loop closed: the socket is gone
|
|
378
|
+
self.unsubscribe(events)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _offer(events: asyncio.Queue, event: dict[str, Any]) -> None:
|
|
382
|
+
if events.full():
|
|
383
|
+
events.get_nowait()
|
|
384
|
+
events.put_nowait(event)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def open_debugger(project, *, tiny: str | None = None, model: str | None = None,
|
|
388
|
+
dtype: str | None = None, device: str | None = None,
|
|
389
|
+
seed: int = DEFAULT_SEED, session: str | None = None):
|
|
390
|
+
"""The debugger of ``mdb serve --tiny FAMILY | --model PATH|NAME``, attached with
|
|
391
|
+
``project`` so its checkpoints are durable. ``model`` is resolved by ``locate_model`` (a
|
|
392
|
+
directory, a cached name or a configured alias; never downloads); its tokenizer is loaded
|
|
393
|
+
when the directory has one. ``device`` applies to tiny models too; ``dtype``/``device``
|
|
394
|
+
None take the configured values."""
|
|
395
|
+
from mdb.core.locate import locate_model
|
|
396
|
+
from mdb.ops.debugger import attach, open_tiny
|
|
397
|
+
|
|
398
|
+
if (tiny is None) == (model is None):
|
|
399
|
+
raise ValueError("give one of tiny= or model=")
|
|
400
|
+
if tiny is not None:
|
|
401
|
+
return open_tiny(tiny, dtype, seed=seed, project=project, session=session,
|
|
402
|
+
device=device)
|
|
403
|
+
root = locate_model(model)
|
|
404
|
+
from mdb.engine.models import load_local
|
|
405
|
+
|
|
406
|
+
loaded = load_local(root, dtype=dtype, device=device)
|
|
407
|
+
tokenizer = None
|
|
408
|
+
if any((root / name).is_file() for name in ("tokenizer.json", "tokenizer_config.json")):
|
|
409
|
+
from transformers import AutoTokenizer
|
|
410
|
+
|
|
411
|
+
tokenizer = AutoTokenizer.from_pretrained(str(root), local_files_only=True)
|
|
412
|
+
return attach(loaded, tokenizer, project=project, session=session)
|
mdb/serve/live_reduce.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Reductions of a live run's values, read the way the ``print`` op reads them.
|
|
2
|
+
|
|
3
|
+
The browser names an address of the live run (``{kind: "occurrence", address}``). The server
|
|
4
|
+
reads the value with ``Run.read(address)`` and its label with ``Run.read_info(address)``: the same
|
|
5
|
+
engine reads ``print`` makes, so every port the run has computed resolves (the cursor's layer
|
|
6
|
+
from the port cache; an earlier layer by re-entering it from its retained boundary cut; a
|
|
7
|
+
boundary from its mark). Nothing is exported or stored: a live reduction writes nothing to the
|
|
8
|
+
project. The tensor never leaves the server; the reduction is ``serve.reduce.reduce_array``,
|
|
9
|
+
relabelled with the value's authority. Runs on the live session's worker thread.
|
|
10
|
+
|
|
11
|
+
Cost: a value outside the port cache (any layer but the cursor's pending one) is recomputed by
|
|
12
|
+
re-entering its layer, once for ``read`` and once for ``read_info``; the web page therefore asks
|
|
13
|
+
only for the rows it shows. An address that names another origin (``branch:...`` or
|
|
14
|
+
``@cut...``) is not a value of the live run: it goes through the project's stored occurrences
|
|
15
|
+
(``serve.reduce.resolve``, the recorded path), never through the live run.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from .reduce import ReduceError, reduce_array
|
|
20
|
+
from .schema import Ev
|
|
21
|
+
|
|
22
|
+
VALUE_FIELDS = ("min", "max", "mean", "std", "absmax", "l2")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def names_origin(address: str) -> bool:
|
|
26
|
+
"""True when ``address`` names an origin other than the live run (``b:...``, ``@cut...``)."""
|
|
27
|
+
base = address.strip().partition("[")[0]
|
|
28
|
+
return base.startswith("@") or ":" in base
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def read_live(session, spec: dict):
|
|
32
|
+
"""``(array, info)`` of the live value at ``spec["address"]``; ``ReduceError`` when the run
|
|
33
|
+
has not computed it or the engine declines to label it."""
|
|
34
|
+
import torch
|
|
35
|
+
|
|
36
|
+
run = session.ctx.run
|
|
37
|
+
if run is None:
|
|
38
|
+
raise ReduceError("unresolved", "the live session has no run yet (start one)", 409)
|
|
39
|
+
address = spec.get("address")
|
|
40
|
+
if not isinstance(address, str) or not address.strip():
|
|
41
|
+
raise ReduceError("bad_pointer", "an occurrence pointer names an address")
|
|
42
|
+
address = address.strip()
|
|
43
|
+
if "[" in address:
|
|
44
|
+
raise ReduceError("bad_pointer", "a live reduction reads a whole value; select with the "
|
|
45
|
+
"reduction's params (slice, topk) instead of an address selector")
|
|
46
|
+
try:
|
|
47
|
+
value = run.read(address)
|
|
48
|
+
provenance = run.read_info(address)
|
|
49
|
+
except (ValueError, KeyError) as error: # not computed yet, before the run, a bad address
|
|
50
|
+
raise ReduceError("unresolved", f"cannot read {address!r}: {error}", 409) from error
|
|
51
|
+
authority = provenance.get("authority")
|
|
52
|
+
if authority is None or provenance.get("state") != "resolved":
|
|
53
|
+
raise ReduceError(provenance.get("state") or "refused",
|
|
54
|
+
f"{address}: the engine declined to label the value "
|
|
55
|
+
f"({provenance.get('reason') or 'no reason given'})", 409)
|
|
56
|
+
authority = {"derived": "derived-exact"}.get(authority, authority) # as `print` labels it
|
|
57
|
+
value = value.detach().cpu()
|
|
58
|
+
array =value.to(torch.float32).numpy() if value.is_floating_point() else value.numpy()
|
|
59
|
+
info = {"shape": list(value.shape), "dtype": str(value.dtype).removeprefix("torch."),
|
|
60
|
+
"authority": authority}
|
|
61
|
+
return array, info
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def relabel(result, authority: str, note: str):
|
|
65
|
+
"""``result`` with its value statistics labelled ``authority`` (``reduce_array`` labels them
|
|
66
|
+
``measured``); counts and the derived histogram/tile domains keep their own labels."""
|
|
67
|
+
if authority not in Ev.__args__:
|
|
68
|
+
raise ReduceError("refused", f"the value's authority {authority!r} is not a record label",
|
|
69
|
+
409)
|
|
70
|
+
data = result.model_dump(mode="json")
|
|
71
|
+
data["note"] = note
|
|
72
|
+
if authority != "measured":
|
|
73
|
+
for key in VALUE_FIELDS:
|
|
74
|
+
if isinstance(data.get(key), dict) and data[key]["ev"] == "measured":
|
|
75
|
+
data[key]["ev"] = authority
|
|
76
|
+
for entry in data.get("entries") or []:
|
|
77
|
+
if entry["v"]["ev"] == "measured":
|
|
78
|
+
entry["v"]["ev"] = authority
|
|
79
|
+
if data.get("ev") == "measured":
|
|
80
|
+
data["ev"] = authority
|
|
81
|
+
return type(result).model_validate(data)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def reduce_live(session, spec: dict, op: str, params: dict):
|
|
85
|
+
"""One reduction of a live value (``project`` reads its direction from the live run too)."""
|
|
86
|
+
array, info = read_live(session, spec)
|
|
87
|
+
result = reduce_array(array, info, spec, op, params,
|
|
88
|
+
direction_of=lambda d: read_live(session, d)[0])
|
|
89
|
+
return relabel(result, info["authority"],
|
|
90
|
+
f"live run at {session.where}, read as `print` reads it (Run.read)")
|