OpenIslet

scripts/verify_cellgemma_islet_v0_1.py

Standalone Zero-GPU / Pure-CPU Fail-Closed Verifier for OpenIslet CellGemma-Islet v0.9.0.

script Release v0.8.0 gen-eb955f8266035aba 77 KB · 6 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_cellgemma_islet_v0_1.py · SHA-256: 31b99284adcaabe1…

#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""
Standalone Zero-GPU / Pure-CPU Fail-Closed Verifier for OpenIslet CellGemma-Islet v0.9.0.

License & Distribution Distinction:
  - This executable verifier script: Apache-2.0 (distributed inside OpenIslet LICENSE for scripts/**;
    any standalone distribution outside the licensed repository MUST include the full Apache-2.0
    license text alongside the 6 runtime verifier inputs per Apache-2.0 §4(a)).
  - Narrative IIP drafts & JSON provenance receipt: CC BY 4.0 (docs/** and data/**).
  - Underlying model weights card (google/cellgemma-e4b, commit 6212145e0131d3744171739ea5232afc6aaa7c76):
    Apache-2.0 research weights (intended for research use with independent experimental validation);
    frozen PubMed bibliographic records are a dated NLM/NCBI E-utilities snapshot (2026-12-02T16:04:39Z)
    subject to NLM data/download terms (https://www.nlm.nih.gov/databases/download.html).

Honest Scope Separation:
  - Default portable mode (6 runtime inputs): deterministically verifies strict JSON/nonfinite
    safety, payload & file SHA-256 integrity, embedded 31-file manifest syntax (NOT external raw
    bytes), exact S1/S2 panel-gene-to-mean & n_up/n_down arithmetic on 120/139 full-vector profiles
    (6,263 embedded 4-decimal NPZ entries) + S1/S2 residual accounting (NOT omitted-gene recovery)
    and composite arithmetic on 19/139 thresholded raw-JSON profiles (70/70 panels flagged
    unverifiable below 0.05; 46/70 S1 nonzero across 17/19 profiles; 70/70 S2 nonzero across 19/19
    profiles), track-specific falsifying Step-0 G1 checks (Track 1 >=0.25/0.25 on post-cutoff CM &
    6-cond Flex; Track 2 >=0.15/0.20 on 8-target RQC; 3x1 vs 5x3) & 8/8 RQC target bindings in Draft C,
    embedded per-file generation-cap sums (142/147, 272/351, 36 unknown), all 23 retrospective
    concordance scalars in Draft C, all 36 core + 40 omega [0,1] + 24 Design B discount 2^20 rows +
    full Design-A parameter & output firewall invariance, strict Section-6 live-odds (`+0.00 percentage
    points`), exact labeled baseline-role bindings (including explicit `inactive Track-B`), exact
    ordered triple header columns (`Ceiling / Locked / Modular` for `phi = 0.25` & `phi = 0.50`),
    exact per-row ceiling strings, BOTH canonical BPR-05 bounds (`64.61%` and `67.25%`), & promoted-
    scalar Markdown binding, 60/60 body/Section-7 PMID parity + 9 curated claim_to_source_map records
    (33 unique PMIDs) body/locator resolution, Graveyard pairs, and fixed host-independent portable
    preflight hygiene across all 6 files (identical result regardless of reader account name;
    canonical OpenIslet exporter checks remain authoritative at submission; pair with a sanitized
    trusted detached manifest or canonical immutable source for full draft-byte integrity).
  - Local source mode (`--verify-local-sources`): scoped explicitly to the 31 local files listed in
    `source_file_sha256_manifest` (verifying exact byte sizes & SHA-256 digests on disk, incl.
    primary Track-1/Track-2 truth NPZs & summaries, locked benchmark plan, scripts, builder, and raw
    results) plus dated NLM snapshot parity across all 60 PubMed records (does not re-extract raw
    NPZ/JSON numeric values into the receipt from scratch; model weights/config remain pinned to HF).
  - Semantic claim-to-full-text fidelity, live NCBI retraction API status, raw-to-receipt numerical
    re-extraction, GPU re-inference, and wet-lab biological hypothesis testing are external to this script.

Fail-Closed Guarantee:
  Uses explicit RuntimeError checks (zero assert statements), remaining 100% fail-closed under
  both `python3 -W error -B` and `python3 -W error -O -B`.

Usage:
  PYTHONDONTWRITEBYTECODE=1 python3 -B verify_cellgemma_islet_v0_1.py
  PYTHONDONTWRITEBYTECODE=1 python3 -B verify_cellgemma_islet_v0_1.py --verify-local-sources
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import re
from pathlib import Path
from typing import Any

HERE = Path(__file__).resolve().parent
RECEIPT_PATH = (
    HERE / "cellgemma_islet_v0_1_receipt.json"
    if (HERE / "cellgemma_islet_v0_1_receipt.json").is_file()
    else HERE.parent / "data" / "extracted" / "cellgemma_islet_v0_1_receipt.json"
)
VERIFIER_PATH = Path(__file__).resolve()
IIP_DRAFT_FILES = {
    "A": "IIP_DRAFT_A_PIRFENIDONE_LOCAL_ANTIFBR_IEC_H4.md",
    "B": "IIP_DRAFT_B_DEUCRAVACITINIB_LOCAL_TYK2_IBMIR_NK.md",
    "C": "IIP_DRAFT_C_BBC3_PMAIP1_JAK2_H3_CHANNEL_C_BYSTANDER.md",
    "D": "IIP_DRAFT_D_CELLGEMMA_BLUEPRINT_GUARDRAILS_AND_HIPCORE_AUDIT.md",
}

SHIPPED_IIP0042_EXACT = {
    "phi_0p25_central": {
        "L1": (0.6641165402574369, 0.6064389039505889, 0.6159208654195334),
        "L3B": (0.7059206074620995, 0.6600787450699173, 0.6657313735189612),
    },
    "phi_0p50_harsh_stress": {
        "L1": (0.6490015923569795, 0.5968696707734863, 0.6057678502003759),
        "L3B": (0.6898542206807782, 0.6491393219690672, 0.6543971951385278),
    },
}

CANONICAL_GY_OFFGRID = {
    "OFFGRID_GUARD_001": "GY-015",
    "OFFGRID_GUARD_002": "GY-016",
    "OFFGRID_GUARD_003": "GY-011",
    "OFFGRID_GUARD_004": "GY-012",
    "OFFGRID_GUARD_005": "GY-013",
    "OFFGRID_GUARD_006": "GY-014",
    "OFFGRID_GUARD_007": "GY-017",
    "OFFGRID_GUARD_008": "GY-018",
    "OFFGRID_GUARD_009": "GY-019",
    "OFFGRID_GUARD_010": "GY-020",
    "OFFGRID_GUARD_011": "GY-021",
    "OFFGRID_GUARD_012": "GY-022",
    "OFFGRID_GUARD_013": "GY-023",
    "OFFGRID_GUARD_014": "GY-024",
    "OFFGRID_GUARD_015": "GY-025",
    "OFFGRID_GUARD_016": "GY-026",
    "OFFGRID_GUARD_017": "GY-027",
    "OFFGRID_GUARD_018": "GY-028",
    "OFFGRID_GUARD_019": "GY-029",
    "OFFGRID_GUARD_020": "GY-030",
    "OFFGRID_GUARD_021": "GY-031",
    "OFFGRID_GUARD_022": "GY-032",
}


def require(cond: bool, msg: str) -> None:
    if not cond:
        raise RuntimeError(f"FAIL-CLOSED VERIFICATION ERROR: {msg}")


def _check_all_finite(obj: Any, path: str = "root") -> None:
    if isinstance(obj, float):
        require(math.isfinite(obj), f"Non-finite float at {path}: {obj!r}")
    elif isinstance(obj, dict):
        for k, v in obj.items():
            _check_all_finite(v, f"{path}.{k}")
    elif isinstance(obj, list):
        for idx, v in enumerate(obj):
            _check_all_finite(v, f"{path}[{idx}]")


def load_strict_json(raw_text: str) -> Any:
    def _reject_dup(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
        out: dict[str, Any] = {}
        for k, v in pairs:
            if k in out:
                raise RuntimeError(f"Duplicate JSON key rejected: {k!r}")
            out[k] = v
        return out

    def _reject_const(tok: str) -> Any:
        raise RuntimeError(f"Non-finite JSON constant rejected: {tok!r}")

    data = json.loads(raw_text, object_pairs_hook=_reject_dup, parse_constant=_reject_const)
    _check_all_finite(data)
    return data


def subadditive_overlap(base: float, delta_a: float, delta_b: float, omega: float) -> float:
    for nm, val in (("base", base), ("delta_a", delta_a), ("delta_b", delta_b), ("omega", omega)):
        require(isinstance(val, (int, float)) and math.isfinite(val), f"Non-finite overlap input {nm}={val!r}")
    require(0.0 <= base < 1.0, f"Invalid base={base}")
    require(delta_a >= 0.0 and delta_b >= 0.0, f"Negative deltas: {delta_a}, {delta_b}")
    require(base + delta_a < 1.0 and base + delta_b < 1.0, f"Envelope breach: {base}, {delta_a}, {delta_b}")
    require(0.0 <= omega <= 1.0, f"Invalid omega={omega}")
    hi = max(delta_a, delta_b)
    lo = min(delta_a, delta_b)
    if lo == 0.0:
        return base + hi
    rem_frac = max(0.0, 1.0 - hi / (1.0 - base))
    val = base + hi + (1.0 - omega) * lo * rem_frac
    require(base <= val < 1.0, f"Out-of-envelope combined value={val}")
    return val


def _bivariate(p1: float, p2: float, phi: float) -> dict[tuple[int, int], float]:
    p1, p2 = min(1.0, max(0.0, p1)), min(1.0, max(0.0, p2))
    p11 = (1.0 - phi) * (p1 * p2) + phi * min(p1, p2)
    return {
        (0, 0): max(0.0, 1.0 - p1 - p2 + p11),
        (1, 0): max(0.0, p1 - p11),
        (0, 1): max(0.0, p2 - p11),
        (1, 1): max(0.0, p11),
    }


def _frechet_joint(probs: list[float], phi: float) -> list[float]:
    m = len(probs)
    n = 1 << m
    d_ind = [0.0] * n
    for mask in range(n):
        w = 1.0
        for i in range(m):
            w *= probs[i] if (mask & (1 << i)) else (1.0 - probs[i])
        d_ind[mask] = w
    if phi == 0.0:
        return d_ind
    order = sorted(range(m), key=lambda i: probs[i])
    d_pos = [0.0] * n
    prev = 0.0
    for idx, i in enumerate(order):
        w = probs[i] - prev
        if w > 0.0:
            d_pos[sum(1 << j for j in order[idx:])] += w
        prev = probs[i]
    d_pos[0] += 1.0 - prev
    return [(1.0 - phi) * d_ind[s] + phi * d_pos[s] for s in range(n)]


def _frechet_couple(inc: list[float], u_new: float, phi: float, target_fn) -> list[float]:
    n0 = len(inc)
    u_new = min(1.0, max(0.0, u_new))
    p_e1 = sum(inc[mi] for mi in range(n0) if target_fn(mi))
    p_e0 = 1.0 - p_e1
    d_ind = [0.0] * (2 * n0)
    for mi in range(n0):
        d_ind[mi] = inc[mi] * (1.0 - u_new)
        d_ind[mi | n0] = inc[mi] * u_new
    d_pos = [0.0] * (2 * n0)
    p_11 = min(p_e1, u_new)
    p_10 = p_e1 - p_11
    p_01 = max(0.0, u_new - p_e1)
    p_00 = p_e0 - p_01
    for mi in range(n0):
        w = inc[mi]
        if w == 0.0:
            continue
        if target_fn(mi):
            d_pos[mi] = p_10 * (w / p_e1)
            d_pos[mi | n0] = p_11 * (w / p_e1)
        else:
            d_pos[mi] = p_00 * (w / p_e0)
            d_pos[mi | n0] = p_01 * (w / p_e0)
    return [(1.0 - phi) * d_ind[s] + phi * d_pos[s] for s in range(2 * n0)]


def eval_5arm_from_inputs(inp: dict[str, Any]) -> dict[str, Any]:
    arms = inp["arms"]
    require(len(arms) == 5 and all(len(a) == 4 for a in arms), "Invalid arms shape")
    pa, pb, px, py, pd = arms
    c1_allo = inp["c1_allo"]
    c2_a, c2_bx, c2_y, c2_univ, c2_auto = inp["c2_a"], inp["c2_bx"], inp["c2_y"], inp["c2_univ"], inp["c2_auto"]
    c2_u0 = inp.get("c2_univ_base_for_a", c2_univ)
    c3_a, c3_bx, c3_y, c3_d = inp["c3_a"], inp["c3_bx"], inp["c3_y"], inp["c3_d"]
    c4_univ, c4_pa, c4_pbx, c4_r3p = inp["c4_univ"], inp["c4_pouch_a"], inp["c4_pouch_bx"], inp["c4_r3p"]
    phi_c = inp["phi_c"]
    phi_yx = 0.75

    u_d1 = min(1.0, max(0.0, pd[0] / c1_allo))
    d1 = [0.0] * 32
    d1[0], d1[15], d1[31] = 1.0 - c1_allo, c1_allo * (1.0 - u_d1), c1_allo * u_d1

    require(c2_a <= c2_bx + 1e-12 and c2_bx <= c2_y + 1e-12 and c2_y <= c2_univ + 1e-12, "Invalid H2 ceilings")
    biv2_y = _bivariate(c2_y / c2_univ, c2_auto / c2_univ, phi_c)
    u_d2 = pd[1] / c2_auto
    if abs(c2_a - c2_bx) <= 1e-12 and abs(c2_univ - c2_u0) <= 1e-12:
        d2_inc = _frechet_joint([pa[1] / c2_bx, pb[1] / c2_bx, px[1] / c2_bx], 0.0)
        r2, u_y2 = c2_bx / c2_y, py[1] / c2_y
        d2_both = _frechet_couple(d2_inc, u_y2, phi_yx, lambda mi: bool(mi & 4))
        d2_allo4 = [r2 * d2_both[k] for k in range(16)]
        d2_allo4[0] += (1.0 - r2) * (1.0 - u_y2)
        d2_allo4[8] += (1.0 - r2) * u_y2