"""Small diagnosis check of the tuned retrievers (user-approved, 2026-11-17, about USD 7). The 200-query efficiency panel (5 crops x 20 IID + 20 held-out), seed 0, K=4, Sonnet. Everything in the request is the MACE request except which four memory entries are listed: same system prompt, classes, KB claims, line format ("[m_id] (label: X) "), in retrieval order. The BM25 arm goes through the same code path and must hit the cache of the recorded P1 MACE calls, which shows the path builds the identical prompt. python -m experiments.retriever_pilot.diag [--limit N] """ from __future__ import annotations import json import sys from collections import defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np from agmem import data, kb as KB, llm from mace10 import jobs as JB, run as RUN from . import pilot as P ARMS = {"bm25_check": "BM25 (paper)", "text_image": "Tuned, no cap", "one_per_disease": "Tuned (best on validation)"} def main(limit=None): caps, P1, _ = P.load() sel = json.loads((P.OUT / "tune_retrieved.json").read_text()) Q = JB.queries(); panel = set(Q[Q.efficiency].image_id) jobs = [j for j in P1 if j["image_id"] in panel][:limit] rec = {} for l in open(P.M10 / "P1" / "predictions.jsonl"): r = json.loads(l) if r["image_id"] in panel: rec[(r["condition"], r["image_id"])] = r llm.set_budget(llm.spent() + 9.0) kbs = {c: (KB.build(c, data.classes(c)), data.classes(c)) for c in {j["crop"] for j in jobs}} out_path = P.OUT / "diag_predictions.jsonl" done = {} if out_path.exists(): for l in out_path.open(): r = json.loads(l); done[(r["arm"], r["image_id"])] = r def one(arm, j): kbd, classes = kbs[j["crop"]] jj = {**RUN.with_shown_labels(j), "variant": "dino_mace", "condition": f"retr_{arm}", "job_id": f"RP|{arm}|s0|r{j['run']}|K4|{j['image_id']}", "retrieved_ids": sel[ARMS[arm]][j["image_id"]]} r = RUN.variant_diagnosis(j["crop"], classes, kbd, caps, jj) return {"arm": arm, **{k: r[k] for k in ("image_id", "crop", "split", "label", "prediction", "correct", "cost_usd", "cache_hit", "memory_ids", "memory_labels_shown")}} todo = [(a, j) for a in ARMS for j in jobs if (a, j["image_id"]) not in done] with ThreadPoolExecutor(6) as ex, out_path.open("a") as f: futs = [ex.submit(one, a, j) for a, j in todo] for k, fu in enumerate(as_completed(futs), 1): r = fu.result(); done[(r["arm"], r["image_id"])] = r; f.write(json.dumps(r) + "\n"); f.flush() if k % 50 == 0: print(f"{k}/{len(todo)} done, spent this run {llm.spent():.2f}", flush=True) # check: BM25 arm reproduces the recorded P1 MACE prompt (cache hit) and prediction chk = [done[("bm25_check", j["image_id"])] for j in jobs] print(f"BM25 arm: cache hits {sum(r['cache_hit'] for r in chk)}/{len(chk)}, same prediction as P1 MACE " f"{sum(r['prediction'] == rec[('mace', r['image_id'])]['prediction'] for r in chk)}/{len(chk)}") acc = defaultdict(dict) for j in jobs: q = j["image_id"] acc[q] = {"crop": j["crop"], "split": j["split"], "SAGE": rec[("sage", q)]["correct"], "MACE (BM25)": rec[("mace", q)]["correct"], "Text + image": done[("text_image", q)]["correct"], "One per disease": done[("one_per_disease", q)]["correct"]} methods = ["SAGE", "MACE (BM25)", "Text + image", "One per disease"] rng = np.random.default_rng(0); lines = ["| Method | IID | held-out | vs MACE (BM25), IID [95% CI] | held-out |", "|---|---:|---:|---:|---:|"] res = {} for m in methods: cells, cis = [], [] for sp in ("iid", "ood"): by = defaultdict(list) for q, r in acc.items(): if r["split"] == sp: by[r["crop"]].append((float(r[m]), float(r["MACE (BM25)"]))) a = 100 * np.mean([np.mean([x for x, _ in v]) for v in by.values()]); cells.append(a); res[f"{m}|{sp}"] = round(a, 1) if m != "MACE (BM25)": ds = [] for _ in range(4000): t = [] for v in by.values(): v = np.array(v); k = rng.integers(0, len(v), len(v)); t.append((v[k, 0] - v[k, 1]).mean()) ds.append(100 * np.mean(t)) d0 = a - 100 * np.mean([np.mean([y for _, y in v]) for v in by.values()]) cis.append(f"{d0:+.1f} [{np.percentile(ds, 2.5):+.1f}, {np.percentile(ds, 97.5):+.1f}]") else: cis.append("") lines.append(f"| {m} | {cells[0]:.1f} | {cells[1]:.1f} | {cis[0]} | {cis[1]} |") new_usd = sum((r["cost_usd"] or 0) for r in done.values() if not r["cache_hit"]) (P.OUT / "diag_table.md").write_text("\n".join(lines) + "\n") (P.OUT / "diag_results.json").write_text(json.dumps({"n_queries": len(jobs), "accuracy_equal_crop": res, "new_usd": round(new_usd, 2)}, indent=1)) print("\n".join(lines)); print(f"new spend USD {new_usd:.2f}") if __name__ == "__main__": main(int(sys.argv[sys.argv.index("--limit") + 1]) if "--limit" in sys.argv else None)