computeharbor-worker 0.2.4__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.
@@ -0,0 +1,43 @@
1
+ from computeharbor_worker.batch_inference import (
2
+ BatchCursorManifest,
3
+ BatchInferenceRunner,
4
+ BatchRunSummary,
5
+ )
6
+ from computeharbor_worker.checkpoint import CheckpointManager
7
+ from computeharbor_worker.client import ControlPlaneClient, ControlPlaneError
8
+ from computeharbor_worker.daemon import run_worker_daemon
9
+ from computeharbor_worker.models import CheckpointManifest, LoRAConfig, RNGStatePayload
10
+ from computeharbor_worker.preemption import MetadataPreemptionWatcher, MetadataProvider
11
+ from computeharbor_worker.storage import (
12
+ CheckpointStore,
13
+ HTTPPresignedStore,
14
+ LocalMirrorObjectStore,
15
+ cuda_synchronize_if_available,
16
+ store_from_uri,
17
+ )
18
+ from computeharbor_worker.supervisor import FailoverResult, run_job_with_failover
19
+ from computeharbor_worker.trainer import LoRATrainer, RunResult
20
+
21
+ __all__ = [
22
+ "BatchCursorManifest",
23
+ "BatchInferenceRunner",
24
+ "BatchRunSummary",
25
+ "CheckpointManager",
26
+ "CheckpointManifest",
27
+ "CheckpointStore",
28
+ "ControlPlaneClient",
29
+ "ControlPlaneError",
30
+ "FailoverResult",
31
+ "HTTPPresignedStore",
32
+ "LoRAConfig",
33
+ "LoRATrainer",
34
+ "LocalMirrorObjectStore",
35
+ "MetadataPreemptionWatcher",
36
+ "MetadataProvider",
37
+ "RNGStatePayload",
38
+ "RunResult",
39
+ "cuda_synchronize_if_available",
40
+ "run_job_with_failover",
41
+ "run_worker_daemon",
42
+ "store_from_uri",
43
+ ]
@@ -0,0 +1,303 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import sys
7
+ import time
8
+ from collections.abc import Mapping, Sequence
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+ from pydantic import BaseModel, ConfigDict, Field
14
+
15
+ from computeharbor_worker.checkpoint import (
16
+ _atomic_write_bytes,
17
+ _decode_json_safe,
18
+ _encode_json_safe,
19
+ )
20
+ from computeharbor_worker.trainer import PreemptionSignalGuard
21
+
22
+
23
+ class BatchCursorManifest(BaseModel):
24
+ model_config = ConfigDict(frozen=True, extra="forbid")
25
+
26
+ job_id: str = Field(min_length=1)
27
+ processed_count: int = Field(ge=0)
28
+ total_records: int = Field(ge=0)
29
+ output_sha256: str = Field(min_length=64, max_length=64)
30
+ preempted: bool = False
31
+ numpy_rng_state_json: str
32
+ flush_duration_ms: float = Field(ge=0.0)
33
+ elapsed_ms: float = Field(default=0.0, ge=0.0)
34
+ records_per_sec: float = Field(default=0.0, ge=0.0)
35
+ estimated_cost_per_million_records_usd: float = Field(default=0.0, ge=0.0)
36
+
37
+
38
+ BatchRunSummary = BatchCursorManifest
39
+
40
+
41
+ def _normalize_prompt(item: str | Mapping[str, Any]) -> str:
42
+ if isinstance(item, str):
43
+ return item
44
+ if "prompt" in item:
45
+ return str(item["prompt"])
46
+ if "text" in item:
47
+ return str(item["text"])
48
+ return json.dumps(dict(item), sort_keys=True, separators=(",", ":"))
49
+
50
+
51
+ class BatchInferenceRunner:
52
+ """Deterministic, checkpointed batch inference worker with atomic SIGTERM recovery."""
53
+
54
+ def __init__(
55
+ self,
56
+ job_id: str,
57
+ checkpoint_dir: Path | str,
58
+ seed: int = 42,
59
+ batch_size: int = 8,
60
+ spot_hourly_usd: float = 0.24,
61
+ ) -> None:
62
+ if batch_size <= 0:
63
+ raise ValueError(f"batch_size must be positive, got {batch_size}")
64
+ if spot_hourly_usd < 0.0:
65
+ raise ValueError(f"spot_hourly_usd must be non-negative, got {spot_hourly_usd}")
66
+ self.job_id = job_id
67
+ self.checkpoint_dir = Path(checkpoint_dir)
68
+ self.checkpoint_dir.mkdir(parents=True, exist_ok=True)
69
+ self.seed = seed
70
+ self.batch_size = batch_size
71
+ self.spot_hourly_usd = spot_hourly_usd
72
+ self.np_rng = np.random.default_rng(seed)
73
+
74
+ self.output_path = self.checkpoint_dir / "output.jsonl"
75
+ self.manifest_path = self.checkpoint_dir / "batch_cursor.manifest.json"
76
+ self._lines: list[str] = []
77
+ self._reconcile_stale_temporaries()
78
+
79
+ def _reconcile_stale_temporaries(self) -> int:
80
+ removed = 0
81
+ for stale in self.checkpoint_dir.glob("*.tmp"):
82
+ stale.unlink(missing_ok=True)
83
+ removed += 1
84
+ return removed
85
+
86
+ def has_checkpoint(self) -> bool:
87
+ return self.manifest_path.is_file() and self.output_path.is_file()
88
+
89
+ def restore_if_available(self) -> BatchCursorManifest | None:
90
+ self._reconcile_stale_temporaries()
91
+ if not self.manifest_path.is_file():
92
+ self._lines = []
93
+ return None
94
+ if not self.output_path.is_file():
95
+ raise FileNotFoundError(f"Missing output JSONL file at {self.output_path}")
96
+
97
+ manifest = BatchCursorManifest.model_validate_json(
98
+ self.manifest_path.read_text(encoding="utf-8")
99
+ )
100
+ raw_bytes = self.output_path.read_bytes()
101
+ actual_sha256 = hashlib.sha256(raw_bytes).hexdigest()
102
+ if actual_sha256 != manifest.output_sha256:
103
+ raise ValueError(
104
+ f"Output JSONL SHA256 mismatch: expected {manifest.output_sha256}, "
105
+ f"got {actual_sha256}"
106
+ )
107
+
108
+ decoded = raw_bytes.decode("utf-8")
109
+ lines = decoded.splitlines(keepends=True)
110
+ if len(lines) != manifest.processed_count:
111
+ raise ValueError(
112
+ f"Output JSONL line count mismatch: expected {manifest.processed_count}, "
113
+ f"got {len(lines)}"
114
+ )
115
+
116
+ np_state = _decode_json_safe(json.loads(manifest.numpy_rng_state_json))
117
+ if not isinstance(np_state, dict):
118
+ raise ValueError("Corrupted numpy RNG state in BatchCursorManifest")
119
+ self.np_rng.bit_generator.state = np_state
120
+ self._lines = lines
121
+ return manifest
122
+
123
+ def _infer_record(self, index: int, prompt: str) -> str:
124
+ rng_val = float(self.np_rng.random())
125
+ prompt_digest = hashlib.sha256(f"{index}:{prompt}".encode()).hexdigest()
126
+ score = round(0.5 * rng_val + 0.5 * (int(prompt_digest[:8], 16) / 0xFFFFFFFF), 8)
127
+ token_digest = hashlib.sha256(
128
+ f"{prompt_digest}:{rng_val:.12f}".encode()
129
+ ).hexdigest()[:16]
130
+ record = {
131
+ "index": index,
132
+ "prompt": prompt,
133
+ "score": score,
134
+ "token_digest": token_digest,
135
+ }
136
+ return json.dumps(record, separators=(",", ":")) + "\n"
137
+
138
+ def _flush(
139
+ self,
140
+ *,
141
+ total_records: int,
142
+ preempted: bool,
143
+ elapsed_ms: float = 0.0,
144
+ records_in_run: int = 0,
145
+ ) -> BatchCursorManifest:
146
+ t0 = time.perf_counter()
147
+ output_bytes = "".join(self._lines).encode("utf-8")
148
+ _atomic_write_bytes(self.output_path, output_bytes)
149
+ output_sha256 = hashlib.sha256(output_bytes).hexdigest()
150
+ flush_ms = round((time.perf_counter() - t0) * 1000.0, 4)
151
+
152
+ elapsed_ms_rounded = round(max(0.0, elapsed_ms), 4)
153
+ elapsed_sec = elapsed_ms_rounded / 1000.0
154
+ if records_in_run > 0 and elapsed_sec > 0.0:
155
+ records_per_sec = round(records_in_run / elapsed_sec, 4)
156
+ cost_per_sec = self.spot_hourly_usd / 3600.0
157
+ estimated_cost_per_million = round(
158
+ (1_000_000.0 / records_per_sec) * cost_per_sec,
159
+ 6,
160
+ )
161
+ else:
162
+ records_per_sec = 0.0
163
+ estimated_cost_per_million = 0.0
164
+
165
+ np_state_json = json.dumps(
166
+ _encode_json_safe(self.np_rng.bit_generator.state),
167
+ sort_keys=True,
168
+ )
169
+ manifest = BatchCursorManifest(
170
+ job_id=self.job_id,
171
+ processed_count=len(self._lines),
172
+ total_records=total_records,
173
+ output_sha256=output_sha256,
174
+ preempted=preempted,
175
+ numpy_rng_state_json=np_state_json,
176
+ flush_duration_ms=flush_ms,
177
+ elapsed_ms=elapsed_ms_rounded,
178
+ records_per_sec=records_per_sec,
179
+ estimated_cost_per_million_records_usd=estimated_cost_per_million,
180
+ )
181
+ _atomic_write_bytes(
182
+ self.manifest_path,
183
+ manifest.model_dump_json(indent=2).encode("utf-8"),
184
+ )
185
+ return manifest
186
+
187
+ def run(
188
+ self,
189
+ prompts: Sequence[str | Mapping[str, Any]],
190
+ *,
191
+ record_delay_sec: float = 0.0,
192
+ simulate_sigterm_at_index: int | None = None,
193
+ ready_file: Path | None = None,
194
+ ) -> BatchCursorManifest:
195
+ run_start = time.perf_counter()
196
+ normalized_prompts = [_normalize_prompt(p) for p in prompts]
197
+ total_records = len(normalized_prompts)
198
+ self.restore_if_available()
199
+
200
+ start_idx = len(self._lines)
201
+ preempted = False
202
+ with PreemptionSignalGuard() as guard:
203
+ for batch_start in range(start_idx, total_records, self.batch_size):
204
+ batch_end = min(batch_start + self.batch_size, total_records)
205
+ for idx in range(batch_start, batch_end):
206
+ self._lines.append(self._infer_record(idx, normalized_prompts[idx]))
207
+
208
+ if ready_file is not None and not ready_file.exists():
209
+ ready_file.write_text(str(len(self._lines)), encoding="utf-8")
210
+
211
+ if (
212
+ simulate_sigterm_at_index is not None
213
+ and len(self._lines) == simulate_sigterm_at_index
214
+ ):
215
+ guard.preempt_requested = True
216
+
217
+ if record_delay_sec > 0.0 and not guard.preempt_requested:
218
+ deadline = time.perf_counter() + record_delay_sec
219
+ while time.perf_counter() < deadline:
220
+ if guard.preempt_requested:
221
+ break
222
+ time.sleep(min(0.002, max(0.0, deadline - time.perf_counter())))
223
+
224
+ if guard.preempt_requested:
225
+ preempted = True
226
+ return self._flush(
227
+ total_records=total_records,
228
+ preempted=True,
229
+ elapsed_ms=(time.perf_counter() - run_start) * 1000.0,
230
+ records_in_run=len(self._lines) - start_idx,
231
+ )
232
+
233
+ if guard.preempt_requested:
234
+ preempted = True
235
+ return self._flush(
236
+ total_records=total_records,
237
+ preempted=True,
238
+ elapsed_ms=(time.perf_counter() - run_start) * 1000.0,
239
+ records_in_run=len(self._lines) - start_idx,
240
+ )
241
+
242
+ return self._flush(
243
+ total_records=total_records,
244
+ preempted=preempted,
245
+ elapsed_ms=(time.perf_counter() - run_start) * 1000.0,
246
+ records_in_run=len(self._lines) - start_idx,
247
+ )
248
+
249
+
250
+ def _load_prompts(prompts_file: str, num_prompts: int) -> list[str | Mapping[str, Any]]:
251
+ if not prompts_file:
252
+ return [f"prompt-{i:04d}" for i in range(num_prompts)]
253
+ raw_text = Path(prompts_file).read_text(encoding="utf-8")
254
+ parsed = json.loads(raw_text)
255
+ if not isinstance(parsed, list):
256
+ raise ValueError(f"Expected JSON array in {prompts_file}")
257
+ prompts: list[str | Mapping[str, Any]] = []
258
+ for entry in parsed:
259
+ if isinstance(entry, str | dict):
260
+ prompts.append(entry)
261
+ else:
262
+ raise ValueError(f"Unsupported prompt entry type: {type(entry).__name__}")
263
+ return prompts
264
+
265
+
266
+ def main(argv: list[str] | None = None) -> int:
267
+ parser = argparse.ArgumentParser(description="ComputeHarbor Deterministic Batch Inference")
268
+ parser.add_argument("--job-id", required=True)
269
+ parser.add_argument("--checkpoint-dir", required=True)
270
+ parser.add_argument("--prompts-file", default="")
271
+ parser.add_argument("--num-prompts", type=int, default=50)
272
+ parser.add_argument("--seed", type=int, default=42)
273
+ parser.add_argument("--batch-size", type=int, default=8)
274
+ parser.add_argument("--spot-hourly-usd", type=float, default=0.24)
275
+ parser.add_argument("--record-delay-sec", type=float, default=0.0)
276
+ parser.add_argument("--ready-file", default="")
277
+ parser.add_argument("--manifest-out", default="")
278
+ args = parser.parse_args(argv)
279
+
280
+ prompts = _load_prompts(args.prompts_file, args.num_prompts)
281
+ runner = BatchInferenceRunner(
282
+ job_id=args.job_id,
283
+ checkpoint_dir=Path(args.checkpoint_dir),
284
+ seed=args.seed,
285
+ batch_size=args.batch_size,
286
+ spot_hourly_usd=args.spot_hourly_usd,
287
+ )
288
+ ready_path = Path(args.ready_file) if args.ready_file else None
289
+ manifest = runner.run(
290
+ prompts,
291
+ record_delay_sec=args.record_delay_sec,
292
+ ready_file=ready_path,
293
+ )
294
+ output_json = manifest.model_dump_json(indent=2)
295
+ if args.manifest_out:
296
+ Path(args.manifest_out).write_text(output_json, encoding="utf-8")
297
+ else:
298
+ sys.stdout.write(output_json + "\n")
299
+ return 0
300
+
301
+
302
+ if __name__ == "__main__":
303
+ raise SystemExit(main())
@@ -0,0 +1,230 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import time
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ import numpy.typing as npt
13
+ from safetensors.numpy import load_file, save_file
14
+
15
+ from computeharbor_worker.models import CheckpointManifest, LoRAConfig, RNGStatePayload
16
+ from computeharbor_worker.storage import CheckpointStore
17
+
18
+ FloatArray = npt.NDArray[np.float64]
19
+
20
+
21
+ def _encode_json_safe(obj: Any) -> Any:
22
+ if isinstance(obj, np.ndarray):
23
+ return {"__ndarray__": obj.tolist(), "dtype": str(obj.dtype)}
24
+ if isinstance(obj, np.generic):
25
+ return obj.item()
26
+ if isinstance(obj, tuple):
27
+ return {"__tuple__": [_encode_json_safe(x) for x in obj]}
28
+ if isinstance(obj, list):
29
+ return [_encode_json_safe(x) for x in obj]
30
+ if isinstance(obj, dict):
31
+ return {str(k): _encode_json_safe(v) for k, v in obj.items()}
32
+ return obj
33
+
34
+
35
+ def _decode_json_safe(obj: Any) -> Any:
36
+ if isinstance(obj, dict):
37
+ if "__ndarray__" in obj:
38
+ return np.array(obj["__ndarray__"], dtype=np.dtype(obj["dtype"]))
39
+ if "__tuple__" in obj:
40
+ return tuple(_decode_json_safe(x) for x in obj["__tuple__"])
41
+ return {k: _decode_json_safe(v) for k, v in obj.items()}
42
+ if isinstance(obj, list):
43
+ return [_decode_json_safe(x) for x in obj]
44
+ return obj
45
+
46
+
47
+ def serialize_rng_state(
48
+ py_state: tuple[Any, ...],
49
+ np_state: Mapping[str, Any],
50
+ ) -> RNGStatePayload:
51
+ return RNGStatePayload(
52
+ python_random_state_json=json.dumps(_encode_json_safe(py_state), sort_keys=True),
53
+ numpy_bit_generator_state_json=json.dumps(_encode_json_safe(np_state), sort_keys=True),
54
+ )
55
+
56
+
57
+ def deserialize_rng_state(
58
+ payload: RNGStatePayload,
59
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
60
+ py_raw = _decode_json_safe(json.loads(payload.python_random_state_json))
61
+ np_raw = _decode_json_safe(json.loads(payload.numpy_bit_generator_state_json))
62
+ if not isinstance(py_raw, tuple) or not isinstance(np_raw, dict):
63
+ raise ValueError("Corrupted RNG state payload")
64
+ return py_raw, np_raw
65
+
66
+
67
+ def _atomic_write_bytes(target: Path, data: bytes) -> None:
68
+ tmp_path = target.with_name(f".{target.name}.{os.getpid()}.tmp")
69
+ with open(tmp_path, "wb") as fh:
70
+ fh.write(data)
71
+ fh.flush()
72
+ os.fsync(fh.fileno())
73
+ os.replace(tmp_path, target)
74
+
75
+
76
+ class CheckpointManager:
77
+ def __init__(
78
+ self,
79
+ checkpoint_dir: Path | str,
80
+ remote_store: CheckpointStore | None = None,
81
+ max_checkpoints: int = 5,
82
+ job_id: str | None = None,
83
+ ) -> None:
84
+ if max_checkpoints < 0:
85
+ raise ValueError(
86
+ f"max_checkpoints must be >= 0 (0 for unlimited), got {max_checkpoints}"
87
+ )
88
+ self.checkpoint_dir = Path(checkpoint_dir)
89
+ self.checkpoint_dir.mkdir(parents=True, exist_ok=True)
90
+ self.remote_store = remote_store
91
+ self.max_checkpoints = max_checkpoints
92
+ self.job_id = job_id
93
+ self.reconcile_stale_temporaries()
94
+
95
+ def _remote_latest_key(self, job_id: str | None = None) -> str:
96
+ effective_id = job_id or self.job_id
97
+ if effective_id:
98
+ return f"{effective_id}/latest.json"
99
+ return "latest.json"
100
+
101
+ def reconcile_stale_temporaries(self) -> int:
102
+ removed = 0
103
+ for stale in self.checkpoint_dir.glob("*.tmp"):
104
+ stale.unlink(missing_ok=True)
105
+ removed += 1
106
+ return removed
107
+
108
+ def prune_old_checkpoints(self) -> int:
109
+ """Remove oldest checkpoint pairs beyond max_checkpoints; 0 means unlimited."""
110
+ if self.max_checkpoints == 0:
111
+ return 0
112
+ manifests = sorted(
113
+ self.checkpoint_dir.glob("step-*.manifest.json"),
114
+ key=lambda p: p.name,
115
+ )
116
+ excess = len(manifests) - self.max_checkpoints
117
+ if excess <= 0:
118
+ return 0
119
+ pruned = 0
120
+ for manifest_path in manifests[:excess]:
121
+ st_name = manifest_path.name.removesuffix(".manifest.json") + ".safetensors"
122
+ st_path = self.checkpoint_dir / st_name
123
+ manifest_path.unlink(missing_ok=True)
124
+ st_path.unlink(missing_ok=True)
125
+ pruned += 1
126
+ return pruned
127
+
128
+ def save(
129
+ self,
130
+ *,
131
+ job_id: str,
132
+ step: int,
133
+ epoch: int,
134
+ loss_history: list[float],
135
+ lora_config: LoRAConfig,
136
+ tensors: dict[str, FloatArray],
137
+ py_rng_state: tuple[Any, ...],
138
+ np_rng_state: Mapping[str, Any],
139
+ preempted: bool = False,
140
+ ) -> CheckpointManifest:
141
+ t0 = time.perf_counter()
142
+ st_filename = f"step-{step:06d}.safetensors"
143
+ st_target = self.checkpoint_dir / st_filename
144
+ st_tmp = self.checkpoint_dir / f".{st_filename}.{os.getpid()}.tmp"
145
+
146
+ save_file(tensors, str(st_tmp))
147
+ with open(st_tmp, "rb") as fh:
148
+ os.fsync(fh.fileno())
149
+ payload_bytes = fh.read()
150
+ os.replace(st_tmp, st_target)
151
+
152
+ digest = hashlib.sha256(payload_bytes).hexdigest()
153
+ flush_ms = (time.perf_counter() - t0) * 1000.0
154
+
155
+ remote_uri: str | None = None
156
+ remote_upload_ms = 0.0
157
+ if self.remote_store is not None:
158
+ upload_t0 = time.perf_counter()
159
+ remote_uri = self.remote_store.put_file(st_target, f"{job_id}/{st_filename}")
160
+ remote_upload_ms = round((time.perf_counter() - upload_t0) * 1000.0, 4)
161
+
162
+ manifest = CheckpointManifest(
163
+ job_id=job_id,
164
+ step=step,
165
+ epoch=epoch,
166
+ loss_history=list(loss_history),
167
+ safetensors_filename=st_filename,
168
+ payload_sha256=digest,
169
+ flush_duration_ms=round(flush_ms, 4),
170
+ preempted=preempted,
171
+ remote_uri=remote_uri,
172
+ remote_upload_ms=remote_upload_ms,
173
+ lora_config=lora_config,
174
+ rng_state=serialize_rng_state(py_rng_state, np_rng_state),
175
+ )
176
+
177
+ manifest_bytes = manifest.model_dump_json(indent=2).encode("utf-8")
178
+ step_manifest_path = self.checkpoint_dir / f"step-{step:06d}.manifest.json"
179
+ latest_manifest_path = self.checkpoint_dir / "latest.json"
180
+
181
+ self.job_id = self.job_id or job_id
182
+ _atomic_write_bytes(step_manifest_path, manifest_bytes)
183
+ _atomic_write_bytes(latest_manifest_path, manifest_bytes)
184
+ if self.remote_store is not None:
185
+ self.remote_store.put_file(step_manifest_path, f"{job_id}/{step_manifest_path.name}")
186
+ self.remote_store.put_file(latest_manifest_path, self._remote_latest_key(job_id))
187
+ self.prune_old_checkpoints()
188
+ return manifest
189
+
190
+ def has_latest(self) -> bool:
191
+ if (self.checkpoint_dir / "latest.json").is_file():
192
+ return True
193
+ if self.remote_store is None:
194
+ return False
195
+ return self.remote_store.exists(self._remote_latest_key())
196
+
197
+ def load_latest(
198
+ self,
199
+ ) -> tuple[CheckpointManifest, dict[str, FloatArray], tuple[Any, ...], dict[str, Any]]:
200
+ self.reconcile_stale_temporaries()
201
+ latest_path = self.checkpoint_dir / "latest.json"
202
+ if not latest_path.is_file():
203
+ remote_key = self._remote_latest_key()
204
+ if self.remote_store is None or not self.remote_store.exists(remote_key):
205
+ raise FileNotFoundError(f"No checkpoint manifest found at {latest_path}")
206
+ self.remote_store.get_file(remote_key, latest_path)
207
+
208
+ manifest = CheckpointManifest.model_validate_json(latest_path.read_text(encoding="utf-8"))
209
+ st_path = self.checkpoint_dir / manifest.safetensors_filename
210
+ if not st_path.is_file():
211
+ if self.remote_store is None:
212
+ raise FileNotFoundError(f"Missing Safetensors file {st_path}")
213
+ self.remote_store.get_file(
214
+ f"{manifest.job_id}/{manifest.safetensors_filename}",
215
+ st_path,
216
+ )
217
+
218
+ actual_sha256 = hashlib.sha256(st_path.read_bytes()).hexdigest()
219
+ if actual_sha256 != manifest.payload_sha256:
220
+ raise ValueError(
221
+ f"Safetensors SHA256 mismatch: expected {manifest.payload_sha256}, "
222
+ f"got {actual_sha256}"
223
+ )
224
+
225
+ raw_tensors = load_file(str(st_path))
226
+ tensors: dict[str, FloatArray] = {
227
+ k: np.asarray(v, dtype=np.float64) for k, v in raw_tensors.items()
228
+ }
229
+ py_state, np_state = deserialize_rng_state(manifest.rng_state)
230
+ return manifest, tensors, py_state, np_state