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.
@@ -0,0 +1,1618 @@
1
+ """Deterministic checkpoint promotion and rollback for bounded training.
2
+
3
+ The controller owns the mutable training boundary, not the training objective.
4
+ It snapshots model parameters/buffers, optimizer state, gradients, module modes,
5
+ process RNG state, named ``torch.Generator`` objects, and a caller-owned cursor.
6
+ Validation, autonomous rollout, and trace-endpoint scores are evaluated under an
7
+ isolated RNG/cursor guard. A candidate is retained only when an explicit
8
+ lexicographic or Pareto policy promotes it; every other outcome restores the
9
+ previous accepted state and verifies its full fingerprint.
10
+
11
+ Decision receipts contain no tensors. They are canonical, hash chained, and
12
+ immutable. ``ImmutableDirectoryReceiptStore`` can publish them with an atomic
13
+ no-overwrite link; callers with a remote store can provide the same ``put``
14
+ interface (for example, an adapter around a Saturn session-step receipt).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import copy
20
+ import hashlib
21
+ import json
22
+ import math
23
+ import os
24
+ import random
25
+ import re
26
+ import tempfile
27
+ from collections import defaultdict
28
+ from collections.abc import Callable, Mapping
29
+ from dataclasses import dataclass, field
30
+ from pathlib import Path
31
+ from types import MappingProxyType
32
+ from typing import Any, Literal, Protocol, TypeVar
33
+
34
+ import torch
35
+
36
+ try:
37
+ import numpy as np
38
+ except ImportError: # pragma: no cover - NumPy state is included when NumPy is installed.
39
+ np = None # type: ignore[assignment]
40
+
41
+ TRAINING_CHECKPOINT_SCHEMA = "saturn-pub-training-state-checkpoint-v1"
42
+ EVALUATION_SCORES_SCHEMA = "saturn-pub-training-evaluation-scores-v1"
43
+ PROMOTION_POLICY_SCHEMA = "saturn-pub-training-promotion-policy-v1"
44
+ DECISION_RECEIPT_SCHEMA = "saturn-pub-training-checkpoint-decision-receipt-v1"
45
+
46
+ ScoreSource = Literal["validation", "autonomous_rollout", "trace_endpoints"]
47
+ Direction = Literal["maximize", "minimize"]
48
+ PolicyKind = Literal["lexicographic", "pareto"]
49
+ _SerializationResult = TypeVar("_SerializationResult")
50
+
51
+ _SOURCES: tuple[ScoreSource, ...] = (
52
+ "validation",
53
+ "autonomous_rollout",
54
+ "trace_endpoints",
55
+ )
56
+ _NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
57
+
58
+
59
+ class TrainingCheckpointError(RuntimeError):
60
+ """Base error for deterministic training checkpoint control."""
61
+
62
+
63
+ class TrainingStateDriftError(TrainingCheckpointError):
64
+ """Raised when the live state no longer matches the accepted checkpoint."""
65
+
66
+
67
+ class EvaluationMutationError(TrainingCheckpointError):
68
+ """Raised when an evaluator mutates model or optimizer state."""
69
+
70
+
71
+ class TrainingIntervalError(TrainingCheckpointError):
72
+ """Raised after a failed interval has been rolled back and receipted."""
73
+
74
+ def __init__(self, message: str, *, receipt: DecisionReceipt) -> None:
75
+ super().__init__(message)
76
+ self.receipt = receipt
77
+
78
+
79
+ class DecisionReceiptError(TrainingCheckpointError):
80
+ """Raised when an immutable decision receipt cannot be verified or stored."""
81
+
82
+
83
+ def _canonical_json_bytes(value: Any) -> bytes:
84
+ return json.dumps(
85
+ value,
86
+ sort_keys=True,
87
+ separators=(",", ":"),
88
+ ensure_ascii=False,
89
+ allow_nan=False,
90
+ ).encode("utf-8")
91
+
92
+
93
+ def _digest_json(value: Any) -> str:
94
+ return hashlib.sha256(_canonical_json_bytes(value)).hexdigest()
95
+
96
+
97
+ def _validate_name(value: str, *, label: str) -> str:
98
+ if not isinstance(value, str) or _NAME_RE.fullmatch(value) is None:
99
+ raise ValueError(f"{label} must be 1-128 ASCII letters, digits, '.', '_' or '-'")
100
+ return value
101
+
102
+
103
+ def _json_value(value: Any, *, label: str) -> Any:
104
+ if value is None or isinstance(value, (str, bool, int)):
105
+ return value
106
+ if isinstance(value, float):
107
+ if not math.isfinite(value):
108
+ raise ValueError(f"{label} contains a non-finite float")
109
+ return value
110
+ if isinstance(value, Mapping):
111
+ result: dict[str, Any] = {}
112
+ for key, item in value.items():
113
+ if not isinstance(key, str) or not key:
114
+ raise ValueError(f"{label} mapping keys must be non-empty strings")
115
+ result[key] = _json_value(item, label=f"{label}.{key}")
116
+ return result
117
+ if isinstance(value, (tuple, list)):
118
+ return [_json_value(item, label=f"{label}[{index}]") for index, item in enumerate(value)]
119
+ raise ValueError(f"{label} is not JSON-like: {type(value).__name__}")
120
+
121
+
122
+ def _metric_map(value: Mapping[str, float], *, label: str) -> dict[str, float]:
123
+ if not isinstance(value, Mapping) or not value:
124
+ raise ValueError(f"{label} must contain at least one score")
125
+ result: dict[str, float] = {}
126
+ for name, score in value.items():
127
+ resolved_name = _validate_name(name, label=f"{label} metric")
128
+ if isinstance(score, bool) or not isinstance(score, (int, float)):
129
+ raise ValueError(f"{label}.{resolved_name} must be numeric")
130
+ resolved_score = float(score)
131
+ if not math.isfinite(resolved_score):
132
+ raise ValueError(f"{label}.{resolved_name} must be finite")
133
+ result[resolved_name] = resolved_score
134
+ return dict(sorted(result.items()))
135
+
136
+
137
+ class EvaluationScores:
138
+ """Immutable scores from the three required checkpoint observables."""
139
+
140
+ __slots__ = ("_body", "_fingerprint")
141
+
142
+ def __init__(
143
+ self,
144
+ *,
145
+ validation: Mapping[str, float],
146
+ autonomous_rollout: Mapping[str, float],
147
+ trace_endpoints: Mapping[str, float],
148
+ evidence: Mapping[str, Any] | None = None,
149
+ ) -> None:
150
+ body = {
151
+ "schema": EVALUATION_SCORES_SCHEMA,
152
+ "validation": _metric_map(validation, label="validation"),
153
+ "autonomous_rollout": _metric_map(autonomous_rollout, label="autonomous_rollout"),
154
+ "trace_endpoints": _metric_map(trace_endpoints, label="trace_endpoints"),
155
+ "evidence": _json_value(evidence or {}, label="evidence"),
156
+ }
157
+ self._body = _canonical_json_bytes(body)
158
+ self._fingerprint = hashlib.sha256(self._body).hexdigest()
159
+
160
+ @classmethod
161
+ def from_value(cls, value: EvaluationScores | Mapping[str, Any]) -> EvaluationScores:
162
+ if isinstance(value, cls):
163
+ return value
164
+ if not isinstance(value, Mapping):
165
+ raise ValueError("checkpoint evaluator must return EvaluationScores or a mapping")
166
+ return cls(
167
+ validation=value.get("validation", {}),
168
+ autonomous_rollout=value.get("autonomous_rollout", {}),
169
+ trace_endpoints=value.get("trace_endpoints", {}),
170
+ evidence=value.get("evidence", {}),
171
+ )
172
+
173
+ @property
174
+ def fingerprint(self) -> str:
175
+ return self._fingerprint
176
+
177
+ def metric(self, source: ScoreSource, name: str) -> float:
178
+ payload = json.loads(self._body)
179
+ try:
180
+ return float(payload[source][name])
181
+ except KeyError as exc:
182
+ raise ValueError(f"evaluation is missing policy score {source}.{name}") from exc
183
+
184
+ def to_dict(self) -> dict[str, Any]:
185
+ return {**json.loads(self._body), "fingerprint": self._fingerprint}
186
+
187
+
188
+ TrainStep = Callable[[int], Mapping[str, Any] | None]
189
+ Evaluator = Callable[[], EvaluationScores | Mapping[str, Any]]
190
+ CursorCapture = Callable[[], Any]
191
+ CursorRestore = Callable[[Any], None]
192
+
193
+
194
+ @dataclass(frozen=True, slots=True)
195
+ class PromotionObjective:
196
+ source: ScoreSource
197
+ metric: str
198
+ direction: Direction
199
+ tolerance: float = 0.0
200
+
201
+ def __post_init__(self) -> None:
202
+ if self.source not in _SOURCES:
203
+ raise ValueError(f"unsupported score source {self.source!r}")
204
+ _validate_name(self.metric, label="objective metric")
205
+ if self.direction not in {"maximize", "minimize"}:
206
+ raise ValueError(f"unsupported objective direction {self.direction!r}")
207
+ if (
208
+ isinstance(self.tolerance, bool)
209
+ or not isinstance(self.tolerance, (int, float))
210
+ or not math.isfinite(float(self.tolerance))
211
+ or float(self.tolerance) < 0.0
212
+ ):
213
+ raise ValueError("objective tolerance must be finite and non-negative")
214
+ object.__setattr__(self, "tolerance", float(self.tolerance))
215
+
216
+ @property
217
+ def key(self) -> tuple[str, str]:
218
+ return self.source, self.metric
219
+
220
+ def to_dict(self) -> dict[str, Any]:
221
+ return {
222
+ "source": self.source,
223
+ "metric": self.metric,
224
+ "direction": self.direction,
225
+ "tolerance": self.tolerance,
226
+ }
227
+
228
+
229
+ @dataclass(frozen=True, slots=True)
230
+ class PromotionPolicy:
231
+ kind: PolicyKind
232
+ objectives: tuple[PromotionObjective, ...]
233
+ require_all_score_sources: bool = False
234
+ schema: str = field(default=PROMOTION_POLICY_SCHEMA, init=False)
235
+
236
+ def __post_init__(self) -> None:
237
+ if self.kind not in {"lexicographic", "pareto"}:
238
+ raise ValueError(f"unsupported promotion policy {self.kind!r}")
239
+ objectives = tuple(self.objectives)
240
+ if not objectives:
241
+ raise ValueError("promotion policy requires at least one objective")
242
+ if len({objective.key for objective in objectives}) != len(objectives):
243
+ raise ValueError("promotion objectives must be unique")
244
+ if self.require_all_score_sources and {objective.source for objective in objectives} != set(
245
+ _SOURCES
246
+ ):
247
+ raise ValueError(
248
+ "promotion policy must score validation, autonomous rollout, and trace endpoints"
249
+ )
250
+ object.__setattr__(self, "objectives", objectives)
251
+
252
+ @property
253
+ def fingerprint(self) -> str:
254
+ return _digest_json(self.to_dict(include_fingerprint=False))
255
+
256
+ def to_dict(self, *, include_fingerprint: bool = True) -> dict[str, Any]:
257
+ payload = {
258
+ "schema": self.schema,
259
+ "kind": self.kind,
260
+ "objectives": [objective.to_dict() for objective in self.objectives],
261
+ "require_all_score_sources": self.require_all_score_sources,
262
+ }
263
+ if include_fingerprint:
264
+ payload["fingerprint"] = self.fingerprint
265
+ return payload
266
+
267
+ def compare(self, baseline: EvaluationScores, candidate: EvaluationScores) -> dict[str, Any]:
268
+ comparisons = []
269
+ states: list[str] = []
270
+ for objective in self.objectives:
271
+ baseline_score = baseline.metric(objective.source, objective.metric)
272
+ candidate_score = candidate.metric(objective.source, objective.metric)
273
+ oriented_delta = (
274
+ candidate_score - baseline_score
275
+ if objective.direction == "maximize"
276
+ else baseline_score - candidate_score
277
+ )
278
+ if oriented_delta > objective.tolerance:
279
+ state = "better"
280
+ elif oriented_delta < -objective.tolerance:
281
+ state = "worse"
282
+ else:
283
+ state = "equivalent"
284
+ states.append(state)
285
+ comparisons.append(
286
+ {
287
+ **objective.to_dict(),
288
+ "baseline": baseline_score,
289
+ "candidate": candidate_score,
290
+ "oriented_delta": oriented_delta,
291
+ "comparison": state,
292
+ }
293
+ )
294
+ decisive_objective: int | None = None
295
+ if self.kind == "lexicographic":
296
+ decisive_objective = next(
297
+ (index for index, state in enumerate(states) if state != "equivalent"),
298
+ None,
299
+ )
300
+ if decisive_objective is None:
301
+ promoted = False
302
+ relation = "equivalent"
303
+ else:
304
+ promoted = states[decisive_objective] == "better"
305
+ relation = "lexicographic-improvement" if promoted else "lexicographic-regression"
306
+ else:
307
+ has_better = "better" in states
308
+ has_worse = "worse" in states
309
+ promoted = has_better and not has_worse
310
+ if promoted:
311
+ relation = "pareto-dominates-baseline"
312
+ elif has_worse and has_better:
313
+ relation = "pareto-tradeoff"
314
+ elif has_worse:
315
+ relation = "pareto-dominated-by-baseline"
316
+ else:
317
+ relation = "equivalent"
318
+ return {
319
+ "policy_fingerprint": self.fingerprint,
320
+ "kind": self.kind,
321
+ "promoted": promoted,
322
+ "relation": relation,
323
+ "decisive_objective_index": decisive_objective,
324
+ "comparisons": comparisons,
325
+ "scalarized_score_used": False,
326
+ }
327
+
328
+
329
+ def _tensor_bytes(value: torch.Tensor) -> bytes:
330
+ if value.layout is not torch.strided:
331
+ raise TrainingCheckpointError(
332
+ f"checkpoint state requires strided tensors, found {value.layout}"
333
+ )
334
+ if value.device.type == "meta":
335
+ raise TrainingCheckpointError("checkpoint state cannot contain meta tensors")
336
+ contiguous = value.detach().cpu().contiguous()
337
+ if contiguous.numel() == 0:
338
+ return b""
339
+ return contiguous.reshape(-1).view(torch.uint8).numpy().tobytes()
340
+
341
+
342
+ def _tensor_view_key(value: torch.Tensor) -> tuple[Any, ...]:
343
+ if value.layout is not torch.strided or value.device.type == "meta":
344
+ _tensor_bytes(value)
345
+ storage = value.untyped_storage()
346
+ return (
347
+ str(value.device),
348
+ int(storage.data_ptr()),
349
+ int(storage.nbytes()),
350
+ str(value.dtype),
351
+ int(value.storage_offset()),
352
+ tuple(int(item) for item in value.shape),
353
+ tuple(int(item) for item in value.stride()),
354
+ )
355
+
356
+
357
+ def _state_manifest(value: Any, *, _tensor_memo: dict[tuple[Any, ...], Any] | None = None) -> Any:
358
+ if _tensor_memo is None:
359
+ _tensor_memo = {}
360
+ if isinstance(value, torch.Tensor):
361
+ key = _tensor_view_key(value)
362
+ cached = _tensor_memo.get(key)
363
+ if cached is not None:
364
+ return cached
365
+ raw = _tensor_bytes(value)
366
+ manifest = {
367
+ "kind": "torch.Tensor",
368
+ "dtype": str(value.dtype),
369
+ "device": str(value.device),
370
+ "shape": [int(item) for item in value.shape],
371
+ "stride": [int(item) for item in value.stride()],
372
+ "storage_offset": int(value.storage_offset()),
373
+ "numel": int(value.numel()),
374
+ "sha256": hashlib.sha256(raw).hexdigest(),
375
+ }
376
+ _tensor_memo[key] = manifest
377
+ return manifest
378
+ if np is not None and isinstance(value, np.ndarray):
379
+ contiguous = np.ascontiguousarray(value)
380
+ return {
381
+ "kind": "numpy.ndarray",
382
+ "dtype": str(value.dtype),
383
+ "shape": [int(item) for item in value.shape],
384
+ "sha256": hashlib.sha256(contiguous.tobytes()).hexdigest(),
385
+ }
386
+ if isinstance(value, Mapping):
387
+ entries = [
388
+ (
389
+ _state_manifest(key, _tensor_memo=_tensor_memo),
390
+ _state_manifest(item, _tensor_memo=_tensor_memo),
391
+ )
392
+ for key, item in value.items()
393
+ ]
394
+ entries.sort(key=lambda row: _canonical_json_bytes(row[0]))
395
+ return {"kind": "mapping", "entries": entries}
396
+ if isinstance(value, tuple):
397
+ return {
398
+ "kind": "tuple",
399
+ "items": [_state_manifest(item, _tensor_memo=_tensor_memo) for item in value],
400
+ }
401
+ if isinstance(value, list):
402
+ return {
403
+ "kind": "list",
404
+ "items": [_state_manifest(item, _tensor_memo=_tensor_memo) for item in value],
405
+ }
406
+ if isinstance(value, bytes):
407
+ return {
408
+ "kind": "bytes",
409
+ "bytes": len(value),
410
+ "sha256": hashlib.sha256(value).hexdigest(),
411
+ }
412
+ if value is None:
413
+ return {"kind": "none"}
414
+ if isinstance(value, bool):
415
+ return {"kind": "bool", "value": value}
416
+ if isinstance(value, int):
417
+ return {"kind": "int", "value": value}
418
+ if isinstance(value, float):
419
+ return {"kind": "float", "hex": value.hex()}
420
+ if isinstance(value, str):
421
+ return {"kind": "str", "value": value}
422
+ if isinstance(value, torch.dtype):
423
+ return {"kind": "torch.dtype", "value": str(value)}
424
+ if isinstance(value, torch.device):
425
+ return {"kind": "torch.device", "value": str(value)}
426
+ raise TrainingCheckpointError(f"checkpoint state contains unsupported {type(value).__name__}")
427
+
428
+
429
+ def _state_digest(value: Any) -> str:
430
+ return _digest_json(_state_manifest(value))
431
+
432
+
433
+ def _training_state_fingerprints(value: Mapping[str, Any]) -> tuple[str, str]:
434
+ """Hash the complete state and its model component in one tensor pass."""
435
+
436
+ manifest = _state_manifest(value)
437
+ if not isinstance(manifest, Mapping) or manifest.get("kind") != "mapping":
438
+ raise TrainingCheckpointError("training state manifest is not a mapping")
439
+ model_key = {"kind": "str", "value": "model_state"}
440
+ model_manifest = None
441
+ for row in manifest.get("entries", ()):
442
+ if isinstance(row, (tuple, list)) and len(row) == 2 and row[0] == model_key:
443
+ model_manifest = row[1]
444
+ break
445
+ if model_manifest is None:
446
+ raise TrainingCheckpointError("training state manifest has no model state")
447
+ return _digest_json(manifest), _digest_json(model_manifest)
448
+
449
+
450
+ def _clone_state(
451
+ value: Any, *, _tensor_memo: dict[tuple[Any, ...], torch.Tensor] | None = None
452
+ ) -> Any:
453
+ if _tensor_memo is None:
454
+ _tensor_memo = {}
455
+ if isinstance(value, torch.Tensor):
456
+ if value.layout is not torch.strided or value.device.type == "meta":
457
+ _tensor_bytes(value)
458
+ key = _tensor_view_key(value)
459
+ if key not in _tensor_memo:
460
+ _tensor_memo[key] = value.detach().cpu().clone(memory_format=torch.preserve_format)
461
+ return _tensor_memo[key]
462
+ if np is not None and isinstance(value, np.ndarray):
463
+ return value.copy()
464
+ if isinstance(value, Mapping):
465
+ return {
466
+ copy.deepcopy(key): _clone_state(item, _tensor_memo=_tensor_memo)
467
+ for key, item in value.items()
468
+ }
469
+ if isinstance(value, tuple):
470
+ return tuple(_clone_state(item, _tensor_memo=_tensor_memo) for item in value)
471
+ if isinstance(value, list):
472
+ return [_clone_state(item, _tensor_memo=_tensor_memo) for item in value]
473
+ if value is None or isinstance(
474
+ value, (str, bool, int, float, bytes, torch.dtype, torch.device)
475
+ ):
476
+ return value
477
+ return copy.deepcopy(value)
478
+
479
+
480
+ def _tensor_inventory(value: Any, *, _seen: set[tuple[Any, ...]] | None = None) -> dict[str, int]:
481
+ if _seen is None:
482
+ _seen = set()
483
+ tensors = 0
484
+ elements = 0
485
+ bytes_ = 0
486
+ if isinstance(value, torch.Tensor):
487
+ key = _tensor_view_key(value)
488
+ if key in _seen:
489
+ return {"tensors": 0, "elements": 0, "bytes": 0}
490
+ _seen.add(key)
491
+ return {
492
+ "tensors": 1,
493
+ "elements": int(value.numel()),
494
+ "bytes": int(value.numel() * value.element_size()),
495
+ }
496
+ if isinstance(value, Mapping):
497
+ children = tuple(value.values())
498
+ elif isinstance(value, (tuple, list)):
499
+ children = tuple(value)
500
+ else:
501
+ children = ()
502
+ for child in children:
503
+ inventory = _tensor_inventory(child, _seen=_seen)
504
+ tensors += inventory["tensors"]
505
+ elements += inventory["elements"]
506
+ bytes_ += inventory["bytes"]
507
+ return {"tensors": tensors, "elements": elements, "bytes": bytes_}
508
+
509
+
510
+ def _capture_runtime_flags() -> dict[str, Any]:
511
+ warn_only = getattr(torch, "is_deterministic_algorithms_warn_only_enabled", None)
512
+ return {
513
+ "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(),
514
+ "deterministic_algorithms_warn_only": bool(warn_only()) if warn_only else False,
515
+ "float32_matmul_precision": torch.get_float32_matmul_precision(),
516
+ "cudnn_benchmark": bool(torch.backends.cudnn.benchmark),
517
+ "cudnn_deterministic": bool(torch.backends.cudnn.deterministic),
518
+ "cudnn_allow_tf32": bool(torch.backends.cudnn.allow_tf32),
519
+ "cuda_matmul_allow_tf32": bool(torch.backends.cuda.matmul.allow_tf32),
520
+ }
521
+
522
+
523
+ def _restore_runtime_flags(value: Mapping[str, Any]) -> None:
524
+ torch.use_deterministic_algorithms(
525
+ bool(value["deterministic_algorithms"]),
526
+ warn_only=bool(value["deterministic_algorithms_warn_only"]),
527
+ )
528
+ torch.set_float32_matmul_precision(str(value["float32_matmul_precision"]))
529
+ torch.backends.cudnn.benchmark = bool(value["cudnn_benchmark"])
530
+ torch.backends.cudnn.deterministic = bool(value["cudnn_deterministic"])
531
+ torch.backends.cudnn.allow_tf32 = bool(value["cudnn_allow_tf32"])
532
+ torch.backends.cuda.matmul.allow_tf32 = bool(value["cuda_matmul_allow_tf32"])
533
+
534
+
535
+ def _capture_rng(generators: Mapping[str, torch.Generator]) -> dict[str, Any]:
536
+ numpy_state = np.random.get_state() if np is not None else None
537
+ # Freeze the CUDA RNG inventory at the first checkpoint whenever CUDA is
538
+ # available. Some CPU optimizers probe CUDA lazily (AdamW does this in
539
+ # recent PyTorch releases), so conditioning this capture on
540
+ # ``is_initialized()`` lets a baseline contain zero CUDA generators while
541
+ # the candidate contains one. CUDA cannot be de-initialized during an
542
+ # exact rollback; eagerly materializing and capturing every visible device
543
+ # makes the inventory stable before the baseline fingerprint is sealed.
544
+ cuda_states = tuple(torch.cuda.get_rng_state_all()) if torch.cuda.is_available() else ()
545
+ return {
546
+ "python": random.getstate(),
547
+ "numpy": numpy_state,
548
+ "torch_cpu": torch.get_rng_state(),
549
+ "torch_cuda": cuda_states,
550
+ "named_torch_generators": {
551
+ name: generator.get_state() for name, generator in generators.items()
552
+ },
553
+ "runtime_flags": _capture_runtime_flags(),
554
+ }
555
+
556
+
557
+ def _restore_rng(value: Mapping[str, Any], generators: Mapping[str, torch.Generator]) -> None:
558
+ random.setstate(value["python"])
559
+ if np is not None and value["numpy"] is not None:
560
+ np.random.set_state(value["numpy"])
561
+ torch.set_rng_state(value["torch_cpu"])
562
+ cuda_states = tuple(value["torch_cuda"])
563
+ if cuda_states:
564
+ if not torch.cuda.is_available() or not torch.cuda.is_initialized():
565
+ raise TrainingCheckpointError("cannot restore captured CUDA RNG state")
566
+ if len(cuda_states) != torch.cuda.device_count():
567
+ raise TrainingCheckpointError("CUDA RNG device inventory changed")
568
+ torch.cuda.set_rng_state_all(list(cuda_states))
569
+ named = value["named_torch_generators"]
570
+ if set(named) != set(generators):
571
+ raise TrainingCheckpointError("named torch.Generator inventory changed")
572
+ for name, generator in generators.items():
573
+ generator.set_state(named[name])
574
+ _restore_runtime_flags(value["runtime_flags"])
575
+
576
+
577
+ def _module_modes(model: torch.nn.Module) -> dict[str, bool]:
578
+ return {name: bool(module.training) for name, module in model.named_modules()}
579
+
580
+
581
+ def _restore_module_modes(model: torch.nn.Module, modes: Mapping[str, bool]) -> None:
582
+ modules = dict(model.named_modules())
583
+ if set(modules) != set(modes):
584
+ raise TrainingCheckpointError("model module inventory changed")
585
+ for name, training in modes.items():
586
+ modules[name].training = bool(training)
587
+
588
+
589
+ def _parameter_flags(model: torch.nn.Module) -> dict[str, bool]:
590
+ return {name: bool(parameter.requires_grad) for name, parameter in model.named_parameters()}
591
+
592
+
593
+ def _restore_parameter_flags(model: torch.nn.Module, flags: Mapping[str, bool]) -> None:
594
+ parameters = dict(model.named_parameters())
595
+ if set(parameters) != set(flags):
596
+ raise TrainingCheckpointError("model parameter inventory changed")
597
+ for name, requires_grad in flags.items():
598
+ parameters[name].requires_grad_(bool(requires_grad))
599
+
600
+
601
+ def _parameter_gradients(model: torch.nn.Module) -> dict[str, torch.Tensor | None]:
602
+ return {
603
+ name: None if parameter.grad is None else _clone_state(parameter.grad)
604
+ for name, parameter in model.named_parameters()
605
+ }
606
+
607
+
608
+ def _restore_parameter_gradients(
609
+ model: torch.nn.Module, gradients: Mapping[str, torch.Tensor | None]
610
+ ) -> None:
611
+ parameters = dict(model.named_parameters())
612
+ if set(parameters) != set(gradients):
613
+ raise TrainingCheckpointError("model gradient inventory changed")
614
+ for name, saved in gradients.items():
615
+ parameter = parameters[name]
616
+ if saved is None:
617
+ parameter.grad = None
618
+ else:
619
+ parameter.grad = saved.to(device=parameter.device, dtype=parameter.dtype).clone()
620
+
621
+
622
+ def _nonpersistent_buffers(model: torch.nn.Module) -> dict[str, torch.Tensor]:
623
+ result: dict[str, torch.Tensor] = {}
624
+ for module_name, module in model.named_modules():
625
+ for local_name in module._non_persistent_buffers_set:
626
+ value = module._buffers.get(local_name)
627
+ if value is None:
628
+ continue
629
+ name = f"{module_name}.{local_name}" if module_name else local_name
630
+ result[name] = value
631
+ return result
632
+
633
+
634
+ def _optimizer_parameter_topology(
635
+ model: torch.nn.Module, optimizer: torch.optim.Optimizer
636
+ ) -> tuple[tuple[str, ...], ...]:
637
+ names_by_id = {id(parameter): name for name, parameter in model.named_parameters()}
638
+ observed: set[int] = set()
639
+ groups = []
640
+ for group_index, group in enumerate(optimizer.param_groups):
641
+ names = []
642
+ for parameter in group.get("params", ()): # type: ignore[union-attr]
643
+ identity = id(parameter)
644
+ if identity not in names_by_id:
645
+ raise TrainingCheckpointError(
646
+ f"optimizer group {group_index} owns a parameter outside the model"
647
+ )
648
+ if identity in observed:
649
+ raise TrainingCheckpointError(
650
+ "optimizer parameter appears in more than one parameter group"
651
+ )
652
+ observed.add(identity)
653
+ names.append(names_by_id[identity])
654
+ if not names:
655
+ raise TrainingCheckpointError(f"optimizer group {group_index} has no model parameters")
656
+ groups.append(tuple(names))
657
+ if not groups:
658
+ raise TrainingCheckpointError("optimizer has no parameter groups")
659
+ return tuple(groups)
660
+
661
+
662
+ def _restore_optimizer(
663
+ model: torch.nn.Module,
664
+ optimizer: torch.optim.Optimizer,
665
+ *,
666
+ state: Mapping[str, Any],
667
+ defaults: Mapping[str, Any],
668
+ topology: tuple[tuple[str, ...], ...],
669
+ ) -> None:
670
+ parameters = dict(model.named_parameters())
671
+ saved_groups = state.get("param_groups")
672
+ if not isinstance(saved_groups, list) or len(saved_groups) != len(topology):
673
+ raise TrainingCheckpointError("saved optimizer parameter groups changed")
674
+ restored_groups = []
675
+ for saved_group, names in zip(saved_groups, topology, strict=True):
676
+ if not isinstance(saved_group, Mapping) or set(names) - set(parameters):
677
+ raise TrainingCheckpointError("saved optimizer topology cannot be restored")
678
+ restored_groups.append(
679
+ {
680
+ **{
681
+ key: _clone_state(value)
682
+ for key, value in saved_group.items()
683
+ if key != "params"
684
+ },
685
+ "params": [parameters[name] for name in names],
686
+ }
687
+ )
688
+ optimizer.defaults.clear()
689
+ optimizer.defaults.update(_clone_state(defaults))
690
+ optimizer.param_groups = restored_groups
691
+ optimizer.state = defaultdict(dict)
692
+ optimizer.load_state_dict(_clone_state(state))
693
+ if _optimizer_parameter_topology(model, optimizer) != topology:
694
+ raise TrainingCheckpointError("restored optimizer topology changed")
695
+
696
+
697
+ def _restore_nonpersistent_buffers(
698
+ model: torch.nn.Module, buffers: Mapping[str, torch.Tensor]
699
+ ) -> None:
700
+ current = _nonpersistent_buffers(model)
701
+ if set(current) != set(buffers):
702
+ raise TrainingCheckpointError("model non-persistent buffer inventory changed")
703
+ with torch.no_grad():
704
+ for name, saved in buffers.items():
705
+ target = current[name]
706
+ target.copy_(saved.to(device=target.device, dtype=target.dtype))
707
+
708
+
709
+ @dataclass(frozen=True, slots=True)
710
+ class TrainingStateSnapshot:
711
+ """Opaque exact-restoration snapshot plus a tensor-free public summary."""
712
+
713
+ fingerprint: str
714
+ summary: Mapping[str, Any]
715
+ _state_manifest: Mapping[str, Any] = field(repr=False)
716
+ _model_state_fingerprint: str = field(repr=False)
717
+ _model_state: Mapping[str, Any] = field(repr=False)
718
+ _optimizer_state: Mapping[str, Any] = field(repr=False)
719
+ _optimizer_defaults: Mapping[str, Any] = field(repr=False)
720
+ _optimizer_topology: tuple[tuple[str, ...], ...] = field(repr=False)
721
+ _gradients: Mapping[str, torch.Tensor | None] = field(repr=False)
722
+ _nonpersistent_buffers: Mapping[str, torch.Tensor] = field(repr=False)
723
+ _module_modes: Mapping[str, bool] = field(repr=False)
724
+ _parameter_flags: Mapping[str, bool] = field(repr=False)
725
+ _rng: Mapping[str, Any] = field(repr=False)
726
+ _cursor: Any = field(repr=False)
727
+ schema: str = field(default=TRAINING_CHECKPOINT_SCHEMA, init=False)
728
+
729
+ @property
730
+ def model_state_fingerprint(self) -> str:
731
+ """Fingerprint of the deployment-visible subset captured with this state."""
732
+
733
+ return self._model_state_fingerprint
734
+
735
+ def _state_parts(self) -> dict[str, Any]:
736
+ return {
737
+ "model_state": self._model_state,
738
+ "optimizer_state": self._optimizer_state,
739
+ "optimizer_defaults": self._optimizer_defaults,
740
+ "optimizer_parameter_topology": self._optimizer_topology,
741
+ "gradients": self._gradients,
742
+ "nonpersistent_buffers": self._nonpersistent_buffers,
743
+ "module_modes": self._module_modes,
744
+ "parameter_requires_grad": self._parameter_flags,
745
+ "rng": self._rng,
746
+ "cursor": self._cursor,
747
+ }
748
+
749
+ @staticmethod
750
+ def _model_manifest(manifest: Mapping[str, Any]) -> Any:
751
+ if manifest.get("kind") != "mapping":
752
+ raise TrainingCheckpointError("training snapshot manifest is not a mapping")
753
+ model_key = {"kind": "str", "value": "model_state"}
754
+ for row in manifest.get("entries", ()):
755
+ if isinstance(row, (tuple, list)) and len(row) == 2 and row[0] == model_key:
756
+ return row[1]
757
+ raise TrainingCheckpointError("training snapshot manifest has no model state")
758
+
759
+ @classmethod
760
+ def _manifest_matches(cls, expected: Any, observed: Any) -> bool:
761
+ """Compare serialized state content while allowing device relocation."""
762
+
763
+ if isinstance(expected, Mapping) and isinstance(observed, Mapping):
764
+ if set(expected) != set(observed):
765
+ return False
766
+ for key in expected:
767
+ if (
768
+ key == "device"
769
+ and expected.get("kind") == "torch.Tensor"
770
+ and observed.get("kind") == "torch.Tensor"
771
+ ):
772
+ continue
773
+ if not cls._manifest_matches(expected[key], observed[key]):
774
+ return False
775
+ return True
776
+ if isinstance(expected, (tuple, list)) and isinstance(observed, (tuple, list)):
777
+ return len(expected) == len(observed) and all(
778
+ cls._manifest_matches(left, right)
779
+ for left, right in zip(expected, observed, strict=True)
780
+ )
781
+ return expected == observed
782
+
783
+ def verify(self) -> None:
784
+ """Verify snapshot custody before a caller mutates its live runtime."""
785
+
786
+ if self.schema != TRAINING_CHECKPOINT_SCHEMA:
787
+ raise TrainingCheckpointError("training snapshot schema changed")
788
+ try:
789
+ fingerprint = _digest_json(self._state_manifest)
790
+ model_fingerprint = _digest_json(self._model_manifest(self._state_manifest))
791
+ observed_manifest = _state_manifest(self._state_parts())
792
+ except Exception as exc:
793
+ raise TrainingCheckpointError("training snapshot manifest is invalid") from exc
794
+ if (
795
+ fingerprint != self.fingerprint
796
+ or model_fingerprint != self.model_state_fingerprint
797
+ or not self._manifest_matches(self._state_manifest, observed_manifest)
798
+ ):
799
+ raise TrainingCheckpointError("training snapshot fingerprint changed")
800
+
801
+ def to_state_dict(self) -> dict[str, Any]:
802
+ """Return a detached, tensor-bearing payload for safe external packing.
803
+
804
+ The payload contains no executable objects or pickle bytes. Callers
805
+ should encode tensor leaves with a tensor-safe format such as
806
+ safetensors and encode the remaining tagged tree as canonical JSON.
807
+ """
808
+
809
+ return {
810
+ "schema": self.schema,
811
+ "fingerprint": self.fingerprint,
812
+ "summary": _clone_state(dict(self.summary)),
813
+ "state_manifest": _clone_state(self._state_manifest),
814
+ "model_state_fingerprint": self.model_state_fingerprint,
815
+ "model_state": _clone_state(self._model_state),
816
+ "optimizer_state": _clone_state(self._optimizer_state),
817
+ "optimizer_defaults": _clone_state(self._optimizer_defaults),
818
+ "optimizer_topology": _clone_state(self._optimizer_topology),
819
+ "gradients": _clone_state(self._gradients),
820
+ "nonpersistent_buffers": _clone_state(self._nonpersistent_buffers),
821
+ "module_modes": _clone_state(self._module_modes),
822
+ "parameter_flags": _clone_state(self._parameter_flags),
823
+ "rng": _clone_state(self._rng),
824
+ "cursor": _clone_state(self._cursor),
825
+ }
826
+
827
+ @classmethod
828
+ def from_state_dict(cls, payload: Mapping[str, Any]) -> TrainingStateSnapshot:
829
+ """Rehydrate a safe payload and reject any content or schema drift."""
830
+
831
+ if not isinstance(payload, Mapping):
832
+ raise TrainingCheckpointError("training snapshot payload must be a mapping")
833
+ expected_keys = {
834
+ "schema",
835
+ "fingerprint",
836
+ "summary",
837
+ "state_manifest",
838
+ "model_state_fingerprint",
839
+ "model_state",
840
+ "optimizer_state",
841
+ "optimizer_defaults",
842
+ "optimizer_topology",
843
+ "gradients",
844
+ "nonpersistent_buffers",
845
+ "module_modes",
846
+ "parameter_flags",
847
+ "rng",
848
+ "cursor",
849
+ }
850
+ if set(payload) != expected_keys:
851
+ raise TrainingCheckpointError("training snapshot payload fields changed")
852
+ if payload.get("schema") != TRAINING_CHECKPOINT_SCHEMA:
853
+ raise TrainingCheckpointError("training snapshot schema changed")
854
+ summary = payload.get("summary")
855
+ state_manifest = payload.get("state_manifest")
856
+ model_state = payload.get("model_state")
857
+ optimizer_state = payload.get("optimizer_state")
858
+ optimizer_defaults = payload.get("optimizer_defaults")
859
+ gradients = payload.get("gradients")
860
+ nonpersistent = payload.get("nonpersistent_buffers")
861
+ modes = payload.get("module_modes")
862
+ flags = payload.get("parameter_flags")
863
+ rng = payload.get("rng")
864
+ if not isinstance(summary, Mapping) or not isinstance(state_manifest, Mapping):
865
+ raise TrainingCheckpointError("training snapshot summary or manifest is invalid")
866
+ for value, label in (
867
+ (model_state, "model state"),
868
+ (optimizer_state, "optimizer state"),
869
+ (optimizer_defaults, "optimizer defaults"),
870
+ (gradients, "gradients"),
871
+ (nonpersistent, "non-persistent buffers"),
872
+ (modes, "module modes"),
873
+ (flags, "parameter flags"),
874
+ (rng, "RNG state"),
875
+ ):
876
+ if not isinstance(value, Mapping):
877
+ raise TrainingCheckpointError(f"training snapshot {label} must be a mapping")
878
+ topology = payload.get("optimizer_topology")
879
+ if not isinstance(topology, (tuple, list)):
880
+ raise TrainingCheckpointError("training snapshot optimizer topology is invalid")
881
+ normalized_topology: tuple[tuple[str, ...], ...] = tuple(
882
+ tuple(_validate_name(str(name), label="optimizer parameter name") for name in group)
883
+ if isinstance(group, (tuple, list))
884
+ else (_validate_name(str(group), label="optimizer parameter name"),)
885
+ for group in topology
886
+ )
887
+ if any(not group for group in normalized_topology):
888
+ raise TrainingCheckpointError("training snapshot optimizer topology is empty")
889
+ if not normalized_topology and (
890
+ optimizer_state != {"state": {}, "param_groups": []} or optimizer_defaults != {}
891
+ ):
892
+ raise TrainingCheckpointError("optimizer-free snapshot contains optimizer state")
893
+ flattened = tuple(name for group in normalized_topology for name in group)
894
+ if len(set(flattened)) != len(flattened):
895
+ raise TrainingCheckpointError(
896
+ "training snapshot optimizer topology contains duplicate parameters"
897
+ )
898
+ try:
899
+ normalized_summary = _json_value(summary, label="training snapshot summary")
900
+ normalized_manifest = _json_value(
901
+ state_manifest, label="training snapshot state manifest"
902
+ )
903
+ except Exception as exc:
904
+ raise TrainingCheckpointError("training snapshot JSON fields are invalid") from exc
905
+ snapshot = cls(
906
+ fingerprint=str(payload.get("fingerprint")),
907
+ summary=MappingProxyType(normalized_summary),
908
+ _state_manifest=normalized_manifest,
909
+ _model_state_fingerprint=str(payload.get("model_state_fingerprint")),
910
+ _model_state=_clone_state(model_state),
911
+ _optimizer_state=_clone_state(optimizer_state),
912
+ _optimizer_defaults=_clone_state(optimizer_defaults),
913
+ _optimizer_topology=normalized_topology,
914
+ _gradients=_clone_state(gradients),
915
+ _nonpersistent_buffers=_clone_state(nonpersistent),
916
+ _module_modes=_clone_state(modes),
917
+ _parameter_flags=_clone_state(flags),
918
+ _rng=_clone_state(rng),
919
+ _cursor=_clone_state(payload.get("cursor")),
920
+ )
921
+ snapshot.verify()
922
+ return snapshot
923
+
924
+ def to_dict(self) -> dict[str, Any]:
925
+ return {
926
+ "schema": self.schema,
927
+ "fingerprint": self.fingerprint,
928
+ **dict(self.summary),
929
+ }
930
+
931
+
932
+ @dataclass(frozen=True, slots=True)
933
+ class AcceptedStateSerializationView:
934
+ """Ephemeral read-only borrow of one verified accepted CPU snapshot.
935
+
936
+ The controller owns every object reachable through ``runtime_state``. A
937
+ serializer may inspect those objects synchronously but must never mutate or
938
+ retain them. Keeping the borrow callback-scoped lets resume custody avoid a
939
+ second optimizer/RNG/cursor snapshot without making rollback state public.
940
+ """
941
+
942
+ accepted_state_fingerprint: str
943
+ model_state_fingerprint: str
944
+ runtime_state: Mapping[str, Any] = field(repr=False)
945
+
946
+
947
+ class TrainingStateBoundary:
948
+ """Policy-free exact state boundary shared by training and structural runtimes.
949
+
950
+ The boundary owns the mutable model/optimizer pair and the caller-owned
951
+ cursor. It captures enough runtime state to restore the pair exactly,
952
+ while leaving promotion policy and durable serialization to callers. A
953
+ model may rebuild its registered modules from ``get_extra_state`` during
954
+ ``load_state_dict``; the normal PyTorch state-dict contract therefore
955
+ remains the topology extension point.
956
+ """
957
+
958
+ def __init__(
959
+ self,
960
+ *,
961
+ model: torch.nn.Module,
962
+ optimizer: torch.optim.Optimizer | None,
963
+ cursor_capture: CursorCapture,
964
+ cursor_restore: CursorRestore,
965
+ torch_generators: Mapping[str, torch.Generator] | None = None,
966
+ ) -> None:
967
+ if not callable(cursor_capture) or not callable(cursor_restore):
968
+ raise ValueError("cursor capture and restore callbacks are required")
969
+ generators = dict(torch_generators or {})
970
+ for name, generator in generators.items():
971
+ _validate_name(name, label="torch generator name")
972
+ if not isinstance(generator, torch.Generator):
973
+ raise ValueError(f"named RNG {name!r} is not a torch.Generator")
974
+ self.model = model
975
+ self.optimizer = optimizer
976
+ self.cursor_capture = cursor_capture
977
+ self.cursor_restore = cursor_restore
978
+ self.torch_generators = MappingProxyType(generators)
979
+ if self.optimizer is not None:
980
+ _optimizer_parameter_topology(self.model, self.optimizer)
981
+
982
+ def _state_parts(self) -> dict[str, Any]:
983
+ return {
984
+ "model_state": self.model.state_dict(),
985
+ "optimizer_state": self.optimizer.state_dict()
986
+ if self.optimizer is not None
987
+ else {"state": {}, "param_groups": []},
988
+ "optimizer_defaults": self.optimizer.defaults if self.optimizer is not None else {},
989
+ "optimizer_parameter_topology": _optimizer_parameter_topology(
990
+ self.model, self.optimizer
991
+ )
992
+ if self.optimizer is not None
993
+ else (),
994
+ "gradients": {
995
+ name: parameter.grad for name, parameter in self.model.named_parameters()
996
+ },
997
+ "nonpersistent_buffers": _nonpersistent_buffers(self.model),
998
+ "module_modes": _module_modes(self.model),
999
+ "parameter_requires_grad": _parameter_flags(self.model),
1000
+ "rng": _capture_rng(self.torch_generators),
1001
+ "cursor": self.cursor_capture(),
1002
+ }
1003
+
1004
+ def _current_state_fingerprints(self) -> tuple[str, str]:
1005
+ return _training_state_fingerprints(self._state_parts())
1006
+
1007
+ def current_state_fingerprint(self) -> str:
1008
+ return self._current_state_fingerprints()[0]
1009
+
1010
+ def _capture_snapshot(
1011
+ self, *, expected_fingerprint: str | None = None
1012
+ ) -> TrainingStateSnapshot:
1013
+ live_fingerprint = expected_fingerprint or self.current_state_fingerprint()
1014
+ live_parts = self._state_parts()
1015
+ live_manifest = _state_manifest(live_parts)
1016
+ model_state = _clone_state(live_parts["model_state"])
1017
+ optimizer_state = _clone_state(live_parts["optimizer_state"])
1018
+ optimizer_defaults = _clone_state(live_parts["optimizer_defaults"])
1019
+ optimizer_topology = (
1020
+ _optimizer_parameter_topology(self.model, self.optimizer)
1021
+ if self.optimizer is not None
1022
+ else ()
1023
+ )
1024
+ gradients = _parameter_gradients(self.model)
1025
+ nonpersistent = {
1026
+ name: _clone_state(value) for name, value in _nonpersistent_buffers(self.model).items()
1027
+ }
1028
+ modes = _module_modes(self.model)
1029
+ flags = _parameter_flags(self.model)
1030
+ rng = _clone_state(_capture_rng(self.torch_generators))
1031
+ cursor = _clone_state(self.cursor_capture())
1032
+ inventory = {
1033
+ "model": _tensor_inventory(model_state),
1034
+ "optimizer": _tensor_inventory(optimizer_state),
1035
+ "gradients": _tensor_inventory(gradients),
1036
+ "nonpersistent_buffers": _tensor_inventory(nonpersistent),
1037
+ }
1038
+ summary = {
1039
+ "model_state_entries": len(model_state),
1040
+ "optimizer_parameter_groups": len(optimizer_state.get("param_groups", [])),
1041
+ "module_count": len(modes),
1042
+ "parameter_count": len(flags),
1043
+ "tensor_inventory": inventory,
1044
+ "snapshot_tensor_bytes": sum(row["bytes"] for row in inventory.values()),
1045
+ "rng_fingerprint": _state_digest(rng),
1046
+ "cursor_fingerprint": _state_digest(cursor),
1047
+ }
1048
+ post_fingerprint, model_state_fingerprint = self._current_state_fingerprints()
1049
+ if post_fingerprint != live_fingerprint:
1050
+ raise TrainingCheckpointError("state changed while its checkpoint was captured")
1051
+ return TrainingStateSnapshot(
1052
+ fingerprint=live_fingerprint,
1053
+ summary=MappingProxyType(summary),
1054
+ _state_manifest=live_manifest,
1055
+ _model_state_fingerprint=model_state_fingerprint,
1056
+ _model_state=model_state,
1057
+ _optimizer_state=optimizer_state,
1058
+ _optimizer_defaults=optimizer_defaults,
1059
+ _optimizer_topology=optimizer_topology,
1060
+ _gradients=gradients,
1061
+ _nonpersistent_buffers=nonpersistent,
1062
+ _module_modes=modes,
1063
+ _parameter_flags=flags,
1064
+ _rng=rng,
1065
+ _cursor=cursor,
1066
+ )
1067
+
1068
+ def _verify_snapshot(self, snapshot: TrainingStateSnapshot) -> None:
1069
+ if not isinstance(snapshot, TrainingStateSnapshot):
1070
+ raise TypeError("restore expects a TrainingStateSnapshot")
1071
+ snapshot.verify()
1072
+
1073
+ def restore(self, snapshot: TrainingStateSnapshot) -> str:
1074
+ """Restore a captured state after verifying its immutable manifest.
1075
+
1076
+ Snapshot verification happens before the first live mutation. This
1077
+ primitive is otherwise non-atomic if a later model, optimizer, cursor,
1078
+ or RNG restore step raises; callers that require atomic restore must
1079
+ capture a rollback state and wrap this method, as
1080
+ :class:`StructuralGrowthSession` does.
1081
+ """
1082
+
1083
+ self._verify_snapshot(snapshot)
1084
+ return self._restore_snapshot(snapshot)
1085
+
1086
+ def capture(self, *, expected_fingerprint: str | None = None) -> TrainingStateSnapshot:
1087
+ """Capture the complete mutable boundary as an opaque snapshot."""
1088
+
1089
+ return self._capture_snapshot(expected_fingerprint=expected_fingerprint)
1090
+
1091
+ def _restore_snapshot(self, snapshot: TrainingStateSnapshot) -> str:
1092
+ if (self.optimizer is None) != (not snapshot._optimizer_topology):
1093
+ raise TrainingCheckpointError("optimizer presence changed across the state boundary")
1094
+ self.model.load_state_dict(_clone_state(snapshot._model_state), strict=True)
1095
+ if self.optimizer is not None:
1096
+ _restore_optimizer(
1097
+ self.model,
1098
+ self.optimizer,
1099
+ state=snapshot._optimizer_state,
1100
+ defaults=snapshot._optimizer_defaults,
1101
+ topology=snapshot._optimizer_topology,
1102
+ )
1103
+ _restore_parameter_flags(self.model, snapshot._parameter_flags)
1104
+ _restore_parameter_gradients(self.model, snapshot._gradients)
1105
+ _restore_nonpersistent_buffers(self.model, snapshot._nonpersistent_buffers)
1106
+ _restore_module_modes(self.model, snapshot._module_modes)
1107
+ self.cursor_restore(_clone_state(snapshot._cursor))
1108
+ _restore_rng(snapshot._rng, self.torch_generators)
1109
+ restored = self.current_state_fingerprint()
1110
+ if restored != snapshot.fingerprint:
1111
+ expected_parts = {
1112
+ "model_state": snapshot._model_state,
1113
+ "optimizer_state": snapshot._optimizer_state,
1114
+ "optimizer_defaults": snapshot._optimizer_defaults,
1115
+ "optimizer_parameter_topology": snapshot._optimizer_topology,
1116
+ "gradients": snapshot._gradients,
1117
+ "nonpersistent_buffers": snapshot._nonpersistent_buffers,
1118
+ "module_modes": snapshot._module_modes,
1119
+ "parameter_requires_grad": snapshot._parameter_flags,
1120
+ "rng": snapshot._rng,
1121
+ "cursor": snapshot._cursor,
1122
+ }
1123
+ observed_parts = self._state_parts()
1124
+ differing = sorted(
1125
+ name
1126
+ for name in expected_parts
1127
+ if _state_digest(expected_parts[name]) != _state_digest(observed_parts[name])
1128
+ )
1129
+ detail = ", ".join(differing) if differing else "cross-component tensor alias topology"
1130
+ raise TrainingCheckpointError(
1131
+ "restored training state is not bit-exact with its checkpoint; "
1132
+ f"differing components: {detail}"
1133
+ )
1134
+ return restored
1135
+
1136
+
1137
+ class DecisionReceipt:
1138
+ """Canonical immutable receipt; callers receive fresh mappings on read."""
1139
+
1140
+ __slots__ = ("_canonical", "_fingerprint")
1141
+
1142
+ def __init__(self, body: Mapping[str, Any]) -> None:
1143
+ normalized = _json_value(body, label="decision receipt")
1144
+ if normalized.get("schema") != DECISION_RECEIPT_SCHEMA:
1145
+ raise DecisionReceiptError("decision receipt schema changed")
1146
+ canonical_body = _canonical_json_bytes(normalized)
1147
+ fingerprint = hashlib.sha256(canonical_body).hexdigest()
1148
+ self._fingerprint = fingerprint
1149
+ self._canonical = _canonical_json_bytes({**normalized, "fingerprint": fingerprint})
1150
+
1151
+ @property
1152
+ def fingerprint(self) -> str:
1153
+ return self._fingerprint
1154
+
1155
+ @property
1156
+ def canonical_bytes(self) -> bytes:
1157
+ return self._canonical
1158
+
1159
+ def to_dict(self) -> dict[str, Any]:
1160
+ payload = json.loads(self._canonical)
1161
+ fingerprint = payload.pop("fingerprint")
1162
+ if fingerprint != _digest_json(payload):
1163
+ raise DecisionReceiptError("decision receipt fingerprint changed")
1164
+ return {**payload, "fingerprint": fingerprint}
1165
+
1166
+
1167
+ class DecisionReceiptStore(Protocol):
1168
+ def put(self, receipt: DecisionReceipt) -> Any:
1169
+ """Persist one no-overwrite decision receipt."""
1170
+
1171
+
1172
+ class ImmutableDirectoryReceiptStore:
1173
+ """Atomic, content-addressed, no-overwrite receipt publication."""
1174
+
1175
+ def __init__(self, root: Path) -> None:
1176
+ self.root = root.expanduser().resolve()
1177
+ self.root.mkdir(parents=True, exist_ok=True)
1178
+ if self.root.is_symlink() or not self.root.is_dir():
1179
+ raise DecisionReceiptError("receipt root must be one real directory")
1180
+
1181
+ def put(self, receipt: DecisionReceipt) -> Path:
1182
+ payload = receipt.to_dict()
1183
+ controller_id = _validate_name(payload["controller_id"], label="receipt controller_id")
1184
+ index = int(payload["decision_index"])
1185
+ destination = self.root / (f"{controller_id}-{index:06d}-{receipt.fingerprint}.json")
1186
+ encoded = receipt.canonical_bytes
1187
+ descriptor, temporary_name = tempfile.mkstemp(prefix=".saturn-decision-", dir=self.root)
1188
+ temporary = Path(temporary_name)
1189
+ try:
1190
+ with os.fdopen(descriptor, "wb") as handle:
1191
+ handle.write(encoded)
1192
+ handle.flush()
1193
+ os.fsync(handle.fileno())
1194
+ try:
1195
+ os.link(temporary, destination)
1196
+ except FileExistsError as exc:
1197
+ if destination.read_bytes() != encoded:
1198
+ raise DecisionReceiptError(
1199
+ "immutable decision receipt path already contains different bytes"
1200
+ ) from exc
1201
+ directory = os.open(self.root, os.O_RDONLY)
1202
+ try:
1203
+ os.fsync(directory)
1204
+ finally:
1205
+ os.close(directory)
1206
+ finally:
1207
+ temporary.unlink(missing_ok=True)
1208
+ if destination.read_bytes() != encoded:
1209
+ raise DecisionReceiptError("published decision receipt cannot be reopened")
1210
+ return destination
1211
+
1212
+
1213
+ class DecisionLedger:
1214
+ """Append-only, fingerprint-chained in-process receipt custody."""
1215
+
1216
+ def __init__(self, controller_id: str) -> None:
1217
+ self.controller_id = _validate_name(controller_id, label="controller_id")
1218
+ self._receipts: tuple[DecisionReceipt, ...] = ()
1219
+
1220
+ @property
1221
+ def receipts(self) -> tuple[DecisionReceipt, ...]:
1222
+ return self._receipts
1223
+
1224
+ @property
1225
+ def head_fingerprint(self) -> str | None:
1226
+ return self._receipts[-1].fingerprint if self._receipts else None
1227
+
1228
+ def append(self, receipt: DecisionReceipt) -> None:
1229
+ payload = receipt.to_dict()
1230
+ if payload.get("controller_id") != self.controller_id:
1231
+ raise DecisionReceiptError("decision receipt belongs to another controller")
1232
+ if payload.get("decision_index") != len(self._receipts):
1233
+ raise DecisionReceiptError("decision receipt index is not append-only")
1234
+ if payload.get("previous_receipt_fingerprint") != self.head_fingerprint:
1235
+ raise DecisionReceiptError("decision receipt chain parent changed")
1236
+ self._receipts = (*self._receipts, receipt)
1237
+
1238
+ def verify(self) -> bool:
1239
+ previous: str | None = None
1240
+ for index, receipt in enumerate(self._receipts):
1241
+ payload = receipt.to_dict()
1242
+ if (
1243
+ payload.get("controller_id") != self.controller_id
1244
+ or payload.get("decision_index") != index
1245
+ or payload.get("previous_receipt_fingerprint") != previous
1246
+ ):
1247
+ return False
1248
+ previous = receipt.fingerprint
1249
+ return True
1250
+
1251
+
1252
+ class DeterministicCheckpointController(TrainingStateBoundary):
1253
+ """Own one accepted training state and transact bounded update intervals."""
1254
+
1255
+ def __init__(
1256
+ self,
1257
+ *,
1258
+ controller_id: str,
1259
+ model: torch.nn.Module,
1260
+ optimizer: torch.optim.Optimizer | None,
1261
+ policy: PromotionPolicy,
1262
+ cursor_capture: CursorCapture,
1263
+ cursor_restore: CursorRestore,
1264
+ max_interval_steps: int,
1265
+ torch_generators: Mapping[str, torch.Generator] | None = None,
1266
+ receipt_store: DecisionReceiptStore | None = None,
1267
+ ) -> None:
1268
+ if isinstance(max_interval_steps, bool) or int(max_interval_steps) < 1:
1269
+ raise ValueError("max_interval_steps must be positive")
1270
+ self.controller_id = _validate_name(controller_id, label="controller_id")
1271
+ super().__init__(
1272
+ model=model,
1273
+ optimizer=optimizer,
1274
+ cursor_capture=cursor_capture,
1275
+ cursor_restore=cursor_restore,
1276
+ torch_generators=torch_generators,
1277
+ )
1278
+ self.policy = policy
1279
+ self.max_interval_steps = int(max_interval_steps)
1280
+ self.receipt_store = receipt_store
1281
+ self.ledger = DecisionLedger(self.controller_id)
1282
+ self._accepted_snapshot: TrainingStateSnapshot | None = None
1283
+ self._accepted_scores: EvaluationScores | None = None
1284
+ self._interval_ids: set[str] = set()
1285
+
1286
+ @property
1287
+ def initialized(self) -> bool:
1288
+ return self._accepted_snapshot is not None
1289
+
1290
+ @property
1291
+ def accepted_state_fingerprint(self) -> str | None:
1292
+ return self._accepted_snapshot.fingerprint if self._accepted_snapshot is not None else None
1293
+
1294
+ @property
1295
+ def accepted_scores(self) -> EvaluationScores | None:
1296
+ return self._accepted_scores
1297
+
1298
+ def with_verified_accepted_state(
1299
+ self,
1300
+ serializer: Callable[[AcceptedStateSerializationView], _SerializationResult],
1301
+ ) -> _SerializationResult:
1302
+ """Serialize from the accepted CPU snapshot after one live-state check.
1303
+
1304
+ Controller operations are synchronous. The callback receives an
1305
+ ephemeral borrow and must not retain or mutate it. Serialization reads
1306
+ only the accepted snapshot after the live equality check, so mutable
1307
+ model/optimizer tensors are neither re-hashed nor copied a second time.
1308
+ """
1309
+
1310
+ if not callable(serializer):
1311
+ raise ValueError("accepted-state serializer callback is required")
1312
+ snapshot = self._accepted_snapshot
1313
+ if snapshot is None:
1314
+ raise TrainingCheckpointError("checkpoint controller has no accepted state")
1315
+ if self.current_state_fingerprint() != snapshot.fingerprint:
1316
+ raise TrainingStateDriftError(
1317
+ "live training state does not match the accepted checkpoint"
1318
+ )
1319
+ runtime_state = MappingProxyType(
1320
+ {
1321
+ "optimizer_state": snapshot._optimizer_state,
1322
+ "optimizer_defaults": snapshot._optimizer_defaults,
1323
+ "optimizer_parameter_topology": snapshot._optimizer_topology,
1324
+ "gradients": snapshot._gradients,
1325
+ "nonpersistent_buffers": snapshot._nonpersistent_buffers,
1326
+ "module_modes": snapshot._module_modes,
1327
+ "parameter_requires_grad": snapshot._parameter_flags,
1328
+ "rng": snapshot._rng,
1329
+ "accepted_training_cursor": snapshot._cursor,
1330
+ }
1331
+ )
1332
+ return serializer(
1333
+ AcceptedStateSerializationView(
1334
+ accepted_state_fingerprint=snapshot.fingerprint,
1335
+ model_state_fingerprint=snapshot.model_state_fingerprint,
1336
+ runtime_state=runtime_state,
1337
+ )
1338
+ )
1339
+
1340
+ def _evaluate_isolated(
1341
+ self,
1342
+ evaluator: Evaluator,
1343
+ *,
1344
+ expected_fingerprint: str | None = None,
1345
+ ) -> EvaluationScores:
1346
+ before = expected_fingerprint or self.current_state_fingerprint()
1347
+ rng = _clone_state(_capture_rng(self.torch_generators))
1348
+ cursor = _clone_state(self.cursor_capture())
1349
+ modes = _module_modes(self.model)
1350
+ try:
1351
+ scores = EvaluationScores.from_value(evaluator())
1352
+ finally:
1353
+ _restore_module_modes(self.model, modes)
1354
+ self.cursor_restore(_clone_state(cursor))
1355
+ _restore_rng(rng, self.torch_generators)
1356
+ after = self.current_state_fingerprint()
1357
+ if after != before:
1358
+ raise EvaluationMutationError(
1359
+ "checkpoint evaluator mutated model, optimizer, gradients, or topology"
1360
+ )
1361
+ return scores
1362
+
1363
+ def _record(self, body: Mapping[str, Any]) -> DecisionReceipt:
1364
+ receipt = DecisionReceipt(
1365
+ {
1366
+ "schema": DECISION_RECEIPT_SCHEMA,
1367
+ "controller_id": self.controller_id,
1368
+ "decision_index": len(self.ledger.receipts),
1369
+ "previous_receipt_fingerprint": self.ledger.head_fingerprint,
1370
+ **dict(body),
1371
+ }
1372
+ )
1373
+ if self.receipt_store is not None:
1374
+ self.receipt_store.put(receipt)
1375
+ self.ledger.append(receipt)
1376
+ return receipt
1377
+
1378
+ def establish_baseline(self, evaluator: Evaluator) -> DecisionReceipt:
1379
+ if self.initialized:
1380
+ raise TrainingCheckpointError("checkpoint controller already has a baseline")
1381
+ snapshot = self._capture_snapshot()
1382
+ try:
1383
+ scores = self._evaluate_isolated(evaluator, expected_fingerprint=snapshot.fingerprint)
1384
+ except Exception:
1385
+ self._restore_snapshot(snapshot)
1386
+ raise
1387
+ receipt = self._record(
1388
+ {
1389
+ "kind": "baseline",
1390
+ "interval_id": "baseline",
1391
+ "bounded_steps": 0,
1392
+ "policy": self.policy.to_dict(),
1393
+ "baseline": None,
1394
+ "candidate": {
1395
+ "state": snapshot.to_dict(),
1396
+ "evaluation": scores.to_dict(),
1397
+ },
1398
+ "comparison": None,
1399
+ "decision": {
1400
+ "promoted": True,
1401
+ "action": "establish-baseline",
1402
+ "reason": "initial-state",
1403
+ },
1404
+ "rollback": {
1405
+ "required": False,
1406
+ "verified_exact": True,
1407
+ },
1408
+ "post_state_fingerprint": snapshot.fingerprint,
1409
+ "train_metadata": {},
1410
+ }
1411
+ )
1412
+ self._accepted_snapshot = snapshot
1413
+ self._accepted_scores = scores
1414
+ return receipt
1415
+
1416
+ def _error_receipt(
1417
+ self,
1418
+ *,
1419
+ interval_id: str,
1420
+ steps: int,
1421
+ baseline: TrainingStateSnapshot,
1422
+ baseline_scores: EvaluationScores,
1423
+ error: Exception,
1424
+ candidate_fingerprint: str | None,
1425
+ train_metadata: Mapping[str, Any],
1426
+ ) -> DecisionReceipt:
1427
+ restored = self._restore_snapshot(baseline)
1428
+ return self._record(
1429
+ {
1430
+ "kind": "interval-error",
1431
+ "interval_id": interval_id,
1432
+ "bounded_steps": steps,
1433
+ "policy": self.policy.to_dict(),
1434
+ "baseline": {
1435
+ "state": baseline.to_dict(),
1436
+ "evaluation": baseline_scores.to_dict(),
1437
+ },
1438
+ "candidate": {
1439
+ "state_fingerprint_before_restore": candidate_fingerprint,
1440
+ "evaluation": None,
1441
+ },
1442
+ "comparison": None,
1443
+ "decision": {
1444
+ "promoted": False,
1445
+ "action": "restore-prior-after-error",
1446
+ "reason": "interval-error",
1447
+ "error_type": type(error).__qualname__,
1448
+ "error_message": str(error),
1449
+ },
1450
+ "rollback": {
1451
+ "required": True,
1452
+ "verified_exact": restored == baseline.fingerprint,
1453
+ },
1454
+ "post_state_fingerprint": restored,
1455
+ "train_metadata": dict(train_metadata),
1456
+ }
1457
+ )
1458
+
1459
+ def run_interval(
1460
+ self,
1461
+ *,
1462
+ interval_id: str,
1463
+ steps: int,
1464
+ train_step: TrainStep,
1465
+ evaluator: Evaluator,
1466
+ ) -> DecisionReceipt:
1467
+ if not self.initialized:
1468
+ raise TrainingCheckpointError("establish a baseline before training")
1469
+ resolved_interval = _validate_name(interval_id, label="interval_id")
1470
+ if resolved_interval == "baseline" or resolved_interval in self._interval_ids:
1471
+ raise ValueError("interval_id must be unique and cannot be 'baseline'")
1472
+ if isinstance(steps, bool) or not 1 <= int(steps) <= self.max_interval_steps:
1473
+ raise ValueError(f"steps must be between 1 and {self.max_interval_steps}")
1474
+ if not callable(train_step) or not callable(evaluator):
1475
+ raise ValueError("train_step and evaluator callbacks are required")
1476
+ baseline = self._accepted_snapshot
1477
+ baseline_scores = self._accepted_scores
1478
+ assert baseline is not None and baseline_scores is not None
1479
+ observed = self.current_state_fingerprint()
1480
+ if observed != baseline.fingerprint:
1481
+ self._restore_snapshot(baseline)
1482
+ raise TrainingStateDriftError(
1483
+ "live training state drifted from the accepted checkpoint; prior restored"
1484
+ )
1485
+ self._interval_ids.add(resolved_interval)
1486
+ train_metadata: dict[str, Any] = {}
1487
+ candidate_fingerprint: str | None = None
1488
+ try:
1489
+ step_receipts = []
1490
+ for step_index in range(int(steps)):
1491
+ raw_metadata = train_step(step_index)
1492
+ if raw_metadata is not None and not isinstance(raw_metadata, Mapping):
1493
+ raise ValueError("train_step callback metadata must be a mapping or None")
1494
+ step_receipts.append(
1495
+ _json_value(raw_metadata or {}, label=f"train step {step_index}")
1496
+ )
1497
+ train_metadata = {
1498
+ "step_callback_invocations": int(steps),
1499
+ "step_receipts": step_receipts,
1500
+ }
1501
+ candidate_fingerprint = self.current_state_fingerprint()
1502
+ candidate_scores = self._evaluate_isolated(
1503
+ evaluator, expected_fingerprint=candidate_fingerprint
1504
+ )
1505
+ comparison = self.policy.compare(baseline_scores, candidate_scores)
1506
+ except Exception as exc:
1507
+ try:
1508
+ if candidate_fingerprint is None:
1509
+ candidate_fingerprint = self.current_state_fingerprint()
1510
+ except Exception:
1511
+ candidate_fingerprint = None
1512
+ receipt = self._error_receipt(
1513
+ interval_id=resolved_interval,
1514
+ steps=int(steps),
1515
+ baseline=baseline,
1516
+ baseline_scores=baseline_scores,
1517
+ error=exc,
1518
+ candidate_fingerprint=candidate_fingerprint,
1519
+ train_metadata=train_metadata,
1520
+ )
1521
+ raise TrainingIntervalError(
1522
+ f"training interval {resolved_interval!r} failed and was restored",
1523
+ receipt=receipt,
1524
+ ) from exc
1525
+ promoted = bool(comparison["promoted"])
1526
+ candidate_snapshot: TrainingStateSnapshot | None = None
1527
+ if promoted:
1528
+ try:
1529
+ candidate_snapshot = self._capture_snapshot(
1530
+ expected_fingerprint=candidate_fingerprint
1531
+ )
1532
+ if candidate_snapshot.fingerprint != candidate_fingerprint:
1533
+ raise TrainingCheckpointError(
1534
+ "candidate changed between evaluation and checkpoint capture"
1535
+ )
1536
+ except Exception as exc:
1537
+ receipt = self._error_receipt(
1538
+ interval_id=resolved_interval,
1539
+ steps=int(steps),
1540
+ baseline=baseline,
1541
+ baseline_scores=baseline_scores,
1542
+ error=exc,
1543
+ candidate_fingerprint=candidate_fingerprint,
1544
+ train_metadata=train_metadata,
1545
+ )
1546
+ raise TrainingIntervalError(
1547
+ f"training interval {resolved_interval!r} failed and was restored",
1548
+ receipt=receipt,
1549
+ ) from exc
1550
+ post_fingerprint = candidate_snapshot.fingerprint
1551
+ else:
1552
+ post_fingerprint = self._restore_snapshot(baseline)
1553
+ receipt_body = {
1554
+ "kind": "interval-decision",
1555
+ "interval_id": resolved_interval,
1556
+ "bounded_steps": int(steps),
1557
+ "policy": self.policy.to_dict(),
1558
+ "baseline": {
1559
+ "state": baseline.to_dict(),
1560
+ "evaluation": baseline_scores.to_dict(),
1561
+ },
1562
+ "candidate": {
1563
+ "state_fingerprint": candidate_fingerprint,
1564
+ "checkpoint": (
1565
+ candidate_snapshot.to_dict() if candidate_snapshot is not None else None
1566
+ ),
1567
+ "evaluation": candidate_scores.to_dict(),
1568
+ },
1569
+ "comparison": comparison,
1570
+ "decision": {
1571
+ "promoted": promoted,
1572
+ "action": "promote-candidate" if promoted else "restore-prior",
1573
+ "reason": comparison["relation"],
1574
+ },
1575
+ "rollback": {
1576
+ "required": not promoted,
1577
+ "verified_exact": (
1578
+ post_fingerprint
1579
+ == (candidate_fingerprint if promoted else baseline.fingerprint)
1580
+ ),
1581
+ },
1582
+ "post_state_fingerprint": post_fingerprint,
1583
+ "train_metadata": train_metadata,
1584
+ }
1585
+ try:
1586
+ receipt = self._record(receipt_body)
1587
+ except Exception:
1588
+ if promoted:
1589
+ self._restore_snapshot(baseline)
1590
+ raise
1591
+ if promoted:
1592
+ assert candidate_snapshot is not None
1593
+ self._accepted_snapshot = candidate_snapshot
1594
+ self._accepted_scores = candidate_scores
1595
+ return receipt
1596
+
1597
+
1598
+ __all__ = [
1599
+ "AcceptedStateSerializationView",
1600
+ "DECISION_RECEIPT_SCHEMA",
1601
+ "EVALUATION_SCORES_SCHEMA",
1602
+ "PROMOTION_POLICY_SCHEMA",
1603
+ "TRAINING_CHECKPOINT_SCHEMA",
1604
+ "DecisionLedger",
1605
+ "DecisionReceipt",
1606
+ "DecisionReceiptError",
1607
+ "DeterministicCheckpointController",
1608
+ "EvaluationMutationError",
1609
+ "EvaluationScores",
1610
+ "ImmutableDirectoryReceiptStore",
1611
+ "PromotionObjective",
1612
+ "PromotionPolicy",
1613
+ "TrainingStateBoundary",
1614
+ "TrainingCheckpointError",
1615
+ "TrainingIntervalError",
1616
+ "TrainingStateDriftError",
1617
+ "TrainingStateSnapshot",
1618
+ ]