"""Small in-process consistency snapshots, not an exported provenance protocol.""" from __future__ import annotations import hashlib import json from dataclasses import dataclass import torch from torch import nn from capstone.inference.image_io import PreparedImage, PreprocessingSpec def json_digest(value: object) -> str: encoded = json.dumps(value, sort_keys=True, allow_nan=False, separators=(",", ":")) return hashlib.sha256(encoded.encode("utf-8")).hexdigest() def tensor_digest(value: torch.Tensor) -> str: value = value.detach().cpu().contiguous() digest = hashlib.sha256(f"{value.dtype}:{tuple(value.shape)}".encode()) digest.update(value.reshape(-1).view(torch.uint8).numpy().tobytes()) return digest.hexdigest() @dataclass(frozen=True) class SourceSnapshot: image_sha256: str image_size: tuple[int, int] model_sha256: str model_card_sha256: str preprocessing: PreprocessingSpec @classmethod def capture(cls, model: nn.Module, prepared: PreparedImage) -> SourceSnapshot: """Compare decoded RGB pixels, state_dict and card across forward passes. Assumes an eval-mode model without concurrent mutation or hidden mutable forward state. This is accidental-mixing detection, not authentication. """ digest = hashlib.sha256(f"{type(model).__module__}.{type(model).__qualname__}".encode()) for name, value in sorted(model.state_dict().items()): digest.update(name.encode()) digest.update(tensor_digest(value).encode()) rgb = prepared.rgb image_digest = hashlib.sha256(f"RGB:{rgb.size}".encode()) image_digest.update(rgb.tobytes()) return cls( image_digest.hexdigest(), rgb.size, digest.hexdigest(), json_digest(getattr(model, "model_card", None)), prepared.preprocessing, )