SyFox / tools /candidate_sweep.py
Mr-DS-ML-85's picture
v3.9.1: engine port, 3 novel-gated fabrics (sst2/agnews/amazon), refreshed libsyfox_core.so
d61eb28 verified
Raw History Blame Contribute Delete
3.97 kB
#!/usr/bin/env python3
"""Train + honestly measure candidate fabrics, then report only the winners.
Method per domain (all measured on _hidden, scored once):
1. learn on _train (single pass, --energy-norm --ngrams on)
2. calibrate on _cal -- temperature/ECE fitted on cal ONLY
3. bench on _hidden -- reported as accuracy, defer rate, honest total
A model is only proposed for shipping if its honest total beats the majority
baseline by a real margin. xnli is included precisely because it is expected to
FAIL: NLI is compositional, and this project's own compose_bench measures field
composition at 0/16. Recording the failure is the point -- it keeps the set
honest and it is the evidence that the win/loss line is drawn at "bag-of-words
work", not "whatever we managed to ship".
"""
import json
import os
import shutil
import subprocess
import sys
import functools
print = functools.partial(__builtins__.print, flush=True)
BIN = "./engine/build/syfox"
DATA = os.path.expanduser("~/syfox-data/hf_v2")
FLAGS = ["--energy-norm", "--ngrams", "on"]
OUT = "/tmp/cand"
_T0 = __import__("time").time()
def _elapsed():
return __import__("time").time() - _T0
def run(args, timeout=7200):
p = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
return p.returncode, p.stdout, p.stderr
def jline(out):
for l in out.splitlines():
if l.startswith("{"):
return json.loads(l)
return {}
def baseline(path):
"""Majority-class share of the hidden labels = the bar to beat."""
from collections import Counter
c = Counter()
for line in open(path):
d = json.loads(line)
for v in (d.get("labels") or {}).values():
c[v] += 1
return c.most_common(1)[0][1] / max(1, sum(c.values()))
def main(domains):
print(f"{'domain':<16}{'nodes':>8}{'MB':>7}{'acc':>8}{'defer':>8}"
f"{'honest':>8}{'base':>8} verdict")
print("-" * 74)
rows = []
for d in domains:
tr = f"{DATA}/{d}_train.jsonl"
cal = f"{DATA}/{d}_cal.jsonl"
hid = f"{DATA}/{d}_hidden.jsonl"
if not (os.path.exists(tr) and os.path.exists(cal) and os.path.exists(hid)):
print(f"{d:<16} (missing split)")
continue
m = f"{OUT}/{d}"
shutil.rmtree(m, ignore_errors=True)
_, so, se = run([BIN, "learn", "--quiet", "--model", m, "--examples", tr] + FLAGS)
if jline(so).get("command") != "learn":
print(f"{d:<16} LEARN FAILED: {se[-120:]}")
continue
run([BIN, "calibrate", "--quiet", "--model", m, "--examples", cal] + FLAGS)
_, bo, _ = run([BIN, "bench", "--model", m, "--eval", hid] + FLAGS)
j = jline(bo)
r = j.get("routing", {})
acc = r.get("choice_accuracy", 0.0)
df = r.get("choice_defer_rate", 0.0)
honest = acc * (1 - df)
base = baseline(hid)
st = json.load(open(f"{m}/meta.json"))
mb = os.path.getsize(f"{m}/substrate.bin") / 1e6
verdict = "SHIP" if honest > base + 0.05 else ("weak" if honest > base else "FAIL")
print(f"{d:<16}{st['nodes']:>8}{mb:>7.1f}{acc:>8.4f}{df:>8.4f}"
f"{honest:>8.4f}{base:>8.4f} {verdict}")
print(f" [{d}] learned+calibrated+benched in "
f"{_elapsed():.0f}s cumulative", flush=True)
rows.append({"domain": d, "nodes": st["nodes"], "mb": round(mb, 1),
"acc": acc, "defer": df, "honest": honest,
"baseline": base, "verdict": verdict})
json.dump(rows, open("build/candidates.json", "w"), indent=1)
ship = [r["domain"] for r in rows if r["verdict"] == "SHIP"]
print("-" * 74)
print("SHIP:", ", ".join(ship) if ship else "(none)")
print("wrote build/candidates.json")
if __name__ == "__main__":
main(sys.argv[1:] or ["sst2", "agnews", "amazon", "toxic", "emotion",
"dbpedia", "imdb", "hate3", "xnli"])