Geoo/THX-01-bucket / bench /v10_eval.py
Geoo's picture
download
raw
9.41 kB
"""Michael's tasks, run with the SAME service-layer logic on any typed-decision backend.
python bench/v10_eval.py thx http://localhost:8094 (THX-01 over its /v1/systemone/batch endpoint)
python bench/v10_eval.py jev (TypeSafe Jev over OpenRouter /api/alpha/decisions)
Tasks: number_native, number_ranges (Michael), excerpt_native, excerpt_chunks (Michael), cite. Results -> results/v10/<name>.json
"""
import asyncio, json, os, re, sys, time
import httpx
ROOT_DIR = os.environ.get("THX01_ROOT", os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.join(ROOT_DIR, "train"))
sys.path.append(os.path.join(ROOT_DIR, "gen"))
from thx01 import number as N, excerpt as X # noqa: E402
from build_v10 import load, range_crit, chunk_crit, unit_of, same # noqa: E402
ROOT = ROOT_DIR
NAME = sys.argv[1]
KEY = {l.split("=", 1)[0]: l.split("=", 1)[1].strip() for l in open(f"{ROOT}/.env") if "=" in l}
# ---------------- backends: list of (state, questions) -> list of answers dicts ----------------
def thx_backend(base):
c = httpx.Client(timeout=600)
def ask(items):
out = []
for i in range(0, len(items), 64):
r = c.post(base + "/v1/systemone/batch", headers={"Authorization": "Bearer " + KEY["THX01_API_KEY"]},
json={"items": [{"state": s, "questions": q} for s, q in items[i:i + 64]]}).json()
out += [x["answers"] for x in r["results"]]
return out
return ask
def or_backend(model):
from llm import Client
def ask(items):
async def run():
C = Client(conc_or=12)
res = await asyncio.gather(*(C.decide(model, s, q, tag=f"v10_{NAME}") for s, q in items))
return [a for a, _ in res]
out = asyncio.run(run())
return [a if a else {k: None for k in q} for a, (_, q) in zip(out, items)]
return ask
ASK = thx_backend(sys.argv[2]) if NAME.startswith("thx") else or_backend({"jev": "~typesafe/jev-latest", "kev": "jaredpalmer/kev-4b"}[NAME])
def choice(a, k="q"):
x = (a or {}).get(k)
return (x or {}).get("choice") if isinstance(x, dict) else None
# ---------------- data ----------------
NUMS = [json.loads(l) for l in open(f"{ROOT}/data/numbers/numbers.jsonl")] + load("numhard", "test")
NUMS = [r for r in NUMS if r["answer"] is None or r["answer"] >= 0]
EXS = load("excerpt", "test")
def f1(a, b):
ta, tb = re.findall(r"\w+", (a or "").lower()), re.findall(r"\w+", (b or "").lower())
if not ta or not tb:
return float(ta == tb)
common = sum(min(ta.count(w), tb.count(w)) for w in set(ta))
if not common:
return 0.0
p, r = common / len(ta), common / len(tb)
return 2 * p * r / (p + r)
# ---------------- tasks ----------------
def number_native():
items, metas = [], []
for r in NUMS:
q, opts, _ = N.to_choice(r["document"], {"instructions": r["question"], "criteria": {"min": -1e15, "max": 1e15}})
items.append((r["document"], {"q": q})); metas.append(opts)
ans = ASK(items); ok = []
for r, a, opts in zip(NUMS, ans, metas):
c = choice(a)
v = None if c in (None, N.NOT_STATED) else opts[int(c[1:])][0]
ok.append((v is None and r["answer"] is None) or (v is not None and r["answer"] is not None and same(v, r["answer"])))
return sum(ok) / len(ok), len(ok)
def number_ranges(nb=255):
rows = [r for r in NUMS if r["answer"] is not None]
lo = [0.0] * len(rows); hi = [float(2 ** 32) if r["answer"] <= 2 ** 32 else 1e13 for r in rows]
alive = [True] * len(rows)
prec = [1.0 if abs(r["answer"] - round(r["answer"])) < 1e-9 else 0.01 for r in rows] # Michael's `precision`
for level in range(10):
idx = [i for i in range(len(rows)) if alive[i] and hi[i] - lo[i] > prec[i]]
if not idx:
break
built = [range_crit(lo[i], hi[i], nb) for i in idx]
ans = ASK([(rows[i]["document"], {"q": {"type": "choice", "instructions": rows[i]["question"], "criteria": c}}) for i, (c, _) in zip(idx, built)])
for i, (c, edges), a in zip(idx, built, ans):
ch = choice(a)
if ch not in c:
alive[i] = False; continue
k = list(c).index(ch)
lo[i], hi[i] = edges[k], edges[k + 1]
if not (lo[i] <= rows[i]["answer"] <= hi[i]):
alive[i] = False
ok = [alive[i] and abs(round(lo[i] / prec[i]) * prec[i] - rows[i]["answer"]) <= max(prec[i], 1e-6 * rows[i]["answer"]) for i in range(len(rows))]
return sum(ok) / len(ok), len(ok)
def excerpt_native():
def predict(states, qs):
return ASK(list(zip(states, qs)))
# batch the two rounds across all documents
S = [X.units(r["document"]) for r in EXS]
r1 = ASK([(r["document"], {"u": X.unit_question(r["document"], sp, r["question"], w)}) for r, sp in zip(EXS, S) for w in ("start", "end")])
second, picks = [], []
for j, (r, sp) in enumerate(zip(EXS, S)):
cs, ce = choice(r1[2 * j], "u"), choice(r1[2 * j + 1], "u")
us = int(cs[1:]) if cs else 0; ue = int(ce[1:]) if ce else us
ue = max(ue, us)
ws, we = X.words(r["document"], sp[us]), X.words(r["document"], sp[ue])
picks.append((us, ue, ws, we))
second += [(r["document"], {"w": X.word_question(r["document"], ws, r["question"], "start")}),
(r["document"], {"w": X.word_question(r["document"], we, r["question"], "end")})]
r2 = ASK(second)
em, f = [], []
for j, (r, (us, ue, ws, we)) in enumerate(zip(EXS, picks)):
a, b = choice(r2[2 * j], "w"), choice(r2[2 * j + 1], "w")
i = int(a[1:]) if a else 0; k = int(b[1:]) if b else len(we) - 1
s, e = ws[i][0], we[k][1]
if us == ue and e <= s:
s, e = S[j][us]
s, e = X._trim(r["document"], s, e)
pred = r["document"][s:e]
gold = r["answer"].strip().strip(".,;:")
em.append(pred.strip().strip(".,;:") == gold); f.append(f1(pred, gold))
return sum(f) / len(f), len(f), sum(em) / len(em)
def excerpt_chunks(nb=255):
"""Michael: iteratively narrow the beginning, then the end, with 255-part choices, down to one word."""
res = {}
for which, key in (("beginning", "start"), ("end", "end")):
lo = [0] * len(EXS); hi = [len(r["document"]) for r in EXS]; done = [False] * len(EXS)
for level in range(6):
idx = [j for j in range(len(EXS)) if not done[j]]
if not idx:
break
built = {j: chunk_crit(EXS[j]["document"], lo[j], hi[j], nb) for j in idx}
idx = [j for j in idx if len(built[j]) >= 2] + [j for j in idx if len(built[j]) < 2 and not done.__setitem__(j, True)]
idx = [j for j in idx if not done[j]]
ans = ASK([(EXS[j]["document"], {"q": {"type": "choice", "instructions": f"Find the choice that contains the {which} of the exact text that answers: {EXS[j]['question']}",
"criteria": {f"part_{i}": EXS[j]["document"][a:b] for i, (a, b) in enumerate(built[j])}}}) for j in idx])
for j, a in zip(idx, ans):
c = choice(a)
k = int(c.split("_")[1]) if c and c.startswith("part_") else 0
lo[j], hi[j] = built[j][k]
if len(re.findall(r"\S+", EXS[j]["document"][lo[j]:hi[j]])) <= 1:
done[j] = True
res[key] = (lo, hi)
f, em = [], []
for j, r in enumerate(EXS):
s, e = res["start"][0][j], res["end"][1][j]
if e <= s:
e = res["start"][1][j]
s, e = X._trim(r["document"], s, e)
pred = r["document"][s:e]; gold = r["answer"].strip().strip(".,;:")
f.append(f1(pred, gold)); em.append(pred.strip().strip(".,;:") == gold)
return sum(f) / len(f), len(f), sum(em) / len(em)
def cite():
rows = EXS[:150]
items, meta = [], []
for r in rows:
sp = X.units(r["document"])
pos = {i for i, (a, b) in enumerate(sp) if a < r["end"] and r["start"] < b}
meta.append((len(items), len(sp), pos))
items += [(r["document"], {"c": X.cite_question(r["document"], s, r["question"])}) for s in sp]
ans = ASK(items); ok = []
for start, n, pos in meta:
ps = [((ans[start + i] or {}).get("c") or {}).get("noul") or 0.0 for i in range(n)]
ok.append(max(range(n), key=ps.__getitem__) in pos)
return sum(ok) / len(ok), len(ok)
if __name__ == "__main__":
os.makedirs(f"{ROOT}/results/v10", exist_ok=True)
out = {}
only = sys.argv[3].split(",") if len(sys.argv) > 3 else None
prev = json.load(open(f"{ROOT}/results/v10/{NAME}.json")) if only and os.path.exists(f"{ROOT}/results/v10/{NAME}.json") else {}
out.update(prev)
for name, fn in [("number_native", number_native), ("number_ranges", number_ranges), ("excerpt_native", excerpt_native),
("excerpt_chunks", excerpt_chunks), ("cite", cite)]:
if only and name not in only:
continue
t0 = time.time(); r = fn()
out[name] = {"score": round(r[0], 4), "n": r[1], "seconds": round(time.time() - t0, 1)}
if len(r) > 2:
out[name]["exact_match"] = round(r[2], 4)
print(name, out[name], flush=True)
json.dump(out, open(f"{ROOT}/results/v10/{NAME}.json", "w"), indent=1)

Xet Storage Details

Size:
9.41 kB
·
Xet hash:
52d5dd9ac13a22672f1e1eda8f6b3a4cbdbbaa44d18b3df2903616cae3c4d286

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