File size: 5,129 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/usr/bin/env python3
"""Bakeoff orchestrator: train + eval every BIO arm with identical settings.

One arm = one subprocess = one variable. Arms never share state. Any arm that
crashes is recorded as failed and the run continues, so one bad candidate
cannot abort the bakeoff.

Usage: run_bakeoff.py [--only tag1,tag2] [--skip-eval]
"""

import argparse
import json
import os
import subprocess
import sys
import time

SCRIPTS = "/opt/vox/sandbox/scripts"
PY = "/opt/vox/venv/bin/python"
CKPT = "/opt/vox/temp/ckpt"
BENCH = "/opt/vox/sandbox/benchmarks"

# Accuracy-first ordering. ONNX/casing/latency are NOT selection filters.
ARMS = [
    ("distilbert-cased", "distilbert/distilbert-base-cased"),
    ("bert-base-cased", "google-bert/bert-base-cased"),
    ("roberta-base", "FacebookAI/roberta-base"),
    ("deberta-v3-base", "microsoft/deberta-v3-base"),
    ("modernbert-base", "answerdotai/ModernBERT-base"),
    ("electra-base-disc", "google/electra-base-discriminator"),
]

COMMON = "--seed 42 --epochs 8 --batch-size 16 --lr-encoder 3e-5 --lr-head 1e-3 --max-len 128"


def sh(cmd, log):
    with open(log, "a") as f:
        f.write(f"\n$ {' '.join(cmd)}\n")
        f.flush()
        p = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT)
    return p.returncode


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--only", default="")
    ap.add_argument("--skip-eval", action="store_true")
    args = ap.parse_args()

    only = {x for x in args.only.split(",") if x}
    arms = [a for a in ARMS if not only or a[0] in only]
    os.makedirs(CKPT, exist_ok=True)
    os.makedirs(BENCH, exist_ok=True)
    os.makedirs("/opt/vox/temp/logs", exist_ok=True)

    summary = []
    for tag, hf in arms:
        out_dir = os.path.join(CKPT, tag)
        log = f"/opt/vox/temp/logs/arm_{tag}.log"
        t0 = time.time()
        print(f"=== {tag} ({hf})", flush=True)

        if not os.path.exists(os.path.join(out_dir, "train_meta.json")):
            rc = sh([PY, "-u", f"{SCRIPTS}/train_span.py", "--model", hf,
                     "--out", out_dir] + COMMON.split(), log)
            if rc != 0:
                print(f"    TRAIN FAILED rc={rc} -> see {log}", flush=True)
                summary.append({"tag": tag, "model": hf, "status": "train_failed"})
                continue
        else:
            print("    checkpoint exists, skipping train", flush=True)

        meta = json.load(open(os.path.join(out_dir, "train_meta.json")))
        print(f"    trained {meta['n_train']} ex, {meta['params_m']}M, "
              f"loss {meta['train_log'][0]['train_loss']}->{meta['train_log'][-1]['train_loss']}, "
              f"{meta['wall_s']}s", flush=True)

        if args.skip_eval:
            continue

        ej = os.path.join(BENCH, f"ft_{tag}.json")
        rc = sh([PY, "-u", f"{SCRIPTS}/eval_span.py", "--model", out_dir, "--tag", f"ft_{tag}",
                 "--out", ej, "--cpu-latency", "--export-onnx", "--onnx-int8"], log)
        if rc != 0 or not os.path.exists(ej):
            print(f"    EVAL FAILED rc={rc} -> see {log}", flush=True)
            summary.append({"tag": tag, "model": hf, "status": "eval_failed"})
            continue

        r = json.load(open(ej))
        b = r["best"]
        summary.append({
            "tag": tag, "model": hf, "params_m": r["params_m"],
            "exact_match": b["exact_match"], "span_word_f1": b["span_word"]["f1"],
            "precision": b["span_word"]["precision"], "recall": b["span_word"]["recall"],
            "over_deletion_rate": b["over_deletion_rate"],
            "harmful_span_rate": b["harmful_span_rate"],
            "thr": b["threshold"], "passes_gate": b["passes_gate"],
            "clean_exact_match": b["per_category"].get("CLEAN", {}).get("exact_match"),
            "dis_exact_match": b["per_category"].get("DISFLUENCY", {}).get("exact_match"),
            "cpu_p95_ms": r.get("cpu_latency", {}).get("p95_ms"),
            "onnx_parity_rate": r.get("onnx", {}).get("parity_rate"),
            "int8_compression": r.get("onnx", {}).get("int8_compression"),
        })
        print(f"    EM={b['exact_match']} f1={b['span_word']['f1']} "
              f"overdel={b['over_deletion_rate']}% harmful={b['harmful_span_rate']}% "
              f"gate={b['passes_gate']} cpu_p95={r.get('cpu_latency',{}).get('p95_ms')}ms "
              f"parity={r.get('onnx',{}).get('parity_rate')}%", flush=True)

    with open("/opt/vox/temp/logs/bakeoff_summary.json", "w") as f:
        json.dump(summary, f, indent=2)
    print("\n=== BAKEOFF SUMMARY ===", flush=True)
    for s in sorted([x for x in summary if "exact_match" in x],
                    key=lambda x: -x["exact_match"]):
        print(f"  {s['tag']:20} EM={s['exact_match']:6} f1={s['span_word_f1']:.3f} "
              f"P={s['precision']:.3f} R={s['recall']:.3f} overdel={s['over_deletion_rate']}% "
              f"harm={s['harmful_span_rate']}% gate={s['passes_gate']} "
              f"cpu_p95={s['cpu_p95_ms']}ms", flush=True)
    print("artifacts: /opt/vox/sandbox/benchmarks/ft_<tag>.json", flush=True)


if __name__ == "__main__":
    main()