"""Standalone inference for the selected frozen EMMA + mean-pooling pointer head.""" import hashlib import json from pathlib import Path import numpy as np import sentencepiece as sp import torch from huggingface_hub import snapshot_download from .core import ( BASE_MODEL, FORMAT, REVISION, PointerHead, branch_features, encode_branches, format_answer, ) from .model import load_backbone BASE_HASHES = { "config.json": "77bc1705d050b2b66ce4511ede67d936ef974744ad9c1cd1b56728e6c6ee2c54", "emma6.onnx": "64488ea8de0f3051b09e5cd6629141e306b5ac120c4210d7da7301a0ccea6eca", "emma6.onnx.data": "a03315af6606cb529fc0f66813c874d800fc699b0199dbfb0083dbd25ab54972", "bpe.model": "81573d5d0cb40466d40516284afc34e47b586c24981ecbf627537dfbe31d6fbd", } def _hash(path: Path) -> str: with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def _base_directory(directory: str | Path | None) -> Path: root = Path(directory) if directory is not None else Path(snapshot_download( BASE_MODEL, revision=REVISION, allow_patterns=list(BASE_HASHES), )) for name, digest in BASE_HASHES.items(): if _hash(root / name) != digest: raise ValueError(f"Base {name} checksum mismatch") return root class Geppo: def __init__(self, bundle: str | Path | None = None, base_directory: str | Path | None = None, device: str | None = None): root = Path(bundle) if bundle is not None else Path(__file__).absolute().parent.parent config = json.loads((root / "config.json").read_text()) checkpoint = root / "selected.npz" if _hash(checkpoint) != config["checkpoint_sha256"]: raise ValueError("Selected checkpoint checksum mismatch") if config["base_model"] != BASE_MODEL: raise ValueError("Unsupported base model") expected = {"architecture": "pointer", "recipe": "frozen", "revision": REVISION, "format": FORMAT, "pooling": "mean"} with np.load(checkpoint, allow_pickle=False) as archive: for key, value in expected.items(): if config[key] != value or str(archive[key]) != value: raise ValueError(f"Unsupported checkpoint {key}") head = PointerHead() head.load_state_dict({key: torch.from_numpy(archive[f"head:{key}"].copy()) for key in head.state_dict()}) calibration = json.loads((root / "calibration.json").read_text()) self.name = config["selected_model"] if (calibration["primary"] != self.name or calibration["checkpoint_sha256"] != config["checkpoint_sha256"]): raise ValueError("Calibration belongs to a different selected model") self.calibration = calibration["models"][self.name] for kind in ("choice", "noul", "score"): temperature = self.calibration[kind]["temperature"] if not np.isfinite(temperature) or temperature <= 0: raise ValueError(f"Invalid {kind} calibration temperature") self.device = device or ("mps" if torch.backends.mps.is_available() else "cpu") base = _base_directory(base_directory) self.model = load_backbone(base, self.device) self.head = head.to(self.device).eval().requires_grad_(False) self.tokenizer = sp.SentencePieceProcessor(model_file=str(base / "bpe.model")) def decide(self, state: str | dict, questions: dict[str, dict]) -> dict: text = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False, sort_keys=True) answers = {} with torch.inference_mode(): for name, question in questions.items(): encoded = encode_branches(self.tokenizer, text, question) query, keys = branch_features(self.model, encoded, self.device, pooling="mean") mask = torch.ones((1, len(keys)), dtype=torch.bool, device=self.device) logits = self.head(query[None], keys[None], mask)[0].cpu().numpy().astype(np.float64) calibration = self.calibration[question["type"]] scaled = logits / calibration["temperature"] probabilities = np.exp(scaled - scaled.max()) probabilities /= probabilities.sum() answer = format_answer(question, encoded["option_ids"], probabilities) answer["calibrated"] = calibration["applied"] answers[name] = answer return {"model": f"geppo-emma-{self.name}", "answers": answers, "calibration": self.calibration, "note": "Experimental probabilities; no reliability guarantee on new domains."}