tablinum-2 / code /anchor_gate.py
chadstthomas's picture
Tablinum-2: the Lite-Beam engram, release 2 (card, code, recipes, 9 released tables)
901f964 verified
Raw History Blame Contribute Delete
3.88 kB
"""anchor_gate.py RETRIEVAL.jsonl BASE.graded.jsonl ENGRAM.graded.jsonl (10-28) - offline estimate of an entity-anchor injection gate
(research/health.md near-miss fix): inject retrieved passages only if they contain a rare anchor from the question (quoted strings,
acronyms, identifiers with digits / _ / . / ::, capitalised names that are not sentence-initial common words); otherwise answer
closed-book. Estimate: where the gate would inject, the outcome is the engram arm's graded answer; where it would block, the
closed-book arm's. (Exact only when every passage passes; a real run injects just the passing passages.) Prints per-domain index for
base / engram / gated under several gate strictnesses, so the rule can be picked before spending GPU time. Also importable: anchors(q)."""
import sys, re, json, collections
STOP = set("""a an the of in on at to for from by with and or but not is are was were be been what which who whom whose when where why how
this that these those it its as into than then there their they he she his her i we you your our under over between during after before
according first second third name give state list identify provide answer exact specific approximately using use based per""".split())
def anchors(q):
out = set()
out |= {m.strip() for m in re.findall(r"[\"“'‘`]([^\"”'’`]{3,80})[\"”'’`]", q)}
out |= set(re.findall(r"\b[A-Z][A-Z0-9]{1,}(?:[-/][A-Z0-9]+)*\b", q)) # acronyms, codes: ICML, HQLA, E0277
out |= set(re.findall(r"\b[\w]+(?:[_.:/§-][\w]+)+\b", q)) # json_encode, 2015/35, 10b-5, std::move
for m in re.finditer(r"(?:(?<=[^.?!]\s)|(?<=^))((?:[A-Z][a-z][\w'-]*)(?:\s+(?:of|de|von|van|der|la|the)?\s*[A-Z][\w'-]+)*)", q):
w = m.group(1).strip()
if m.start(1) == 0 and len(w.split()) == 1:
continue # sentence-initial single word
if w.lower() not in STOP and len(w) > 3:
out.add(w)
return {a for a in out if not re.fullmatch(r"\d{1,4}", a) and a.lower() not in STOP}
norm = lambda s: re.sub(r"\s+", " ", re.sub(r"[^\w§/.:-]+", " ", s.lower())).strip()
def passes(q, hit, need=1):
A = [norm(a) for a in anchors(q)]; t = " " + norm(hit["title"] + " " + hit["text"]) + " "
return sum(1 for a in A if a and a in t) >= min(need, len(A)) if A else False
if __name__ == "__main__":
R = {d["id"]: d["hits"] for d in map(json.loads, open(sys.argv[1]))}
L = lambda p: {d["id"]: d for d in map(json.loads, open(p))}
B, V = L(sys.argv[2]), L(sys.argv[3]); k = next(x for x in next(iter(B.values())) if "grade" in x.lower())
s = lambda g: {"CORRECT": 1, "INCORRECT": -1}.get(str(g).upper(), 0)
rules = {"any passage, 1 anchor": lambda q, h: any(passes(q, x, 1) for x in h[:3]),
"any passage, 2 anchors": lambda q, h: any(passes(q, x, 2) for x in h[:3]),
"top passage, 1 anchor": lambda q, h: bool(h) and passes(q, h[0], 1)}
for name, rule in rules.items():
D = collections.defaultdict(lambda: [0, 0, 0, 0, 0])
for i in B:
if i not in V:
continue
q = B[i]["q"]; inj = rule(q, R.get(i, [])); r = D[B[i]["domain"][:22]]
r[0] += 1; r[1] += s(B[i][k]); r[2] += s(V[i][k]); r[3] += s(V[i][k]) if inj else s(B[i][k]); r[4] += inj
print(f"== {name}")
tot = [0] * 5
for d, r in sorted(D.items()):
tot = [a + b for a, b in zip(tot, r)]
print(f" {d:22s} n={r[0]:3d} base {100 * r[1] / r[0]:6.1f} engram {100 * r[2] / r[0]:6.1f} gated {100 * r[3] / r[0]:6.1f} (injects {r[4]})")
print(f" {'all':22s} n={tot[0]:3d} base {100 * tot[1] / tot[0]:6.1f} engram {100 * tot[2] / tot[0]:6.1f} gated {100 * tot[3] / tot[0]:6.1f} (injects {tot[4]})")