File size: 4,558 Bytes
46e27b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Phase A — re-score the existing bakeoff under the DUAL Gate 2 constraint.

The stored benchmark JSONs already contain a complete threshold sweep with both
`over_deletion_rate` and `harmful_span_rate`, so re-selecting the operating
point is arithmetically identical to what the updated harness would produce,
without re-running inference.

Reports, per arm: which thresholds pass each gate, whether ANY threshold passes
both, and the resulting gap to target.
"""
import glob
import json
import os
import sys

sys.path.insert(0, "/opt/vox/sandbox/scripts")
from span_common import HARMFUL_SPAN_GATE, OVER_DELETION_GATE

OUT = "/opt/vox/sandbox/benchmarks/gate2_rescored.json"


def reselect(sweep):
    for r in sweep:
        r["passes_over_deletion_gate"] = r["over_deletion_rate"] < OVER_DELETION_GATE
        r["passes_harmful_gate"] = r["harmful_span_rate"] < HARMFUL_SPAN_GATE
        r["passes_gate"] = r["passes_over_deletion_gate"] and r["passes_harmful_gate"]
    ok = [r for r in sweep if r["passes_gate"]]
    if ok:
        best = max(ok, key=lambda r: r["exact_match"])
        best = dict(best)
        best["no_threshold_satisfies_gate"] = False
    else:
        best = dict(min(sweep, key=lambda r: (r["harmful_span_rate"], r["over_deletion_rate"])))
        best["no_threshold_satisfies_gate"] = True
    return best, ok


def main():
    report = {"gates": {"over_deletion_rate": OVER_DELETION_GATE,
                        "harmful_span_rate": HARMFUL_SPAN_GATE}, "arms": {}}
    print(f"GATE 2 (dual): over_deletion < {OVER_DELETION_GATE}%  AND  "
          f"harmful_span < {HARMFUL_SPAN_GATE}%\n")
    hdr = (f"{'arm':22} {'thr':>5} {'EM':>7} {'P':>6} {'R':>6} {'F1':>6} "
           f"{'overdel%':>9} {'harm%':>7} {'od':>3} {'harm':>5} both")
    print(hdr)
    print("-" * len(hdr))

    for path in sorted(glob.glob("/opt/vox/sandbox/benchmarks/ft_*.json")):
        tag = os.path.basename(path)[3:-5]
        d = json.load(open(path))
        best, ok = reselect(d["sweep"])
        d["best"] = best
        d["gates"] = report["gates"]
        n_pass = len(ok)
        # write the corrected selection back so the artifact matches the harness
        json.dump(d, open(path, "w"), indent=2)

        s = best
        report["arms"][tag] = {
            "params_m": d.get("params_m"), "cpu_p95_ms": d.get("cpu_latency", {}).get("p95_ms"),
            "best": {k: s.get(k) for k in ("threshold", "exact_match", "span_word",
                                           "over_deletion_rate", "harmful_span_rate",
                                           "passes_gate", "no_threshold_satisfies_gate")},
            "per_category": s.get("per_category"),
            "thresholds_passing_both": n_pass,
            "thresholds_passing_over_deletion_only":
                sum(1 for r in d["sweep"] if r["passes_over_deletion_gate"]),
            "thresholds_passing_harmful_only":
                sum(1 for r in d["sweep"] if r["passes_harmful_gate"]),
            "min_harmful_span_rate": min(r["harmful_span_rate"] for r in d["sweep"]),
            "min_over_deletion_rate": min(r["over_deletion_rate"] for r in d["sweep"]),
        }
        print(f"{tag:22} {s['threshold']:>5} {s['exact_match']:>7} "
              f"{s['span_word']['precision']:>6} {s['span_word']['recall']:>6} "
              f"{s['span_word']['f1']:>6} {s['over_deletion_rate']:>9} "
              f"{s['harmful_span_rate']:>7} "
              f"{'Y' if s['passes_over_deletion_gate'] else 'n':>3} "
              f"{'Y' if s['passes_harmful_gate'] else 'n':>5} "
              f"{'YES' if s['passes_gate'] else 'NO':>4}")

    print()
    any_pass = [t for t, v in report["arms"].items() if v["best"]["passes_gate"]]
    print(f"arms passing BOTH gates: {len(any_pass)}/{len(report['arms'])}"
          f"{' -> ' + ', '.join(any_pass) if any_pass else ''}")
    print("\nGap to target (best achievable per arm, i.e. most conservative threshold):")
    print(f"{'arm':22} {'min harmful%':>13} {'target':>7} {'gap':>7}   "
          f"{'min overdel%':>13} {'target':>7}")
    for tag, v in sorted(report["arms"].items(),
                         key=lambda kv: kv[1]["min_harmful_span_rate"]):
        mh, mo = v["min_harmful_span_rate"], v["min_over_deletion_rate"]
        print(f"{tag:22} {mh:>13} {HARMFUL_SPAN_GATE:>7} {round(mh - HARMFUL_SPAN_GATE, 3):>7}   "
              f"{mo:>13} {OVER_DELETION_GATE:>7}")
    json.dump(report, open(OUT, "w"), indent=2)
    print(f"\nwritten: {OUT}")


if __name__ == "__main__":
    main()