Download code/engram_eval.py from tablinum/beam-engram-tables: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/tablinum/beam-engram-tables/resolve/main/code/engram_eval.py
- Command line
-
hf download hf://datasets/tablinum/beam-engram-tables/code/engram_eval.py
-
curl -L -o engram_eval.py https://huggingface.co/datasets/tablinum/beam-engram-tables/resolve/main/code/engram_eval.py
10.6 kB
| """engram_eval.py {aa|sqa} {base|engram} OUT.jsonl [--effort minimal] [--par 8] [--limit N] [--k 3] - paired knowledge eval of | |
| Beam with and without the engram (10-19). aa = AA-Omniscience-Public (600; Beam FP8 Omniscience Index 8.8 on its card), | |
| sqa = SimpleQA-verified (1000, Wikipedia-sourced). Same AA answer prompt for both (abstaining is allowed and scored 0). | |
| engram arm: top-k re-ranked passages injected into the user turn before the question (retrievals cached in | |
| qa/<ds>_retrieval.jsonl, shared by every run). Resumable; grade with grade.py. Items are identical across arms (paired).""" | |
| import argparse, csv, hashlib, json, os, re, sys, threading, time, urllib.request, concurrent.futures as cf | |
| E = "/mnt/optane/engram" | |
| ap = argparse.ArgumentParser(); ap.add_argument("ds"); ap.add_argument("arm"); ap.add_argument("out") | |
| ap.add_argument("--effort", default="minimal"); ap.add_argument("--par", type=int, default=8); ap.add_argument("--limit", type=int, default=0) | |
| ap.add_argument("--k", type=int, default=3); ap.add_argument("--retrieve-only", action="store_true"); ap.add_argument("--max-tokens", type=int, default=4096) | |
| ap.add_argument("--inject", default="v0", help="v0: plain reference block; v1: use a passage only if it states the answer (10-20 near-miss fix)") | |
| ap.add_argument("--domains", default="", help="comma list of domains to keep (after --limit sampling)") | |
| ap.add_argument("--no-scrub", action="store_true", help="keep passages sharing a 13-gram with the question (benchmark copies)") | |
| ap.add_argument("--tables", default="wiki", help="comma list, or 'auto' = route by domain (ROUTE) over the tables that exist") | |
| ap.add_argument("--route", default="auto", choices=["auto", "release"], help="auto = all verticals; release = Software+Law only, closed-book elsewhere") | |
| ap.add_argument("--split", default="all", choices=["all", "dev", "test"], help="all, the hash/round-robin dev 200, or the untouched test 400") | |
| ap.add_argument("--dry-run", action="store_true", help="print the selected split/route counts and exit") | |
| ap.add_argument("--backend", default="local", choices=["local", "acp"], help="acp: opencode ACP (FP8 Beam = opencode/beam-free), tools/acp_client.py") | |
| ap.add_argument("--acp-model", default="opencode/beam-free"); ap.add_argument("--acp-effort", default="low") | |
| ap.add_argument("--url", default="http://100.74.68.37:18360/v1/chat/completions"); A = ap.parse_args() | |
| SYS = """You are answering questions about {domain}, and in particular {subtopic}. | |
| You will be given a question, answer with JUST the answer (no explanation). | |
| If you do not know the answer, or you need more context or tools to answer the question, | |
| be clear about this - it is better that you say this than get the wrong answer.""" | |
| if A.ds == "aa": | |
| items = [{"id": r["question_id"], "q": r["question"], "gold": r["answer"], "domain": r["domain"], "sub": r["subtopic"]} | |
| for r in csv.DictReader(open(f"{E}/qa/AA-Omniscience_dataset_public.csv"))] | |
| else: | |
| items = [{"id": r["original_index"], "q": r["problem"], "gold": r["answer"], "domain": r["topic"], "sub": r["answer_type"], "urls": r["urls"]} | |
| for r in csv.DictReader(open(f"{E}/qa/simpleqa_verified.csv"))] | |
| def sample(src, n): | |
| """The fixed hash sample: AA round-robins its six domains, so dev is balanced.""" | |
| rr = sorted(src, key=lambda it: hashlib.sha1(f"{A.ds}:{it['id']}".encode()).hexdigest()) | |
| if A.ds == "aa": | |
| by = {} | |
| for it in rr: | |
| by.setdefault(it["domain"], []).append(it) | |
| rr = [it for grp in zip(*by.values()) for it in grp] | |
| return rr[:n] if n else rr | |
| DEV_N = 200 | |
| if A.split == "dev": | |
| items = sample(items, DEV_N) | |
| elif A.split == "test": | |
| dev_ids = {it["id"] for it in sample(items, DEV_N)} | |
| items = sorted((it for it in items if it["id"] not in dev_ids), | |
| key=lambda it: hashlib.sha1(f"{A.ds}:{it['id']}".encode()).hexdigest()) | |
| if A.limit: | |
| items = items[:A.limit] | |
| elif A.limit: # a fixed sample, the same items for every arm | |
| items = sample(items, A.limit) | |
| if A.domains: # after the split, so a domain subset is the same items as in the full run (paired) | |
| items = [it for it in items if it["domain"] in A.domains.split(",")] | |
| if A.dry_run: | |
| by = {} | |
| for it in items: by[it["domain"]] = by.get(it["domain"], 0) + 1 | |
| print(f"split={A.split} route={A.route} tables={A.tables} n={len(items)} domains={by}") | |
| print("first ids", [it["id"] for it in items[:5]], "last ids", [it["id"] for it in items[-5:]]) | |
| sys.exit(0) | |
| # oer is the shared open-textbook table for Finance, STEM and Humanities; health/law/software have dedicated tables. | |
| ROUTE_AUTO = {"Health": ["health", "wiki"], "Law": ["law", "wiki"], "Finance": ["oer", "wiki"], "Software Engineering": ["software", "wiki"], | |
| "Science Engineering and Mathematics": ["oer", "wiki"], "Humanities and Social Sciences": ["oer", "wiki"]} | |
| ROUTE_RELEASE = {"Health": [], "Law": ["law", "wiki"], "Finance": [], "Software Engineering": ["software", "wiki"], | |
| "Science Engineering and Mathematics": [], "Humanities and Social Sciences": []} | |
| ROUTE = ROUTE_RELEASE if A.route == "release" else ROUTE_AUTO | |
| HAVE = {"wiki"} | {t for t in os.listdir(f"{E}/tables") if os.path.exists(f"{E}/tables/{t}/index/engram.index")} if os.path.isdir(f"{E}/tables") else {"wiki"} | |
| _default = ["wiki"] if A.route == "auto" else [] | |
| tables_for = lambda it: [t for t in ROUTE.get(it["domain"], _default) if t in HAVE] if A.tables == "auto" else A.tables.split(",") | |
| RET = {} | |
| if A.arm == "engram": | |
| # include the resolved route in the cache key: a route edit must not silently reuse old retrievals | |
| route_sig = hashlib.sha1(json.dumps({d: [t for t in ts if t in HAVE] for d, ts in sorted(ROUTE.items())}).encode()).hexdigest()[:8] | |
| tag = "" if A.tables == "wiki" else "_" + (("release" if A.route == "release" else "auto") + "-" + "-".join(sorted(HAVE)) + "-" + route_sig if A.tables == "auto" else A.tables.replace(",", "-")) | |
| rf = f"{E}/qa/{A.ds}_retrieval{tag}.jsonl" | |
| if os.path.exists(rf): | |
| RET = {d["id"]: d["hits"] for d in map(json.loads, open(rf))} | |
| need = [it for it in items if it["id"] not in RET and tables_for(it)] | |
| if need: | |
| sys.path.insert(0, f"{E}/tools"); from engram import Engram | |
| eg = Engram(tables=sorted({t for it in need for t in tables_for(it)})); t0 = time.time() | |
| with open(rf, "a") as f: | |
| for it in need: | |
| hits = [{k: h[k] for k in ("table", "pid", "title", "section", "text", "score")} for h in eg.retrieve(it["q"], k=10, tables=tables_for(it))] | |
| RET[it["id"]] = hits; f.write(json.dumps({"id": it["id"], "hits": hits}) + "\n") | |
| print(f"retrieved {len(need)} in {time.time() - t0:.0f} s", flush=True) | |
| if A.retrieve_only: | |
| sys.exit(0) | |
| done = {d["id"] for d in map(json.loads, open(A.out))} if os.path.exists(A.out) else set() | |
| lock = threading.Lock() | |
| INJECT = { | |
| "v0": "Reference passages (retrieved automatically; they may be incomplete or irrelevant):\n{refs}\n\nQuestion: {q}", | |
| # v1 (10-20): AA's engram losses were near-misses copied from passages about a neighbouring fact (1958 vs 1959, rule -14 vs -15) | |
| "v1": "Reference passages (retrieved automatically; they may be incomplete or irrelevant):\n{refs}\n\n" | |
| "Use a passage only if it states the answer to this exact question. A passage about a related but different item, " | |
| "version, year, rule or case does not answer it: then rely on your own knowledge, or say you don't know.\n\nQuestion: {q}", | |
| } | |
| _w = lambda s: re.sub(r"[^a-z0-9 ]+", " ", s.lower()).split() | |
| grams = lambda s, n=13: {tuple(x[i:i + n]) for x in [_w(s)] for i in range(len(x) - n + 1)} | |
| def refs_for(it): # 10-20 leak guard: a passage that copies 13+ words of the question is a benchmark copy, not knowledge | |
| if not tables_for(it): | |
| return [] | |
| g = set() if A.no_scrub else grams(it["q"]) | |
| return [h for h in RET.get(it["id"], []) if not (g & grams(h["text"]))][:A.k] | |
| def ask(it): | |
| q = it["q"] | |
| if A.arm == "engram": | |
| refs = "\n".join(f"[{i + 1}] {h['text']}" for i, h in enumerate(refs_for(it))) | |
| if refs: # no table for this domain = exactly the closed-book prompt | |
| q = INJECT[A.inject].format(refs=refs, q=it["q"]) | |
| body = {"model": "beam-1.0", "max_tokens": A.max_tokens, "temperature": 0.7, "top_p": 0.99, | |
| "chat_template_kwargs": ({} if A.effort == "default" else {"reasoning_effort": A.effort}), | |
| "messages": [{"role": "system", "content": SYS.format(domain=it["domain"], subtopic=it["sub"])}, {"role": "user", "content": q}]} | |
| t0 = time.time(); tools_used = 0 | |
| if A.backend == "acp": # system prompt goes at the top of the user turn (ACP has no system slot) | |
| r = ACP_.ask(body["messages"][0]["content"] + "\n\n" + body["messages"][1]["content"], model=A.acp_model, effort=A.acp_effort) | |
| ans, fin, n, err, tools_used = r["text"], ("error" if r["err"] else r["stop"]), r["usage"].get("outputTokens", 0) + r["usage"].get("thoughtTokens", 0), r["err"], r["tool_calls"] | |
| else: | |
| try: | |
| d = json.load(urllib.request.urlopen(urllib.request.Request(A.url, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=7200)) | |
| m = d["choices"][0]["message"]; ans, fin, n, err = (m.get("content") or "").strip(), d["choices"][0].get("finish_reason"), d["usage"]["completion_tokens"], None | |
| except Exception as e: | |
| ans, fin, n, err = "", "error", 0, str(e)[:300] | |
| rec = {"id": it["id"], "ds": A.ds, "arm": A.arm, "effort": A.effort, "k": A.k, "inject": A.inject, "tables": A.tables if A.arm == "engram" else "", | |
| "route": A.route if A.arm == "engram" else "", "split": A.split, "q": it["q"], "gold": it["gold"], "domain": it["domain"], | |
| "answer": ans, "finish": fin, "tokens": n, "backend": A.backend if A.backend == "local" else A.acp_model + "@" + A.acp_effort, "tool_calls": tools_used, "s": round(time.time() - t0, 1), "err": err} | |
| with lock: | |
| with open(A.out, "a") as f: | |
| f.write(json.dumps(rec) + "\n") | |
| print(f"{time.strftime('%H:%M:%S')} {it['id']} {n} tok {rec['s']} s | {ans[:60]!r} | gold {it['gold'][:40]!r}", flush=True) | |
| if A.backend == "acp": | |
| sys.path.insert(0, f"{E}/tools"); from acp_client import ACP; ACP_ = ACP() | |
| todo = [it for it in items if it["id"] not in done] | |
| print(f"{A.ds}/{A.arm}: {len(items)} items, {len(done)} done, {len(todo)} to go, effort {A.effort}, par {A.par}", flush=True) | |
| with cf.ThreadPoolExecutor(A.par) as ex: | |
| list(ex.map(ask, todo)) | |