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/values.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Small value utilities shared by the runtime and durable store."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def canonical(value: Any) -> bytes:
|
|
13
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def digest(value: Any) -> str:
|
|
17
|
+
return hashlib.sha256(canonical(value)).hexdigest()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def tensor(value: Any) -> bool:
|
|
21
|
+
# Avoid importing torch when inspecting only metadata.
|
|
22
|
+
return type(value).__module__.startswith("torch") and hasattr(value, "detach")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def clone(value: Any) -> Any:
|
|
26
|
+
if tensor(value):
|
|
27
|
+
# Snapshot ABI: preserve safe dense tensor layout because native kernels
|
|
28
|
+
# can be bitwise layout-sensitive. Durable storage seals and restores it.
|
|
29
|
+
return value.detach().clone(memory_format=__import__("torch").preserve_format)
|
|
30
|
+
if isinstance(value, Mapping):
|
|
31
|
+
return {key: clone(item) for key, item in value.items()}
|
|
32
|
+
if isinstance(value, tuple):
|
|
33
|
+
return tuple(clone(item) for item in value)
|
|
34
|
+
if isinstance(value, list):
|
|
35
|
+
return [clone(item) for item in value]
|
|
36
|
+
return copy.deepcopy(value)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _scalar(value: Any) -> dict[str, Any]:
|
|
40
|
+
if value is None:
|
|
41
|
+
return {"kind": "scalar", "type": "none", "value": None}
|
|
42
|
+
if type(value) is bool:
|
|
43
|
+
return {"kind": "scalar", "type": "bool", "value": value}
|
|
44
|
+
if type(value) is int:
|
|
45
|
+
return {"kind": "scalar", "type": "int", "value": value}
|
|
46
|
+
if type(value) is float:
|
|
47
|
+
canonical(value)
|
|
48
|
+
return {"kind": "scalar", "type": "float", "value": value}
|
|
49
|
+
if type(value) is str:
|
|
50
|
+
return {"kind": "scalar", "type": "str", "value": value}
|
|
51
|
+
raise ValueError(f"unsupported sealed value: {type(value).__name__}")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class TensorFacts:
|
|
55
|
+
"""Facts about a tensor's content (its ``describe`` descriptor, that it is all finite),
|
|
56
|
+
remembered while the tensor object lives and its version counter, data pointer, shape,
|
|
57
|
+
stride, dtype and device are unchanged.
|
|
58
|
+
|
|
59
|
+
The key is the same guard the ``shares_state`` contract already relies on (``core``: a
|
|
60
|
+
sealed tensor is immutable, every in-place write bumps its version counter, which views
|
|
61
|
+
share). A tensor without a version counter (an inference tensor) is never remembered. A
|
|
62
|
+
write that bypasses the counter (through ``.data``, ``numpy()`` or a raw storage) is not
|
|
63
|
+
seen here, as it is not seen by the in-place guard; ``describe`` and ``StateCut.verify``
|
|
64
|
+
never use this memo and always re-hash.
|
|
65
|
+
|
|
66
|
+
Writes that bypass the version counter (``.data``, ``numpy()``, dlpack, raw kernels) are
|
|
67
|
+
not detected, the same as in main's in-place guard. For the native K/V cache this means
|
|
68
|
+
the decoder holds the state's tensors by reference only while no foreign forward hook is
|
|
69
|
+
registered; foreign hooks force the copying path.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(self) -> None:
|
|
73
|
+
self._entries: dict[int, tuple[Any, tuple[Any, ...], dict[str, Any]]] = {}
|
|
74
|
+
|
|
75
|
+
@staticmethod
|
|
76
|
+
def _key(value: Any) -> tuple[Any, ...] | None:
|
|
77
|
+
if value.is_inference():
|
|
78
|
+
return None
|
|
79
|
+
return (
|
|
80
|
+
value._version,
|
|
81
|
+
value.data_ptr(),
|
|
82
|
+
tuple(value.shape),
|
|
83
|
+
tuple(value.stride()),
|
|
84
|
+
value.dtype,
|
|
85
|
+
value.device,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def get(self, value: Any, fact: str) -> Any:
|
|
89
|
+
entry = self._entries.get(id(value))
|
|
90
|
+
if entry is None or entry[0]() is not value:
|
|
91
|
+
return None
|
|
92
|
+
key = self._key(value)
|
|
93
|
+
if key is None or key != entry[1]:
|
|
94
|
+
return None
|
|
95
|
+
return entry[2].get(fact)
|
|
96
|
+
|
|
97
|
+
def put(self, value: Any, fact: str, result: Any) -> None:
|
|
98
|
+
import weakref
|
|
99
|
+
|
|
100
|
+
key = self._key(value)
|
|
101
|
+
if key is None:
|
|
102
|
+
return
|
|
103
|
+
ident = id(value)
|
|
104
|
+
entry = self._entries.get(ident)
|
|
105
|
+
if entry is not None and entry[0]() is value and entry[1] == key:
|
|
106
|
+
entry[2][fact] = result
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
def forget(ref: Any, ident: int = ident) -> None:
|
|
110
|
+
current = self._entries.get(ident)
|
|
111
|
+
if current is not None and current[0] is ref:
|
|
112
|
+
self._entries.pop(ident, None)
|
|
113
|
+
|
|
114
|
+
self._entries[ident] = (weakref.ref(value, forget), key, {fact: result})
|
|
115
|
+
|
|
116
|
+
def __len__(self) -> int:
|
|
117
|
+
return len(self._entries)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
TENSOR_FACTS = TensorFacts()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _describe_tensor(value: Any) -> dict[str, Any]:
|
|
124
|
+
raw = value.detach().cpu().contiguous().reshape(-1).view(__import__("torch").uint8)
|
|
125
|
+
content_digest = hashlib.sha256(raw.numpy()).hexdigest() # the buffer, not a bytes copy
|
|
126
|
+
return {
|
|
127
|
+
"kind": "tensor",
|
|
128
|
+
"sha256": content_digest,
|
|
129
|
+
# Compatibility alias for callers that consumed the v1 summary.
|
|
130
|
+
"tensor": content_digest,
|
|
131
|
+
"shape": list(value.shape),
|
|
132
|
+
"dtype": str(value.dtype),
|
|
133
|
+
"layout": "strided-dense",
|
|
134
|
+
"stride": list(value.stride()),
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _copy_descriptor(described: dict[str, Any]) -> dict[str, Any]:
|
|
139
|
+
return {**described, "shape": list(described["shape"]), "stride": list(described["stride"])}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def describe(value: Any) -> Any:
|
|
143
|
+
"""Return a typed, canonical content descriptor.
|
|
144
|
+
|
|
145
|
+
Tags are intentional: JSON alone cannot distinguish tuples from lists and
|
|
146
|
+
Python considers values such as ``True`` and ``1`` equal. State and
|
|
147
|
+
operation seals must preserve those distinctions.
|
|
148
|
+
"""
|
|
149
|
+
return _describe(value, False)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def describe_remembered(value: Any) -> Any:
|
|
153
|
+
"""``describe(value)``, hashing a tensor only when ``TENSOR_FACTS`` holds no descriptor
|
|
154
|
+
for it (same object, same version counter, pointer and layout): for sealing a state whose
|
|
155
|
+
tensors are shared with earlier seals (a layer transition replaces one K/V layer of L).
|
|
156
|
+
The descriptor is the very one ``describe`` gives; verification paths use ``describe``."""
|
|
157
|
+
return _describe(value, True)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _describe(value: Any, remember: bool) -> Any:
|
|
161
|
+
if tensor(value):
|
|
162
|
+
if not remember:
|
|
163
|
+
return _describe_tensor(value)
|
|
164
|
+
known = TENSOR_FACTS.get(value, "describe")
|
|
165
|
+
if known is None:
|
|
166
|
+
known = _describe_tensor(value)
|
|
167
|
+
TENSOR_FACTS.put(value, "describe", known)
|
|
168
|
+
return _copy_descriptor(known)
|
|
169
|
+
if isinstance(value, Mapping):
|
|
170
|
+
return describe_mapping({key: _describe(item, remember) for key, item in value.items()})
|
|
171
|
+
if isinstance(value, tuple):
|
|
172
|
+
return {"kind": "tuple", "items": [_describe(item, remember) for item in value]}
|
|
173
|
+
if isinstance(value, list):
|
|
174
|
+
return {"kind": "list", "items": [_describe(item, remember) for item in value]}
|
|
175
|
+
return _scalar(value)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def describe_mapping(described: Mapping[Any, Any]) -> dict[str, Any]:
|
|
179
|
+
"""``describe`` of a mapping whose items are already described (``{key: describe(item)}``).
|
|
180
|
+
|
|
181
|
+
Lets a caller that holds the descriptor of every item seal the mapping without hashing the
|
|
182
|
+
items again; ``describe`` of a mapping is defined through this function, so both agree.
|
|
183
|
+
"""
|
|
184
|
+
items = [{"key": describe(key), "value": item} for key, item in described.items()]
|
|
185
|
+
if all(type(key) is str and _PLAIN_KEY.fullmatch(key) for key in described):
|
|
186
|
+
# canonical() of a plain string key is '{"kind":"scalar","type":"str","value":"KEY"}':
|
|
187
|
+
# with no character that JSON escapes and none below '"', the byte order of those
|
|
188
|
+
# encodings is the code-point order of the keys, so sort without encoding them
|
|
189
|
+
items.sort(key=lambda item: item["key"]["value"])
|
|
190
|
+
else:
|
|
191
|
+
items.sort(key=lambda item: canonical(item["key"]))
|
|
192
|
+
return {"kind": "mapping", "items": items}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# printable ASCII above '"' except '\\': canonical JSON leaves them as they are, and each sorts
|
|
196
|
+
# after the closing quote, so a key that is a prefix of another sorts first in both orders
|
|
197
|
+
_PLAIN_KEY = __import__("re").compile(r"[#-\[\]-~]*")
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def legacy_describe_v1(value: Any) -> Any:
|
|
201
|
+
"""Reproduce the v1 descriptor solely to verify historical artifacts.
|
|
202
|
+
|
|
203
|
+
This format is not authoritative for value typing because it collapsed
|
|
204
|
+
lists/tuples and did not tag scalars. New seals must use :func:`describe`.
|
|
205
|
+
"""
|
|
206
|
+
if tensor(value):
|
|
207
|
+
raw = value.detach().cpu().contiguous().reshape(-1).view(__import__("torch").uint8)
|
|
208
|
+
return {
|
|
209
|
+
"tensor": hashlib.sha256(raw.numpy().tobytes()).hexdigest(),
|
|
210
|
+
"shape": list(value.shape),
|
|
211
|
+
"dtype": str(value.dtype),
|
|
212
|
+
}
|
|
213
|
+
if isinstance(value, Mapping):
|
|
214
|
+
return {key: legacy_describe_v1(item) for key, item in value.items()}
|
|
215
|
+
if isinstance(value, (tuple, list)):
|
|
216
|
+
return [legacy_describe_v1(item) for item in value]
|
|
217
|
+
canonical(value)
|
|
218
|
+
return value
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def identity(model: Any, configuration: Any) -> str:
|
|
222
|
+
"""Bind actual parameter/buffer content, rather than trusting a model name."""
|
|
223
|
+
return digest({"config": configuration, "state": describe(model.state_dict())})
|
saturn/writers.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Fit a small state-dependent residual writer from explicitly paired state cuts.
|
|
2
|
+
|
|
3
|
+
This is supervised trace fitting. Consumer behavior must be evaluated separately.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def fit_low_rank_writer(recipient, donor, *, address, rank=8, ridge=1e-3):
|
|
14
|
+
recipient.verify()
|
|
15
|
+
donor.verify()
|
|
16
|
+
source = recipient.payload[address]
|
|
17
|
+
target = donor.payload[address]
|
|
18
|
+
if source.shape != target.shape or source.ndim < 2:
|
|
19
|
+
raise ValueError("paired states require matching geometry")
|
|
20
|
+
if not isinstance(rank, int) or isinstance(rank, bool) or rank < 1:
|
|
21
|
+
raise ValueError("rank must be a positive integer")
|
|
22
|
+
if not np.isfinite(ridge) or ridge <= 0:
|
|
23
|
+
raise ValueError("ridge must be finite and positive")
|
|
24
|
+
width = source.shape[-1]
|
|
25
|
+
x = source.detach().float().cpu().numpy().reshape(-1, width)
|
|
26
|
+
y = (target.detach().float().cpu() - source.detach().float().cpu()).numpy().reshape(-1, width)
|
|
27
|
+
if len(x) < 2 or not np.isfinite(x).all() or not np.isfinite(y).all():
|
|
28
|
+
raise ValueError("paired states must have finite values and at least two rows")
|
|
29
|
+
mean = x.mean(axis=0)
|
|
30
|
+
centered = x - mean
|
|
31
|
+
rank = min(rank, len(x) - 1, width)
|
|
32
|
+
_, _, vt = np.linalg.svd(centered, full_matrices=False)
|
|
33
|
+
basis = vt[:rank].T.astype(np.float32)
|
|
34
|
+
z = centered @ basis
|
|
35
|
+
weights = np.linalg.solve(z.T @ z + np.eye(rank, dtype=np.float32) * ridge, z.T @ y)
|
|
36
|
+
bias = y.mean(axis=0)
|
|
37
|
+
predicted = z @ weights + bias
|
|
38
|
+
mse = float(np.mean((predicted - y) ** 2))
|
|
39
|
+
energy = float(np.mean(y**2))
|
|
40
|
+
arrays = dict(mean=mean, basis=basis, weights=weights, bias=bias)
|
|
41
|
+
metadata = {
|
|
42
|
+
"schema": "saturn-pub-low-rank-writer-v1",
|
|
43
|
+
"recipe": "centered recipient PCA followed by ridge residual regression",
|
|
44
|
+
"address": address,
|
|
45
|
+
"rank": rank,
|
|
46
|
+
"ridge": ridge,
|
|
47
|
+
"recipient_cut": recipient.fingerprint,
|
|
48
|
+
"donor_cut": donor.fingerprint,
|
|
49
|
+
"recipient_model": recipient.model_identity,
|
|
50
|
+
"donor_model": donor.model_identity,
|
|
51
|
+
"recipient_boundary": recipient.boundary,
|
|
52
|
+
"donor_boundary": donor.boundary,
|
|
53
|
+
"rows": len(x),
|
|
54
|
+
"dimension": width,
|
|
55
|
+
"fit_mse": mse,
|
|
56
|
+
"target_delta_rms": energy**0.5,
|
|
57
|
+
"relative_fit_mse": mse / energy if energy else None,
|
|
58
|
+
"claim_boundary": "One paired trace; reconstruction does not establish consumer capability.",
|
|
59
|
+
}
|
|
60
|
+
return arrays, metadata
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def save_low_rank_writer(path, arrays, metadata):
|
|
64
|
+
"""Seal FP16 serving arrays and separate construction provenance; no donor weights."""
|
|
65
|
+
path = Path(path)
|
|
66
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
packed = {
|
|
68
|
+
name: np.asarray(arrays[name], dtype=np.float16)
|
|
69
|
+
for name in ("mean", "basis", "weights", "bias")
|
|
70
|
+
}
|
|
71
|
+
if any(not np.isfinite(value).all() for value in packed.values()):
|
|
72
|
+
raise ValueError("writer overflows serving precision")
|
|
73
|
+
np.savez_compressed(path, **packed, gain=np.array([0], dtype=np.float16))
|
|
74
|
+
result = {
|
|
75
|
+
**metadata,
|
|
76
|
+
"package_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
|
|
77
|
+
"package_bytes": path.stat().st_size,
|
|
78
|
+
"serving_scalar_count": sum(value.size for value in packed.values()) + 1,
|
|
79
|
+
"serving_dtype": "float16",
|
|
80
|
+
}
|
|
81
|
+
path.with_suffix(".json").write_text(json.dumps(result, indent=2))
|
|
82
|
+
return result
|