model-runtime 0.5.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.
- model_runtime-0.5.0.dist-info/METADATA +618 -0
- model_runtime-0.5.0.dist-info/RECORD +36 -0
- model_runtime-0.5.0.dist-info/WHEEL +4 -0
- model_runtime-0.5.0.dist-info/entry_points.txt +2 -0
- model_runtime-0.5.0.dist-info/licenses/LICENSE +202 -0
- model_runtime-0.5.0.dist-info/licenses/NOTICE +6 -0
- saturn/__init__.py +28 -0
- saturn/adapters/__init__.py +63 -0
- saturn/adapters/_residency.py +196 -0
- saturn/adapters/decoder.py +1679 -0
- saturn/adapters/diffusion.py +438 -0
- saturn/adapters/flux1.py +661 -0
- saturn/adapters/flux2.py +630 -0
- saturn/adapters/mamba.py +620 -0
- saturn/adapters/qwen.py +637 -0
- saturn/causal.py +260 -0
- saturn/cli.py +382 -0
- saturn/contracts.py +175 -0
- saturn/core.py +1979 -0
- saturn/dependencies.py +61 -0
- saturn/interop/__init__.py +37 -0
- saturn/interop/circuit_tracer.py +1198 -0
- saturn/investigation.py +109 -0
- saturn/numerics.py +213 -0
- saturn/observers.py +289 -0
- saturn/paths.py +324 -0
- saturn/program.py +364 -0
- saturn/route.py +774 -0
- saturn/shared_store.py +257 -0
- saturn/store.py +835 -0
- saturn/symbols.py +398 -0
- saturn/training/__init__.py +61 -0
- saturn/training/_checkpoint.py +1618 -0
- saturn/trial.py +514 -0
- saturn/values.py +223 -0
- saturn/writers.py +82 -0
saturn/causal.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""Typed causal-path evidence linked to exact cuts and receipts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from types import MappingProxyType
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .core import Receipt, Session, StateCut
|
|
11
|
+
from .values import clone, describe, digest
|
|
12
|
+
|
|
13
|
+
_KINDS = frozenset(
|
|
14
|
+
{
|
|
15
|
+
"source",
|
|
16
|
+
"address",
|
|
17
|
+
"carrier",
|
|
18
|
+
"writer",
|
|
19
|
+
"consumer",
|
|
20
|
+
"first-divergence",
|
|
21
|
+
"repair",
|
|
22
|
+
"collateral",
|
|
23
|
+
"native-consumer",
|
|
24
|
+
}
|
|
25
|
+
)
|
|
26
|
+
_EFFECT_KINDS = ("first-divergence", "repair", "collateral", "native-consumer")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class PortObservation:
|
|
31
|
+
"""One raw observation at a declared causal port or effect plane."""
|
|
32
|
+
|
|
33
|
+
kind: str
|
|
34
|
+
port: str
|
|
35
|
+
value: Any
|
|
36
|
+
model_identity: str
|
|
37
|
+
parent: str
|
|
38
|
+
clock: Mapping[str, Any]
|
|
39
|
+
cut: str
|
|
40
|
+
receipt: str
|
|
41
|
+
note: str | None = None
|
|
42
|
+
fingerprint: str = field(init=False)
|
|
43
|
+
|
|
44
|
+
def __post_init__(self) -> None:
|
|
45
|
+
if self.kind not in _KINDS:
|
|
46
|
+
raise ValueError(f"unsupported causal observation kind: {self.kind}")
|
|
47
|
+
for label, value in (
|
|
48
|
+
("port", self.port),
|
|
49
|
+
("model_identity", self.model_identity),
|
|
50
|
+
("parent", self.parent),
|
|
51
|
+
("cut", self.cut),
|
|
52
|
+
("receipt", self.receipt),
|
|
53
|
+
):
|
|
54
|
+
if not isinstance(value, str) or not value:
|
|
55
|
+
raise ValueError(f"{label} must be a non-empty string")
|
|
56
|
+
clock = clone(dict(self.clock))
|
|
57
|
+
if not clock:
|
|
58
|
+
raise ValueError("clock must be a non-empty mapping")
|
|
59
|
+
object.__setattr__(self, "clock", MappingProxyType(clock))
|
|
60
|
+
object.__setattr__(self, "value", clone(self.value))
|
|
61
|
+
object.__setattr__(self, "fingerprint", digest(self._body()))
|
|
62
|
+
|
|
63
|
+
def _body(self) -> dict[str, Any]:
|
|
64
|
+
return {
|
|
65
|
+
"schema": "saturn-pub-port-observation-v1",
|
|
66
|
+
"kind": self.kind,
|
|
67
|
+
"port": self.port,
|
|
68
|
+
"value": describe(self.value),
|
|
69
|
+
"model_identity": self.model_identity,
|
|
70
|
+
"parent": self.parent,
|
|
71
|
+
"clock": dict(self.clock),
|
|
72
|
+
"cut": self.cut,
|
|
73
|
+
"receipt": self.receipt,
|
|
74
|
+
"note": self.note,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
def to_dict(self) -> dict[str, Any]:
|
|
78
|
+
return {**self._body(), "fingerprint": self.fingerprint}
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def record(
|
|
82
|
+
cls,
|
|
83
|
+
kind: str,
|
|
84
|
+
port: str,
|
|
85
|
+
value: Any,
|
|
86
|
+
session: Session,
|
|
87
|
+
receipt: Receipt,
|
|
88
|
+
*,
|
|
89
|
+
parent: str,
|
|
90
|
+
cut: StateCut | None = None,
|
|
91
|
+
) -> PortObservation:
|
|
92
|
+
"""Bind a live observation to the current exact cut and producing receipt."""
|
|
93
|
+
cut = session.capture(retain=False) if cut is None else cut
|
|
94
|
+
cut.verify()
|
|
95
|
+
if cut.model_identity != session.adapter.model_identity or dict(cut.execution) != dict(
|
|
96
|
+
session.adapter.execution
|
|
97
|
+
):
|
|
98
|
+
raise ValueError("observation cut belongs to another model or execution contract")
|
|
99
|
+
receipt_body = receipt.to_dict()
|
|
100
|
+
if receipt_body.get("result") != cut.fingerprint:
|
|
101
|
+
raise ValueError("observation cut is not the producing receipt result")
|
|
102
|
+
point = getattr(cut, "execution_point", None)
|
|
103
|
+
if point is None:
|
|
104
|
+
point = getattr(session.inspect(), "execution_point", {"boundary": cut.boundary})
|
|
105
|
+
return cls(
|
|
106
|
+
kind,
|
|
107
|
+
port,
|
|
108
|
+
value,
|
|
109
|
+
cut.model_identity,
|
|
110
|
+
parent,
|
|
111
|
+
point,
|
|
112
|
+
cut.fingerprint,
|
|
113
|
+
receipt.fingerprint,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class CausalPath:
|
|
119
|
+
"""An evidence graph over one model/root parent and declared clock support."""
|
|
120
|
+
|
|
121
|
+
source: str
|
|
122
|
+
address: str
|
|
123
|
+
carrier: str
|
|
124
|
+
writer: str
|
|
125
|
+
consumer: str
|
|
126
|
+
model_identity: str
|
|
127
|
+
parent: str
|
|
128
|
+
clocks: tuple[Mapping[str, Any], ...]
|
|
129
|
+
observations: tuple[PortObservation, ...] = ()
|
|
130
|
+
fingerprint: str = field(init=False)
|
|
131
|
+
|
|
132
|
+
def __post_init__(self) -> None:
|
|
133
|
+
for label in (
|
|
134
|
+
"source",
|
|
135
|
+
"address",
|
|
136
|
+
"carrier",
|
|
137
|
+
"writer",
|
|
138
|
+
"consumer",
|
|
139
|
+
"model_identity",
|
|
140
|
+
"parent",
|
|
141
|
+
):
|
|
142
|
+
if not getattr(self, label):
|
|
143
|
+
raise ValueError(f"{label} must be non-empty")
|
|
144
|
+
clocks = tuple(MappingProxyType(clone(dict(clock))) for clock in self.clocks)
|
|
145
|
+
if not clocks or any(not clock for clock in clocks):
|
|
146
|
+
raise ValueError("causal path requires at least one non-empty supported clock")
|
|
147
|
+
clock_ids = [digest(dict(clock)) for clock in clocks]
|
|
148
|
+
if len(set(clock_ids)) != len(clock_ids):
|
|
149
|
+
raise ValueError("supported clocks must be distinct")
|
|
150
|
+
object.__setattr__(self, "clocks", clocks)
|
|
151
|
+
for row in self.observations:
|
|
152
|
+
if row.model_identity != self.model_identity:
|
|
153
|
+
raise ValueError("observation model is outside causal-path support")
|
|
154
|
+
if row.parent != self.parent:
|
|
155
|
+
raise ValueError("observation parent is outside causal-path support")
|
|
156
|
+
if digest(dict(row.clock)) not in clock_ids:
|
|
157
|
+
raise ValueError("observation clock is outside causal-path support")
|
|
158
|
+
if row.kind in {"source", "address", "carrier", "writer", "consumer"}:
|
|
159
|
+
expected = getattr(self, row.kind)
|
|
160
|
+
if row.port != expected:
|
|
161
|
+
raise ValueError(f"{row.kind} observation is bound to an undeclared port")
|
|
162
|
+
divergence = [row for row in self.observations if row.kind == "first-divergence"]
|
|
163
|
+
if len(divergence) > 1:
|
|
164
|
+
raise ValueError("causal path can declare only one first divergence")
|
|
165
|
+
object.__setattr__(self, "fingerprint", digest(self._body()))
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def first_divergence(self) -> PortObservation | None:
|
|
169
|
+
return next((row for row in self.observations if row.kind == "first-divergence"), None)
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
def repair(self) -> tuple[PortObservation, ...]:
|
|
173
|
+
return tuple(row for row in self.observations if row.kind == "repair")
|
|
174
|
+
|
|
175
|
+
@property
|
|
176
|
+
def collateral(self) -> tuple[PortObservation, ...]:
|
|
177
|
+
return tuple(row for row in self.observations if row.kind == "collateral")
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def native_consumer(self) -> tuple[PortObservation, ...]:
|
|
181
|
+
return tuple(row for row in self.observations if row.kind == "native-consumer")
|
|
182
|
+
|
|
183
|
+
def with_observations(self, *rows: PortObservation) -> CausalPath:
|
|
184
|
+
return CausalPath(
|
|
185
|
+
self.source,
|
|
186
|
+
self.address,
|
|
187
|
+
self.carrier,
|
|
188
|
+
self.writer,
|
|
189
|
+
self.consumer,
|
|
190
|
+
self.model_identity,
|
|
191
|
+
self.parent,
|
|
192
|
+
self.clocks,
|
|
193
|
+
self.observations + tuple(rows),
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
def _body(self) -> dict[str, Any]:
|
|
197
|
+
return {
|
|
198
|
+
"schema": "saturn-pub-causal-path-v1",
|
|
199
|
+
"model_identity": self.model_identity,
|
|
200
|
+
"parent": self.parent,
|
|
201
|
+
"supported_clocks": [dict(clock) for clock in self.clocks],
|
|
202
|
+
"nodes": {
|
|
203
|
+
"source": self.source,
|
|
204
|
+
"address": self.address,
|
|
205
|
+
"writer": self.writer,
|
|
206
|
+
"carrier": self.carrier,
|
|
207
|
+
"consumer": self.consumer,
|
|
208
|
+
},
|
|
209
|
+
"edges": [
|
|
210
|
+
{"from": self.source, "to": self.address, "relation": "routes-to"},
|
|
211
|
+
{"from": self.address, "to": self.writer, "relation": "selects-writer"},
|
|
212
|
+
{"from": self.writer, "to": self.carrier, "relation": "writes"},
|
|
213
|
+
{"from": self.carrier, "to": self.consumer, "relation": "consumed-by"},
|
|
214
|
+
],
|
|
215
|
+
"observations": [row.to_dict() for row in self.observations],
|
|
216
|
+
"effects": {
|
|
217
|
+
kind: [row.fingerprint for row in self.observations if row.kind == kind]
|
|
218
|
+
for kind in _EFFECT_KINDS
|
|
219
|
+
},
|
|
220
|
+
"interpretation": "observations-only; no automatic scientific verdict",
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
def to_dict(self) -> dict[str, Any]:
|
|
224
|
+
return {**self._body(), "fingerprint": self.fingerprint}
|
|
225
|
+
|
|
226
|
+
@classmethod
|
|
227
|
+
def from_observations(
|
|
228
|
+
cls,
|
|
229
|
+
*,
|
|
230
|
+
source: str,
|
|
231
|
+
address: str,
|
|
232
|
+
carrier: str,
|
|
233
|
+
writer: str,
|
|
234
|
+
consumer: str,
|
|
235
|
+
observations: Sequence[PortObservation],
|
|
236
|
+
) -> CausalPath:
|
|
237
|
+
rows = tuple(observations)
|
|
238
|
+
if not rows:
|
|
239
|
+
raise ValueError("cannot infer causal-path support without observations")
|
|
240
|
+
clocks: list[Mapping[str, Any]] = []
|
|
241
|
+
seen: set[str] = set()
|
|
242
|
+
for row in rows:
|
|
243
|
+
identifier = digest(dict(row.clock))
|
|
244
|
+
if identifier not in seen:
|
|
245
|
+
clocks.append(row.clock)
|
|
246
|
+
seen.add(identifier)
|
|
247
|
+
return cls(
|
|
248
|
+
source,
|
|
249
|
+
address,
|
|
250
|
+
carrier,
|
|
251
|
+
writer,
|
|
252
|
+
consumer,
|
|
253
|
+
rows[0].model_identity,
|
|
254
|
+
rows[0].parent,
|
|
255
|
+
tuple(clocks),
|
|
256
|
+
rows,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
__all__ = ["CausalPath", "PortObservation"]
|
saturn/cli.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"""An in-process debugger; every operation delegates to the public Session API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import shlex
|
|
8
|
+
from fnmatch import fnmatchcase
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .core import Act, Session
|
|
12
|
+
from .observers import ObservationError, Observer, WatchEvent
|
|
13
|
+
from .paths import Trajectory, compare_trajectories
|
|
14
|
+
from .store import LocalStore
|
|
15
|
+
from .symbols import SymbolTable, backtrace, structural_symbols
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Debugger:
|
|
19
|
+
def __init__(self, session: Session):
|
|
20
|
+
self.branches = {"root": session}
|
|
21
|
+
self.active = "root"
|
|
22
|
+
self.cuts = {}
|
|
23
|
+
self.breakpoints: list[str] = []
|
|
24
|
+
self.observer = Observer(reader=self._read_observed)
|
|
25
|
+
self.watch_events: list[WatchEvent] = []
|
|
26
|
+
self.watch_errors: list[dict[str, Any]] = []
|
|
27
|
+
self.max_continue_steps = 1000
|
|
28
|
+
self.symbols = SymbolTable()
|
|
29
|
+
self.symbol_context = ""
|
|
30
|
+
self.trajectories: dict[str, Trajectory] = {}
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def session(self) -> Session:
|
|
34
|
+
return self.branches[self.active]
|
|
35
|
+
|
|
36
|
+
def _read_observed(self, session: Session, address: str) -> Any:
|
|
37
|
+
if address.startswith("symbol:"):
|
|
38
|
+
binding = self.symbols.resolve(session, address[7:], context=self.symbol_context)
|
|
39
|
+
return tuple(session.read_port(location) for location in binding.locations)
|
|
40
|
+
return session.read(address)
|
|
41
|
+
|
|
42
|
+
def _frame(self) -> dict[str, Any]:
|
|
43
|
+
frame = self.session.inspect()
|
|
44
|
+
result = {"branch": self.active, "boundary": frame.boundary, "slots": dict(frame.slots)}
|
|
45
|
+
point = getattr(frame, "execution_point", None)
|
|
46
|
+
surface = getattr(frame, "surface", None)
|
|
47
|
+
if point is not None:
|
|
48
|
+
result["execution_point"] = dict(point)
|
|
49
|
+
if surface is not None:
|
|
50
|
+
result["surface"] = dict(surface)
|
|
51
|
+
return result
|
|
52
|
+
|
|
53
|
+
def _observe(self, receipt: Any) -> tuple[WatchEvent, ...]:
|
|
54
|
+
try:
|
|
55
|
+
events = self.observer.evaluate(self.session, self.active, receipt=receipt)
|
|
56
|
+
except ObservationError as exc:
|
|
57
|
+
self.cuts[exc.cut.fingerprint] = exc.cut
|
|
58
|
+
self.watch_events.extend(exc.events)
|
|
59
|
+
self.watch_errors.append(
|
|
60
|
+
{
|
|
61
|
+
"branch": self.active,
|
|
62
|
+
"cut": exc.cut.fingerprint,
|
|
63
|
+
"receipt": receipt.fingerprint,
|
|
64
|
+
"errors": list(exc.errors),
|
|
65
|
+
}
|
|
66
|
+
)
|
|
67
|
+
raise
|
|
68
|
+
for event in events:
|
|
69
|
+
self.cuts[event.cut.fingerprint] = event.cut
|
|
70
|
+
self.watch_events.extend(events)
|
|
71
|
+
return events
|
|
72
|
+
|
|
73
|
+
def _step(self) -> Any:
|
|
74
|
+
step = getattr(self.session, "step", None)
|
|
75
|
+
return step() if step is not None else self.session.continue_()
|
|
76
|
+
|
|
77
|
+
def advance(
|
|
78
|
+
self,
|
|
79
|
+
steps: int = 1,
|
|
80
|
+
*,
|
|
81
|
+
patterns: list[str] | None = None,
|
|
82
|
+
stop_on_breakpoint: bool = False,
|
|
83
|
+
trace: bool = False,
|
|
84
|
+
) -> dict[str, Any]:
|
|
85
|
+
"""Advance one micro-transition at a time so watches see every safe point."""
|
|
86
|
+
if isinstance(steps, bool) or not isinstance(steps, int) or steps < 1:
|
|
87
|
+
raise ValueError("continue limit must be positive")
|
|
88
|
+
patterns = patterns or []
|
|
89
|
+
rows = []
|
|
90
|
+
receipts = []
|
|
91
|
+
for completed in range(1, steps + 1):
|
|
92
|
+
receipt = self._step()
|
|
93
|
+
receipts.append(receipt.to_dict())
|
|
94
|
+
events = self._observe(receipt)
|
|
95
|
+
frame = self._frame()
|
|
96
|
+
if trace:
|
|
97
|
+
rows.append(
|
|
98
|
+
{
|
|
99
|
+
"step": completed,
|
|
100
|
+
"frame": frame,
|
|
101
|
+
"receipt": receipt.to_dict(),
|
|
102
|
+
"watch_events": [event.to_dict() for event in events],
|
|
103
|
+
}
|
|
104
|
+
)
|
|
105
|
+
if events:
|
|
106
|
+
return {
|
|
107
|
+
"stop": "watchpoint",
|
|
108
|
+
"steps": completed,
|
|
109
|
+
"events": [event.to_dict() for event in events],
|
|
110
|
+
"frame": frame,
|
|
111
|
+
"receipts": receipts,
|
|
112
|
+
**({"trace": rows} if trace else {}),
|
|
113
|
+
}
|
|
114
|
+
matches = [pattern for pattern in patterns if fnmatchcase(frame["boundary"], pattern)]
|
|
115
|
+
if matches and stop_on_breakpoint:
|
|
116
|
+
return {
|
|
117
|
+
"stop": "breakpoint",
|
|
118
|
+
"steps": completed,
|
|
119
|
+
"matched": matches,
|
|
120
|
+
"frame": frame,
|
|
121
|
+
"receipts": receipts,
|
|
122
|
+
**({"trace": rows} if trace else {}),
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
"stop": "step-limit",
|
|
126
|
+
"steps": steps,
|
|
127
|
+
"frame": self._frame(),
|
|
128
|
+
"receipts": receipts,
|
|
129
|
+
**({"trace": rows} if trace else {}),
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
def _until(self, patterns: list[str], limit: int) -> dict[str, Any]:
|
|
133
|
+
# Advance first: continuing from a breakpoint must make forward progress.
|
|
134
|
+
return self.advance(limit, patterns=patterns, stop_on_breakpoint=True)
|
|
135
|
+
|
|
136
|
+
def execute(self, line: str) -> Any:
|
|
137
|
+
args = shlex.split(line)
|
|
138
|
+
if not args:
|
|
139
|
+
return None
|
|
140
|
+
command, *rest = args
|
|
141
|
+
if command == "info" and rest == ["steps"]:
|
|
142
|
+
cut = self.session.capture(retain=False)
|
|
143
|
+
_, state, _ = self.session._cut_state(cut)
|
|
144
|
+
return {
|
|
145
|
+
"point": dict(cut.execution_point or {}),
|
|
146
|
+
"next_transition": self.session.adapter.transition(state).to_dict(),
|
|
147
|
+
}
|
|
148
|
+
if command == "info" and rest == ["symbols"]:
|
|
149
|
+
return {
|
|
150
|
+
"structural": structural_symbols(self.session),
|
|
151
|
+
"qualified": [row.to_dict() for row in self.symbols.bindings],
|
|
152
|
+
}
|
|
153
|
+
if command == "resolve" and len(rest) == 1:
|
|
154
|
+
binding = self.symbols.resolve(self.session, rest[0], context=self.symbol_context)
|
|
155
|
+
return binding.to_dict()
|
|
156
|
+
if command == "backtrace" and len(rest) == 1:
|
|
157
|
+
if rest[0].startswith("symbol:"):
|
|
158
|
+
binding = self.symbols.resolve(
|
|
159
|
+
self.session, rest[0][7:], context=self.symbol_context
|
|
160
|
+
)
|
|
161
|
+
return {
|
|
162
|
+
"binding": binding.to_dict(),
|
|
163
|
+
"provenance": [backtrace(self.session, loc.slot) for loc in binding.locations],
|
|
164
|
+
"granularity": "slot-level-dependencies",
|
|
165
|
+
}
|
|
166
|
+
return backtrace(self.session, rest[0])
|
|
167
|
+
if command == "diff" and len(rest) == 3 and rest[2] == "--first-divergence":
|
|
168
|
+
return compare_trajectories(self.trajectories[rest[0]], self.trajectories[rest[1]])
|
|
169
|
+
if command in ("inspect", "where") and not rest:
|
|
170
|
+
return self._frame()
|
|
171
|
+
if command == "read" and len(rest) == 1:
|
|
172
|
+
if rest[0].startswith("symbol:"):
|
|
173
|
+
from .values import describe
|
|
174
|
+
|
|
175
|
+
return describe(self._read_observed(self.session, rest[0]))
|
|
176
|
+
value = self.session.read(rest[0])
|
|
177
|
+
return value.tolist() if hasattr(value, "tolist") else value
|
|
178
|
+
if command == "break" and len(rest) == 1:
|
|
179
|
+
if rest[0] not in self.breakpoints:
|
|
180
|
+
self.breakpoints.append(rest[0])
|
|
181
|
+
return {"breakpoints": list(self.breakpoints)}
|
|
182
|
+
if command == "breakpoints" and not rest:
|
|
183
|
+
return {"breakpoints": list(self.breakpoints)}
|
|
184
|
+
if command == "delete" and len(rest) == 1:
|
|
185
|
+
if rest[0] == "all":
|
|
186
|
+
self.breakpoints.clear()
|
|
187
|
+
else:
|
|
188
|
+
self.breakpoints.remove(rest[0])
|
|
189
|
+
return {"breakpoints": list(self.breakpoints)}
|
|
190
|
+
if command == "until" and len(rest) in (1, 2):
|
|
191
|
+
return self._until(
|
|
192
|
+
[rest[0]], int(rest[1]) if len(rest) == 2 else self.max_continue_steps
|
|
193
|
+
)
|
|
194
|
+
if command == "continue" and not rest and self.breakpoints:
|
|
195
|
+
return self._until(self.breakpoints, self.max_continue_steps)
|
|
196
|
+
if command == "continue" and not rest and self.observer.watchpoints:
|
|
197
|
+
return self.advance(self.max_continue_steps)
|
|
198
|
+
if command in ("step", "next", "continue") and len(rest) <= 1:
|
|
199
|
+
steps = int(rest[0]) if rest else 1
|
|
200
|
+
# An explicit budget preserves the legacy exact-N breakpoint behavior. Watches
|
|
201
|
+
# still stop at a retained safe point; bare continue handles installed breaks above.
|
|
202
|
+
return self.advance(steps)
|
|
203
|
+
if command == "trace" and len(rest) <= 1:
|
|
204
|
+
return self.advance(int(rest[0]) if rest else 1, trace=True)
|
|
205
|
+
if command == "watch" and len(rest) in (2, 3):
|
|
206
|
+
threshold = float(rest[2]) if len(rest) == 3 else None
|
|
207
|
+
watch = self.observer.add(rest[0], rest[1], threshold)
|
|
208
|
+
# Establish change-watch semantics at the command's current branch and safe point.
|
|
209
|
+
try:
|
|
210
|
+
self.observer.sync(self.session, self.active)
|
|
211
|
+
except Exception:
|
|
212
|
+
self.observer.remove(watch.identifier)
|
|
213
|
+
raise
|
|
214
|
+
return watch.to_dict()
|
|
215
|
+
if command == "watchpoints" and not rest:
|
|
216
|
+
return {"watchpoints": [watch.to_dict() for watch in self.observer.watchpoints]}
|
|
217
|
+
if command == "unwatch" and len(rest) == 1:
|
|
218
|
+
if rest[0] == "all":
|
|
219
|
+
self.observer.clear()
|
|
220
|
+
else:
|
|
221
|
+
self.observer.remove(rest[0])
|
|
222
|
+
return {"watchpoints": [watch.to_dict() for watch in self.observer.watchpoints]}
|
|
223
|
+
if command == "capture" and len(rest) == 1:
|
|
224
|
+
self.cuts[rest[0]] = self.session.capture()
|
|
225
|
+
return {"cut": rest[0], "fingerprint": self.cuts[rest[0]].fingerprint}
|
|
226
|
+
if command == "fork" and len(rest) in (1, 2):
|
|
227
|
+
if rest[0] in self.branches:
|
|
228
|
+
raise ValueError("branch name already exists")
|
|
229
|
+
self.branches[rest[0]] = self.session.fork(
|
|
230
|
+
self.cuts[rest[1]] if len(rest) == 2 else None
|
|
231
|
+
)
|
|
232
|
+
return {"branch": rest[0]}
|
|
233
|
+
if command == "use" and len(rest) == 1:
|
|
234
|
+
if rest[0] not in self.branches:
|
|
235
|
+
raise ValueError("unknown branch")
|
|
236
|
+
self.active = rest[0]
|
|
237
|
+
# A new branch gets a baseline at its selected cursor. Existing branches retain theirs.
|
|
238
|
+
if not self.observer.has_baseline(self.active):
|
|
239
|
+
self.observer.sync(self.session, self.active)
|
|
240
|
+
return {"active": self.active}
|
|
241
|
+
if command == "zero" and len(rest) == 1:
|
|
242
|
+
receipt = self.session.apply(Act.zero(rest[0]))
|
|
243
|
+
events = self._observe(receipt)
|
|
244
|
+
result = receipt.to_dict()
|
|
245
|
+
if events:
|
|
246
|
+
result["watch_events"] = [event.to_dict() for event in events]
|
|
247
|
+
return result
|
|
248
|
+
if command in ("add", "replace") and len(rest) == 2:
|
|
249
|
+
value = json.loads(rest[1])
|
|
250
|
+
current = self.session.read(rest[0])
|
|
251
|
+
if hasattr(current, "shape"):
|
|
252
|
+
import torch
|
|
253
|
+
|
|
254
|
+
value = torch.as_tensor(value, device=current.device, dtype=current.dtype)
|
|
255
|
+
if command == "add" and value.ndim == 0:
|
|
256
|
+
value = torch.ones_like(current) * value
|
|
257
|
+
act = Act.add(rest[0], value) if command == "add" else Act.replace(rest[0], value)
|
|
258
|
+
receipt = self.session.apply(act)
|
|
259
|
+
events = self._observe(receipt)
|
|
260
|
+
result = receipt.to_dict()
|
|
261
|
+
if events:
|
|
262
|
+
result["watch_events"] = [event.to_dict() for event in events]
|
|
263
|
+
return result
|
|
264
|
+
if command == "restore" and len(rest) == 1:
|
|
265
|
+
result = self.session.restore(self.cuts[rest[0]]).to_dict()
|
|
266
|
+
self.observer.sync(self.session, self.active)
|
|
267
|
+
return result
|
|
268
|
+
if command in ("compare", "diff") and len(rest) == 1:
|
|
269
|
+
if rest[0] in self.branches:
|
|
270
|
+
other = self.branches[rest[0]]
|
|
271
|
+
elif rest[0] in self.cuts:
|
|
272
|
+
other = self.session.fork(self.cuts[rest[0]])
|
|
273
|
+
else:
|
|
274
|
+
raise ValueError("unknown branch or cut")
|
|
275
|
+
return self.session.compare(other)
|
|
276
|
+
if command == "replay" and 1 <= len(rest) <= 3:
|
|
277
|
+
cut_name = rest[0]
|
|
278
|
+
steps = int(rest[1]) if len(rest) >= 2 else 1
|
|
279
|
+
name = rest[2] if len(rest) == 3 else f"replay-{len(self.branches)}"
|
|
280
|
+
if name in self.branches:
|
|
281
|
+
raise ValueError("branch name already exists")
|
|
282
|
+
replay = getattr(self.session, "replay", None)
|
|
283
|
+
branch = (
|
|
284
|
+
replay(self.cuts[cut_name], steps=steps)
|
|
285
|
+
if replay
|
|
286
|
+
else self.session.fork(self.cuts[cut_name])
|
|
287
|
+
)
|
|
288
|
+
if replay is None:
|
|
289
|
+
branch.continue_(steps)
|
|
290
|
+
self.branches[name] = branch
|
|
291
|
+
return {"branch": name, "steps": steps, "frame": self._frame_for(name)}
|
|
292
|
+
if command == "commit" and len(rest) == 1:
|
|
293
|
+
return self.session.commit(self.branches[rest[0]]).to_dict()
|
|
294
|
+
if command == "abort" and len(rest) == 1:
|
|
295
|
+
return self.session.abort(self.branches[rest[0]]).to_dict()
|
|
296
|
+
if command == "save" and len(rest) == 2:
|
|
297
|
+
return {"saved": LocalStore(rest[0]).save(self.cuts[rest[1]])}
|
|
298
|
+
if command == "load" and len(rest) == 3:
|
|
299
|
+
device = getattr(self.session.adapter, "device", None)
|
|
300
|
+
cut = (
|
|
301
|
+
LocalStore(rest[0]).load(rest[1], device=str(device))
|
|
302
|
+
if device is not None
|
|
303
|
+
else LocalStore(rest[0]).load(rest[1])
|
|
304
|
+
)
|
|
305
|
+
self.session._compatible(cut)
|
|
306
|
+
self.cuts[rest[2]] = cut
|
|
307
|
+
return {"cut": rest[2], "fingerprint": cut.fingerprint}
|
|
308
|
+
if command == "help":
|
|
309
|
+
return (
|
|
310
|
+
"inspect / where | read ADDRESS | step / next [N] | break BOUNDARY_PATTERN | "
|
|
311
|
+
"info steps / symbols | resolve SYMBOL | backtrace SLOT | "
|
|
312
|
+
"breakpoints | delete PATTERN / all | continue [N] | until PATTERN [MAX_STEPS] | "
|
|
313
|
+
"watch ADDRESS change / nonfinite | watch ADDRESS gt / lt THRESHOLD | "
|
|
314
|
+
"watchpoints | unwatch ID / all | trace [N] | capture NAME | fork BRANCH [CUT] | "
|
|
315
|
+
"use BRANCH | zero ADDRESS | add ADDRESS JSON | replace ADDRESS JSON | "
|
|
316
|
+
"compare / diff BRANCH_OR_CUT | replay CUT [STEPS] [BRANCH] | commit BRANCH | "
|
|
317
|
+
"diff NATIVE_TRACE CANDIDATE_TRACE --first-divergence | "
|
|
318
|
+
"abort BRANCH | restore CUT | save DIRECTORY CUT | load DIRECTORY DIGEST NAME | quit"
|
|
319
|
+
)
|
|
320
|
+
raise ValueError("unknown command or wrong arguments; use help")
|
|
321
|
+
|
|
322
|
+
def _frame_for(self, branch: str) -> dict[str, Any]:
|
|
323
|
+
active = self.active
|
|
324
|
+
self.active = branch
|
|
325
|
+
try:
|
|
326
|
+
return self._frame()
|
|
327
|
+
finally:
|
|
328
|
+
self.active = active
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def main(argv: list[str] | None = None) -> int:
|
|
332
|
+
parser = argparse.ArgumentParser(description="Inspect, branch, and replay native model state")
|
|
333
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
334
|
+
debug = sub.add_parser("debug", help="start an offline in-process model debugger")
|
|
335
|
+
debug.add_argument("--family", choices=("ar", "diffusion"), default="ar")
|
|
336
|
+
debug.add_argument("--script", help="read debugger commands from a text file")
|
|
337
|
+
inspect = sub.add_parser("inspect", help="verify a saved metadata descriptor without torch")
|
|
338
|
+
inspect.add_argument("directory")
|
|
339
|
+
inspect.add_argument("digest")
|
|
340
|
+
route = sub.add_parser("route", help="offline metadata-delta route: validate | select | show")
|
|
341
|
+
route.add_argument("route_args", nargs=argparse.REMAINDER)
|
|
342
|
+
args = parser.parse_args(argv)
|
|
343
|
+
if args.command == "route":
|
|
344
|
+
from .route import main as route_main
|
|
345
|
+
|
|
346
|
+
return route_main(args.route_args)
|
|
347
|
+
if args.command == "inspect":
|
|
348
|
+
print(json.dumps(LocalStore(args.directory).inspect(args.digest), indent=2))
|
|
349
|
+
return 0
|
|
350
|
+
if args.family == "ar":
|
|
351
|
+
from .adapters.qwen import QwenAdapter
|
|
352
|
+
|
|
353
|
+
session = QwenAdapter.tiny().session([5, 7, 11])
|
|
354
|
+
else:
|
|
355
|
+
from .adapters.diffusion import DiffusionAdapter
|
|
356
|
+
|
|
357
|
+
session = DiffusionAdapter.tiny().session()
|
|
358
|
+
debugger = Debugger(session)
|
|
359
|
+
if args.script:
|
|
360
|
+
from pathlib import Path
|
|
361
|
+
|
|
362
|
+
for line in Path(args.script).read_text().splitlines():
|
|
363
|
+
if line.strip() in ("quit", "exit"):
|
|
364
|
+
break
|
|
365
|
+
print(json.dumps(debugger.execute(line), indent=2))
|
|
366
|
+
return 0
|
|
367
|
+
print("Saturn local debugger. Random offline model. Type help or quit.")
|
|
368
|
+
while True:
|
|
369
|
+
try:
|
|
370
|
+
line = input(f"{debugger.active}> ")
|
|
371
|
+
if line.strip() in ("quit", "exit"):
|
|
372
|
+
return 0
|
|
373
|
+
print(json.dumps(debugger.execute(line), indent=2))
|
|
374
|
+
except (EOFError, KeyboardInterrupt):
|
|
375
|
+
print()
|
|
376
|
+
return 0
|
|
377
|
+
except Exception as exc:
|
|
378
|
+
print(f"{type(exc).__name__}: {exc}")
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
if __name__ == "__main__":
|
|
382
|
+
raise SystemExit(main())
|