Download scripts/verify_artifacts.py from BinxNet/fermi-4fgl-rf-classifier: direct link, hf CLI and curl.
- Browser
- Download file 3.63 kB
-
https://huggingface.co/BinxNet/fermi-4fgl-rf-classifier/resolve/main/scripts/verify_artifacts.py
- Command line
-
hf download hf://BinxNet/fermi-4fgl-rf-classifier/scripts/verify_artifacts.py
-
curl -L -o verify_artifacts.py https://huggingface.co/BinxNet/fermi-4fgl-rf-classifier/resolve/main/scripts/verify_artifacts.py
3.63 kB
| """Verify SHA-256 checksums, safe skops loading, and ONNX probability parity for exported v2 models.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import onnxruntime as ort | |
| import pandas as pd | |
| import skops.io as sio | |
| REPO_ROOT = Path(__file__).resolve().parent.parent | |
| def _sha256(path: Path) -> str: | |
| h = hashlib.sha256() | |
| with path.open("rb") as f: | |
| for chunk in iter(lambda: f.read(65536), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def _sample_rows_from_predictions(csv_path: Path) -> pd.DataFrame: | |
| df = pd.read_csv(csv_path) | |
| idx = list(range(min(3, len(df)))) + [len(df) // 2] + list(range(max(0, len(df) - 4), len(df))) | |
| return df.iloc[idx].reset_index(drop=True) | |
| def main() -> None: | |
| cfg = json.loads((REPO_ROOT / "config.json").read_text(encoding="utf-8")) | |
| pred_csv = REPO_ROOT / "data" / "fermi_4fgl_3class_predictions.csv" | |
| sample_df = _sample_rows_from_predictions(pred_csv) | |
| rng = np.random.default_rng(42) | |
| for name, spec in cfg["models"].items(): | |
| skops_path = REPO_ROOT / spec["skops_path"] | |
| onnx_path = REPO_ROOT / spec["onnx_path"] | |
| n_classes = len(spec["classes"]) | |
| if not skops_path.exists() or not onnx_path.exists(): | |
| raise FileNotFoundError(f"Missing model artifact for {name}") | |
| if _sha256(skops_path) != spec["sha256"]["skops"]: | |
| raise ValueError(f"{name} skops SHA-256 mismatch") | |
| if _sha256(onnx_path) != spec["sha256"]["onnx"]: | |
| raise ValueError(f"{name} onnx SHA-256 mismatch") | |
| untrusted = sio.get_untrusted_types(file=skops_path) | |
| clf = sio.load(skops_path, trusted=untrusted) | |
| sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"]) | |
| input_name = sess.get_inputs()[0].name | |
| n_feats = len(spec["features"]) | |
| X_syn = rng.normal(loc=0.0, scale=2.0, size=(16, n_feats)).astype(np.float32) | |
| if set(spec["features"]).issubset({"pl_index", "log_var", "log_eflux", "abs_b", "is_curved", "sig"}): | |
| spec_str = sample_df["spectrum_type"].fillna("").astype(str).str.strip() | |
| gamma_df = pd.DataFrame({ | |
| "pl_index": sample_df["pl_index"].to_numpy(dtype=float), | |
| "log_var": np.log10(np.clip(sample_df["variability_index"].fillna(1.0).to_numpy(dtype=float), 0.1, None)), | |
| "log_eflux": np.log10(np.clip(sample_df["energy_flux"].to_numpy(dtype=float), 1e-16, None)), | |
| "abs_b": np.abs(sample_df["bii"].fillna(0.0).to_numpy(dtype=float)), | |
| "is_curved": spec_str.isin(["LogParabola", "PLSuperExpCutoff"]).astype(float), | |
| "sig": sample_df["detection_significance"].fillna(0.0).to_numpy(dtype=float), | |
| }) | |
| X_probe = np.vstack([X_syn, gamma_df[spec["features"]].to_numpy(dtype=np.float32)]) | |
| else: | |
| X_probe = X_syn | |
| p_skops = clf.predict_proba(X_probe) | |
| _, p_onnx = sess.run(None, {input_name: X_probe}) | |
| if p_onnx.shape != (len(X_probe), n_classes): | |
| raise ValueError(f"{name}: unexpected ONNX shape {p_onnx.shape}, expected {(len(X_probe), n_classes)}") | |
| max_diff = float(np.max(np.abs(p_skops - p_onnx))) | |
| if max_diff >= 1e-5: | |
| raise ValueError(f"{name}: skops vs ONNX max_abs_diff={max_diff} >= 1e-5") | |
| print( | |
| f"[OK] {name} ({n_classes}-class): sha256 verified | untrusted_types={len(untrusted)} | " | |
| f"skops_vs_onnx_max_diff={max_diff:.2e}" | |
| ) | |
| if __name__ == "__main__": | |
| main() | |