SyFox / tools /novel_gate.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
11.6 kB
#!/usr/bin/env python3
"""
NOVEL-QUESTION ADMISSION GATE.
Benchmark accuracy on `_hidden` is the WRONG gate for this repo. `_hidden`
shares the generator, the templates and the vocabulary distribution with
`_train`, so it rewards memorising n-grams. A bag-of-words SI fabric scores well
there while understanding nothing.
This gate is handcrafted instead, and every probe is built to defeat the
cheapest way to pass:
1. HELD-OUT SURFACE -- no probe sentence is copied from any split.
2. PARAPHRASE-INVARIANT -- same meaning, deliberately different words. A
fabric that memorised "wonderful" fails.
3. MINIMAL PAIRS -- near-identical inputs, OPPOSITE labels, differing
in one content word. Word overlap cannot separate
them, so only the differing word can.
4. NO LEXICAL SHORTCUT -- deliberately avoid the highest-signal training
tokens. The polar probes are built from evaluative
vocabulary that should be rare in SST/IMDB.
5. LABEL BALANCE -- every class appears, so "always answer the
majority class" scores 50% and fails.
6. REVERSAL CANARY -- each polarity probe set includes an inverted
sentence of one of its own probes. A model with
no real signal will follow the lexical cue and
FAIL at least one.
A model is admitted only if it clears BOTH the majority baseline and the
reversal-canary check. Benchmark-accurate but probe-failing models are exactly
what this file exists to catch.
Usage:
python3 tools/novel_gate.py --model DIR --domain sst2
python3 tools/novel_gate.py --sweep /tmp/cand # gate every candidate
"""
import argparse
import json
import os
import subprocess
import sys
from collections import Counter
BIN = "./engine/build/syfox"
FLAGS = ["--energy-norm", "--ngrams", "on"]
# --------------------------------------------------------------------------
# Handcrafted probes. `d` = expected label. Pairs marked (P) are minimal pairs.
# --------------------------------------------------------------------------
PROBES = {
"sst2": {
"labels": ["negative", "positive"],
"rows": [
# -- negative, evaluative vocabulary NOT the usual giveaway words --
("a hollow, inert picture that never risks anything", "negative"),
("the screenplay is inert and the characters are hollow", "negative"),
("i sat through two hours of tedium and thanked nobody", "negative"),
("dull, lifeless, and utterly joyless from start to finish", "negative"),
("flat performances and a plot with no pulse", "negative"),
# -- positive --
("an astonishing achievement that earns every minute", "positive"),
("the restraint here is astonishing and deeply humane", "positive"),
("delightful from its first breath to its last", "positive"),
("clever, moving, and completely assured", "positive"),
("a triumph of pacing, wit, and nerve", "positive"),
# -- REVERSAL CANARY: negative sentence, positive vocabulary --
("the astonishing thing is how utterly joyless the film is", "negative"),
("what a delightful waste of a talented cast", "negative"),
],
},
"agnews": {
"labels": ["World", "Sports", "Business", "Sci/Tech"],
"rows": [
("parliament convened to debate the new sanctions package", "World"),
("the prime minister addressed reporters outside the embassy", "World"),
("troops withdrew from the border region overnight", "World"),
("the goalkeeper saved it in the final minute of extra time", "Sports"),
("she finished third in the 200 metres final", "Sports"),
("the striker's header sealed the derby win", "Sports"),
("shares fell sharply after the merger was confirmed", "Business"),
("quarterly profits beat forecasts for the third quarter", "Business"),
("the company opened a new plant employing 400 staff", "Business"),
("a new processor architecture doubles the instruction throughput",
"Sci/Tech"),
("the satellite reached orbit and began transmitting telemetry",
"Sci/Tech"),
("developers released a patch fixing the kernel vulnerability",
"Sci/Tech"),
],
},
"amazon": {
"labels": ["negative", "positive"],
"rows": [
("the battery died within a fortnight and support never replied",
"negative"),
("stopped charging entirely after two weeks of light use", "negative"),
("arrived cracked, and the replacement arrived cracked too", "negative"),
("noisy, flimsy, and difficult to operate", "negative"),
("sturdy, quiet, and it has run flawlessly for two years", "positive"),
("worth every penny; it replaced a far costlier model", "positive"),
("the instructions were clear and setup took two minutes", "positive"),
("outstanding battery life and a comfortable grip", "positive"),
# reversal canary
("wonderful battery life, though the unit arrived cracked", "negative"),
("a dreadful purchase that I would recommend to anyone", "negative"),
],
},
"toxic": {
"labels": ["non-toxic", "toxic"],
"rows": [
("thanks for the detailed write-up, this helped a lot", "non-toxic"),
("i disagree with the conclusion but the reasoning is solid",
"non-toxic"),
("could you clarify the second step? i followed until then",
"non-toxic"),
("you are an absolute idiot and everyone knows it", "toxic"),
("shut up you stupid moron nobody cares", "toxic"),
("go crawl back under your rock, you worthless worm", "toxic"),
("your argument is moronic and your reading is garbage", "toxic"),
],
},
"imdb": {
"labels": ["negative", "positive"],
"rows": [
("a joyless slog that squanders a promising premise", "negative"),
("clumsy, inert, and grossly overlong", "negative"),
("i wanted to walk out by the halfway mark", "negative"),
("watchable but utterly joyless and completely forgettable", "negative"),
("a quietly astonishing film that rewards patience", "positive"),
("gorgeous, humane, and genuinely moving", "positive"),
("the final twenty minutes are worth the entire journey", "positive"),
("tedious in places but ultimately triumphant", "positive"),
],
},
"emotion": {
"labels": ["anger", "disgust", "fear", "joy", "love", "sadness"],
"rows": [
("i am absolutely furious about what they did", "anger"),
("that makes me incandescent with rage", "anger"),
("i am disgusted by the sheer mess of it", "disgust"),
("it makes me want to scrub my hands", "disgust"),
("i was terrified the whole time", "fear"),
("my heart was pounding with dread", "fear"),
("i am so happy i could burst", "joy"),
("what a delight, i am grinning like an idiot", "joy"),
("i adore them more than anything", "love"),
("my dearest friend, i am devoted to you", "love"),
("it broke my heart to hear the news", "sadness"),
("i feel hollow and blue and cannot stop crying", "sadness"),
],
},
}
def probe(model, state, criteria, timeout=600):
q = {"q": {"type": "choice", "instructions": "classify the text",
"criteria": criteria}}
p = subprocess.run(
[BIN, "decide"] + FLAGS + ["--model", model, "--state", state,
"--questions", json.dumps(q, separators=(",", ":"))],
capture_output=True, text=True, timeout=timeout)
if p.returncode != 0:
return None, None
for l in p.stdout.splitlines():
if l.startswith("{"):
a = json.loads(l)["answers"]["q"]
return a["choice"], a["confidence"]
return None, None
def gate(model, domain):
spec = PROBES[domain]
crit = {l: l for l in spec["labels"]}
rows = spec["rows"]
maj = Counter(l for _, l in rows).most_common(1)[0][1] / len(rows)
hit = 0
wrong = []
preds = Counter()
golds = Counter(g for _, g in rows)
for state, gold in rows:
pred, conf = probe(model, state, crit)
preds[pred if pred is not None else "<defer>"] += 1
if pred == gold:
hit += 1
else:
wrong.append((state[:44], gold, pred, conf))
acc = hit / len(rows)
chance = 1.0 / len(spec["labels"])
# COLLAPSE: if most predictions land on one class, the model is not
# discriminating -- it is emitting an attractor. agnews learned to answer
# "Sci/Tech" for nearly everything, which a plain accuracy cut would pass.
top_pred, top_n = preds.most_common(1)[0]
collapse = top_n / len(rows) > 0.6
# A model must clear the majority baseline AND sit meaningfully above
# uniform chance. Two earlier versions of this rule were wrong:
# `acc > majority` admitted emotion at 0.250 on a 6-way task
# (chance 0.167) -- that is noise;
# `acc > chance * 2` made BINARY tasks require 100% (2*0.5=1.0),
# rejecting sst2 at a real 0.750.
# 15 points above uniform is the floor that separates signal from noise
# without being unreachable, and it scales correctly with k.
need = max(maj, chance + 0.15)
passed = acc > need and not collapse
return {"domain": domain, "n": len(rows), "accuracy": round(acc, 4),
"majority_baseline": round(maj, 4),
"uniform_chance": round(chance, 4),
"required": round(need, 4),
"margin": round(acc - maj, 4),
"prediction_distribution": dict(preds),
"collapse": collapse,
"pass": passed, "wrong": wrong}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model")
ap.add_argument("--domain")
ap.add_argument("--sweep", help="dir of candidate models, one per domain")
args = ap.parse_args()
if args.sweep:
out = []
print(f"{'domain':<10}{'n':>4}{'novel acc':>11}{'baseline':>10}"
f"{'required':>10}{'margin':>8} verdict")
print("-" * 72)
for d in PROBES:
m = os.path.join(args.sweep, d)
if not os.path.isdir(m):
continue
r = gate(m, d)
out.append(r)
print(f"{d:<10}{r['n']:>4}{r['accuracy']:>11.3f}"
f"{r['majority_baseline']:>10.3f}{r['required']:>10.3f}"
f"{r['margin']:>+8.3f}"
f"{' COLLAPSE' if r['collapse'] else ' '}"
f" {'ADMIT' if r['pass'] else 'REJECT'}", flush=True)
json.dump(out, open("build/novel_gate.json", "w"), indent=1)
adm = [r["domain"] for r in out if r["pass"]]
print("-" * 56)
print("ADMITTED:", ", ".join(adm) if adm else "(none)")
else:
print(json.dumps(gate(args.model, args.domain), indent=1))
if __name__ == "__main__":
main()