nnai-bench / evaluate_models.py
vynly's picture
Publish measured CAEL and MICA model runs with frozen evidence
a5e77f8 verified
Raw History Blame Contribute Delete
10.7 kB
"""Frozen native multiple-choice evaluation of existing CAEL and MICA models.
Inference consumes only id/prompt/choices, never gold labels, generation programs,
category-specific solvers or scheduling reference code. No fitting is performed.
Run with the existing Python environment that supplies numpy/scipy/sklearn.
"""
from __future__ import annotations
import argparse
from collections import Counter
import hashlib
import importlib.metadata
import json
import os
from pathlib import Path
import platform
import shutil
import socket
import sys
import time
for key in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
os.environ[key] = "1"
HERE = Path(__file__).resolve().parent
PROJECT = HERE.parent
RUNS = HERE / "model_runs" / "2026-10-19"
sys.path.insert(0, str(PROJECT))
from benchmark import VERSION, read_rows, dump, score
def sha(path):
with Path(path).open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def environment():
packages = {}
for name in ("numpy", "scipy", "scikit-learn", "joblib"):
try: packages[name] = importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError: packages[name] = None
return {"python": platform.python_version(), "platform": platform.system(), "machine": platform.machine(),
"processor": platform.processor(), "logical_cpus": os.cpu_count(), "threads": 1, "packages": packages}
def freeze():
RUNS.mkdir(parents=True, exist_ok=True)
if (RUNS / "freeze.json").exists():
raise RuntimeError("A frozen evaluation already exists; do not overwrite it or tune on its test outputs")
active = json.loads((PROJECT / "research/active_models.json").read_text(encoding="utf-8"))
language = Path(active["language"]["path"])
if sha(language) != active["language"]["sha256"]:
raise ValueError("CAEL selected checkpoint changed")
choice = active["choice"]
for name, expected in choice["code"].items():
if sha(PROJECT / "cael_unified" / (name + ".py")) != expected:
raise ValueError("CAEL reviewed chooser changed")
language_manifest = json.loads(language.read_text(encoding="utf-8"))
files = {str(language.relative_to(PROJECT)).replace("\\", "/"): sha(language)}
for name, expected in language_manifest["files"].items():
path = language.parent / name
if sha(path) != expected: raise ValueError(f"Checkpoint mismatch: {name}")
files[str(path.relative_to(PROJECT)).replace("\\", "/")] = expected
for rel in ("models/cael-knowledge-v1/knowledge.sqlite", "data/arc_corpus/arc_corpus.sqlite"):
if not (PROJECT / rel).is_file(): raise FileNotFoundError(rel)
files[rel] = sha(PROJECT / rel)
sources = ("cael_unified/count_language.py", "cael_unified/choice.py", "cael_unified/wordmath.py",
"cael_unified/bundle.py", "cael_unified/entity_binding.py")
source_root = RUNS / "cael_source"
for rel in sources:
path = PROJECT / rel
files[rel] = sha(path)
target = source_root / rel
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(path, target)
(source_root / "cael_unified/__init__.py").write_text("", encoding="utf-8")
shutil.copyfile(PROJECT / "LICENSE", source_root / "LICENSE")
for name in ("model.json", "SOURCES.json", "TRAINING_PROTOCOL.md", "TRAINING_NOTICES.md", "EARLIER_TRAINING_NOTICES.md"):
if (language.parent / name).exists():
shutil.copyfile(language.parent / name, source_root / name)
mica_root = PROJECT / "cael_flamew"
mica_manifest = json.loads((mica_root / "MANIFEST.json").read_text(encoding="utf-8"))
mica_files = {}
for name, expected in mica_manifest["files"].items():
path = mica_root / name
if not path.is_file() or sha(path) != expected:
raise ValueError(f"MICA package mismatch: {name}")
mica_files[name] = expected
value = {"benchmark_version": VERSION, "inference_input": "questions/test.jsonl: id/prompt/choices only",
"questions_sha256": sha(HERE / "dataset/questions/test.jsonl"), "test_sha256": sha(HERE / "dataset/data/test.jsonl"),
"runner_sha256": sha(__file__), "environment": environment(),
"test_exposure": "Maintainer also authored the public benchmark with a coding assistant. Existing model weights and inference code frozen before this run; no benchmark fitting or task-specific inference code added.",
"scheduling": "Not evaluated: current native APIs do not produce structured shift assignments.",
"cael": {"name": "CAEL 0.2.3 (whole-system MC)", "language_checkpoint": str(language.relative_to(PROJECT)).replace("\\", "/"),
"choice": {k: choice[k] for k in ("weight", "arc_weight", "short_limit")}, "files": files},
"mica": {"name": "MICA Flame-W 0.3.6", "repository": "vynly/mica-flame-w-0.3.6",
"revision": "ade0152787446966969048bbc7bdc789059638e2", "files": mica_files}}
dump(RUNS / "freeze.json", value)
print("Frozen model assets, native inference sources, inputs and settings; no predictions scored yet.", flush=True)
def offline():
def denied(*args, **kwargs):
raise RuntimeError("Network connections disabled during benchmark inference")
socket.socket.connect = denied
socket.socket.connect_ex = denied
socket.create_connection = denied
socket.getaddrinfo = denied
class CaelAdapter:
def __init__(self, frozen):
from cael_unified.count_language import CountLanguage
from cael_unified.choice import Evidence, choose
from cael_unified.bundle import ROOT
self.model = CountLanguage((PROJECT / frozen["language_checkpoint"]).parent)
self.config = frozen["choice"]
self.evidence = Evidence(PROJECT / "models/cael-knowledge-v1/knowledge.sqlite")
self.arc = Evidence(PROJECT / "data/arc_corpus/arc_corpus.sqlite", table="sentences")
self.choose = choose
def predict(self, prompt, choices):
scores = self.model.score_endings(prompt, choices)
index, details = self.choose(prompt, choices, scores, self.evidence, self.config["weight"], self.config["short_limit"],
extra=[(self.arc, self.config["arc_weight"])])
return "ABCD"[index], {**details, "continuation_scores": scores}
class MicaAdapter:
def __init__(self, frozen):
sys.path.insert(0, str(PROJECT / "cael_flamew"))
from answer import Prototype
self.model = Prototype()
def predict(self, prompt, choices):
# Generic formatting only: last line is the question, earlier lines story.
context, sep, question = prompt.rpartition("\n")
if not sep: context, question = "", prompt
answer = self.model.answer({"context": context, "question": question, "choices": choices})
return "ABCD"[answer["answer_index"]], {"route": answer["route"]}
def verify_frozen(name, frozen):
if frozen["runner_sha256"] != sha(__file__): raise ValueError("Frozen runner changed")
if frozen["questions_sha256"] != sha(HERE / "dataset/questions/test.jsonl"): raise ValueError("Test inputs changed")
root = PROJECT if name == "cael" else PROJECT / "cael_flamew"
for rel, expected in frozen[name]["files"].items():
if sha(root / rel) != expected: raise ValueError(f"Frozen asset changed: {rel}")
def evaluate(name, limit=None):
frozen = json.loads((RUNS / "freeze.json").read_text(encoding="utf-8"))
verify_frozen(name, frozen)
destination = RUNS / name
destination.mkdir(exist_ok=True)
input_rows = read_rows(HERE / "dataset/questions/test.jsonl")
# Deliberately drop split/category/difficulty before invoking the adapter.
inputs = [{k: row[k] for k in ("id", "prompt", "choices")} for row in input_rows]
if any("answer" in r or "program" in r for r in inputs): raise ValueError("Gold in inference inputs")
if limit is not None: inputs = inputs[:limit]
offline()
start = time.perf_counter()
adapter = (CaelAdapter if name == "cael" else MicaAdapter)(frozen[name])
predictions, traces = [], []
trace_file = destination / ("smoke.rows.jsonl" if limit else "test.rows.jsonl")
with trace_file.open("w", encoding="utf-8", newline="\n") as stream:
for i, row in enumerate(inputs):
item_start = time.perf_counter()
try:
prediction, detail = adapter.predict(row["prompt"], row["choices"])
except Exception as exc:
prediction, detail = "ABSTAIN", {"route": "error", "error": type(exc).__name__ + ": " + str(exc)}
predictions.append({"id": row["id"], "prediction": prediction})
trace = {"id": row["id"], "prediction": prediction, "seconds": round(time.perf_counter()-item_start,6), **detail}
traces.append(trace)
stream.write(json.dumps(trace, ensure_ascii=False) + "\n"); stream.flush()
if (i+1)%50==0: print(name, i+1, "/",len(inputs), "elapsed",round(time.perf_counter()-start,1), flush=True)
elapsed = time.perf_counter()-start
dump(destination / ("smoke.predictions.json" if limit else "test.predictions.json"), predictions)
if limit:
print(name,"smoke predictions",len(predictions),"errors",sum(t["route"]=="error" for t in traces));return
# Gold labels are opened only after all model predictions have been saved.
if frozen["test_sha256"] != sha(HERE / "dataset/data/test.jsonl"): raise ValueError("Gold file changed")
report = score(predictions, read_rows(HERE / "dataset/data/test.jsonl"))
dump(destination / "test.report.json", report)
dump(destination / "run.json", {"name": frozen[name]["name"], "items":len(predictions),"elapsed_seconds":elapsed,
"route_counts":dict(Counter(t["route"] for t in traces)),"environment":environment(),
"predictions_sha256":sha(destination/"test.predictions.json"),"trace_sha256":sha(trace_file),
"freeze_sha256":sha(RUNS/"freeze.json"),"network":"socket connections and DNS denied for inference", "status":"maintainer-run, not independent reproduction"})
print(name,"complete",round(report["macro_accuracy"],4),"coverage",report["coverage"],"seconds",round(elapsed,2),flush=True)
if __name__ == "__main__":
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("command",choices=("freeze","cael","mica"))
parser.add_argument("--limit",type=int)
args=parser.parse_args()
if args.command=="freeze": freeze()
else: evaluate(args.command,args.limit)