Geoo/THX-01-bucket / bench /run_bench.py
Geoo's picture
download
raw
5.14 kB
"""Accuracy / calibration / latency benchmark for System One checkpoints (+ Router)."""
import argparse, json, sys, time
import numpy as np, torch
sys.path.insert(0, "./pkg"); sys.path.insert(0, "./bench")
import thx01 as systemone, tasks
from thx01.lang import analyse
from thx01.common import ece_score
ap = argparse.ArgumentParser()
ap.add_argument("--models", default="thx01=.")
ap.add_argument("--n", type=int, default=1000)
ap.add_argument("--out", default="results/bench.json")
ap.add_argument("--router", default="") # e.g. "en=english,other=multilingual,az=azerbaijani"
ap.add_argument("--latency", action="store_true")
ap.add_argument("--suite", default="v1")
a = ap.parse_args()
suite = tasks.eval_suite(a.n) if a.suite == "v1" else tasks.eval_suite_v2(a.n)
models = dict(kv.split("=") for kv in a.models.split(","))
res = {"tasks": {}, "latency": {}}
preds = {}
def score(triples, outs):
correct, conf, brier = [], [], []
for (st, q, gold), o in zip(triples, outs):
(qid, g), = gold.items()
ans = o["answers"][qid]
if ans["type"] == "score":
pr = ans["probabilities"]; top = max(pr, key=pr.get)
correct.append(int(top) == int(g)); conf.append(max(pr.values()))
brier.append(sum((v - (1.0 if int(k) == int(g) else 0.0)) ** 2 for k, v in pr.items()))
elif ans["type"] == "noul":
p1 = ans["noul"]; c = p1 >= 0.5
correct.append(c == g); conf.append(max(p1, 1 - p1)); brier.append((p1 - float(g)) ** 2)
else:
pr = ans["probabilities"]
correct.append(ans["choice"] == g); conf.append(max(pr.values()))
brier.append(sum((v - (1.0 if k == g else 0.0)) ** 2 for k, v in pr.items()))
c, f = np.array(correct, float), np.array(conf)
return {"acc": round(c.mean(), 4), "ece": round(ece_score(f, c), 4), "conf": round(f.mean(), 4),
"brier": round(float(np.mean(brier)), 4), "n": len(c)}, c
for name, path in models.items():
sub = None
if "/" in path and path.split("/", 1)[1] in ("multilingual", "typed-decisions"):
path, sub = path.split("/", 1)
ag = systemone.load(path, subfolder=sub, device="cuda")
preds[name] = {}
for t, triples in suite.items():
t0 = time.perf_counter()
outs = ag.predict_batch([x[0] for x in triples], [x[1] for x in triples], batch_size=64)
m, c = score(triples, outs)
m["sec"] = round(time.perf_counter() - t0, 2)
res["tasks"].setdefault(t, {})[name] = m
preds[name][t] = c
print(f"{name:14s} {t:28s} {m}", flush=True)
if a.latency:
st = {"body": "Hi, we were billed twice for March. Please refund the duplicate today or we will cancel our plan."}
base = tasks.triage_like = {
"department": {"type": "choice", "instructions": "Which department?", "criteria": {"billing": "", "technical": "", "sales": "", "other": ""}},
"urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["low", "medium", "high"]},
"churn": {"type": "noul", "instructions": "Does the user threaten to cancel?"},
"refund": {"type": "noul", "instructions": "Does the user request a refund?"},
"sentiment": {"type": "choice", "instructions": "Sentiment?", "criteria": ["positive", "neutral", "negative"]}}
for nq in (1, 5, 10, 50):
qs = {f"{k}_{i}": v for i in range(10) for k, v in base.items()}
qs = dict(list(qs.items())[:nq])
for _ in range(5): ag.predict(st, qs)
ts = []
for _ in range(40):
torch.cuda.synchronize(); t0 = time.perf_counter(); ag.predict(st, qs); torch.cuda.synchronize()
ts.append((time.perf_counter() - t0) * 1000)
res["latency"].setdefault(name, {})[nq] = {"p50_ms": round(float(np.percentile(ts, 50)), 2),
"p95_ms": round(float(np.percentile(ts, 95)), 2)}
# detection overhead
t0 = time.perf_counter()
for _ in range(2000): analyse(st)
res["latency"]["router_detection_us"] = round((time.perf_counter() - t0) / 2000 * 1e6, 1)
res["latency"][name]["vram_gb"] = round(torch.cuda.max_memory_allocated() / 1e9, 2)
print(name, res["latency"][name], flush=True)
del ag; torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
if a.router:
route_stats = {}
from systemone import Router
R = Router(models={k: (models[k].split("/")[0], models[k].split("/")[1]) if "/" in models[k] and models[k].split("/",1)[1] in ("multilingual",) else models[k] for k in models})
for t, triples in suite.items():
picks = [R.route(st, q)["model"] for st, q, g in triples]
c = np.array([preds[p][t][i] for i, p in enumerate(picks)])
res["tasks"][t]["router"] = {"acc": round(c.mean(), 4), "n": len(c)}
route_stats[t] = {m: picks.count(m) for m in set(picks)}
print(f"{'router':14s} {t:28s} acc={c.mean():.4f} routes={route_stats[t]}")
res["routing"] = route_stats
json.dump(res, open(a.out, "w"), indent=1)

Xet Storage Details

Size:
5.14 kB
·
Xet hash:
8be05a28d28fe459cd6d315221aa3203e0cf5af6a9663bdbb994895d90239673

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.