File size: 6,835 Bytes
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python3
"""A candidate model against the base model of its tier, over the validation set: passed or not.

  python3 stats/gate.py --base Qwen3.5-9B-4bit --candidate some-model
  python3 stats/gate.py --base A --candidate B --mail other/mail --scan other/scan [--json]

Reads the result files of the two labels:

  <mail>/samples|real|rewrite/<label>.json          (default mail/results/triage)
  <scan>/posture|process/rules/<label>.json         (default scan/results)

and checks the candidate against the base. Three things have no allowance: suspicious mail missed, answers that did
not come out, high-severity findings missed. The scores pass unless the paired comparison (stats/paired.py) says the
candidate is worse: more questions lost than gained with McNemar p below 0.05, or for the scan F2 an interval of the
difference that lies wholly below zero. Under the verdict it prints the paired comparison of every set. Exit code 0 passed, 1 not passed, 2 the question sets differ, 3 a result is missing.
"""
from __future__ import annotations

import argparse
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import paired  # noqa: E402

# The fixed allowances that are left. One place, so a change of thresholds is a change here.
MARGINS = {
    "false_alarm": 1,        # normal mail flagged suspicious: at most this many more than the base
    "retried": 0.02,         # share of answers that needed a second try
}
ALPHA = 0.05                 # "worse" below means: worse, and the paired comparison calls it a difference at this level
MAIL_SETS = ("samples", "real", "rewrite")
SCAN_SETS = ("posture", "process")


def read(path: str) -> dict | None:
    return paired.load(path) if os.path.exists(path) else None


def check(name: str, base, cand, limit: str, ok: bool) -> dict:
    return {"check": name, "base": base, "candidate": cand, "threshold": limit, "passed": bool(ok)}


def not_worse(name: str, p: dict) -> dict:
    """Right/wrong questions: fails when more went from right to wrong than back and the McNemar test calls it a difference."""
    worse = len(p["lost"]) > len(p["gained"]) and p["p"] < ALPHA
    b, c = p["base"], p["candidate"]
    return check(name, f"{b['right']}/{b['n']}", f"{c['right']}/{c['n']}",
                 f"not worse: {len(p['lost'])} lost, {len(p['gained'])} gained, p = {p['p']:.3f}", not worse)


def gate(mail: dict, scan: dict, pairs: dict) -> list:
    """mail, scan: {set: (base, candidate)}; pairs: {"mail/<set>" | "scan/<set>": paired.compare(...)}. A missing set is left out.

    Hard, no allowance: suspicious mail, answers that did not come out, high-severity findings missed.
    Everything else passes unless the paired comparison says the candidate is worse."""
    out = []
    if "samples" in mail:
        b, c = (d["score"] for d in mail["samples"])
        out.append(check("suspicious mail caught", f"{b['safety']}/{b['safety_n']}", f"{c['safety']}/{c['safety_n']}",
                         "not below the base, and none missed", c["safety"] >= b["safety"] and c["safety"] == c["safety_n"]))
        out.append(check("normal mail flagged", b["false_alarm"], c["false_alarm"], f"at most base + {MARGINS['false_alarm']}",
                         c["false_alarm"] <= b["false_alarm"] + MARGINS["false_alarm"]))
        retried = c["n"] - c["failed"] - c["json_first_try"]
        out.append(check("no answer", b["failed"], c["failed"], "0", c["failed"] == 0))
        out.append(check("needed a second try", b["n"] - b["failed"] - b["json_first_try"], retried,
                         f"at most {MARGINS['retried']:.0%} of {c['n']}", retried <= MARGINS["retried"] * c["n"]))
    for name in MAIL_SETS:
        for group, p in (pairs.get(f"mail/{name}") or {"groups": {}})["groups"].items():
            out.append(not_worse(f"{name}, {group} right", p))
    for name in SCAN_SETS:
        if name not in scan:
            continue
        b, c = (d["score"] for d in scan[name])
        p = pairs[f"scan/{name}"]["groups"]["scan"]
        out.append(check(f"scan {name}, F2", b["f2"], c["f2"], f"not worse: difference 95% {p['low']:+.3f} to {p['high']:+.3f}", p["high"] >= 0))
        out.append(check(f"scan {name}, high missed", b["high_missed"], c["high_missed"], "at most the base", c["high_missed"] <= b["high_missed"]))
        out.append(check(f"scan {name}, no answer", b.get("failed", 0), c.get("failed", 0), "at most the base", c.get("failed", 0) <= b.get("failed", 0)))
    return out


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--base", required=True, help="label of the base model's results")
    ap.add_argument("--candidate", required=True)
    ap.add_argument("--mail", default="mail/results/triage")
    ap.add_argument("--scan", default="scan/results")
    ap.add_argument("--json", action="store_true")
    args = ap.parse_args()

    mail, scan, missing, pairs = {}, {}, [], {}
    wanted = [("mail", s, os.path.join(args.mail, s)) for s in MAIL_SETS] + [("scan", s, os.path.join(args.scan, s, "rules")) for s in SCAN_SETS]
    for where, name, folder in wanted:
        files = [os.path.join(folder, label + ".json") for label in (args.base, args.candidate)]
        both = [read(p) for p in files]
        if None in both:
            missing += [p for p, d in zip(files, both) if d is None]
            continue
        (mail if where == "mail" else scan)[name] = both
        pairs[f"{where}/{name}"] = paired.compare(*both)
    checks = gate(mail, scan, pairs)
    differ = [k for k, c in pairs.items() if any(n.startswith("QUESTION SETS DIFFER") for n in c["notes"])]
    passed = bool(checks) and all(c["passed"] for c in checks) and not missing and not differ
    verdict = "sets differ" if differ else "incomplete" if missing else "passed" if passed else "not passed"
    if args.json:
        print(json.dumps({"base": args.base, "candidate": args.candidate, "verdict": verdict, "missing": missing,
                          "checks": checks, "paired": pairs}, ensure_ascii=False, indent=1))
    else:
        print(f"base {args.base} · candidate {args.candidate}\n")
        for c in checks:
            print(f"  {'ok  ' if c['passed'] else 'FAIL'} {c['check']:28s} base {str(c['base']):>8s}  candidate {str(c['candidate']):>8s}   ({c['threshold']})")
        for p in missing:
            print(f"  ---- not run: {p}")
        for k in differ:
            print(f"  ---- question sets differ: {k}")
        print(f"\n{verdict.upper()}\n")
        for k, c in pairs.items():
            print(f"== {k}")
            paired.show(c)
            print()
    sys.exit(2 if differ else 3 if missing else 0 if passed else 1)


if __name__ == "__main__":
    main()