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/store.py
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
1
|
+
"""Verified local custody with per-slot content-addressed pages, never pickle."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import tempfile
|
|
10
|
+
import warnings
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .core import Receipt, StateCut
|
|
16
|
+
from .values import canonical, clone, describe, digest, legacy_describe_v1, tensor
|
|
17
|
+
|
|
18
|
+
_LEGACY_CAVEAT = (
|
|
19
|
+
"saturn-pub-statecut-v1 typing is non-authoritative historical evidence: "
|
|
20
|
+
"lists/tuples and JSON scalar types were not independently sealed"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _safe_id(value: str) -> str:
|
|
25
|
+
if len(value) != 64 or any(c not in "0123456789abcdef" for c in value):
|
|
26
|
+
raise ValueError("expected a lowercase SHA-256 identifier")
|
|
27
|
+
return value
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _publish(path: Path, data: bytes) -> bool:
|
|
31
|
+
if path.suffix == ".safetensors":
|
|
32
|
+
from .shared_store import publish_configured
|
|
33
|
+
|
|
34
|
+
shared = publish_configured(path, data)
|
|
35
|
+
if shared is not None:
|
|
36
|
+
return shared
|
|
37
|
+
try:
|
|
38
|
+
existing = path.read_bytes()
|
|
39
|
+
except FileNotFoundError:
|
|
40
|
+
pass
|
|
41
|
+
else:
|
|
42
|
+
if existing != data:
|
|
43
|
+
raise ValueError("existing artifact does not match its content address")
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
|
48
|
+
temporary = Path(stream.name)
|
|
49
|
+
stream.write(data)
|
|
50
|
+
stream.flush()
|
|
51
|
+
os.fsync(stream.fileno())
|
|
52
|
+
admitted = False
|
|
53
|
+
try:
|
|
54
|
+
try:
|
|
55
|
+
os.link(temporary, path)
|
|
56
|
+
admitted = True
|
|
57
|
+
try:
|
|
58
|
+
directory = os.open(path.parent, os.O_RDONLY)
|
|
59
|
+
try:
|
|
60
|
+
os.fsync(directory)
|
|
61
|
+
finally:
|
|
62
|
+
os.close(directory)
|
|
63
|
+
except OSError:
|
|
64
|
+
# Some filesystems do not expose directory fsync; the file itself
|
|
65
|
+
# was already flushed before the immutable link was published.
|
|
66
|
+
pass
|
|
67
|
+
except FileExistsError:
|
|
68
|
+
if path.read_bytes() != data:
|
|
69
|
+
raise ValueError("existing artifact does not match its content address")
|
|
70
|
+
finally:
|
|
71
|
+
temporary.unlink()
|
|
72
|
+
return admitted
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _scalar_type(value: Any) -> str:
|
|
76
|
+
if value is None:
|
|
77
|
+
return "none"
|
|
78
|
+
if type(value) is bool:
|
|
79
|
+
return "bool"
|
|
80
|
+
if type(value) is int:
|
|
81
|
+
return "int"
|
|
82
|
+
if type(value) is float:
|
|
83
|
+
canonical(value)
|
|
84
|
+
return "float"
|
|
85
|
+
if type(value) is str:
|
|
86
|
+
return "str"
|
|
87
|
+
raise ValueError(f"unsupported durable value: {type(value).__name__}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _encode(value: Any, tensors: dict[str, Any]) -> Any:
|
|
91
|
+
if tensor(value):
|
|
92
|
+
name = f"tensor_{len(tensors)}"
|
|
93
|
+
tensors[name] = value.detach().cpu().contiguous().clone()
|
|
94
|
+
return {
|
|
95
|
+
"kind": "tensor",
|
|
96
|
+
"name": name,
|
|
97
|
+
"shape": list(value.shape),
|
|
98
|
+
"stride": list(value.stride()),
|
|
99
|
+
}
|
|
100
|
+
if isinstance(value, Mapping):
|
|
101
|
+
if any(not isinstance(key, str) for key in value):
|
|
102
|
+
raise ValueError("durable state mappings require string keys")
|
|
103
|
+
return {
|
|
104
|
+
"kind": "mapping",
|
|
105
|
+
"items": {key: _encode(item, tensors) for key, item in sorted(value.items())},
|
|
106
|
+
}
|
|
107
|
+
if isinstance(value, tuple):
|
|
108
|
+
return {"kind": "tuple", "items": [_encode(item, tensors) for item in value]}
|
|
109
|
+
if isinstance(value, list):
|
|
110
|
+
return {"kind": "list", "items": [_encode(item, tensors) for item in value]}
|
|
111
|
+
return {"kind": "scalar", "type": _scalar_type(value), "value": value}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _decode(value: Any, tensors: dict[str, Any], used: set[str] | None = None) -> Any:
|
|
115
|
+
if not isinstance(value, dict) or not isinstance(value.get("kind"), str):
|
|
116
|
+
raise ValueError("invalid stored value descriptor")
|
|
117
|
+
used = set() if used is None else used
|
|
118
|
+
kind = value["kind"]
|
|
119
|
+
if kind == "tensor":
|
|
120
|
+
name = value.get("name")
|
|
121
|
+
if not isinstance(name, str) or name not in tensors or name in used:
|
|
122
|
+
raise ValueError("invalid or repeated tensor page reference")
|
|
123
|
+
used.add(name)
|
|
124
|
+
stored = tensors[name]
|
|
125
|
+
shape = value.get("shape")
|
|
126
|
+
stride = value.get("stride")
|
|
127
|
+
if (
|
|
128
|
+
not isinstance(shape, list)
|
|
129
|
+
or not isinstance(stride, list)
|
|
130
|
+
or len(shape) != len(stride)
|
|
131
|
+
or any(type(size) is not int or size < 0 for size in shape)
|
|
132
|
+
or any(type(step) is not int or step < 0 for step in stride)
|
|
133
|
+
or tuple(shape) != tuple(stored.shape)
|
|
134
|
+
):
|
|
135
|
+
raise ValueError("invalid tensor layout descriptor")
|
|
136
|
+
# Accept permutations of a compact dense layout. This bounds physical
|
|
137
|
+
# storage to numel and excludes overlaps, broadcast views, and sparse
|
|
138
|
+
# as_strided layouts whose hydration could amplify resources.
|
|
139
|
+
expected = 1
|
|
140
|
+
for step, size in sorted(
|
|
141
|
+
((step, size) for size, step in zip(shape, stride) if size > 1),
|
|
142
|
+
key=lambda item: item[0],
|
|
143
|
+
):
|
|
144
|
+
if step != expected:
|
|
145
|
+
raise ValueError("tensor layout is not non-overlapping dense")
|
|
146
|
+
expected *= size
|
|
147
|
+
if stored.numel() and expected != stored.numel():
|
|
148
|
+
raise ValueError("tensor layout resource contract mismatch")
|
|
149
|
+
if tuple(stride) == tuple(stored.stride()):
|
|
150
|
+
return stored
|
|
151
|
+
restored = __import__("torch").empty_strided(
|
|
152
|
+
tuple(shape), tuple(stride), dtype=stored.dtype, device=stored.device
|
|
153
|
+
)
|
|
154
|
+
restored.copy_(stored)
|
|
155
|
+
return restored
|
|
156
|
+
if kind == "mapping":
|
|
157
|
+
items = value.get("items")
|
|
158
|
+
if not isinstance(items, dict) or any(not isinstance(key, str) for key in items):
|
|
159
|
+
raise ValueError("invalid stored mapping")
|
|
160
|
+
return {key: _decode(item, tensors, used) for key, item in items.items()}
|
|
161
|
+
if kind in ("list", "tuple"):
|
|
162
|
+
encoded_items = value.get("items")
|
|
163
|
+
if not isinstance(encoded_items, list):
|
|
164
|
+
raise ValueError("invalid stored sequence")
|
|
165
|
+
items = [_decode(item, tensors, used) for item in encoded_items]
|
|
166
|
+
return tuple(items) if kind == "tuple" else items
|
|
167
|
+
if kind == "scalar":
|
|
168
|
+
scalar = value.get("value")
|
|
169
|
+
if value.get("type") != _scalar_type(scalar):
|
|
170
|
+
raise ValueError("stored scalar type tag mismatch")
|
|
171
|
+
return scalar
|
|
172
|
+
raise ValueError("unknown stored value kind")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _decode_v1(value: Any, tensors: dict[str, Any]) -> Any:
|
|
176
|
+
kind = value["kind"]
|
|
177
|
+
if kind == "tensor":
|
|
178
|
+
return tensors[value["name"]]
|
|
179
|
+
if kind == "mapping":
|
|
180
|
+
return {key: _decode_v1(item, tensors) for key, item in value["items"].items()}
|
|
181
|
+
if kind in ("list", "tuple"):
|
|
182
|
+
items = [_decode_v1(item, tensors) for item in value["items"]]
|
|
183
|
+
return tuple(items) if kind == "tuple" else items
|
|
184
|
+
if kind == "scalar":
|
|
185
|
+
return value["value"]
|
|
186
|
+
raise ValueError("unknown legacy stored value kind")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _move(value: Any, device: str) -> Any:
|
|
190
|
+
if tensor(value):
|
|
191
|
+
return value.to(device)
|
|
192
|
+
if isinstance(value, Mapping):
|
|
193
|
+
return {key: _move(item, device) for key, item in value.items()}
|
|
194
|
+
if isinstance(value, tuple):
|
|
195
|
+
return tuple(_move(item, device) for item in value)
|
|
196
|
+
if isinstance(value, list):
|
|
197
|
+
return [_move(item, device) for item in value]
|
|
198
|
+
return clone(value)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class LocalStore:
|
|
202
|
+
def __init__(self, root: str | Path):
|
|
203
|
+
self.root = Path(root)
|
|
204
|
+
self._last_admission: dict[str, Any] | None = None
|
|
205
|
+
|
|
206
|
+
@property
|
|
207
|
+
def last_admission(self) -> dict[str, Any] | None:
|
|
208
|
+
return None if self._last_admission is None else clone(self._last_admission)
|
|
209
|
+
|
|
210
|
+
def _save_slot(self, value: Any) -> tuple[str, set[str], int, int]:
|
|
211
|
+
tensors: dict[str, Any] = {}
|
|
212
|
+
encoded = _encode(value, tensors)
|
|
213
|
+
blob_id = None
|
|
214
|
+
blob_bytes = b""
|
|
215
|
+
admitted = 0
|
|
216
|
+
if tensors:
|
|
217
|
+
from safetensors.torch import save
|
|
218
|
+
|
|
219
|
+
blob_bytes = save(tensors)
|
|
220
|
+
blob_id = hashlib.sha256(blob_bytes).hexdigest()
|
|
221
|
+
if _publish(self.root / "blobs" / f"{blob_id}.safetensors", blob_bytes):
|
|
222
|
+
admitted += len(blob_bytes)
|
|
223
|
+
page = canonical(
|
|
224
|
+
{
|
|
225
|
+
"schema": "saturn-pub-slot-page-v1",
|
|
226
|
+
"encoded": encoded,
|
|
227
|
+
"tensor_blob": blob_id,
|
|
228
|
+
"value": describe(value),
|
|
229
|
+
}
|
|
230
|
+
)
|
|
231
|
+
page_id = hashlib.sha256(page).hexdigest()
|
|
232
|
+
if _publish(self.root / "pages" / f"{page_id}.json", page):
|
|
233
|
+
admitted += len(page)
|
|
234
|
+
return (
|
|
235
|
+
page_id,
|
|
236
|
+
(set() if blob_id is None else {blob_id}),
|
|
237
|
+
len(page) + len(blob_bytes),
|
|
238
|
+
admitted,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
def save(self, cut: StateCut) -> str:
|
|
242
|
+
cut.verify()
|
|
243
|
+
slots: dict[str, str] = {}
|
|
244
|
+
blobs: set[str] = set()
|
|
245
|
+
logical_bytes = admitted_bytes = 0
|
|
246
|
+
for name, value in sorted(cut.payload.items()):
|
|
247
|
+
if not isinstance(name, str):
|
|
248
|
+
raise ValueError("durable state slots require string names")
|
|
249
|
+
page_id, physical, logical, admitted = self._save_slot(value)
|
|
250
|
+
slots[name] = page_id
|
|
251
|
+
blobs.update(physical)
|
|
252
|
+
logical_bytes += logical
|
|
253
|
+
admitted_bytes += admitted
|
|
254
|
+
metadata = {
|
|
255
|
+
"schema": "saturn-pub-local-cut-v2",
|
|
256
|
+
"manifest": cut.manifest(),
|
|
257
|
+
"fingerprint": cut.fingerprint,
|
|
258
|
+
"logical_parent": cut.parent,
|
|
259
|
+
"slots": slots,
|
|
260
|
+
"physical_blobs": sorted(blobs),
|
|
261
|
+
"execution_point": None if cut.execution_point is None else dict(cut.execution_point),
|
|
262
|
+
"surface": None if cut.surface is None else dict(cut.surface),
|
|
263
|
+
}
|
|
264
|
+
body = canonical(metadata)
|
|
265
|
+
logical_bytes += len(body)
|
|
266
|
+
if _publish(self.root / "cuts" / f"{cut.fingerprint}.json", body):
|
|
267
|
+
admitted_bytes += len(body)
|
|
268
|
+
self._last_admission = {
|
|
269
|
+
"cut": cut.fingerprint,
|
|
270
|
+
"logical_bytes": logical_bytes,
|
|
271
|
+
"admitted_bytes": admitted_bytes,
|
|
272
|
+
"deduplicated_bytes": logical_bytes - admitted_bytes,
|
|
273
|
+
"slot_pages": len(slots),
|
|
274
|
+
"physical_blobs": len(blobs),
|
|
275
|
+
}
|
|
276
|
+
return cut.fingerprint
|
|
277
|
+
|
|
278
|
+
def save_report(self, cut: StateCut) -> dict[str, Any]:
|
|
279
|
+
self.save(cut)
|
|
280
|
+
assert self._last_admission is not None
|
|
281
|
+
return clone(self._last_admission)
|
|
282
|
+
|
|
283
|
+
def _read_page(self, page_id: str) -> tuple[Any, dict[str, Any]]:
|
|
284
|
+
identifier = _safe_id(page_id)
|
|
285
|
+
raw = (self.root / "pages" / f"{identifier}.json").read_bytes()
|
|
286
|
+
if hashlib.sha256(raw).hexdigest() != identifier:
|
|
287
|
+
raise ValueError("slot page digest mismatch")
|
|
288
|
+
page = json.loads(raw)
|
|
289
|
+
if page.get("schema") != "saturn-pub-slot-page-v1":
|
|
290
|
+
raise ValueError("unknown slot page schema")
|
|
291
|
+
tensors: dict[str, Any] = {}
|
|
292
|
+
blob_id = page.get("tensor_blob")
|
|
293
|
+
if blob_id is not None:
|
|
294
|
+
from safetensors.torch import load
|
|
295
|
+
|
|
296
|
+
blob_id = _safe_id(blob_id)
|
|
297
|
+
blob = (self.root / "blobs" / f"{blob_id}.safetensors").read_bytes()
|
|
298
|
+
if hashlib.sha256(blob).hexdigest() != blob_id:
|
|
299
|
+
raise ValueError("tensor blob digest mismatch")
|
|
300
|
+
tensors = load(blob)
|
|
301
|
+
used: set[str] = set()
|
|
302
|
+
value = _decode(page.get("encoded"), tensors, used)
|
|
303
|
+
if used != set(tensors):
|
|
304
|
+
raise ValueError("slot page contains unreferenced tensor data")
|
|
305
|
+
if describe(value) != page.get("value"):
|
|
306
|
+
raise ValueError("slot page descriptor does not match hydrated value")
|
|
307
|
+
return value, page
|
|
308
|
+
|
|
309
|
+
def _load_v2(self, identifier: str, data: dict[str, Any], *, device: str) -> StateCut:
|
|
310
|
+
manifest = data.get("manifest")
|
|
311
|
+
if not isinstance(manifest, dict) or digest(manifest) != identifier:
|
|
312
|
+
raise ValueError("StateCut manifest digest mismatch")
|
|
313
|
+
if data.get("fingerprint") != identifier:
|
|
314
|
+
raise ValueError("stored StateCut fingerprint mismatch")
|
|
315
|
+
if data.get("logical_parent") != manifest.get("parent"):
|
|
316
|
+
raise ValueError("logical ancestry does not match the StateCut manifest")
|
|
317
|
+
slots = data.get("slots")
|
|
318
|
+
if not isinstance(slots, dict) or any(
|
|
319
|
+
not isinstance(name, str) or not isinstance(page, str) for name, page in slots.items()
|
|
320
|
+
):
|
|
321
|
+
raise ValueError("invalid StateCut slot inventory")
|
|
322
|
+
payload: dict[str, Any] = {}
|
|
323
|
+
observed_blobs: set[str] = set()
|
|
324
|
+
for name, page_id in slots.items():
|
|
325
|
+
value, page = self._read_page(page_id)
|
|
326
|
+
payload[name] = value
|
|
327
|
+
if page.get("tensor_blob") is not None:
|
|
328
|
+
observed_blobs.add(page["tensor_blob"])
|
|
329
|
+
if sorted(observed_blobs) != data.get("physical_blobs"):
|
|
330
|
+
raise ValueError("physical blob inventory mismatch")
|
|
331
|
+
cut = StateCut(
|
|
332
|
+
manifest["model_identity"],
|
|
333
|
+
manifest["execution"],
|
|
334
|
+
manifest["boundary"],
|
|
335
|
+
manifest["parent"],
|
|
336
|
+
payload,
|
|
337
|
+
data.get("execution_point"),
|
|
338
|
+
data.get("surface"),
|
|
339
|
+
)
|
|
340
|
+
if cut.fingerprint != identifier or cut.manifest() != manifest:
|
|
341
|
+
raise ValueError("stored descriptor does not match hydrated payload")
|
|
342
|
+
cut.verify()
|
|
343
|
+
if device != "cpu":
|
|
344
|
+
cut = StateCut(
|
|
345
|
+
cut.model_identity,
|
|
346
|
+
cut.execution,
|
|
347
|
+
cut.boundary,
|
|
348
|
+
cut.parent,
|
|
349
|
+
_move(cut.payload, device),
|
|
350
|
+
cut.execution_point,
|
|
351
|
+
cut.surface,
|
|
352
|
+
)
|
|
353
|
+
if cut.fingerprint != identifier:
|
|
354
|
+
raise ValueError("device hydration changed StateCut identity")
|
|
355
|
+
return cut
|
|
356
|
+
|
|
357
|
+
def _load_v1(self, identifier: str, data: dict[str, Any], *, device: str) -> StateCut:
|
|
358
|
+
warnings.warn(_LEGACY_CAVEAT, RuntimeWarning, stacklevel=3)
|
|
359
|
+
manifest = data.get("manifest")
|
|
360
|
+
if (
|
|
361
|
+
not isinstance(manifest, dict)
|
|
362
|
+
or manifest.get("schema") != "saturn-pub-statecut-v1"
|
|
363
|
+
or digest(manifest) != identifier
|
|
364
|
+
or data.get("fingerprint") != identifier
|
|
365
|
+
):
|
|
366
|
+
raise ValueError("legacy StateCut manifest digest mismatch")
|
|
367
|
+
tensors: dict[str, Any] = {}
|
|
368
|
+
if data.get("blob") is not None:
|
|
369
|
+
from safetensors.torch import load
|
|
370
|
+
|
|
371
|
+
blob_id = _safe_id(data["blob"])
|
|
372
|
+
blob = (self.root / "blobs" / f"{blob_id}.safetensors").read_bytes()
|
|
373
|
+
if hashlib.sha256(blob).hexdigest() != blob_id:
|
|
374
|
+
raise ValueError("legacy tensor blob digest mismatch")
|
|
375
|
+
tensors = load(blob)
|
|
376
|
+
payload = _decode_v1(data.get("encoded"), tensors)
|
|
377
|
+
expected = {
|
|
378
|
+
"schema": "saturn-pub-statecut-v1",
|
|
379
|
+
"model_identity": manifest["model_identity"],
|
|
380
|
+
"execution": manifest["execution"],
|
|
381
|
+
"boundary": manifest["boundary"],
|
|
382
|
+
"parent": manifest["parent"],
|
|
383
|
+
"payload": legacy_describe_v1(payload),
|
|
384
|
+
}
|
|
385
|
+
if expected != manifest:
|
|
386
|
+
raise ValueError("legacy descriptor does not match hydrated payload")
|
|
387
|
+
return StateCut(
|
|
388
|
+
manifest["model_identity"],
|
|
389
|
+
manifest["execution"],
|
|
390
|
+
manifest["boundary"],
|
|
391
|
+
manifest["parent"],
|
|
392
|
+
_move(payload, device),
|
|
393
|
+
{
|
|
394
|
+
"authority": "non-authoritative-historical-v1",
|
|
395
|
+
"source_fingerprint": identifier,
|
|
396
|
+
"caveat": _LEGACY_CAVEAT,
|
|
397
|
+
},
|
|
398
|
+
None,
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
def load(self, identifier: str, *, device: str = "cpu") -> StateCut:
|
|
402
|
+
identifier = _safe_id(identifier)
|
|
403
|
+
data = json.loads((self.root / "cuts" / f"{identifier}.json").read_bytes())
|
|
404
|
+
if data.get("schema") == "saturn-pub-local-cut-v2":
|
|
405
|
+
return self._load_v2(identifier, data, device=device)
|
|
406
|
+
return self._load_v1(identifier, data, device=device)
|
|
407
|
+
|
|
408
|
+
def receipt(self, receipt: Receipt) -> str:
|
|
409
|
+
_publish(
|
|
410
|
+
self.root / "receipts" / f"{receipt.fingerprint}.json", canonical(receipt.to_dict())
|
|
411
|
+
)
|
|
412
|
+
return receipt.fingerprint
|
|
413
|
+
|
|
414
|
+
def inspect(self, identifier: str) -> dict[str, Any]:
|
|
415
|
+
identifier = _safe_id(identifier)
|
|
416
|
+
data = json.loads((self.root / "cuts" / f"{identifier}.json").read_bytes())
|
|
417
|
+
manifest = data.get("manifest")
|
|
418
|
+
if not isinstance(manifest, dict) or digest(manifest) != identifier:
|
|
419
|
+
raise ValueError("manifest digest mismatch")
|
|
420
|
+
if data.get("fingerprint") != identifier:
|
|
421
|
+
raise ValueError("stored StateCut fingerprint mismatch")
|
|
422
|
+
if manifest.get("schema") == "saturn-pub-statecut-v1":
|
|
423
|
+
warnings.warn(_LEGACY_CAVEAT, RuntimeWarning, stacklevel=2)
|
|
424
|
+
return {**manifest, "historical_typing_caveat": _LEGACY_CAVEAT}
|
|
425
|
+
if data.get("schema") != "saturn-pub-local-cut-v2":
|
|
426
|
+
raise ValueError("unknown local cut schema")
|
|
427
|
+
return manifest
|
|
428
|
+
|
|
429
|
+
def export_graph(
|
|
430
|
+
self, heads: Mapping[str, str], *, include_data: bool = False
|
|
431
|
+
) -> dict[str, Any]:
|
|
432
|
+
if not heads or any(not isinstance(name, str) or not name for name in heads):
|
|
433
|
+
raise ValueError("export heads require non-empty string names")
|
|
434
|
+
pending = list(heads.values())
|
|
435
|
+
cuts: dict[str, Any] = {}
|
|
436
|
+
page_ids: set[str] = set()
|
|
437
|
+
blob_ids: set[str] = set()
|
|
438
|
+
while pending:
|
|
439
|
+
identifier = _safe_id(pending.pop())
|
|
440
|
+
if identifier in cuts:
|
|
441
|
+
continue
|
|
442
|
+
path = self.root / "cuts" / f"{identifier}.json"
|
|
443
|
+
if not path.exists():
|
|
444
|
+
raise ValueError(f"local ancestor is unavailable: {identifier}")
|
|
445
|
+
data = json.loads(path.read_bytes())
|
|
446
|
+
if (
|
|
447
|
+
data.get("schema") != "saturn-pub-local-cut-v2"
|
|
448
|
+
or digest(data["manifest"]) != identifier
|
|
449
|
+
):
|
|
450
|
+
raise ValueError("ReplayBundle exports require authoritative verified v2 cuts")
|
|
451
|
+
cuts[identifier] = data
|
|
452
|
+
page_ids.update(data["slots"].values())
|
|
453
|
+
blob_ids.update(data["physical_blobs"])
|
|
454
|
+
parent = data.get("logical_parent")
|
|
455
|
+
if parent is not None and (self.root / "cuts" / f"{parent}.json").exists():
|
|
456
|
+
pending.append(parent)
|
|
457
|
+
objects: dict[str, Any] = {"pages": {}, "blobs": {}}
|
|
458
|
+
if include_data:
|
|
459
|
+
for identifier in sorted(page_ids):
|
|
460
|
+
raw = (self.root / "pages" / f"{_safe_id(identifier)}.json").read_bytes()
|
|
461
|
+
if hashlib.sha256(raw).hexdigest() != identifier:
|
|
462
|
+
raise ValueError("cannot export a corrupt slot page")
|
|
463
|
+
objects["pages"][identifier] = base64.b64encode(raw).decode("ascii")
|
|
464
|
+
for identifier in sorted(blob_ids):
|
|
465
|
+
raw = (self.root / "blobs" / f"{_safe_id(identifier)}.safetensors").read_bytes()
|
|
466
|
+
if hashlib.sha256(raw).hexdigest() != identifier:
|
|
467
|
+
raise ValueError("cannot export a corrupt tensor blob")
|
|
468
|
+
objects["blobs"][identifier] = base64.b64encode(raw).decode("ascii")
|
|
469
|
+
return {
|
|
470
|
+
"schema": "saturn-pub-local-graph-v1",
|
|
471
|
+
"heads": dict(heads),
|
|
472
|
+
"cuts": cuts,
|
|
473
|
+
"objects": objects,
|
|
474
|
+
"data_included": include_data,
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
def import_graph(self, graph: Mapping[str, Any], *, allow_data: bool = False) -> None:
|
|
478
|
+
if graph.get("schema") != "saturn-pub-local-graph-v1":
|
|
479
|
+
raise ValueError("unknown local graph schema")
|
|
480
|
+
if not graph.get("data_included") or not allow_data:
|
|
481
|
+
raise ValueError("cut data import requires data_included and allow_data=True")
|
|
482
|
+
cuts = dict(graph.get("cuts", {}))
|
|
483
|
+
objects = dict(graph.get("objects", {}))
|
|
484
|
+
pages = dict(objects.get("pages", {}))
|
|
485
|
+
blobs = dict(objects.get("blobs", {}))
|
|
486
|
+
decoded_pages: dict[str, bytes] = {}
|
|
487
|
+
decoded_blobs: dict[str, bytes] = {}
|
|
488
|
+
heads = dict(graph.get("heads", {}))
|
|
489
|
+
if not heads or any(identifier not in cuts for identifier in heads.values()):
|
|
490
|
+
raise ValueError("imported graph head is absent from its cut inventory")
|
|
491
|
+
for identifier, encoded in pages.items():
|
|
492
|
+
raw = base64.b64decode(encoded, validate=True)
|
|
493
|
+
if hashlib.sha256(raw).hexdigest() != _safe_id(identifier):
|
|
494
|
+
raise ValueError("imported slot page digest mismatch")
|
|
495
|
+
decoded_pages[identifier] = raw
|
|
496
|
+
for identifier, encoded in blobs.items():
|
|
497
|
+
raw = base64.b64decode(encoded, validate=True)
|
|
498
|
+
if hashlib.sha256(raw).hexdigest() != _safe_id(identifier):
|
|
499
|
+
raise ValueError("imported tensor blob digest mismatch")
|
|
500
|
+
decoded_blobs[identifier] = raw
|
|
501
|
+
for identifier, data in cuts.items():
|
|
502
|
+
identifier = _safe_id(identifier)
|
|
503
|
+
if data.get("schema") != "saturn-pub-local-cut-v2":
|
|
504
|
+
raise ValueError("imported graph contains a non-v2 cut")
|
|
505
|
+
if data.get("fingerprint") != identifier or digest(data.get("manifest")) != identifier:
|
|
506
|
+
raise ValueError("imported cut manifest digest mismatch")
|
|
507
|
+
if not set(data.get("slots", {}).values()).issubset(decoded_pages):
|
|
508
|
+
raise ValueError("imported graph is missing a slot page")
|
|
509
|
+
if not set(data.get("physical_blobs", ())).issubset(decoded_blobs):
|
|
510
|
+
raise ValueError("imported graph is missing a tensor blob")
|
|
511
|
+
hydrated_pages: dict[str, Any] = {}
|
|
512
|
+
for identifier, raw in decoded_pages.items():
|
|
513
|
+
page = json.loads(raw)
|
|
514
|
+
if page.get("schema") != "saturn-pub-slot-page-v1":
|
|
515
|
+
raise ValueError("imported graph contains an unknown slot page")
|
|
516
|
+
tensors: dict[str, Any] = {}
|
|
517
|
+
blob_id = page.get("tensor_blob")
|
|
518
|
+
if blob_id is not None:
|
|
519
|
+
if blob_id not in decoded_blobs:
|
|
520
|
+
raise ValueError("imported slot page references a missing tensor blob")
|
|
521
|
+
from safetensors.torch import load
|
|
522
|
+
|
|
523
|
+
tensors = load(decoded_blobs[blob_id])
|
|
524
|
+
used: set[str] = set()
|
|
525
|
+
value = _decode(page.get("encoded"), tensors, used)
|
|
526
|
+
if used != set(tensors) or describe(value) != page.get("value"):
|
|
527
|
+
raise ValueError("imported slot page does not hydrate to its descriptor")
|
|
528
|
+
hydrated_pages[identifier] = value
|
|
529
|
+
for identifier, data in cuts.items():
|
|
530
|
+
manifest = data["manifest"]
|
|
531
|
+
payload = {name: hydrated_pages[page] for name, page in data["slots"].items()}
|
|
532
|
+
observed_blobs = sorted(
|
|
533
|
+
{
|
|
534
|
+
json.loads(decoded_pages[page]).get("tensor_blob")
|
|
535
|
+
for page in data["slots"].values()
|
|
536
|
+
if json.loads(decoded_pages[page]).get("tensor_blob") is not None
|
|
537
|
+
}
|
|
538
|
+
)
|
|
539
|
+
if observed_blobs != data["physical_blobs"]:
|
|
540
|
+
raise ValueError("imported cut physical blob inventory mismatch")
|
|
541
|
+
cut = StateCut(
|
|
542
|
+
manifest["model_identity"],
|
|
543
|
+
manifest["execution"],
|
|
544
|
+
manifest["boundary"],
|
|
545
|
+
manifest["parent"],
|
|
546
|
+
payload,
|
|
547
|
+
data.get("execution_point"),
|
|
548
|
+
data.get("surface"),
|
|
549
|
+
)
|
|
550
|
+
if cut.fingerprint != identifier or cut.manifest() != manifest:
|
|
551
|
+
raise ValueError("imported cut does not hydrate to its identity")
|
|
552
|
+
for identifier, raw in decoded_blobs.items():
|
|
553
|
+
_publish(self.root / "blobs" / f"{identifier}.safetensors", raw)
|
|
554
|
+
for identifier, raw in decoded_pages.items():
|
|
555
|
+
_publish(self.root / "pages" / f"{identifier}.json", raw)
|
|
556
|
+
for identifier, data in cuts.items():
|
|
557
|
+
_publish(self.root / "cuts" / f"{identifier}.json", canonical(data))
|
|
558
|
+
|
|
559
|
+
# Single tensors by content address (occurrence values). Each is one safetensors file,
|
|
560
|
+
# tensors/<sha256 of the file>.safetensors, holding one tensor named "tensor" with
|
|
561
|
+
# little-endian payload bytes; __metadata__ records the payload sha256. The file is written
|
|
562
|
+
# here byte for byte (canonical header, space-padded to 8 bytes), so numpy arrays need no
|
|
563
|
+
# torch and bfloat16 round-trips through torch only.
|
|
564
|
+
#
|
|
565
|
+
# Temporary files (``tensors/tmp*``, unique per write: tempfile picks a fresh random name)
|
|
566
|
+
# that a killed process left behind are removed by the next successful put once they are
|
|
567
|
+
# older than ``_STALE_TMP_SECONDS``; a file a live process is writing is younger than that.
|
|
568
|
+
# A blob hard-linked into a shared pool (``shared_store``) is never repaired from here: if
|
|
569
|
+
# it is corrupt the pooled object is, and the pool is repaired there.
|
|
570
|
+
|
|
571
|
+
def put_tensor(self, value: Any) -> dict[str, Any]:
|
|
572
|
+
dtype, shape, payload = _tensor_payload(value)
|
|
573
|
+
payload_sha = hashlib.sha256(payload).hexdigest()
|
|
574
|
+
header = {
|
|
575
|
+
"__metadata__": {"schema": _TENSOR_SCHEMA, "sha256": payload_sha},
|
|
576
|
+
"tensor": {
|
|
577
|
+
"dtype": _SAFETENSORS_DTYPES[dtype][0],
|
|
578
|
+
"shape": shape,
|
|
579
|
+
"data_offsets": [0, len(payload)],
|
|
580
|
+
},
|
|
581
|
+
}
|
|
582
|
+
raw_header = json.dumps(header, sort_keys=True, separators=(",", ":")).encode()
|
|
583
|
+
raw_header += b" " * (-len(raw_header) % 8)
|
|
584
|
+
data = len(raw_header).to_bytes(8, "little") + raw_header + payload
|
|
585
|
+
ref = hashlib.sha256(data).hexdigest()
|
|
586
|
+
path = self.root / "tensors" / f"{ref}.safetensors"
|
|
587
|
+
self._repair_tensor(path, data)
|
|
588
|
+
_publish(path, data)
|
|
589
|
+
self._remove_stale_temporaries(path.parent)
|
|
590
|
+
return {
|
|
591
|
+
"ref": ref,
|
|
592
|
+
"shape": shape,
|
|
593
|
+
"dtype": dtype,
|
|
594
|
+
"sha256": payload_sha,
|
|
595
|
+
"bytes": len(payload),
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
@staticmethod
|
|
599
|
+
def _remove_stale_temporaries(directory: Path) -> None:
|
|
600
|
+
"""Delete ``tmp*`` files older than ``_STALE_TMP_SECONDS`` (best effort, never raises)."""
|
|
601
|
+
import time
|
|
602
|
+
|
|
603
|
+
cutoff = time.time() - _STALE_TMP_SECONDS
|
|
604
|
+
try:
|
|
605
|
+
entries = list(directory.iterdir())
|
|
606
|
+
except OSError:
|
|
607
|
+
return
|
|
608
|
+
for entry in entries:
|
|
609
|
+
if not entry.name.startswith("tmp"):
|
|
610
|
+
continue
|
|
611
|
+
try:
|
|
612
|
+
if entry.is_file() and not entry.is_symlink() and entry.stat().st_mtime < cutoff:
|
|
613
|
+
entry.unlink(missing_ok=True)
|
|
614
|
+
except OSError:
|
|
615
|
+
continue
|
|
616
|
+
|
|
617
|
+
@staticmethod
|
|
618
|
+
def _repair_tensor(path: Path, data: bytes) -> None:
|
|
619
|
+
"""Replace an on-disk blob whose bytes differ from its content address, atomically.
|
|
620
|
+
|
|
621
|
+
The correct bytes are written to a temporary file in the same directory, fsynced and
|
|
622
|
+
renamed over the damaged file, so a reader sees the old or the new file, never a mix.
|
|
623
|
+
A blob that is a directory is a ``ValueError``; a damaged blob hard-linked into a shared
|
|
624
|
+
pool is a ``ValueError`` naming the pooled object (repair it in the pool).
|
|
625
|
+
"""
|
|
626
|
+
if path.is_dir():
|
|
627
|
+
raise ValueError(f"tensor blob path {path} is a directory, not a file")
|
|
628
|
+
try:
|
|
629
|
+
existing = path.read_bytes()
|
|
630
|
+
except FileNotFoundError:
|
|
631
|
+
return
|
|
632
|
+
if existing == data:
|
|
633
|
+
return
|
|
634
|
+
LocalStore._refuse_pooled_blob(path, data)
|
|
635
|
+
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
|
636
|
+
temporary = Path(stream.name)
|
|
637
|
+
stream.write(data)
|
|
638
|
+
stream.flush()
|
|
639
|
+
os.fsync(stream.fileno())
|
|
640
|
+
try:
|
|
641
|
+
os.replace(temporary, path)
|
|
642
|
+
except BaseException:
|
|
643
|
+
temporary.unlink(missing_ok=True)
|
|
644
|
+
raise
|
|
645
|
+
try:
|
|
646
|
+
directory = os.open(path.parent, os.O_RDONLY)
|
|
647
|
+
except OSError:
|
|
648
|
+
return
|
|
649
|
+
try:
|
|
650
|
+
os.fsync(directory)
|
|
651
|
+
finally:
|
|
652
|
+
os.close(directory)
|
|
653
|
+
|
|
654
|
+
@staticmethod
|
|
655
|
+
def _refuse_pooled_blob(path: Path, data: bytes) -> None:
|
|
656
|
+
"""A corrupt blob that is the same inode as its shared-pool object is not repaired here."""
|
|
657
|
+
try:
|
|
658
|
+
if path.stat().st_nlink < 2:
|
|
659
|
+
return
|
|
660
|
+
from .shared_store import configured_store
|
|
661
|
+
|
|
662
|
+
pool = configured_store(path)
|
|
663
|
+
if pool is None:
|
|
664
|
+
return
|
|
665
|
+
pooled = pool.object_path(hashlib.sha256(data).hexdigest())
|
|
666
|
+
if pooled.exists() and os.path.samefile(path, pooled):
|
|
667
|
+
raise ValueError(
|
|
668
|
+
f"the pooled object {pooled} is corrupt (it is hard-linked at {path}); "
|
|
669
|
+
"repair it in the shared pool: remove the object there and publish the "
|
|
670
|
+
"tensor again; this store does not repair a pooled blob"
|
|
671
|
+
)
|
|
672
|
+
except ValueError:
|
|
673
|
+
raise
|
|
674
|
+
except OSError:
|
|
675
|
+
return
|
|
676
|
+
|
|
677
|
+
@staticmethod
|
|
678
|
+
def _tensor_ref(ref: Any) -> str:
|
|
679
|
+
if not isinstance(ref, str):
|
|
680
|
+
raise ValueError(
|
|
681
|
+
f"expected a lowercase SHA-256 identifier (text), not {type(ref).__name__}"
|
|
682
|
+
)
|
|
683
|
+
return _safe_id(ref)
|
|
684
|
+
|
|
685
|
+
def has_tensor(self, ref: str, *, verify: bool = False) -> bool:
|
|
686
|
+
"""Whether the blob exists; with ``verify`` also that its size, header and hash are sound."""
|
|
687
|
+
path = self.root / "tensors" / f"{self._tensor_ref(ref)}.safetensors"
|
|
688
|
+
if not path.is_file():
|
|
689
|
+
return False
|
|
690
|
+
if not verify:
|
|
691
|
+
return True
|
|
692
|
+
try:
|
|
693
|
+
self._read_tensor(ref)
|
|
694
|
+
except (ValueError, OSError):
|
|
695
|
+
return False
|
|
696
|
+
return True
|
|
697
|
+
|
|
698
|
+
def tensor_info(self, ref: str) -> dict[str, Any]:
|
|
699
|
+
"""Verified descriptor of a stored tensor, without materialising it."""
|
|
700
|
+
dtype, shape, payload_sha, payload = self._read_tensor(ref)
|
|
701
|
+
return {
|
|
702
|
+
"ref": ref,
|
|
703
|
+
"shape": shape,
|
|
704
|
+
"dtype": dtype,
|
|
705
|
+
"sha256": payload_sha,
|
|
706
|
+
"bytes": len(payload),
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
def get_tensor(
|
|
710
|
+
self, ref: str, *, device: str | None = None, framework: str | None = None
|
|
711
|
+
) -> Any:
|
|
712
|
+
"""Rebuild a stored tensor after verifying both digests.
|
|
713
|
+
|
|
714
|
+
Returns a numpy array unless ``device`` is given, ``framework="torch"``, or the dtype
|
|
715
|
+
has no numpy form (bfloat16): then a torch tensor (torch is imported only then). The
|
|
716
|
+
numpy array is a writable copy (never a view of the verified bytes); so is the torch one.
|
|
717
|
+
"""
|
|
718
|
+
if framework not in (None, "numpy", "torch"):
|
|
719
|
+
raise ValueError("framework is 'numpy' or 'torch'")
|
|
720
|
+
dtype, shape, _, payload = self._read_tensor(ref)
|
|
721
|
+
if framework == "numpy" and (device is not None or dtype == "bfloat16"):
|
|
722
|
+
raise ValueError("a bfloat16 tensor or a device placement needs framework='torch'")
|
|
723
|
+
if framework == "torch" or device is not None or dtype == "bfloat16":
|
|
724
|
+
import torch
|
|
725
|
+
|
|
726
|
+
torch_dtype = getattr(torch, dtype)
|
|
727
|
+
if not payload:
|
|
728
|
+
restored = torch.empty(shape, dtype=torch_dtype)
|
|
729
|
+
else:
|
|
730
|
+
restored = torch.frombuffer(bytearray(payload), dtype=torch.uint8)
|
|
731
|
+
restored = restored.view(torch_dtype).reshape(shape)
|
|
732
|
+
return restored if device is None else restored.to(device)
|
|
733
|
+
import numpy as np
|
|
734
|
+
|
|
735
|
+
little = np.dtype(dtype).newbyteorder("<")
|
|
736
|
+
return np.frombuffer(payload, dtype=little).reshape(shape).astype(np.dtype(dtype))
|
|
737
|
+
|
|
738
|
+
def _read_tensor(self, ref: str) -> tuple[str, list[int], str, bytes]:
|
|
739
|
+
identifier = self._tensor_ref(ref)
|
|
740
|
+
blob = self.root / "tensors" / f"{identifier}.safetensors"
|
|
741
|
+
if blob.is_dir():
|
|
742
|
+
raise ValueError(f"tensor blob path {blob} is a directory, not a file")
|
|
743
|
+
data = blob.read_bytes()
|
|
744
|
+
if hashlib.sha256(data).hexdigest() != identifier:
|
|
745
|
+
raise ValueError("tensor blob digest mismatch")
|
|
746
|
+
size = int.from_bytes(data[:8], "little") if len(data) >= 8 else -1
|
|
747
|
+
if size < 2 or 8 + size > len(data):
|
|
748
|
+
raise ValueError("tensor blob header is malformed")
|
|
749
|
+
try:
|
|
750
|
+
header = json.loads(data[8 : 8 + size])
|
|
751
|
+
entry = header["tensor"]
|
|
752
|
+
metadata = header["__metadata__"]
|
|
753
|
+
codes = {code: name for name, (code, _) in _SAFETENSORS_DTYPES.items()}
|
|
754
|
+
if (
|
|
755
|
+
not isinstance(header, dict)
|
|
756
|
+
or not isinstance(entry, dict)
|
|
757
|
+
or not isinstance(metadata, dict)
|
|
758
|
+
or not isinstance(entry["dtype"], str)
|
|
759
|
+
):
|
|
760
|
+
raise ValueError("header sections are mappings and the dtype is text")
|
|
761
|
+
dtype = codes[entry["dtype"]]
|
|
762
|
+
shape = entry["shape"]
|
|
763
|
+
begin, end = entry["data_offsets"]
|
|
764
|
+
except (ValueError, KeyError, TypeError, RecursionError) as error:
|
|
765
|
+
raise ValueError("tensor blob header is malformed") from error
|
|
766
|
+
if (
|
|
767
|
+
set(header) != {"__metadata__", "tensor"}
|
|
768
|
+
or type(begin) is not int
|
|
769
|
+
or type(end) is not int
|
|
770
|
+
or metadata.get("schema") != _TENSOR_SCHEMA
|
|
771
|
+
or not isinstance(shape, list)
|
|
772
|
+
or any(type(n) is not int or n < 0 for n in shape)
|
|
773
|
+
):
|
|
774
|
+
raise ValueError("tensor blob header is malformed")
|
|
775
|
+
payload = data[8 + size :]
|
|
776
|
+
count = 1
|
|
777
|
+
for n in shape:
|
|
778
|
+
count *= n
|
|
779
|
+
expected = count * _SAFETENSORS_DTYPES[dtype][1]
|
|
780
|
+
if (begin, end) != (0, len(payload)) or len(payload) != expected:
|
|
781
|
+
raise ValueError("tensor blob payload does not match its header")
|
|
782
|
+
payload_sha = hashlib.sha256(payload).hexdigest()
|
|
783
|
+
if metadata.get("sha256") != payload_sha:
|
|
784
|
+
raise ValueError("tensor payload digest mismatch")
|
|
785
|
+
return dtype, shape, payload_sha, payload
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
_TENSOR_SCHEMA = "saturn-pub-tensor-v1"
|
|
789
|
+
_STALE_TMP_SECONDS = 3600
|
|
790
|
+
# dtype name -> (safetensors code, bytes per element)
|
|
791
|
+
_SAFETENSORS_DTYPES = {
|
|
792
|
+
"bool": ("BOOL", 1),
|
|
793
|
+
"uint8": ("U8", 1),
|
|
794
|
+
"int8": ("I8", 1),
|
|
795
|
+
"int16": ("I16", 2),
|
|
796
|
+
"uint16": ("U16", 2),
|
|
797
|
+
"int32": ("I32", 4),
|
|
798
|
+
"uint32": ("U32", 4),
|
|
799
|
+
"int64": ("I64", 8),
|
|
800
|
+
"uint64": ("U64", 8),
|
|
801
|
+
"float16": ("F16", 2),
|
|
802
|
+
"bfloat16": ("BF16", 2),
|
|
803
|
+
"float32": ("F32", 4),
|
|
804
|
+
"float64": ("F64", 8),
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def _tensor_payload(value: Any) -> tuple[str, list[int], bytes]:
|
|
809
|
+
"""(dtype name, shape, little-endian bytes) of a torch tensor or numpy array."""
|
|
810
|
+
if tensor(value):
|
|
811
|
+
import sys
|
|
812
|
+
|
|
813
|
+
import torch
|
|
814
|
+
|
|
815
|
+
if sys.byteorder != "little":
|
|
816
|
+
raise ValueError("torch tensor blobs require a little-endian host")
|
|
817
|
+
# Lazy conjugate/negation views carry a flag the raw storage does not: materialise them.
|
|
818
|
+
value = value.detach().resolve_conj().resolve_neg().cpu().contiguous()
|
|
819
|
+
dtype = str(value.dtype).removeprefix("torch.")
|
|
820
|
+
if dtype not in _SAFETENSORS_DTYPES:
|
|
821
|
+
raise ValueError(f"unsupported tensor dtype: {dtype}")
|
|
822
|
+
payload = value.reshape(-1).view(torch.uint8).numpy().tobytes()
|
|
823
|
+
return dtype, list(value.shape), payload
|
|
824
|
+
if type(value).__module__ == "numpy" and hasattr(value, "dtype"):
|
|
825
|
+
import numpy as np
|
|
826
|
+
|
|
827
|
+
array = np.asarray(value) # ascontiguousarray would turn a 0-d array into 1-d
|
|
828
|
+
if not array.flags.c_contiguous:
|
|
829
|
+
array = array.copy(order="C")
|
|
830
|
+
dtype = array.dtype.name
|
|
831
|
+
if dtype not in _SAFETENSORS_DTYPES or dtype == "bfloat16":
|
|
832
|
+
raise ValueError(f"unsupported array dtype: {array.dtype}")
|
|
833
|
+
array = array.astype(array.dtype.newbyteorder("<"), copy=False)
|
|
834
|
+
return dtype, list(array.shape), array.tobytes()
|
|
835
|
+
raise ValueError("put_tensor expects a torch tensor or a numpy array")
|