Datasets:
Formats:
parquet
Languages:
English
Size:
10K - 100K
Tags:
agriculture
plant-disease
crop-disease
vision-language-model
retrieval-augmented-generation
memory
License:
Download code/experiments/retriever_pilot/full.py from tirtho149/MACE-Bench: direct link, hf CLI and curl.
- Browser
- Download file 9.82 kB
-
https://huggingface.co/datasets/tirtho149/MACE-Bench/resolve/main/code/experiments/retriever_pilot/full.py
- Command line
-
hf download hf://datasets/tirtho149/MACE-Bench/code/experiments/retriever_pilot/full.py
-
curl -L -o full.py https://huggingface.co/datasets/tirtho149/MACE-Bench/resolve/main/code/experiments/retriever_pilot/full.py
9.82 kB
| """Full-scale, apples-to-apples run of text + image retrieval (user-approved 2026-11-17). | |
| Same 1,600 queries, seed 0, K=4 memory, KB, prompts and line format as the paper's MACE (P1 for Sonnet, E1_haiku for | |
| Haiku). Only the four listed memory entries change: BM25 (k1=2.0, b=0.3, no organ repeat) + 1.5 x min-max DINOv2 | |
| similarity, chosen on the validation set in tune.py before any test query was diagnosed. | |
| Arms | |
| sonnet text_image new calls (the 200 efficiency-panel calls from diag.py are reused from the cache) | |
| haiku text_image new calls | |
| haiku bm25_check must hit the cache of the recorded E1_haiku MACE calls (proves the identical prompt) | |
| Scoring follows mace10/results.py: equal-crop mean, paired 95% bootstrap within crop (2,000 resamples), Holm. | |
| python -m experiments.retriever_pilot.full run # model calls (resumable) | |
| python -m experiments.retriever_pilot.full analyze # tables only, no calls | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import sys | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| import numpy as np | |
| import pandas as pd | |
| from agmem import data, kb as KB, llm | |
| from mace10 import results as RES, run as RUN | |
| from . import pilot as P | |
| HAIKU = "claude-haiku-5-5" | |
| ROOT = P.HERE.parents[1] | |
| E1 = ROOT / "experiments/mace_extension/raw_results/E1_haiku/predictions.jsonl" | |
| PRED = P.OUT / "full_predictions.jsonl" | |
| def jobs_and_sel(): | |
| caps, P1, _ = P.load() | |
| sel = json.loads((P.OUT / "tune_retrieved.json").read_text()) | |
| out = {"text_image": sel["Tuned, no cap"], "bm25_check": sel["BM25 (paper)"]} | |
| pt = P.HERE / "plan" / "out" / "test_retrieved.json" | |
| if pt.exists(): | |
| T = json.loads(pt.read_text()); out["gen_A"] = T["gen_G3_p0|A"]; out["gen_B"] = T["gen_G3_p0|B"] | |
| li = P.OUT / "llm_image_retrieved.json" | |
| if li.exists(): | |
| out["llm_image"] = json.loads(li.read_text())["retrieved"] | |
| return caps, P1, out | |
| def run(arms=(("haiku", "bm25_check"), ("haiku", "text_image"), ("sonnet", "text_image")), pred=None, threads=6): | |
| pred = pred or PRED | |
| caps, P1, sel = jobs_and_sel() | |
| kbs = {c: (KB.build(c, data.classes(c)), data.classes(c)) for c in {j["crop"] for j in P1}} | |
| done = set() | |
| if pred.exists(): | |
| done = {(r["model"], r["arm"], r["image_id"]) for r in map(json.loads, pred.open())} | |
| llm.set_budget(llm.spent() + 30.0) | |
| def one(model, 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[arm][j["image_id"]]} | |
| with llm.use_model(None if model == "sonnet" else HAIKU): | |
| r = RUN.variant_diagnosis(j["crop"], classes, kbd, caps, jj) | |
| return {"model": model, "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 = [(m, a, j) for m, a in arms for j in P1 if (m, a, j["image_id"]) not in done] | |
| print(f"{len(todo)} jobs to run", flush=True) | |
| with ThreadPoolExecutor(threads) as ex, pred.open("a") as f: | |
| futs = [ex.submit(one, m, a, j) for m, a, j in todo] | |
| for k, fu in enumerate(as_completed(futs), 1): | |
| f.write(json.dumps(fu.result()) + "\n"); f.flush() | |
| if k % 200 == 0: | |
| print(f"{k}/{len(todo)} ledger {llm.spent():.2f}", flush=True) | |
| def analyze(): | |
| caps, P1, sel = jobs_and_sel() | |
| W = pd.read_csv(RES.OUT / "results_wide.csv"); W = W[W.hero].copy() | |
| R = pd.DataFrame(map(json.loads, PRED.open())).drop_duplicates(["model", "arm", "image_id"], keep="last") | |
| H = pd.DataFrame(map(json.loads, E1.open())) | |
| for c, col in (("sage", "h_sage"), ("mace", "h_mace"), ("labels", "h_labels")): | |
| W[col] = W.image_id.map(H[H.condition == c].set_index("image_id").correct).astype(float) | |
| W["ti"] = W.image_id.map(R[(R.model == "sonnet") & (R.arm == "text_image")].set_index("image_id").correct).astype(float) | |
| W["h_ti"] = W.image_id.map(R[(R.model == "haiku") & (R.arm == "text_image")].set_index("image_id").correct).astype(float) | |
| chk = R[(R.model == "haiku") & (R.arm == "bm25_check")].set_index("image_id") | |
| hchk = H[H.condition == "mace"].set_index("image_id") | |
| lab = {j["image_id"]: (j["label"], {m["image_id"]: m["label"] for m in j["memory"]}) for j in P1} | |
| W["hit_ti"] = [float(lab[q][0] in [lab[q][1][m] for m in sel["text_image"][q]]) for q in W.image_id] | |
| check = {"haiku_bm25_cache_hits": int(chk.cache_hit.sum()), "haiku_bm25_same_prediction": int((chk.prediction == hchk.reindex(chk.index).prediction).sum()), "n": int(len(chk)), | |
| "missing": {c: int(W[c].isna().sum()) for c in ("ti", "h_ti", "h_sage", "h_mace", "h_labels")}} | |
| print(check) | |
| rows = [("Sonnet 5.5", "SAGE", "sage"), ("Sonnet 5.5", "DINOv2 1-NN", "dino_s0"), ("Sonnet 5.5", "Labels only", "labels_all"), | |
| ("Sonnet 5.5", "MACE, BM25 (paper)", "mace"), ("Sonnet 5.5", "MACE, text + image retrieval", "ti"), | |
| ("Haiku 5.5", "SAGE", "h_sage"), ("Haiku 5.5", "Labels only", "h_labels"), ("Haiku 5.5", "MACE, BM25 (paper)", "h_mace"), ("Haiku 5.5", "MACE, text + image retrieval", "h_ti")] | |
| cols = [c for _, _, c in rows] | |
| out = {"check": check, "acc": {}, "contrasts": {}} | |
| for sp in ("iid", "ood"): | |
| d = W[W.split == sp]; bs = RES.fast_boot(d, cols) | |
| out["acc"][sp] = {c: {"acc": RES.eq_mean(d, c), "ci": RES.ci(bs[c]), "macro": RES.macro(d, c)} for c in cols} | |
| for name, a, b in (("sonnet_ti_minus_mace", "ti", "mace"), ("haiku_ti_minus_mace", "h_ti", "h_mace"), ("sonnet_ti_minus_dino", "ti", "dino_s0"), | |
| ("sonnet_ti_minus_sage", "ti", "sage"), ("haiku_ti_minus_sage", "h_ti", "h_sage")): | |
| v = bs[a] - bs[b]; est = RES.eq_mean(d, a) - RES.eq_mean(d, b) | |
| p = float(min(1.0, 2 * min((v <= 0).mean(), (v >= 0).mean()))) | |
| out["contrasts"][f"{name}|{sp}"] = {"est": est, "ci": RES.ci(v), "p_boot": max(p, 1 / len(v))} | |
| # hit / miss of each retriever, Sonnet | |
| for nm, hcol, mcol in (("bm25", "hit", "mace"), ("text_image", "hit_ti", "ti")): | |
| for h in (1.0, 0.0): | |
| g = d[d[hcol] == h] | |
| out.setdefault("hit_miss", {})[f"{nm}|{sp}|{'hit' if h else 'miss'}"] = {"n": int(len(g)), "share": float(100 * (d[hcol] == h).mean()), "mace": float(100 * g[mcol].mean()), "sage": float(100 * g.sage.mean())} | |
| fam = [k for k in out["contrasts"] if k.split("|")[0] in ("sonnet_ti_minus_mace", "haiku_ti_minus_mace")] | |
| adj = RES.holm([out["contrasts"][k]["p_boot"] for k in fam]) | |
| for k, a in zip(fam, adj): | |
| out["contrasts"][k]["p_holm"] = a | |
| per = W.groupby(["crop", "split"])[["sage", "mace", "ti", "h_mace", "h_ti"]].mean().mul(100).round(1).reset_index() | |
| out["per_crop"] = per.to_dict("records") | |
| (P.OUT / "full_results.json").write_text(json.dumps(out, indent=1, default=float)) | |
| A = out["acc"]; best = {sp: {m: max(A[sp][c]["acc"] for mm, _, c in rows if mm == m) for m in ("Sonnet 5.5", "Haiku 5.5")} for sp in A} | |
| f = lambda sp, c, m: (r"\cellcolor{bestgreen}" if abs(A[sp][c]["acc"] - best[sp][m]) < 1e-9 else "") + f"{A[sp][c]['acc']:.1f} {{\\scriptsize[{A[sp][c]['ci'][0]:.1f}, {A[sp][c]['ci'][1]:.1f}]}}" | |
| md = ["| Model | Method | IID | held-out |", "|---|---|---:|---:|"] | |
| tex = [r"\begin{tabular}{llcc}", r"\toprule", r"Model & Method & IID & Held-out \\", r"\midrule"] | |
| for i, (m, n, c) in enumerate(rows): | |
| md.append(f"| {m} | {n} | {A['iid'][c]['acc']:.1f} [{A['iid'][c]['ci'][0]:.1f}, {A['iid'][c]['ci'][1]:.1f}] | {A['ood'][c]['acc']:.1f} [{A['ood'][c]['ci'][0]:.1f}, {A['ood'][c]['ci'][1]:.1f}] |") | |
| tex.append(("\\midrule\n" if i == 5 else "") + f"{m if i in (0, 5) else ''} & {n} & {f('iid', c, m)} & {f('ood', c, m)} \\\\") | |
| tex += [r"\bottomrule", r"\end{tabular}"] | |
| C = out["contrasts"] | |
| md += ["", "| Contrast (points) | IID | held-out |", "|---|---:|---:|"] | |
| for k in ("sonnet_ti_minus_mace", "haiku_ti_minus_mace", "sonnet_ti_minus_dino", "sonnet_ti_minus_sage", "haiku_ti_minus_sage"): | |
| cell = lambda sp: f"{C[f'{k}|{sp}']['est']:+.1f} [{C[f'{k}|{sp}']['ci'][0]:+.1f}, {C[f'{k}|{sp}']['ci'][1]:+.1f}]" + (f", Holm p {C[f'{k}|{sp}']['p_holm']:.3f}" if "p_holm" in C[f"{k}|{sp}"] else "") | |
| md.append(f"| {k.replace('_', ' ')} | {cell('iid')} | {cell('ood')} |") | |
| HM = out["hit_miss"] | |
| md += ["", "| Sonnet, retriever | split | hit share | MACE on hits | SAGE on hits | MACE on misses | SAGE on misses |", "|---|---|---:|---:|---:|---:|---:|"] | |
| for nm in ("bm25", "text_image"): | |
| for sp in ("iid", "ood"): | |
| h, m = HM[f"{nm}|{sp}|hit"], HM[f"{nm}|{sp}|miss"] | |
| md.append(f"| {nm} | {sp} | {h['share']:.1f} | {h['mace']:.1f} | {h['sage']:.1f} | {m['mace']:.1f} | {m['sage']:.1f} |") | |
| md += ["", "| Crop | split | SAGE | MACE BM25 | MACE text+image | Haiku MACE BM25 | Haiku text+image |", "|---|---|---:|---:|---:|---:|---:|"] | |
| md += [f"| {r['crop']} | {r['split']} | {r['sage']} | {r['mace']} | {r['ti']} | {r['h_mace']} | {r['h_ti']} |" for r in out["per_crop"]] | |
| (P.OUT / "full_tables.md").write_text("\n".join(md) + "\n"); (P.OUT / "full_table_hero.tex").write_text("\n".join(tex) + "\n") | |
| print("\n".join(md)) | |
| if __name__ == "__main__": | |
| if sys.argv[1] == "run_gen": | |
| run(arms=(("haiku", "gen_A"), ("haiku", "gen_B"), ("sonnet", "gen_A"), ("sonnet", "gen_B")), pred=P.OUT / "full_predictions_gen.jsonl", threads=6) | |
| elif sys.argv[1] == "run_llm_image": | |
| run(arms=(("haiku", "llm_image"), ("sonnet", "llm_image")), pred=P.OUT / "full_predictions_llm_image.jsonl", threads=4) | |
| else: | |
| {"run": run, "analyze": analyze}[sys.argv[1]]() | |