model-debugger 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/core/pointers.py
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
"""The pointer rule: records hold locators and digests, never tensors.
|
|
2
|
+
|
|
3
|
+
Moved here unchanged from ``mdb.symbol_reads`` (which re-exports every name, so existing
|
|
4
|
+
imports and serialized records are byte-identical): the bounds (``check_bounded``), seals
|
|
5
|
+
(``seal_digest``) and the ``file`` / ``parameter`` / ``run`` pointers. The only code change is
|
|
6
|
+
that numpy is no longer imported at module load: a numpy scalar can only exist once numpy is
|
|
7
|
+
in ``sys.modules``, so ``_bounded`` looks it up there.
|
|
8
|
+
|
|
9
|
+
New here: the ``occurrence`` pointer (a value named by its canonical address and the program,
|
|
10
|
+
recipe event and cut that produce it) and a resolver registry. ``resolve(pointer, **context)``
|
|
11
|
+
dispatches on ``pointer["kind"]`` and raises ``Unresolved`` (never returns None). The
|
|
12
|
+
``occurrence`` resolver needs the engine and is registered by it, not here.
|
|
13
|
+
|
|
14
|
+
Pointer kinds and their fields:
|
|
15
|
+
|
|
16
|
+
* ``file``: ``locator {root, path}``, ``digest {sha256, size}``, optional ``array``,
|
|
17
|
+
``selector``, ``json_pointer``, ``role``. ``locator.path`` is relative and stays under its
|
|
18
|
+
root: ``validate_pointer`` refuses an absolute path, a ``..`` component (``/`` or ``\\``
|
|
19
|
+
separated), an empty path and a NUL byte; the ``file`` resolver also resolves the path and
|
|
20
|
+
requires it to lie under the resolved root (a symlink out of the root is refused), without
|
|
21
|
+
touching the target, with one outcome for an existing and a missing target.
|
|
22
|
+
* ``parameter``: ``parameter``, ``model`` (``model_identity`` record), optional ``selector``.
|
|
23
|
+
* ``run``: ``run_id``, optional ``plan_sha256`` and ``plan`` (a file pointer).
|
|
24
|
+
* ``occurrence``: ``address`` (canonical address JSON), ``program``, ``recipe``, ``event``,
|
|
25
|
+
``cut``, ``value {shape, dtype, sha256}``, optional ``authority``.
|
|
26
|
+
* ``tensor``: ``ref`` (the blob id in a saturn ``LocalStore``), ``sha256`` (of the raw
|
|
27
|
+
little-endian payload, ``tensor_digest``), ``shape``, ``dtype``. ``resolve_tensor`` reads it
|
|
28
|
+
from a ``LocalStore``, checking both digests.
|
|
29
|
+
"""
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import hashlib
|
|
33
|
+
import json
|
|
34
|
+
import math
|
|
35
|
+
import numbers
|
|
36
|
+
import sys
|
|
37
|
+
from collections.abc import Mapping
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
|
|
40
|
+
MAX_INLINE_ITEMS = 64
|
|
41
|
+
MAX_RECORD_ITEMS = 4096
|
|
42
|
+
MAX_RECORD_BYTES = 64 * 1024
|
|
43
|
+
MAX_META_BYTES = 64 * 1024
|
|
44
|
+
MAX_TEXT_BYTES = 4 * 1024
|
|
45
|
+
|
|
46
|
+
# How a number was obtained. Never merged into one field with resolution state.
|
|
47
|
+
AUTHORITIES = ("measured", "derived-exact", "derived-local", "bound", "supplied")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class RecordError(ValueError):
|
|
51
|
+
"""A record or pointer is malformed, unbounded, or claims more than its evidence.
|
|
52
|
+
|
|
53
|
+
``mdb.symbol_reads.SymbolReadError`` is this class.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Unresolved(LookupError):
|
|
58
|
+
"""A pointer could not be turned into its value.
|
|
59
|
+
|
|
60
|
+
``refused`` is True when the target was found but failed verification (wrong digest or
|
|
61
|
+
identity), False when it is simply not available in the given context.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(self, reason, *, refused=False):
|
|
65
|
+
self.reason, self.refused = reason, refused
|
|
66
|
+
super().__init__(reason)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# --------------------------------------------------------------------------- bounds and seals
|
|
70
|
+
|
|
71
|
+
def check_bounded(value, label="record", *, max_bytes=MAX_RECORD_BYTES, max_items=MAX_RECORD_ITEMS):
|
|
72
|
+
"""Return ``value`` as plain JSON, refusing arrays, tensors, bytes and oversized data.
|
|
73
|
+
|
|
74
|
+
Enforced recursively: no tensor-like value (0-d arrays included), no raw bytes, no
|
|
75
|
+
non-finite number, text <= ``MAX_TEXT_BYTES``, mappings <= 4 x ``MAX_INLINE_ITEMS`` keys,
|
|
76
|
+
any sequence <= ``MAX_INLINE_ITEMS`` items counting every item of the sequences nested in
|
|
77
|
+
it (a 48 x 48 list holds 2352), <= ``max_items`` values in total, and <= ``max_bytes`` of
|
|
78
|
+
canonical JSON. numpy scalars (``np.bool_``, ``np.int64``, ``np.float32``...) convert.
|
|
79
|
+
"""
|
|
80
|
+
count = [0]
|
|
81
|
+
out = _bounded(value, label, 0, count, max_items, None)
|
|
82
|
+
if max_bytes is not None:
|
|
83
|
+
size = len(_canonical(out).encode())
|
|
84
|
+
if size > max_bytes:
|
|
85
|
+
raise RecordError(f"{label} is {size} bytes (> {max_bytes}); store it by pointer")
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _bounded(value, label, depth, count, max_items, run):
|
|
90
|
+
if depth > 16:
|
|
91
|
+
raise RecordError(label + " nests too deeply")
|
|
92
|
+
count[0] += 1
|
|
93
|
+
if count[0] > max_items:
|
|
94
|
+
raise RecordError(f"{label}: more than {max_items} values in one record; store it by pointer")
|
|
95
|
+
np = sys.modules.get("numpy")
|
|
96
|
+
if np is not None and isinstance(value, np.generic):
|
|
97
|
+
value = value.item()
|
|
98
|
+
if value is None or isinstance(value, (bool, str)):
|
|
99
|
+
if isinstance(value, str) and len(value.encode()) > MAX_TEXT_BYTES:
|
|
100
|
+
raise RecordError(label + " text exceeds the inline limit")
|
|
101
|
+
return value
|
|
102
|
+
if isinstance(value, numbers.Integral):
|
|
103
|
+
return int(value)
|
|
104
|
+
if isinstance(value, numbers.Real):
|
|
105
|
+
if not math.isfinite(float(value)):
|
|
106
|
+
raise RecordError(label + " is not finite")
|
|
107
|
+
return float(value)
|
|
108
|
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
|
109
|
+
raise RecordError(label + " holds raw bytes; reference the artifact by pointer")
|
|
110
|
+
if any(hasattr(value, a) for a in ("shape", "ndim", "detach", "__array__")):
|
|
111
|
+
raise RecordError(label + " holds an array or tensor; reference it by pointer")
|
|
112
|
+
if isinstance(value, Mapping):
|
|
113
|
+
if len(value) > MAX_INLINE_ITEMS * 4:
|
|
114
|
+
raise RecordError(label + " has too many keys")
|
|
115
|
+
out = {}
|
|
116
|
+
for key, item in value.items():
|
|
117
|
+
if not isinstance(key, str):
|
|
118
|
+
raise RecordError(label + " has a non-text key")
|
|
119
|
+
out[key] = _bounded(item, f"{label}.{key}", depth + 1, count, max_items, None)
|
|
120
|
+
return out
|
|
121
|
+
if isinstance(value, (list, tuple)):
|
|
122
|
+
if len(value) > MAX_INLINE_ITEMS:
|
|
123
|
+
raise RecordError(
|
|
124
|
+
f"{label} has {len(value)} items (> {MAX_INLINE_ITEMS}); store it by pointer")
|
|
125
|
+
# Items of directly nested sequences share the outermost sequence's item budget.
|
|
126
|
+
run = [0] if run is None else run
|
|
127
|
+
run[0] += len(value)
|
|
128
|
+
if run[0] > MAX_INLINE_ITEMS:
|
|
129
|
+
raise RecordError(f"{label} holds more than {MAX_INLINE_ITEMS} items across nested "
|
|
130
|
+
"sequences; store it by pointer")
|
|
131
|
+
return [_bounded(item, f"{label}[{i}]", depth + 1, count, max_items,
|
|
132
|
+
run if isinstance(item, (list, tuple)) else None)
|
|
133
|
+
for i, item in enumerate(value)]
|
|
134
|
+
raise RecordError(f"{label} has unsupported type {type(value).__name__}")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _canonical(value):
|
|
138
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def seal_digest(value):
|
|
142
|
+
return hashlib.sha256(_canonical(value).encode()).hexdigest()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _sealed(body, label):
|
|
146
|
+
body = check_bounded(body, label)
|
|
147
|
+
return {**body, "fingerprint": seal_digest(body)}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _sha(value, label):
|
|
151
|
+
text = str(value or "").removeprefix("sha256:")
|
|
152
|
+
if len(text) != 64 or any(c not in "0123456789abcdef" for c in text):
|
|
153
|
+
raise RecordError(label + " must be a sha256 hex digest")
|
|
154
|
+
return text
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _text(value, label):
|
|
158
|
+
if not isinstance(value, str) or not value.strip() or value != value.strip():
|
|
159
|
+
raise RecordError(label + " must be non-empty text without surrounding whitespace")
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _number(value, label, *, optional=True):
|
|
164
|
+
if value is None and optional:
|
|
165
|
+
return None
|
|
166
|
+
if isinstance(value, bool) or not isinstance(value, numbers.Real) or not math.isfinite(float(value)):
|
|
167
|
+
raise RecordError(label + " must be a finite number")
|
|
168
|
+
return float(value)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def file_sha256(path):
|
|
172
|
+
h = hashlib.sha256()
|
|
173
|
+
with open(path, "rb") as handle:
|
|
174
|
+
for block in iter(lambda: handle.read(1 << 20), b""):
|
|
175
|
+
h.update(block)
|
|
176
|
+
return h.hexdigest()
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# --------------------------------------------------------------------------- pointers and identity
|
|
180
|
+
|
|
181
|
+
def declare_root(name, path):
|
|
182
|
+
"""A named storage root: pointers hold ``name`` + a relative path, never the absolute path."""
|
|
183
|
+
return {"name": _text(name, "root name"), "path": str(Path(path).resolve())}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def file_pointer(path, *, root, array=None, selector=None, json_pointer=None, sha256=None, role=None):
|
|
187
|
+
"""Reference saved bytes: locator (root name + relative path) and digest (sha256 + size).
|
|
188
|
+
|
|
189
|
+
``root`` comes from ``declare_root``; the file must lie under it. ``sha256`` is computed when
|
|
190
|
+
not supplied. The bytes are never copied.
|
|
191
|
+
"""
|
|
192
|
+
path = Path(path).resolve()
|
|
193
|
+
try:
|
|
194
|
+
relative = path.relative_to(Path(root["path"]))
|
|
195
|
+
except ValueError as error:
|
|
196
|
+
raise RecordError(f"{path} is not under the declared root {root['name']!r}") from error
|
|
197
|
+
pointer = {"kind": "file", "locator": {"root": root["name"], "path": relative.as_posix()},
|
|
198
|
+
"digest": {"sha256": _sha(sha256, "file sha256") if sha256 else file_sha256(path),
|
|
199
|
+
"size": path.stat().st_size}}
|
|
200
|
+
for key, value in (("array", array), ("selector", selector), ("json_pointer", json_pointer),
|
|
201
|
+
("role", role)):
|
|
202
|
+
if value is not None:
|
|
203
|
+
pointer[key] = list(value) if isinstance(value, tuple) else value
|
|
204
|
+
return check_bounded(pointer, "file pointer")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _locate(pointer, roots):
|
|
208
|
+
"""``(path, real, inside)``: the root-joined path, its fully resolved real path and whether
|
|
209
|
+
that stays under the resolved root. Nothing is opened or hashed, so an existing and a
|
|
210
|
+
missing target give one outcome. A path that is absolute, climbs with ``..`` or cannot be
|
|
211
|
+
resolved (a symlink loop) is not inside."""
|
|
212
|
+
locator = pointer["locator"]
|
|
213
|
+
if locator["root"] not in roots:
|
|
214
|
+
raise RecordError(f"pointer names undeclared root {locator['root']!r}")
|
|
215
|
+
root = Path(roots[locator["root"]])
|
|
216
|
+
try:
|
|
217
|
+
_relative_path(locator["path"])
|
|
218
|
+
path = root / locator["path"]
|
|
219
|
+
base = root.resolve()
|
|
220
|
+
real = path.resolve()
|
|
221
|
+
except (RecordError, OSError, RuntimeError, ValueError, TypeError):
|
|
222
|
+
return root / "?", None, False
|
|
223
|
+
return path, real, real.is_relative_to(base)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def resolve_pointer(pointer, roots):
|
|
227
|
+
"""Path of a file pointer under ``roots`` ({name: path}); refuses an undeclared root.
|
|
228
|
+
|
|
229
|
+
Confined like ``resolve``: a path that leaves its root (absolute, ``..``, a symlink out) is
|
|
230
|
+
a ``RecordError`` whether or not the target exists. The target is not opened.
|
|
231
|
+
"""
|
|
232
|
+
path, real, inside = _locate(pointer, roots)
|
|
233
|
+
if not inside:
|
|
234
|
+
raise RecordError(ESCAPE)
|
|
235
|
+
return path
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def verify_pointer(pointer, roots):
|
|
239
|
+
"""Resolve a file pointer and check its digest (size, then sha256)."""
|
|
240
|
+
path, real, inside = _locate(pointer, roots)
|
|
241
|
+
if not inside:
|
|
242
|
+
raise RecordError(ESCAPE)
|
|
243
|
+
digest = pointer["digest"]
|
|
244
|
+
if real.stat().st_size != digest["size"] or file_sha256(real) != digest["sha256"]:
|
|
245
|
+
raise RecordError(f"{path} does not match its pointer digest")
|
|
246
|
+
return path
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def model_identity(name, *, checkpoint_sha256=None, resolve_by=None):
|
|
250
|
+
"""A model name plus whether it is a verified identity.
|
|
251
|
+
|
|
252
|
+
With ``checkpoint_sha256`` the status is ``verified``. Without it the name only stands in
|
|
253
|
+
for an identity: status ``unresolved``, and ``resolve_by`` must say what would resolve it.
|
|
254
|
+
"""
|
|
255
|
+
record = {"name": _text(name, "model name")}
|
|
256
|
+
if checkpoint_sha256 is not None:
|
|
257
|
+
record.update(identity_status="verified", checkpoint_sha256=_sha(checkpoint_sha256, "checkpoint sha256"))
|
|
258
|
+
else:
|
|
259
|
+
if not resolve_by:
|
|
260
|
+
raise RecordError("an unverified model name says what would resolve it ('resolve_by')")
|
|
261
|
+
record.update(identity_status="unresolved", resolve_by=str(resolve_by))
|
|
262
|
+
return check_bounded(record, "model identity")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _identity_record(value):
|
|
266
|
+
if value is None:
|
|
267
|
+
return None
|
|
268
|
+
value = dict(value)
|
|
269
|
+
if value.get("identity_status") == "verified":
|
|
270
|
+
return model_identity(value.get("name"), checkpoint_sha256=value.get("checkpoint_sha256"))
|
|
271
|
+
if value.get("identity_status") == "unresolved":
|
|
272
|
+
return model_identity(value.get("name"), resolve_by=value.get("resolve_by"))
|
|
273
|
+
raise RecordError("model identity_status must be 'verified' or 'unresolved'")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def parameter_pointer(model_identity_name, parameter, *, selector=None, checkpoint_sha256=None, resolve_by=None):
|
|
277
|
+
"""Reference a model parameter by model identity + parameter name (+ optional selector).
|
|
278
|
+
|
|
279
|
+
Without ``checkpoint_sha256`` the model name is not a verified identity: the pointer says
|
|
280
|
+
``identity_status: "unresolved"`` and needs ``resolve_by``.
|
|
281
|
+
"""
|
|
282
|
+
if not model_identity_name or not parameter:
|
|
283
|
+
raise RecordError("parameter pointer needs a model identity and parameter name")
|
|
284
|
+
pointer = {"kind": "parameter", "parameter": str(parameter),
|
|
285
|
+
"model": model_identity(str(model_identity_name), checkpoint_sha256=checkpoint_sha256,
|
|
286
|
+
resolve_by=resolve_by or ("checkpoint sha256 of the file holding "
|
|
287
|
+
"this parameter"))}
|
|
288
|
+
if selector is not None:
|
|
289
|
+
pointer["selector"] = list(selector)
|
|
290
|
+
return check_bounded(pointer, "parameter pointer")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def run_pointer(run_id, *, plan_sha256=None, plan=None):
|
|
294
|
+
"""Reference a run by id, its plan hash and optionally the plan's file pointer."""
|
|
295
|
+
pointer = {"kind": "run", "run_id": _text(run_id, "run id")}
|
|
296
|
+
if plan_sha256 is not None:
|
|
297
|
+
pointer["plan_sha256"] = _sha(plan_sha256, "plan sha256")
|
|
298
|
+
if plan is not None:
|
|
299
|
+
if plan_sha256 is not None and plan["digest"]["sha256"] != pointer["plan_sha256"]:
|
|
300
|
+
raise RecordError("plan pointer digest differs from plan sha256")
|
|
301
|
+
pointer["plan"] = dict(plan)
|
|
302
|
+
return check_bounded(pointer, "run pointer")
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# --------------------------------------------------------------------------- occurrence pointer
|
|
306
|
+
|
|
307
|
+
OCCURRENCE_FIELDS = ("kind", "address", "program", "recipe", "event", "cut", "value")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _ref(value, label):
|
|
311
|
+
"""A short reference: non-empty text of [A-Za-z0-9_.:-], at most 128 characters."""
|
|
312
|
+
allowed = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-")
|
|
313
|
+
if not isinstance(value, str) or not 0 < len(value) <= 128 or set(value) - allowed:
|
|
314
|
+
raise RecordError(label + " must be a short reference ([A-Za-z0-9_.:-], <= 128 chars)")
|
|
315
|
+
return value
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
INT_CAP = 10 ** 15 # a sealed integer holds at most 15 decimal digits (records.INT_DIGITS)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _count_ok(n):
|
|
322
|
+
return isinstance(n, int) and not isinstance(n, bool) and 0 <= n < INT_CAP
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _value_descriptor(shape, dtype, sha256):
|
|
326
|
+
if not isinstance(shape, (list, tuple)) or not all(_count_ok(n) for n in shape):
|
|
327
|
+
raise RecordError("occurrence value shape must be a list of integers in [0, 10**15)")
|
|
328
|
+
if not isinstance(dtype, str) or not dtype or len(dtype) > 32:
|
|
329
|
+
raise RecordError("occurrence value dtype must be short text such as 'bfloat16'")
|
|
330
|
+
return {"shape": list(shape), "dtype": dtype,
|
|
331
|
+
"sha256": None if sha256 is None else _sha(sha256, "occurrence value sha256")}
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _occurrence_address(address, ports, global_ports):
|
|
335
|
+
"""An ``Occurrence`` from an object, text or JSON.
|
|
336
|
+
|
|
337
|
+
Text is parsed against the port lists (default: the Qwen2 list). JSON and objects are
|
|
338
|
+
checked against the lists only when they are given: stored pointers are validated without
|
|
339
|
+
the engine's port program, so any well-formed port name passes there.
|
|
340
|
+
"""
|
|
341
|
+
from . import address as addresses
|
|
342
|
+
|
|
343
|
+
check = ports is not None or global_ports is not None
|
|
344
|
+
try:
|
|
345
|
+
if isinstance(address, str):
|
|
346
|
+
return addresses.parse(address, ports=ports, global_ports=global_ports)
|
|
347
|
+
if isinstance(address, Mapping):
|
|
348
|
+
return addresses.from_json(dict(address), ports=ports, global_ports=global_ports,
|
|
349
|
+
check_ports=check)
|
|
350
|
+
if isinstance(address, (addresses.Occurrence, addresses.StateCell)):
|
|
351
|
+
if check and isinstance(address, addresses.Occurrence):
|
|
352
|
+
addresses.from_json(address.to_json(), ports=ports, global_ports=global_ports)
|
|
353
|
+
return address
|
|
354
|
+
except addresses.AddressError as error:
|
|
355
|
+
raise RecordError(f"occurrence address: {error}") from error
|
|
356
|
+
raise RecordError("an occurrence address is an Occurrence, its text or its JSON")
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def occurrence_pointer(address, *, program, shape, dtype, sha256=None, recipe=None, event=None,
|
|
360
|
+
cut=None, authority=None, ports=None, global_ports=None):
|
|
361
|
+
"""Point at one occurrence value by address and the program that produced it.
|
|
362
|
+
|
|
363
|
+
``address`` is an ``Occurrence`` (not a state cell), its text or its JSON. ``program``
|
|
364
|
+
names the producing program (``stepped``, ``prefill``...); it must agree with the
|
|
365
|
+
address's own ``~program`` when that is set. ``recipe`` and ``cut`` say how to rebuild the
|
|
366
|
+
value, ``event`` is the recipe event index, ``sha256`` the value's raw little-endian bytes
|
|
367
|
+
(None until hashed). ``ports``/``global_ports``: see ``_occurrence_address``.
|
|
368
|
+
"""
|
|
369
|
+
from . import address as addresses
|
|
370
|
+
|
|
371
|
+
occurrence = _occurrence_address(address, ports, global_ports)
|
|
372
|
+
if not isinstance(occurrence, addresses.Occurrence):
|
|
373
|
+
raise RecordError("an occurrence pointer names a port occurrence, not a state cell")
|
|
374
|
+
program = _ref(program, "occurrence program")
|
|
375
|
+
if occurrence.program is not None and occurrence.program != program:
|
|
376
|
+
raise RecordError("occurrence pointer program differs from its address program")
|
|
377
|
+
if event is not None and not _count_ok(event):
|
|
378
|
+
raise RecordError("occurrence event must be a recipe event index in [0, 10**15)")
|
|
379
|
+
pointer = {"kind": "occurrence", "address": occurrence.to_json(), "program": program,
|
|
380
|
+
"recipe": None if recipe is None else _ref(recipe, "occurrence recipe"),
|
|
381
|
+
"event": event, "cut": None if cut is None else _sha(cut, "occurrence cut"),
|
|
382
|
+
"value": _value_descriptor(shape, dtype, sha256)}
|
|
383
|
+
if authority is not None:
|
|
384
|
+
if authority not in AUTHORITIES:
|
|
385
|
+
raise RecordError("authority must be one of " + ", ".join(AUTHORITIES))
|
|
386
|
+
pointer["authority"] = authority
|
|
387
|
+
return check_bounded(pointer, "occurrence pointer")
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def validate_occurrence_pointer(pointer, *, ports=None, global_ports=None):
|
|
391
|
+
"""Re-validate a stored occurrence pointer; returns it in canonical form or raises."""
|
|
392
|
+
if not isinstance(pointer, Mapping) or pointer.get("kind") != "occurrence":
|
|
393
|
+
raise RecordError("not an occurrence pointer")
|
|
394
|
+
keys = set(pointer)
|
|
395
|
+
if not set(OCCURRENCE_FIELDS) <= keys <= set(OCCURRENCE_FIELDS) | {"authority"}:
|
|
396
|
+
raise RecordError("occurrence pointer fields are " + ", ".join(OCCURRENCE_FIELDS)
|
|
397
|
+
+ " and optional authority")
|
|
398
|
+
value = pointer["value"]
|
|
399
|
+
if not isinstance(value, Mapping) or set(value) != {"shape", "dtype", "sha256"}:
|
|
400
|
+
raise RecordError("occurrence value is {shape, dtype, sha256}")
|
|
401
|
+
if not isinstance(pointer["address"], Mapping):
|
|
402
|
+
raise RecordError("a stored occurrence pointer holds the address JSON")
|
|
403
|
+
address = _occurrence_address(pointer["address"], ports, global_ports)
|
|
404
|
+
rebuilt = occurrence_pointer(address, program=pointer["program"], shape=value["shape"],
|
|
405
|
+
dtype=value["dtype"], sha256=value["sha256"],
|
|
406
|
+
recipe=pointer["recipe"], event=pointer["event"],
|
|
407
|
+
cut=pointer["cut"], authority=pointer.get("authority"))
|
|
408
|
+
if _canonical(rebuilt) != _canonical(check_bounded(dict(pointer), "occurrence pointer")):
|
|
409
|
+
raise RecordError("occurrence pointer is not in canonical form")
|
|
410
|
+
return rebuilt
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
# --------------------------------------------------------------------------- tensor pointer
|
|
414
|
+
|
|
415
|
+
TENSOR_FIELDS = ("kind", "ref", "sha256", "shape", "dtype")
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def tensor_pointer(ref, *, sha256, shape, dtype):
|
|
419
|
+
"""Point at one tensor blob of a saturn ``LocalStore`` (``put_tensor``'s result).
|
|
420
|
+
|
|
421
|
+
``ref`` is the blob id (sha256 of the stored file), ``sha256`` the payload digest, so the
|
|
422
|
+
pointer is checked twice on resolve: the store checks the file, the resolver the payload.
|
|
423
|
+
"""
|
|
424
|
+
descriptor = _value_descriptor(shape, dtype, sha256)
|
|
425
|
+
if descriptor["sha256"] is None:
|
|
426
|
+
raise RecordError("a tensor pointer needs the payload sha256")
|
|
427
|
+
return check_bounded({"kind": "tensor", "ref": _sha(ref, "tensor blob ref"),
|
|
428
|
+
"sha256": descriptor["sha256"], "shape": descriptor["shape"],
|
|
429
|
+
"dtype": descriptor["dtype"]}, "tensor pointer")
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def validate_tensor_pointer(pointer):
|
|
433
|
+
"""Re-validate a stored tensor pointer; returns it in canonical form or raises."""
|
|
434
|
+
if not isinstance(pointer, Mapping) or set(pointer) != set(TENSOR_FIELDS):
|
|
435
|
+
raise RecordError("tensor pointer fields are " + ", ".join(TENSOR_FIELDS))
|
|
436
|
+
rebuilt = tensor_pointer(pointer["ref"], sha256=pointer["sha256"], shape=pointer["shape"],
|
|
437
|
+
dtype=pointer["dtype"])
|
|
438
|
+
if _canonical(rebuilt) != _canonical(check_bounded(dict(pointer), "tensor pointer")):
|
|
439
|
+
raise RecordError("tensor pointer is not in canonical form")
|
|
440
|
+
return rebuilt
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
ESCAPE = "file pointer path must be non-empty, relative and stay under its root"
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _relative_path(path):
|
|
447
|
+
"""Refuse an absolute, empty, NUL-holding or ``..``-climbing path (text only; the message
|
|
448
|
+
never repeats the path, so a refusal tells nothing about the filesystem)."""
|
|
449
|
+
if not isinstance(path, str):
|
|
450
|
+
return path
|
|
451
|
+
flat = path.replace("\\", "/")
|
|
452
|
+
if (not path.strip() or "\0" in path or flat.startswith("/")
|
|
453
|
+
or (len(flat) > 1 and flat[0].isalpha() and flat[1] == ":")
|
|
454
|
+
or ".." in flat.split("/")):
|
|
455
|
+
raise RecordError(ESCAPE)
|
|
456
|
+
return path
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def validate_pointer(pointer):
|
|
460
|
+
"""Structural check of any pointer kind; unknown kinds need only bounded JSON and a kind."""
|
|
461
|
+
if not isinstance(pointer, Mapping) or not isinstance(pointer.get("kind"), str):
|
|
462
|
+
raise RecordError("a pointer is a mapping with a 'kind'")
|
|
463
|
+
kind = pointer["kind"]
|
|
464
|
+
if kind == "occurrence":
|
|
465
|
+
return validate_occurrence_pointer(pointer)
|
|
466
|
+
if kind == "tensor":
|
|
467
|
+
return validate_tensor_pointer(pointer)
|
|
468
|
+
pointer = check_bounded(dict(pointer), f"{kind} pointer")
|
|
469
|
+
if kind == "file":
|
|
470
|
+
locator, digest = pointer.get("locator"), pointer.get("digest")
|
|
471
|
+
if (not isinstance(locator, dict) or set(locator) != {"root", "path"}
|
|
472
|
+
or not isinstance(digest, dict) or set(digest) != {"sha256", "size"}):
|
|
473
|
+
raise RecordError("file pointer needs locator {root, path} and digest {sha256, size}")
|
|
474
|
+
_sha(digest["sha256"], "file sha256")
|
|
475
|
+
_relative_path(locator["path"])
|
|
476
|
+
elif kind == "parameter":
|
|
477
|
+
if not isinstance(pointer.get("parameter"), str) or not pointer["parameter"]:
|
|
478
|
+
raise RecordError("parameter pointer needs a parameter name")
|
|
479
|
+
_identity_record(pointer.get("model"))
|
|
480
|
+
elif kind == "run":
|
|
481
|
+
_text(pointer.get("run_id"), "run id")
|
|
482
|
+
return pointer
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# --------------------------------------------------------------------------- resolvers
|
|
486
|
+
|
|
487
|
+
_RESOLVERS = {}
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def register_resolver(kind, resolver, *, replace=False):
|
|
491
|
+
"""Register ``resolver(pointer, **context)`` for pointers of ``kind``."""
|
|
492
|
+
if not isinstance(kind, str) or not kind:
|
|
493
|
+
raise ValueError("resolver kind must be non-empty text")
|
|
494
|
+
if kind in _RESOLVERS and not replace:
|
|
495
|
+
raise ValueError(f"a resolver for {kind!r} is already registered")
|
|
496
|
+
_RESOLVERS[kind] = resolver
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def unregister_resolver(kind):
|
|
500
|
+
_RESOLVERS.pop(kind, None)
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def resolvers():
|
|
504
|
+
return tuple(sorted(_RESOLVERS))
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def resolve(pointer, **context):
|
|
508
|
+
"""The value a pointer names. Raises ``Unresolved`` when it cannot be produced."""
|
|
509
|
+
kind = pointer.get("kind") if isinstance(pointer, Mapping) else None
|
|
510
|
+
if isinstance(pointer, Mapping) and "kind" in pointer and not isinstance(kind, str):
|
|
511
|
+
raise Unresolved("malformed pointer: kind must be text", refused=True)
|
|
512
|
+
if kind not in _RESOLVERS:
|
|
513
|
+
raise Unresolved(f"no resolver registered for pointer kind {kind!r}")
|
|
514
|
+
try:
|
|
515
|
+
value = _RESOLVERS[kind](pointer, **context)
|
|
516
|
+
except Unresolved:
|
|
517
|
+
raise
|
|
518
|
+
except Exception as error: # a resolver (built in or plug-in) never leaks a raw exception
|
|
519
|
+
raise Unresolved(f"resolver {kind} failed: {type(error).__name__}", refused=True) from error
|
|
520
|
+
if value is None:
|
|
521
|
+
raise Unresolved(f"the {kind!r} resolver returned no value")
|
|
522
|
+
return value
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _well_formed(pointer):
|
|
526
|
+
"""The pointer passes ``validate_pointer``; otherwise ``Unresolved`` (never KeyError)."""
|
|
527
|
+
try:
|
|
528
|
+
return validate_pointer(pointer)
|
|
529
|
+
except (RecordError, TypeError, ValueError, KeyError, AttributeError) as error:
|
|
530
|
+
raise Unresolved(f"malformed pointer: {error}", refused=True) from error
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _resolve_file(pointer, *, roots=None, **_):
|
|
534
|
+
"""Checked path of a file pointer; context ``roots`` = {root name: directory}."""
|
|
535
|
+
pointer = _well_formed(pointer)
|
|
536
|
+
locator, digest = pointer["locator"], pointer["digest"]
|
|
537
|
+
if (not isinstance(locator["root"], str) or not isinstance(locator["path"], str)
|
|
538
|
+
or isinstance(digest["size"], bool) or not isinstance(digest["size"], int)):
|
|
539
|
+
raise Unresolved("malformed pointer: locator root/path are text and digest size an integer",
|
|
540
|
+
refused=True)
|
|
541
|
+
if roots is None:
|
|
542
|
+
raise Unresolved("file pointer needs roots={name: directory}")
|
|
543
|
+
if pointer["locator"]["root"] not in roots:
|
|
544
|
+
raise Unresolved(f"root {pointer['locator']['root']!r} is not declared in this context")
|
|
545
|
+
path, real, inside = _locate(pointer, roots) # follows symlinks; target not opened yet
|
|
546
|
+
if not inside:
|
|
547
|
+
raise Unresolved("outside root", refused=True)
|
|
548
|
+
if not real.is_file():
|
|
549
|
+
raise Unresolved(f"{path} is missing")
|
|
550
|
+
if real.stat().st_size != digest["size"] or file_sha256(real) != digest["sha256"]:
|
|
551
|
+
raise Unresolved(f"{path} does not match its pointer digest", refused=True)
|
|
552
|
+
return real # the path that was checked, not the unresolved one a symlink swap could redirect
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _resolve_parameter(pointer, *, parameters=None, model=None, checkpoint_sha256=None,
|
|
556
|
+
allow_unverified=False, **_):
|
|
557
|
+
"""A named parameter (selected), from ``parameters`` (a mapping) or ``model``.
|
|
558
|
+
|
|
559
|
+
A verified pointer needs the context's ``checkpoint_sha256`` to equal its own; an
|
|
560
|
+
unresolved identity is refused unless ``allow_unverified=True``.
|
|
561
|
+
"""
|
|
562
|
+
pointer = _well_formed(pointer)
|
|
563
|
+
if not isinstance(pointer.get("selector", []), (list, tuple)):
|
|
564
|
+
raise Unresolved("malformed pointer: parameter selector must be a list", refused=True)
|
|
565
|
+
identity = pointer.get("model")
|
|
566
|
+
if not isinstance(identity, Mapping):
|
|
567
|
+
raise Unresolved("malformed pointer: a parameter pointer names its model identity",
|
|
568
|
+
refused=True)
|
|
569
|
+
if identity.get("identity_status") == "verified":
|
|
570
|
+
if checkpoint_sha256 is None:
|
|
571
|
+
raise Unresolved("verified parameter pointer needs the context's checkpoint_sha256")
|
|
572
|
+
if checkpoint_sha256 != identity["checkpoint_sha256"]:
|
|
573
|
+
raise Unresolved("checkpoint differs from the pointer's identity", refused=True)
|
|
574
|
+
elif not allow_unverified:
|
|
575
|
+
raise Unresolved("model identity is unresolved: " + str(identity.get("resolve_by")))
|
|
576
|
+
if parameters is None and model is not None:
|
|
577
|
+
if not hasattr(model, "named_parameters"):
|
|
578
|
+
raise Unresolved("model= needs a named_parameters() method")
|
|
579
|
+
parameters = dict(model.named_parameters())
|
|
580
|
+
if parameters is None:
|
|
581
|
+
raise Unresolved("parameter pointer needs parameters= or model=")
|
|
582
|
+
if not isinstance(parameters, Mapping):
|
|
583
|
+
raise Unresolved("parameters= must be a mapping")
|
|
584
|
+
if pointer["parameter"] not in parameters:
|
|
585
|
+
raise Unresolved(f"parameter {pointer['parameter']!r} is not in this model")
|
|
586
|
+
value = parameters[pointer["parameter"]]
|
|
587
|
+
for index in pointer.get("selector", ()):
|
|
588
|
+
try:
|
|
589
|
+
value = value[index]
|
|
590
|
+
except (IndexError, KeyError, TypeError) as error:
|
|
591
|
+
raise Unresolved("parameter selector is outside the parameter", refused=True) from error
|
|
592
|
+
return value
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def resolve_tensor(pointer, *, store=None, framework="torch"):
|
|
596
|
+
"""The tensor a tensor pointer names, from ``store`` (a ``LocalStore``).
|
|
597
|
+
|
|
598
|
+
A missing blob is ``Unresolved``; a blob that fails the store's digest checks or whose
|
|
599
|
+
payload digest, shape or dtype differs from the pointer is a refusal naming the blob. Not
|
|
600
|
+
in the ``resolve`` registry (which stays file and parameter): call it directly.
|
|
601
|
+
"""
|
|
602
|
+
pointer = _well_formed(pointer)
|
|
603
|
+
if store is None:
|
|
604
|
+
raise Unresolved("tensor pointer needs store= (the LocalStore holding its blob)")
|
|
605
|
+
ref = pointer["ref"]
|
|
606
|
+
if not store.has_tensor(ref):
|
|
607
|
+
raise Unresolved(f"tensor blob {ref} is missing from the store")
|
|
608
|
+
try:
|
|
609
|
+
info = store.tensor_info(ref)
|
|
610
|
+
value = store.get_tensor(ref, framework=framework)
|
|
611
|
+
except (ValueError, OSError) as error:
|
|
612
|
+
raise Unresolved(f"tensor blob {ref} is corrupt: {error}", refused=True) from error
|
|
613
|
+
if (info["sha256"], info["shape"], info["dtype"]) != (
|
|
614
|
+
pointer["sha256"], pointer["shape"], pointer["dtype"]):
|
|
615
|
+
raise Unresolved(f"tensor blob {ref} differs from its pointer (payload digest, shape or "
|
|
616
|
+
"dtype)", refused=True)
|
|
617
|
+
return value
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
register_resolver("file", _resolve_file)
|
|
621
|
+
register_resolver("parameter", _resolve_parameter)
|