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/investigation.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Same-parent causal panels. Measurements stay separate from certification."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .core import Act, Session, StateCut
|
|
10
|
+
from .values import describe, digest
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Arm:
|
|
15
|
+
name: str
|
|
16
|
+
acts: tuple[Act, ...] = ()
|
|
17
|
+
role: str = "candidate"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Investigation:
|
|
22
|
+
question: str
|
|
23
|
+
arms: tuple[Arm, ...]
|
|
24
|
+
steps: int
|
|
25
|
+
|
|
26
|
+
def __post_init__(self) -> None:
|
|
27
|
+
names = [arm.name for arm in self.arms]
|
|
28
|
+
if not self.question or len(set(names)) != len(names) or not self.arms or self.steps < 1:
|
|
29
|
+
raise ValueError("question, distinct arms, and a positive continuation budget required")
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def fingerprint(self) -> str:
|
|
33
|
+
return digest(
|
|
34
|
+
{
|
|
35
|
+
"question": self.question,
|
|
36
|
+
"steps": self.steps,
|
|
37
|
+
"arms": [
|
|
38
|
+
{
|
|
39
|
+
"name": arm.name,
|
|
40
|
+
"role": arm.role,
|
|
41
|
+
"acts": [act.manifest() for act in arm.acts],
|
|
42
|
+
}
|
|
43
|
+
for arm in self.arms
|
|
44
|
+
],
|
|
45
|
+
}
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def doses(
|
|
50
|
+
cls, question: str, address: str, payload: Any, doses: Sequence[float], *, steps: int
|
|
51
|
+
) -> Investigation:
|
|
52
|
+
arms = [Arm("native", role="native")]
|
|
53
|
+
for index, dose in enumerate(doses):
|
|
54
|
+
arms.append(
|
|
55
|
+
Arm(
|
|
56
|
+
f"dose-{index}:{dose}",
|
|
57
|
+
(Act.add(address, payload, dose=dose),),
|
|
58
|
+
"no-op" if dose == 0 else "candidate",
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
return cls(question, tuple(arms), steps)
|
|
62
|
+
|
|
63
|
+
def run(
|
|
64
|
+
self,
|
|
65
|
+
session: Session,
|
|
66
|
+
evaluator: Callable[[Session], Mapping[str, Any]],
|
|
67
|
+
*,
|
|
68
|
+
parent: StateCut | None = None,
|
|
69
|
+
) -> dict[str, Any]:
|
|
70
|
+
cut = parent or session.capture()
|
|
71
|
+
rows = []
|
|
72
|
+
for arm in self.arms:
|
|
73
|
+
branch = session.fork(cut)
|
|
74
|
+
try:
|
|
75
|
+
for act in arm.acts:
|
|
76
|
+
branch.apply(act)
|
|
77
|
+
branch.continue_(self.steps)
|
|
78
|
+
# Evaluate a private child so evaluators cannot mutate the measured branch.
|
|
79
|
+
metrics = dict(evaluator(branch.fork()))
|
|
80
|
+
row = {
|
|
81
|
+
"name": arm.name,
|
|
82
|
+
"role": arm.role,
|
|
83
|
+
"status": "completed",
|
|
84
|
+
"metrics": metrics,
|
|
85
|
+
"output": describe(branch.capture().payload),
|
|
86
|
+
"receipts": [r.to_dict() for r in branch.receipts],
|
|
87
|
+
}
|
|
88
|
+
except Exception as exc:
|
|
89
|
+
row = {
|
|
90
|
+
"name": arm.name,
|
|
91
|
+
"role": arm.role,
|
|
92
|
+
"status": "instrument-error",
|
|
93
|
+
"error": f"{type(exc).__name__}: {exc}",
|
|
94
|
+
"receipts": [r.to_dict() for r in branch.receipts],
|
|
95
|
+
}
|
|
96
|
+
rows.append(row)
|
|
97
|
+
return {
|
|
98
|
+
"schema": "saturn-pub-investigation-v1",
|
|
99
|
+
"question": self.question,
|
|
100
|
+
"plan": self.fingerprint,
|
|
101
|
+
"parent": cut.fingerprint,
|
|
102
|
+
"rows": rows,
|
|
103
|
+
"terminal_status": "not-assessed",
|
|
104
|
+
"independent_specimens": 1,
|
|
105
|
+
"logical_arms": len(self.arms),
|
|
106
|
+
"continuation_steps": self.steps,
|
|
107
|
+
"budget_unit": "adapter-transition",
|
|
108
|
+
"model_loads": 1,
|
|
109
|
+
}
|
saturn/numerics.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""The live numerical environment an adapter binds into ``execution["numeric_scope"]``.
|
|
2
|
+
|
|
3
|
+
Every field here is a process-wide torch setting that can change native results bit for bit, so
|
|
4
|
+
a StateCut fingerprint binds it (through the adapter's ``execution``) and ``validate_execution``
|
|
5
|
+
refuses, naming the field, when the live value drifts from the bound one.
|
|
6
|
+
|
|
7
|
+
``bf16_reduced_precision_reduction`` / ``fp16_reduced_precision_reduction`` are
|
|
8
|
+
``torch.backends.cuda.matmul.allow_{bf16,fp16}_reduced_precision_reduction``: when true (the
|
|
9
|
+
torch default) cuBLAS may accumulate bf16/fp16 matmuls in reduced precision (split-K partial
|
|
10
|
+
sums rounded to the input dtype), so a ``bound`` that assumes float32 accumulation does not
|
|
11
|
+
hold. On a torch build without the attribute the field is the string ``"absent"``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import math
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
REDUCED_PRECISION_FIELDS = (
|
|
21
|
+
"bf16_reduced_precision_reduction",
|
|
22
|
+
"fp16_reduced_precision_reduction",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _flag(value: Any) -> Any:
|
|
27
|
+
"""A JSON-stable rendering of a backend flag (some torch builds return a tuple)."""
|
|
28
|
+
if isinstance(value, bool):
|
|
29
|
+
return value
|
|
30
|
+
if isinstance(value, (tuple, list)):
|
|
31
|
+
return [_flag(item) for item in value]
|
|
32
|
+
if isinstance(value, int):
|
|
33
|
+
return bool(value)
|
|
34
|
+
return str(value)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _matmul_flag(name: str) -> Any:
|
|
38
|
+
import torch
|
|
39
|
+
|
|
40
|
+
matmul = getattr(getattr(torch.backends, "cuda", None), "matmul", None)
|
|
41
|
+
try:
|
|
42
|
+
value = getattr(matmul, name)
|
|
43
|
+
except (AttributeError, RuntimeError):
|
|
44
|
+
return "absent"
|
|
45
|
+
return _flag(value)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def live_numeric_environment() -> dict[str, Any]:
|
|
49
|
+
"""The drift-checked fields of a numeric scope, read from the live torch globals."""
|
|
50
|
+
import torch
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
"tf32_matmul": bool(torch.backends.cuda.matmul.allow_tf32),
|
|
54
|
+
"torch_num_threads": torch.get_num_threads(),
|
|
55
|
+
"deterministic_algorithms": torch.are_deterministic_algorithms_enabled(),
|
|
56
|
+
"float32_matmul_precision": torch.get_float32_matmul_precision(),
|
|
57
|
+
"bf16_reduced_precision_reduction": _matmul_flag(
|
|
58
|
+
"allow_bf16_reduced_precision_reduction"
|
|
59
|
+
),
|
|
60
|
+
"fp16_reduced_precision_reduction": _matmul_flag(
|
|
61
|
+
"allow_fp16_reduced_precision_reduction"
|
|
62
|
+
),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def numeric_scope(**constants: Any) -> dict[str, Any]:
|
|
67
|
+
"""An adapter's ``numeric_scope``: its declared constants plus the live environment."""
|
|
68
|
+
return {**constants, **live_numeric_environment()}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def scope_difference(recorded: Mapping[str, Any], current: Mapping[str, Any]) -> list[str]:
|
|
72
|
+
"""``name: recorded R, current C`` for every field whose value differs (sorted by name)."""
|
|
73
|
+
names = sorted(set(recorded) | set(current))
|
|
74
|
+
return [
|
|
75
|
+
f"{name}: recorded {recorded.get(name, 'missing')!r}, current {current.get(name, 'missing')!r}"
|
|
76
|
+
for name in names
|
|
77
|
+
if recorded.get(name, "missing") != current.get(name, "missing")
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def check_numeric_environment(expected: Mapping[str, Any]) -> None:
|
|
82
|
+
"""Refuse when a live field differs from ``expected`` (the bound scope), naming the field."""
|
|
83
|
+
live = live_numeric_environment()
|
|
84
|
+
differing = scope_difference(
|
|
85
|
+
{name: expected.get(name, "missing") for name in live}, live
|
|
86
|
+
)
|
|
87
|
+
if differing:
|
|
88
|
+
raise ValueError(
|
|
89
|
+
"live numerical environment drifted from the execution ABI ("
|
|
90
|
+
+ "; ".join(differing)
|
|
91
|
+
+ "); rewrap"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
MEASURE_ROWS = (1, 16) # token rows per stage: a decode step and a short prefill
|
|
96
|
+
MEASURE_LAYERS = 3 # first, middle, last
|
|
97
|
+
MEASURE_CHUNK = 4096 # output rows of the float32 reference cast at once
|
|
98
|
+
SUPPORTED_SCALED = 2.0 # largest deviation (eps x sum|terms| units) the premise accepts
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _ulp_index(value: Any) -> Any:
|
|
102
|
+
"""Monotone integer index of 16-bit floats (adjacent representable values differ by 1)."""
|
|
103
|
+
import torch
|
|
104
|
+
|
|
105
|
+
bits = value.view(torch.int16).to(torch.int32)
|
|
106
|
+
return torch.where(bits < 0, -(bits & 0x7FFF), bits)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _stage_deviation(module: Any, rows: int, generator: Any) -> tuple[int, float]:
|
|
110
|
+
"""``(ulps, scaled)`` of ``module(x)`` natively against the float32 accumulate-then-round
|
|
111
|
+
reference, on ``rows`` standard-normal rows (batch 1): the largest ulp-index distance
|
|
112
|
+
(informational: near a cancellation it is huge for a tiny absolute gap) and the largest
|
|
113
|
+
``|native - ref| / (eps S)`` with ``S = sum |terms|`` (+ ``|bias|``), the unit the rounding
|
|
114
|
+
bounds are written in. ``x`` is cast to float32 once, the weight one block of output rows
|
|
115
|
+
at a time (nothing wider than a block is kept)."""
|
|
116
|
+
import torch
|
|
117
|
+
import torch.nn.functional as F
|
|
118
|
+
|
|
119
|
+
weight, bias = module.weight, module.bias
|
|
120
|
+
eps = float(torch.finfo(weight.dtype).eps)
|
|
121
|
+
tiny = float(torch.finfo(torch.float32).tiny)
|
|
122
|
+
x = torch.randn(1, rows, weight.shape[1], generator=generator).to(
|
|
123
|
+
device=weight.device, dtype=weight.dtype)
|
|
124
|
+
with torch.no_grad():
|
|
125
|
+
native = module(x)
|
|
126
|
+
wide = x.float()
|
|
127
|
+
magnitude = wide.abs()
|
|
128
|
+
ulps, scaled = 0, 0.0
|
|
129
|
+
for start in range(0, int(weight.shape[0]), MEASURE_CHUNK):
|
|
130
|
+
stop = start + MEASURE_CHUNK
|
|
131
|
+
block, bblock = weight[start:stop].float(), (
|
|
132
|
+
None if bias is None else bias[start:stop].float())
|
|
133
|
+
got = native[..., start:stop]
|
|
134
|
+
if not bool(torch.isfinite(got.float()).all()):
|
|
135
|
+
return 1 << 20, float("inf")
|
|
136
|
+
ref = F.linear(wide, block, bblock).to(weight.dtype)
|
|
137
|
+
size = F.linear(magnitude, block.abs(), None if bblock is None else bblock.abs())
|
|
138
|
+
gap = (got.float() - ref.float()).abs()
|
|
139
|
+
scaled = max(scaled, float((gap / (eps * size.clamp_min(tiny))).max()))
|
|
140
|
+
ulps = max(ulps, int((_ulp_index(got) - _ulp_index(ref)).abs().max()))
|
|
141
|
+
del block, bblock, ref, size, gap
|
|
142
|
+
return ulps, scaled
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def measure_accumulation(layer_modules: Any, head: Any = None) -> dict[str, Any]:
|
|
146
|
+
"""Whether native 16-bit linear stages equal "accumulate in float32, round once", measured
|
|
147
|
+
on this device at batch 1: the first, middle and last layer's ``nn.Linear`` of each type, plus
|
|
148
|
+
``head``, each recomputed on ``MEASURE_ROWS`` token rows and compared in ulps. Inputs are
|
|
149
|
+
seeded standard-normal rows (not the run's activations). Supported when the largest
|
|
150
|
+
deviation (``max_deviation_milli`` / 1000, in ``eps x sum|terms|``) is at most
|
|
151
|
+
``SUPPORTED_SCALED``; it is the premise's measured widening."""
|
|
152
|
+
import torch
|
|
153
|
+
|
|
154
|
+
generator = torch.Generator().manual_seed(0)
|
|
155
|
+
count = len(layer_modules)
|
|
156
|
+
picks = sorted({0, count // 2, count - 1})[:MEASURE_LAYERS]
|
|
157
|
+
stages: list[Any] = []
|
|
158
|
+
for index in picks:
|
|
159
|
+
seen: set[str] = set()
|
|
160
|
+
for name, module in layer_modules[index].named_modules():
|
|
161
|
+
leaf = name.rsplit(".", 1)[-1]
|
|
162
|
+
if isinstance(module, torch.nn.Linear) and leaf not in seen:
|
|
163
|
+
seen.add(leaf)
|
|
164
|
+
stages.append((leaf, module))
|
|
165
|
+
if isinstance(head, torch.nn.Linear):
|
|
166
|
+
stages.append(("lm_head", head))
|
|
167
|
+
by_type: dict[str, float] = {}
|
|
168
|
+
by_ulp: dict[str, int] = {}
|
|
169
|
+
for leaf, module in stages:
|
|
170
|
+
for rows in MEASURE_ROWS:
|
|
171
|
+
ulps, scaled = _stage_deviation(module, rows, generator)
|
|
172
|
+
by_type[leaf] = max(by_type.get(leaf, 0.0), scaled)
|
|
173
|
+
by_ulp[leaf] = max(by_ulp.get(leaf, 0), ulps)
|
|
174
|
+
by_milli = {k: math.ceil(v * 1000.0) if math.isfinite(v) else 1 << 30 for k, v in by_type.items()}
|
|
175
|
+
worst = max(by_milli.values(), default=0)
|
|
176
|
+
first = stages[0][1] if stages else None
|
|
177
|
+
return {
|
|
178
|
+
"premise": "fp32-then-round" if stages and worst <= 1000 * SUPPORTED_SCALED else "unsupported",
|
|
179
|
+
"device": str(first.weight.device.type) if first is not None else "none",
|
|
180
|
+
"dtype": str(first.weight.dtype) if first is not None else "none",
|
|
181
|
+
"batch": 1, "rows": list(MEASURE_ROWS), "stages": len(stages) * len(MEASURE_ROWS),
|
|
182
|
+
"unit": "milli eps x sum|terms| (1000 |native - fp32-then-round| / (eps sum|terms|), "
|
|
183
|
+
"rounded up; integers because a numeric scope holds no bare floats)",
|
|
184
|
+
"max_deviation_milli": worst, "by_type_milli": dict(sorted(by_milli.items())),
|
|
185
|
+
"max_ulp_index": max(by_ulp.values(), default=0), "by_type_ulp_index": dict(sorted(by_ulp.items())),
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def needs_accumulation_measurement(device_type: str, dtype: Any) -> bool:
|
|
190
|
+
"""A 16-bit CUDA run whose reduced-precision-reduction flag is not off: the one case where
|
|
191
|
+
the accumulation precision of native matmuls is not already fixed by the scope."""
|
|
192
|
+
import torch
|
|
193
|
+
|
|
194
|
+
if device_type != "cuda" or dtype not in (torch.bfloat16, torch.float16):
|
|
195
|
+
return False
|
|
196
|
+
name = "bf16" if dtype == torch.bfloat16 else "fp16"
|
|
197
|
+
value = _matmul_flag(f"allow_{name}_reduced_precision_reduction")
|
|
198
|
+
off = value is False or (isinstance(value, list) and bool(value) and all(
|
|
199
|
+
item is False for item in value))
|
|
200
|
+
return not off
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
__all__ = [
|
|
204
|
+
"MEASURE_ROWS",
|
|
205
|
+
"SUPPORTED_SCALED",
|
|
206
|
+
"measure_accumulation",
|
|
207
|
+
"needs_accumulation_measurement",
|
|
208
|
+
"REDUCED_PRECISION_FIELDS",
|
|
209
|
+
"check_numeric_environment",
|
|
210
|
+
"live_numeric_environment",
|
|
211
|
+
"numeric_scope",
|
|
212
|
+
"scope_difference",
|
|
213
|
+
]
|
saturn/observers.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""Live, branch-aware diagnostic watchpoints over public Session state."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Callable, Mapping
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from types import MappingProxyType
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .core import Receipt, Session, StateCut
|
|
12
|
+
from .values import clone, describe, digest, tensor
|
|
13
|
+
|
|
14
|
+
_PREDICATES = frozenset({"change", "gt", "lt", "nonfinite"})
|
|
15
|
+
_UNSET = object()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _describe(value: Any) -> Any:
|
|
19
|
+
"""Describe anomalous scalars without asking JSON to encode NaN/Infinity."""
|
|
20
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
21
|
+
return {"nonfinite": repr(value)}
|
|
22
|
+
if isinstance(value, Mapping):
|
|
23
|
+
items = [{"key": describe(key), "value": _describe(item)} for key, item in value.items()]
|
|
24
|
+
items.sort(key=lambda item: digest(item["key"]))
|
|
25
|
+
return {"kind": "mapping", "items": items}
|
|
26
|
+
if isinstance(value, (tuple, list)):
|
|
27
|
+
return {
|
|
28
|
+
"kind": "tuple" if isinstance(value, tuple) else "list",
|
|
29
|
+
"items": [_describe(item) for item in value],
|
|
30
|
+
}
|
|
31
|
+
return describe(value)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Watchpoint:
|
|
36
|
+
"""A diagnostic predicate. It has no scientific or promotion authority."""
|
|
37
|
+
|
|
38
|
+
identifier: str
|
|
39
|
+
address: str
|
|
40
|
+
predicate: str
|
|
41
|
+
threshold: float | None = None
|
|
42
|
+
|
|
43
|
+
def __post_init__(self) -> None:
|
|
44
|
+
if not self.identifier or not self.address:
|
|
45
|
+
raise ValueError("watch identifier and address must be non-empty")
|
|
46
|
+
if self.predicate not in _PREDICATES:
|
|
47
|
+
raise ValueError(f"unsupported watch predicate: {self.predicate}")
|
|
48
|
+
if self.predicate in ("gt", "lt"):
|
|
49
|
+
if self.threshold is None or not math.isfinite(float(self.threshold)):
|
|
50
|
+
raise ValueError(f"{self.predicate} watch requires a finite threshold")
|
|
51
|
+
object.__setattr__(self, "threshold", float(self.threshold))
|
|
52
|
+
elif self.threshold is not None:
|
|
53
|
+
raise ValueError(f"{self.predicate} watch does not accept a threshold")
|
|
54
|
+
|
|
55
|
+
def to_dict(self) -> dict[str, Any]:
|
|
56
|
+
return {
|
|
57
|
+
"identifier": self.identifier,
|
|
58
|
+
"address": self.address,
|
|
59
|
+
"predicate": self.predicate,
|
|
60
|
+
"threshold": self.threshold,
|
|
61
|
+
"authority": "diagnostic-only",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class WatchEvent:
|
|
67
|
+
"""A watch fire bound to the exact retained safe-point cut and step receipt."""
|
|
68
|
+
|
|
69
|
+
watchpoint: Watchpoint
|
|
70
|
+
branch: str
|
|
71
|
+
cut: StateCut = field(repr=False)
|
|
72
|
+
execution_point: Mapping[str, Any]
|
|
73
|
+
previous: Any
|
|
74
|
+
current: Any
|
|
75
|
+
receipt: str | None = None
|
|
76
|
+
fingerprint: str = field(init=False)
|
|
77
|
+
|
|
78
|
+
def __post_init__(self) -> None:
|
|
79
|
+
if not self.branch:
|
|
80
|
+
raise ValueError("watch event branch must be non-empty")
|
|
81
|
+
self.cut.verify()
|
|
82
|
+
point = clone(dict(self.execution_point))
|
|
83
|
+
object.__setattr__(self, "execution_point", MappingProxyType(point))
|
|
84
|
+
object.__setattr__(self, "previous", clone(self.previous))
|
|
85
|
+
object.__setattr__(self, "current", clone(self.current))
|
|
86
|
+
if self.cut.execution_point is not None and point != dict(self.cut.execution_point):
|
|
87
|
+
raise ValueError("watch execution point does not match cut")
|
|
88
|
+
object.__setattr__(
|
|
89
|
+
self,
|
|
90
|
+
"fingerprint",
|
|
91
|
+
digest(
|
|
92
|
+
{
|
|
93
|
+
"schema": "saturn-pub-watch-event-v1",
|
|
94
|
+
"watchpoint": self.watchpoint.to_dict(),
|
|
95
|
+
"branch": self.branch,
|
|
96
|
+
"cut": self.cut.fingerprint,
|
|
97
|
+
"execution_point": point,
|
|
98
|
+
"previous": _describe(self.previous),
|
|
99
|
+
"current": _describe(self.current),
|
|
100
|
+
"receipt": self.receipt,
|
|
101
|
+
}
|
|
102
|
+
),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
def to_dict(self) -> dict[str, Any]:
|
|
106
|
+
self.verify()
|
|
107
|
+
return {
|
|
108
|
+
"schema": "saturn-pub-watch-event-v1",
|
|
109
|
+
"fingerprint": self.fingerprint,
|
|
110
|
+
"watchpoint": self.watchpoint.to_dict(),
|
|
111
|
+
"branch": self.branch,
|
|
112
|
+
"cut": self.cut.fingerprint,
|
|
113
|
+
"boundary": self.cut.boundary,
|
|
114
|
+
"execution_point": dict(self.execution_point),
|
|
115
|
+
"previous": _describe(self.previous),
|
|
116
|
+
"current": _describe(self.current),
|
|
117
|
+
"receipt": self.receipt,
|
|
118
|
+
"authority": "diagnostic-only",
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
def verify(self) -> None:
|
|
122
|
+
self.cut.verify()
|
|
123
|
+
body = {
|
|
124
|
+
"schema": "saturn-pub-watch-event-v1",
|
|
125
|
+
"watchpoint": self.watchpoint.to_dict(),
|
|
126
|
+
"branch": self.branch,
|
|
127
|
+
"cut": self.cut.fingerprint,
|
|
128
|
+
"execution_point": dict(self.execution_point),
|
|
129
|
+
"previous": _describe(self.previous),
|
|
130
|
+
"current": _describe(self.current),
|
|
131
|
+
"receipt": self.receipt,
|
|
132
|
+
}
|
|
133
|
+
if digest(body) != self.fingerprint:
|
|
134
|
+
raise ValueError("watch event content changed")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class ObservationError(ValueError):
|
|
138
|
+
"""One broken watch does not erase completed fires from other watches."""
|
|
139
|
+
|
|
140
|
+
def __init__(self, errors, events, cut):
|
|
141
|
+
super().__init__("; ".join(f"{row['address']}: {row['reason']}" for row in errors))
|
|
142
|
+
self.errors = tuple(errors)
|
|
143
|
+
self.events = tuple(events)
|
|
144
|
+
self.cut = cut
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _samples(value: Any) -> list[float]:
|
|
148
|
+
if tensor(value):
|
|
149
|
+
raw = value.detach().cpu().reshape(-1)
|
|
150
|
+
return [float(item) for item in raw.tolist()]
|
|
151
|
+
if isinstance(value, bool):
|
|
152
|
+
return []
|
|
153
|
+
if isinstance(value, (int, float)):
|
|
154
|
+
return [float(value)]
|
|
155
|
+
if isinstance(value, Mapping):
|
|
156
|
+
result: list[float] = []
|
|
157
|
+
for item in value.values():
|
|
158
|
+
result.extend(_samples(item))
|
|
159
|
+
return result
|
|
160
|
+
if isinstance(value, (tuple, list)):
|
|
161
|
+
result = []
|
|
162
|
+
for item in value:
|
|
163
|
+
result.extend(_samples(item))
|
|
164
|
+
return result
|
|
165
|
+
return []
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _fires(watch: Watchpoint, previous: Any, current: Any) -> bool:
|
|
169
|
+
if watch.predicate == "change":
|
|
170
|
+
return previous is not _UNSET and _describe(previous) != _describe(current)
|
|
171
|
+
values = _samples(current)
|
|
172
|
+
if not values:
|
|
173
|
+
return False
|
|
174
|
+
if watch.predicate == "nonfinite":
|
|
175
|
+
return any(not math.isfinite(value) for value in values)
|
|
176
|
+
if watch.predicate == "gt":
|
|
177
|
+
return any(value > float(watch.threshold) for value in values)
|
|
178
|
+
return any(value < float(watch.threshold) for value in values)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class Observer:
|
|
182
|
+
"""Own watch specifications and per-branch baselines outside Session."""
|
|
183
|
+
|
|
184
|
+
def __init__(self, reader: Callable[[Session, str], Any] | None = None) -> None:
|
|
185
|
+
self._watches: dict[str, Watchpoint] = {}
|
|
186
|
+
self._baselines: dict[tuple[str, str], Any] = {}
|
|
187
|
+
self._next_identifier = 1
|
|
188
|
+
self._read = reader or (lambda session, address: session.read(address))
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def watchpoints(self) -> tuple[Watchpoint, ...]:
|
|
192
|
+
return tuple(self._watches.values())
|
|
193
|
+
|
|
194
|
+
def has_baseline(self, branch: str) -> bool:
|
|
195
|
+
return all(
|
|
196
|
+
(branch, watch.identifier) in self._baselines for watch in self._watches.values()
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
def add(
|
|
200
|
+
self,
|
|
201
|
+
address: str,
|
|
202
|
+
predicate: str,
|
|
203
|
+
threshold: float | None = None,
|
|
204
|
+
*,
|
|
205
|
+
identifier: str | None = None,
|
|
206
|
+
) -> Watchpoint:
|
|
207
|
+
if identifier is None:
|
|
208
|
+
while f"watch-{self._next_identifier}" in self._watches:
|
|
209
|
+
self._next_identifier += 1
|
|
210
|
+
identifier = f"watch-{self._next_identifier}"
|
|
211
|
+
self._next_identifier += 1
|
|
212
|
+
if identifier in self._watches:
|
|
213
|
+
raise ValueError(f"watch already exists: {identifier}")
|
|
214
|
+
watch = Watchpoint(identifier, address, predicate, threshold)
|
|
215
|
+
self._watches[identifier] = watch
|
|
216
|
+
return watch
|
|
217
|
+
|
|
218
|
+
def remove(self, identifier: str) -> None:
|
|
219
|
+
if identifier not in self._watches:
|
|
220
|
+
raise ValueError(f"unknown watch: {identifier}")
|
|
221
|
+
del self._watches[identifier]
|
|
222
|
+
self._baselines = {
|
|
223
|
+
key: value for key, value in self._baselines.items() if key[1] != identifier
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
def clear(self) -> None:
|
|
227
|
+
self._watches.clear()
|
|
228
|
+
self._baselines.clear()
|
|
229
|
+
|
|
230
|
+
def sync(self, session: Session, branch: str) -> None:
|
|
231
|
+
"""Reset a branch after restore/rewind and seed every current watch."""
|
|
232
|
+
values = {
|
|
233
|
+
(branch, watch.identifier): clone(self._read(session, watch.address))
|
|
234
|
+
for watch in self._watches.values()
|
|
235
|
+
}
|
|
236
|
+
self._baselines = {key: value for key, value in self._baselines.items() if key[0] != branch}
|
|
237
|
+
self._baselines.update(values)
|
|
238
|
+
|
|
239
|
+
def evaluate(
|
|
240
|
+
self,
|
|
241
|
+
session: Session,
|
|
242
|
+
branch: str,
|
|
243
|
+
*,
|
|
244
|
+
receipt: Receipt | None = None,
|
|
245
|
+
) -> tuple[WatchEvent, ...]:
|
|
246
|
+
fired: list[tuple[Watchpoint, Any, Any]] = []
|
|
247
|
+
current_values = {}
|
|
248
|
+
errors = []
|
|
249
|
+
for watch in self._watches.values():
|
|
250
|
+
key = (branch, watch.identifier)
|
|
251
|
+
try:
|
|
252
|
+
current = self._read(session, watch.address)
|
|
253
|
+
previous = self._baselines.get(key, _UNSET)
|
|
254
|
+
fires = _fires(watch, previous, current)
|
|
255
|
+
except Exception as exc:
|
|
256
|
+
errors.append(
|
|
257
|
+
{
|
|
258
|
+
"identifier": watch.identifier,
|
|
259
|
+
"address": watch.address,
|
|
260
|
+
"reason": f"{type(exc).__name__}: {exc}",
|
|
261
|
+
}
|
|
262
|
+
)
|
|
263
|
+
continue
|
|
264
|
+
if fires:
|
|
265
|
+
fired.append((watch, None if previous is _UNSET else previous, current))
|
|
266
|
+
current_values[key] = clone(current)
|
|
267
|
+
if not fired and not errors:
|
|
268
|
+
self._baselines.update(current_values)
|
|
269
|
+
return ()
|
|
270
|
+
# One retained cut is the shared safe point for every predicate fired by this transition.
|
|
271
|
+
cut = session.capture()
|
|
272
|
+
point = getattr(cut, "execution_point", None)
|
|
273
|
+
if point is None:
|
|
274
|
+
frame = session.inspect()
|
|
275
|
+
point = getattr(frame, "execution_point", {"boundary": frame.boundary})
|
|
276
|
+
receipt_id = None if receipt is None else receipt.fingerprint
|
|
277
|
+
if receipt is not None and receipt.to_dict().get("result") != cut.fingerprint:
|
|
278
|
+
raise ValueError("watch receipt does not produce the observed cut")
|
|
279
|
+
events = tuple(
|
|
280
|
+
WatchEvent(watch, branch, cut, point, previous, current, receipt_id)
|
|
281
|
+
for watch, previous, current in fired
|
|
282
|
+
)
|
|
283
|
+
self._baselines.update(current_values)
|
|
284
|
+
if errors:
|
|
285
|
+
raise ObservationError(errors, events, cut)
|
|
286
|
+
return events
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
__all__ = ["Observer", "WatchEvent", "Watchpoint", "ObservationError"]
|