tirtho149's picture
Add retriever study (code, predictions, one-pager), refresh response cache
874eec2 verified
Raw History Blame Contribute Delete
11.7 kB
"""Retriever pilot (branch retriever-pilot, 2026-11-17): can a small neural scoring function replace BM25 in MACE?
Shreyan's idea: a small task-specific retrieval network whose weights are written by a bigger LLM. This pilot compares
retrievers on the exact P1 MACE setting (seed 0, K=4, the same per-query memory banks, 1,600 queries) WITHOUT any
diagnosis call. It measures retrieval only, with the proxies the paper already ties to MACE accuracy:
hit@4 true disease among the four retrieved entries (MACE gains only on hits; Q3)
vote majority label of the four retrieved entries (ties -> best-ranked), a no-VLM lookup accuracy
top1 label of the best-ranked entry
Retrievers, all scoring a (test caption, memory caption) pair from the same 16 pair features:
bm25 the paper's retriever (whole-caption BM25 with organ x3), must reproduce the recorded P1 retrieval
nn_linear logistic regression on the 16 features, trained on memory entries only (leave-one-out pseudo-queries)
nn_mlp 16-16-1 MLP, same training data
llm_schema linear weights written by Sonnet from the feature definitions, crop and disease list only
llm_memory linear weights written by Sonnet from the same, plus the crop's memory captions and labels
No query label or query image is used for training or for the LLM context. Results: out/results.json, out/table.md.
python -m experiments.retriever_pilot.pilot [--no-llm]
"""
from __future__ import annotations
import gzip
import json
import sys
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
from agmem import llm, packet
HERE = Path(__file__).resolve().parent
OUT = HERE / "out"; OUT.mkdir(exist_ok=True)
M10 = HERE.parents[1] / "mace10" / "out"
FIELDS = packet.FIELDS
FEATS = ["bm25_whole"] + [f"bm25_{f}" for f in FIELDS] + [f"jaccard_{f}" for f in FIELDS] + ["organ_match"]
FEAT_DOC = {
"bm25_whole": "BM25 of the whole test caption (organ counted 3 times) against the whole memory caption, scaled so the best memory entry is 1. This is the current MACE retriever.",
"organ_match": "1 if the two captions name the same organ (leaf, stem, pod, ...), else 0.",
**{f"bm25_{f}": f"BM25 of the test caption's '{f}' field against the memory caption's '{f}' field, scaled to max 1 within the memory." for f in FIELDS},
**{f"jaccard_{f}": f"Word-set overlap (Jaccard, 0 to 1) between the two captions' '{f}' fields." for f in FIELDS},
}
def load():
caps = json.loads((M10 / "captions.json").read_text())
jobs = [json.loads(l) for l in gzip.open(M10 / "jobs_all.jsonl.gz", "rt")]
P1 = [j for j in jobs if j["pkg"] == "P1" and j["condition"] == "mace"]
rec = {}
for l in open(M10 / "P1" / "predictions.jsonl"):
r = json.loads(l)
if r["condition"] == "mace":
rec[r["image_id"]] = [m[2:] for m in r["memory_ids"]]
return caps, P1, rec
def ftok(cap, f):
return packet.tok(cap.get(f, "") or "")
def features(qcap, mem_ids, caps):
"""16 pair features for one test caption against every entry of its memory bank (n x 16)."""
q = packet.tok(packet.caption_text(qcap)) + packet.tok(str(qcap.get("organ", ""))) * 3
whole = packet.bm25(q, {m: packet.tok(packet.caption_text(caps[m])) for m in mem_ids})
cols = [[whole[m] for m in mem_ids]]
for f in FIELDS:
s = packet.bm25(ftok(qcap, f), {m: ftok(caps[m], f) for m in mem_ids}) if ftok(qcap, f) else {m: 0.0 for m in mem_ids}
cols.append([s[m] for m in mem_ids])
for f in FIELDS:
a = set(ftok(qcap, f)); cols.append([len(a & set(ftok(caps[m], f))) / max(1, len(a | set(ftok(caps[m], f)))) for m in mem_ids])
cols.append([float(str(qcap.get("organ")) == str(caps[m].get("organ"))) for m in mem_ids])
return np.array(cols, dtype=float).T
def top4(scores, mem_ids, tiebreak=None):
"""Highest scores first; ties broken by memory id, as packet.build does."""
return [mem_ids[i] for i in sorted(range(len(mem_ids)), key=lambda i: (-scores[i], ("m_" + mem_ids[i])))][:4]
def metrics(ret_ids, labels, truth):
labs = [labels[m] for m in ret_ids]
c = Counter(labs); best = max(c.values()); vote = next(l for l in labs if c[l] == best)
return {"hit4": float(truth in labs), "vote": float(vote == truth), "top1": float(labs[0] == truth)}
def train_data(P1, caps):
"""Leave-one-out pseudo-queries over each unique memory bank: memory entries only, never a query."""
seen, X, y = set(), [], []
for j in P1:
ids = tuple(sorted(m["image_id"] for m in j["memory"]))
if ids in seen:
continue
seen.add(ids); lab = {m["image_id"]: m["label"] for m in j["memory"]}
for q in ids:
rest = [m for m in ids if m != q]
X.append(features(caps[q], rest, caps)); y += [int(lab[m] == lab[q]) for m in rest]
return np.vstack(X), np.array(y), len(seen)
LLM_SYS = ("You program the weights of a small linear scoring network for a retrieval system. Output only one JSON object: "
'{"weights": {<feature name>: <number between -3 and 3>, ...}, "rationale": "<at most 60 words>"}. '
"Use every feature name exactly once.")
def llm_prompt(crop, diseases, bank, caps, with_memory):
lines = [f"Task: a frozen vision-language model diagnoses {crop.lower()} diseases. Each reference image in memory is stored as a",
"label-free text caption plus its disease label. For a test image we caption it the same way, score every memory entry with",
"score = sum_i w_i * feature_i, and give the 4 highest-scoring entries (caption + label) to the diagnosis model.",
"Good weights rank entries of the test image's true disease highest; the label is unknown at test time.",
"", f"Possible diseases: {', '.join(diseases)}.", "", "Features (each computed between the test caption and one memory caption):"]
lines += [f"- {k}: {FEAT_DOC[k]}" for k in FEATS]
if with_memory:
lines += ["", f"The memory for this crop ({len(bank)} entries), as 'label | caption':"]
lines += [f"- {lab} | {packet.caption_text(caps[i])}" for i, lab in bank]
lines += ["", "Write the weights."]
return "\n".join(lines)
def last_json(text):
"""Last JSON object in the reply that has a 'weights' key (a reply may restate the object after a correction)."""
dec, found, i = json.JSONDecoder(), None, 0
while (i := text.find("{", i)) != -1:
try:
obj, end = dec.raw_decode(text, i)
if isinstance(obj, dict) and "weights" in obj:
found = obj
i = end
except ValueError:
i += 1
return found
def llm_weights(P1, caps, with_memory):
out = {}
for crop in sorted({j["crop"] for j in P1}):
J = [j for j in P1 if j["crop"] == crop]
bank = sorted({(m["image_id"], m["label"]) for m in J[0]["memory"]}, key=lambda x: (x[1], x[0]))
diseases = sorted({lab for _, lab in bank})
r = llm.call(LLM_SYS, [{"type": "text", "text": llm_prompt(crop, diseases, bank, caps, with_memory)}],
stage="retriever_pilot", tag=f"{'memory' if with_memory else 'schema'}|{crop}", reserve_usd=0.15)
p = last_json(r.get("text", "") or "") or {}
w = p.get("weights", {})
out[crop] = {"w": [float(w.get(k, 0.0)) for k in FEATS], "rationale": p.get("rationale"), "missing": [k for k in FEATS if k not in w],
"cost_usd": r.get("cost_usd"), "cache_hit": r.get("cache_hit")}
return out
def main(use_llm=True):
caps, P1, rec = load()
X, y, nb = train_data(P1, caps)
sc = StandardScaler().fit(X)
lin = LogisticRegression(max_iter=2000, class_weight="balanced").fit(sc.transform(X), y)
mlp = MLPClassifier(hidden_layer_sizes=(16,), max_iter=400, random_state=0, early_stopping=True).fit(sc.transform(X), y)
print(f"training pairs {len(y):,} from {nb} memory banks, positive rate {y.mean():.3f}")
LW = {}
if use_llm:
llm.set_budget(llm.spent() + 3.0)
LW = {"llm_schema": llm_weights(P1, caps, False), "llm_memory": llm_weights(P1, caps, True)}
(OUT / "llm_weights.json").write_text(json.dumps({k: {c: {**v, "features": FEATS} for c, v in d.items()} for k, d in LW.items()}, indent=1))
rows, same = [], 0
for j in P1:
mem_ids = [m["image_id"] for m in j["memory"]]; labels = {m["image_id"]: m["label"] for m in j["memory"]}
F = features(caps[j["image_id"]], mem_ids, caps); Z = sc.transform(F)
S = {"bm25": F[:, 0], "nn_linear": lin.decision_function(Z), "nn_mlp": mlp.predict_proba(Z)[:, 1]}
for k, d in LW.items():
S[k] = F @ np.array(d[j["crop"]]["w"])
ret = {k: top4(s, mem_ids) for k, s in S.items()}
same += ret["bm25"] == rec[j["image_id"]]
for k, r in ret.items():
rows.append({"retriever": k, "crop": j["crop"], "split": j["split"], "image_id": j["image_id"], **metrics(r, labels, j["label"])})
print(f"bm25 reproduces the recorded P1 retrieval on {same}/{len(P1)} queries")
agg = defaultdict(lambda: defaultdict(list))
for r in rows:
for m in ("hit4", "vote", "top1"):
agg[(r["retriever"], r["split"], m)][r["crop"]].append(r[m])
res = {f"{k[0]}|{k[1]}|{k[2]}": round(100 * float(np.mean([np.mean(v) for v in d.values()])), 1) for k, d in agg.items()}
# paired bootstrap of hit@4 difference vs bm25, equal-crop, over queries within crop
rng = np.random.default_rng(0); boot = {}
by = defaultdict(dict)
for r in rows:
by[(r["retriever"], r["split"], r["crop"])][r["image_id"]] = r["hit4"]
for name in {r["retriever"] for r in rows} - {"bm25"}:
for sp in ("iid", "ood"):
crops = sorted({c for (n, s, c) in by if n == "bm25" and s == sp}); ds = []
for _ in range(2000):
vals = []
for c in crops:
ids = list(by[("bm25", sp, c)]); pick = rng.integers(0, len(ids), len(ids))
vals.append(np.mean([by[(name, sp, c)][ids[i]] - by[("bm25", sp, c)][ids[i]] for i in pick]))
ds.append(100 * np.mean(vals))
boot[f"{name}|{sp}"] = [round(float(np.percentile(ds, 2.5)), 1), round(float(np.percentile(ds, 97.5)), 1)]
names = ["bm25", "nn_linear", "nn_mlp"] + list(LW)
md = ["| Retriever | hit@4 IID | hit@4 held-out | vote IID | vote held-out | top-1 IID | top-1 held-out | hit@4 vs BM25, IID [95% CI] | held-out |", "|---|" + "---:|" * 8]
for n in names:
ci = lambda sp: "" if n == "bm25" else f"{res[f'{n}|{sp}|hit4'] - res[f'bm25|{sp}|hit4']:+.1f} {boot[f'{n}|{sp}']}"
md.append(f"| {n} | " + " | ".join(f"{res[f'{n}|{sp}|{m}']:.1f}" for m in ("hit4", "vote", "top1") for sp in ("iid", "ood")).replace(" | ", " | ")
+ f" | {ci('iid')} | {ci('ood')} |")
# reorder columns: metric-major already: hit iid, hit ood, vote iid, vote ood, top1 iid, top1 ood
(OUT / "table.md").write_text("\n".join(md) + "\n")
coef = dict(zip(FEATS, np.round(lin.coef_[0], 3).tolist()))
(OUT / "results.json").write_text(json.dumps({"equal_crop_percent": res, "hit4_diff_ci": boot, "bm25_reproduces_P1": f"{same}/{len(P1)}",
"train_pairs": int(len(y)), "train_banks": nb, "nn_linear_coef_standardized": coef}, indent=1))
print("\n".join(md)); print("nn_linear coefficients (standardized):", coef)
if __name__ == "__main__":
main(use_llm="--no-llm" not in sys.argv)