beam-engram-tables / code /twopass.py
chadstthomas's picture
Engram code
3bc7886 verified
Raw History Blame Contribute Delete
9.65 kB
"""twopass.py {aa|sqa} ORDER OUT.jsonl [--limit 200] [--par 8] [--tables wiki] [--k 3] - two-pass engram answering (10-20).
The order of operations is the experiment:
A memory first: pass 1 = closed-book best guess + confidence (no abstaining) -> first-stage retrieval with q AND q + draft,
re-ranked against q alone -> pass 2 = AA answer prompt with the passages and the draft: take a passage's answer only if it
states the answer to this exact question, else keep a medium/high-confidence draft, else abstain.
C reconcile existing runs: the closed-book answer (runs/<ds>_base.jsonl) and the read-the-passages answer
(runs/<ds>_engram_v1.jsonl) as two drafts -> retrieval with q + both -> one pass-2 check. Costs one Beam pass.
Why: AA losses with plain injection were (a) near-misses copied from passages about a neighbouring fact and (b) abstentions on
facts the model knew, once off-target passages were shown (k=5: 11 correct -> abstained). Anchoring the model's own answer
before it reads, and letting the draft widen retrieval toward the right entity, targets both. The method is outside the
weights, so a recipe proven here runs unchanged on FP8 (--url).
Files: OUT.p1.jsonl (A drafts), OUT.ret.jsonl (pass-2 retrievals), OUT.jsonl (final; grade.py-compatible, tokens = both passes)."""
import argparse, csv, json, os, re, sys, threading, time, hashlib, urllib.request, concurrent.futures as cf
E = "/mnt/optane/engram"
ap = argparse.ArgumentParser(); ap.add_argument("ds"); ap.add_argument("order", choices=["A", "C"]); ap.add_argument("out")
ap.add_argument("--limit", type=int, default=200); ap.add_argument("--par", type=int, default=8); ap.add_argument("--k", type=int, default=3)
ap.add_argument("--tables", default="wiki"); ap.add_argument("--effort", default="minimal"); ap.add_argument("--max-tokens", type=int, default=4096)
ap.add_argument("--domains", default=""); ap.add_argument("--backend", default="local", choices=["local", "acp"])
ap.add_argument("--acp-model", default="opencode/beam-free"); ap.add_argument("--acp-effort", default="low");
ap.add_argument("--c-from", default="", help="order C drafts: BASE.jsonl,READ.jsonl (default runs/<ds>_base.jsonl,runs/<ds>_engram_v1.jsonl)"); 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."""
SYS_DRAFT = """You are answering questions about {domain}, and in particular {subtopic}.
Give your single best answer from memory, even if you are unsure - this is a draft that will be checked later.
Reply with exactly two lines:
Answer: <just the answer>
Confidence: <high, medium or low>"""
CHECK = """Reference passages (retrieved automatically; they may be incomplete or irrelevant):
{refs}
{drafts}
Check the earlier answer against the passages before you reply:
- If a passage states the answer to this exact question, answer with what the passage states.
- A passage about a related but different item, version, year, rule or case does not answer it; ignore such passages.
- If no passage states the answer, keep the earlier answer only if you still believe it is right; otherwise say you don't know.
Question: {q}"""
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"]}
for r in csv.DictReader(open(f"{E}/qa/simpleqa_verified.csv"))]
rr = sorted(items, key=lambda it: hashlib.sha1(f"{A.ds}:{it['id']}".encode()).hexdigest()) # same sample as engram_eval.py --limit
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]
items = rr[:A.limit]
if A.domains:
items = [it for it in items if it["domain"] in A.domains.split(",")]
lock = threading.Lock(); log = lambda *a: print(time.strftime("%H:%M:%S"), *a, flush=True)
load = lambda f: {d["id"]: d for d in map(json.loads, open(f))} if os.path.exists(f) else {}
def append(f, rec):
with lock:
with open(f, "a") as fh:
fh.write(json.dumps(rec) + "\n")
ACP_ = None
def chat(system, user):
if A.backend == "acp": # opencode ACP: system text at the top of the user turn; any tool use is reported as an error
r = ACP_.ask(system + "\n\n" + user, model=A.acp_model, effort=A.acp_effort)
err = r["err"] or (f"tool_calls={r['tool_calls']}" if r["tool_calls"] else None)
return r["text"], ("error" if r["err"] else r["stop"]), r["usage"].get("outputTokens", 0) + r["usage"].get("thoughtTokens", 0), err
body = {"model": "beam-1.0", "max_tokens": A.max_tokens, "temperature": 0.7, "top_p": 0.99, "chat_template_kwargs": {"reasoning_effort": A.effort},
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
try:
d = json.load(urllib.request.urlopen(urllib.request.Request(A.url, json.dumps(body).encode(), {"Content-Type": "application/json"}), timeout=7200))
c = d["choices"][0]
return (c["message"].get("content") or "").strip(), c.get("finish_reason"), d["usage"]["completion_tokens"], None
except Exception as e:
return "", "error", 0, str(e)[:300]
if A.backend == "acp":
sys.path.insert(0, f"{E}/tools"); from acp_client import ACP; ACP_ = ACP()
# ---- pass 1 (order A): closed-book drafts
drafts = {}
if A.order == "A":
p1f = A.out[:-6] + ".p1.jsonl"; P1 = load(p1f)
def draft(it):
t0 = time.time(); txt, fin, n, err = chat(SYS_DRAFT.format(domain=it["domain"], subtopic=it["sub"]), it["q"])
m = re.search(r"answer:\s*(.+)", txt, re.I); c = re.search(r"confidence:\s*(high|medium|low)", txt, re.I)
rec = {"id": it["id"], "draft": (m.group(1).strip() if m else txt.split("\n")[0].strip())[:300], "conf": c.group(1).lower() if c else "low",
"raw": txt[:500], "finish": fin, "tokens": n, "s": round(time.time() - t0, 1), "err": err}
append(p1f, rec); P1[it["id"]] = rec
todo = [it for it in items if it["id"] not in P1]; log(f"pass 1: {len(todo)} drafts to go")
with cf.ThreadPoolExecutor(A.par) as ex:
list(ex.map(draft, todo))
for it in items:
d = P1[it["id"]]; drafts[it["id"]] = {"tokens": d["tokens"], "list": [d["draft"]],
"text": f"Your earlier answer, from memory before seeing the passages: {d['draft']} (your confidence: {d['conf']})"}
else:
cb, cv = A.c_from.split(",") if A.c_from else (f"{E}/runs/{A.ds}_base.jsonl", f"{E}/runs/{A.ds}_engram_v1.jsonl")
B, V = load(cb), load(cv)
for it in items:
b, v = B[it["id"]]["answer"], V[it["id"]]["answer"]
drafts[it["id"]] = {"tokens": B[it["id"]]["tokens"] + V[it["id"]]["tokens"], "list": [b, v],
"text": f"Your earlier answers: from memory, before seeing any passages: {b or '(none)'}\n"
f"After reading an earlier set of passages: {v or '(none)'}"}
# ---- retrieval for pass 2: q + each draft widens the first stage; the re-rank is against q alone
retf = A.out[:-6] + ".ret.jsonl"; RET = {k: v["hits"] for k, v in load(retf).items()}
need = [it for it in items if it["id"] not in RET]
if need:
sys.path.insert(0, f"{E}/tools"); from engram import Engram
eg = Engram(tables=A.tables.split(",")); t0 = time.time()
for it in need:
extra = [f"{it['q']} {d}" for d in drafts[it["id"]]["list"] if d and len(d) < 200]
hits = [{k: h[k] for k in ("table", "pid", "title", "section", "text", "score")} for h in eg.retrieve(it["q"], k=10, extra=extra)]
RET[it["id"]] = hits; append(retf, {"id": it["id"], "hits": hits})
log(f"retrieved {len(need)} in {time.time() - t0:.0f} s")
_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)}
# ---- pass 2: check
done = load(A.out)
def check(it):
g = grams(it["q"]); hits = [h for h in RET[it["id"]] if not (g & grams(h["text"]))][:A.k] # 13-gram leak guard, as engram_eval
refs = "\n".join(f"[{i + 1}] {h['text']}" for i, h in enumerate(hits)); t0 = time.time()
ans, fin, n, err = chat(SYS.format(domain=it["domain"], subtopic=it["sub"]), CHECK.format(refs=refs, drafts=drafts[it["id"]]["text"], q=it["q"]))
rec = {"id": it["id"], "ds": A.ds, "arm": f"twopass{A.order}", "backend": A.backend if A.backend == "local" else A.acp_model + "@" + A.acp_effort, "effort": A.effort, "k": A.k, "tables": A.tables, "q": it["q"], "gold": it["gold"],
"domain": it["domain"], "draft": drafts[it["id"]]["list"], "answer": ans, "finish": fin, "tokens": n + drafts[it["id"]]["tokens"],
"tokens_p2": n, "s": round(time.time() - t0, 1), "err": err}
append(A.out, rec)
log(f"{it['id']} {n} tok | draft {str(drafts[it['id']]['list'])[:50]} -> {ans[:50]!r} | gold {it['gold'][:30]!r}")
todo = [it for it in items if it["id"] not in done]; log(f"pass 2: {len(todo)} to go (order {A.order})")
with cf.ThreadPoolExecutor(A.par) as ex:
list(ex.map(check, todo))