"""MACE neural-retrieval baseline, following the experimental plan of 2026-11-17 (plan/README.md). Retrieval stage only: no diagnosis call. Generator calls (12 short Sonnet calls) are the only paid step. Frozen pipeline: P1 MACE, seed 0, K=4 memory per disease, the same per-query memory (eligible references), k = 4 references to the VLM, the same line format. BM25 is the paper's (whole caption, organ repeated 3 times, k1 1.2, b 0.75) and reproduces the recorded P1 retrieval on 1,600/1,600 queries. Development split: training-fold images in the seed-0 K=16 memory but not in the K=4 memory, never test queries, scored against the K=4 memory of the same crop and fold (2,215 queries). Test queries, captions, labels and retrievals are not used for weight generation, fitting or selection. Experiment A: every method reorders the same BM25 top 20. Experiment B: every method scores the whole memory. Features x(q, r), computed from caption text only (no labels, collections or filenames), standardized with dev statistics: idf_cov IDF-weighted share of the query's terms that appear in the reference (IDF over the memory) overlap token-set Jaccard trigram character-trigram Jaccard emb_cos cosine of frozen bge-small-en-v1.5 embeddings of the caption text len_ratio log(query tokens / reference tokens) Scorer: 5 -> 4 -> 1 ReLU MLP (29 parameters). BM25 score and rank are not inputs. Methods: bm25, cosine, rrf (BM25 + cosine, k=60), sup_linear, sup_mlp_matched (same 16 triplets as G2/G3), sup_mlp_full (all dev pairs), gen_G0..G3 x 3 example packs. Relevance: same crop and disease label (label-based). python -m experiments.retriever_pilot.plan.run_plan """ from __future__ import annotations import json import math from collections import Counter, defaultdict from pathlib import Path import numpy as np from agmem import llm, packet from .. import pilot as P, tune as T HERE = Path(__file__).resolve().parent OUT = HERE / "out"; OUT.mkdir(exist_ok=True) FEATS = ["idf_cov", "overlap", "trigram", "emb_cos", "len_ratio"] K, POOL_A = 4, 20 GEN_MODEL_NOTE = "sonnet (claude-sonnet-5-5), temperature default, one call per condition and pack" # ---------------------------------------------------------------- data def load(): caps, P1, _ = P.load() d = np.load(P.M10 / "dinov2_embeddings.npz"); Ei = d["E"].astype(np.float32); Ei /= np.linalg.norm(Ei, axis=1, keepdims=True) idx_i = {k: i for i, k in enumerate(d["ids"])} dev, test = T.items(P1, caps, Ei, idx_i) # same dev set as tune.py (needs DINOv2 only for membership) t = np.load(HERE / "text_emb.npz"); Et = t["E"]; idx_t = {k: i for i, k in enumerate(t["ids"])} return caps, dev, test, Et, idx_t def bm25_paper(qcap, mids, caps): q = packet.tok(packet.caption_text(qcap)) + packet.tok(str(qcap.get("organ", ""))) * 3 s = packet.bm25(q, {m: packet.tok(packet.caption_text(caps[m])) for m in mids}) return np.array([s[m] for m in mids]) def trigrams(s): s = " " + re.sub(r"\s+", " ", s.lower()) + " " return {s[i:i + 3] for i in range(len(s) - 2)} import re # noqa: E402 def featurize(its, caps, Et, idx_t): """Per item: BM25 scores, raw features (n x 5), ordering keys.""" out = [] for c, sp, q, lab, mids, mlabs in its: qt = packet.tok(packet.caption_text(caps[q])); docs = [packet.tok(packet.caption_text(caps[m])) for m in mids] N = len(docs); df = Counter(t for d in docs for t in set(d)); idf = {t: math.log(1 + (N - df[t] + 0.5) / (df[t] + 0.5)) for t in df} qs = set(qt); qidf = sum(idf.get(t, math.log(1 + (N + 0.5) / 0.5)) for t in qs) or 1.0 qtri = trigrams(packet.caption_text(caps[q])); qe = Et[idx_t[q]] X = np.zeros((N, 5)) for i, (m, d) in enumerate(zip(mids, docs)): ds = set(d); rtri = trigrams(packet.caption_text(caps[m])) X[i] = [sum(idf[t] for t in qs & ds) / qidf, len(qs & ds) / max(1, len(qs | ds)), len(qtri & rtri) / max(1, len(qtri | rtri)), float(Et[idx_t[m]] @ qe), math.log(max(1, len(qt)) / max(1, len(d)))] out.append({"bm25": bm25_paper(caps[q], mids, caps), "X": X, "keys": ["m_" + m for m in mids]}) return out def order(score, keys): return sorted(range(len(keys)), key=lambda i: (-score[i], keys[i])) # ---------------------------------------------------------------- scorers def mlp_init(rng): return {"W1": rng.normal(0, 0.5, (4, 5)), "b1": np.zeros(4), "w2": rng.normal(0, 0.5, 4), "b2": np.zeros(1)} def mlp_score(p, Z): return np.maximum(0, Z @ p["W1"].T + p["b1"]) @ p["w2"] + p["b2"][0] def fit_pairwise(Zp, Zn, kind="mlp", seed=0, epochs=400, lr=0.03, l2=1e-3): """RankNet-style pairwise logistic loss on (positive, negative) feature rows; numpy Adam.""" rng = np.random.default_rng(seed) p = mlp_init(rng) if kind == "mlp" else {"w": np.zeros(5)} m = {k: np.zeros_like(v) for k, v in p.items()}; v = {k: np.zeros_like(x) for k, x in p.items()} for ep in range(1, epochs + 1): if kind == "mlp": hp, hn = Zp @ p["W1"].T + p["b1"], Zn @ p["W1"].T + p["b1"]; ap, an = np.maximum(0, hp), np.maximum(0, hn) diff = ap @ p["w2"] - an @ p["w2"]; g = -1 / (1 + np.exp(diff)) / len(diff) # d loss / d diff gw2 = (ap - an).T @ g; ghp = np.outer(g, p["w2"]) * (hp > 0); ghn = -np.outer(g, p["w2"]) * (hn > 0) grads = {"W1": ghp.T @ Zp + ghn.T @ Zn, "b1": ghp.sum(0) + ghn.sum(0), "w2": gw2, "b2": np.zeros(1)} else: diff = (Zp - Zn) @ p["w"]; g = -1 / (1 + np.exp(diff)) / len(diff); grads = {"w": (Zp - Zn).T @ g} for k in p: gk = grads[k] + l2 * p[k]; m[k] = 0.9 * m[k] + 0.1 * gk; v[k] = 0.999 * v[k] + 0.001 * gk ** 2 p[k] = p[k] - lr * (m[k] / (1 - 0.9 ** ep)) / (np.sqrt(v[k] / (1 - 0.999 ** ep)) + 1e-8) return p # ---------------------------------------------------------------- generator GEN_SYS = ("You write the weights of a tiny neural network that ranks reference captions for a crop-disease retrieval system. " "Output only one JSON object: {\"W1\": [[5 numbers] x 4 rows], \"b1\": [4 numbers], \"w2\": [4 numbers], \"b2\": [1 number], " "\"rationale\": \"\"}. All numbers finite, between -5 and 5.") def gen_prompt(cond, scale, cap_examples, triplets): L = ["A frozen vision-language model diagnoses crop disease. Each reference image in memory is stored as a label-free text caption", "(organ, location, lesion shape and margin, color, texture, distribution, visible discriminators) plus its disease label.", "A test image is captioned the same way. A scorer ranks every reference caption of the same crop; the top 4 go to the model.", "Objective: references with the test image's disease must score above distractors, especially distractors from the same crop", "that share crop vocabulary but describe a different disease. The label of the test image is unknown at ranking time.", "", "Network: s = w2 . ReLU(W1 x + b1) + b2, with W1 of shape 4 x 5, b1 of length 4, w2 of length 4, b2 of length 1 (29 parameters).", "Input x is the 5 standardized features below, in this order (each value = (raw - mean) / sd, with mean and sd fixed from development data):"] desc = {"idf_cov": "IDF-weighted share of the test caption's terms that appear in the reference caption (0 to 1)", "overlap": "token-set Jaccard overlap of the two captions (0 to 1)", "trigram": "character-trigram Jaccard similarity of the two captions (0 to 1)", "emb_cos": "cosine similarity of frozen sentence embeddings of the two captions", "len_ratio": "log(test caption tokens / reference caption tokens)"} for i, f in enumerate(FEATS): L.append(f" x[{i}] {f}: {desc[f]}; raw mean {scale['mu'][i]:.3f}, raw sd {scale['sd'][i]:.3f}") if cond in ("G1", "G3"): L += ["", "Representative memory captions (label | caption):"] + [f"- {lab} | {txt}" for lab, txt in cap_examples] if cond in ("G2", "G3"): L += ["", "Development examples: for a test caption, a relevant reference (same disease) and a distractor (different disease, same crop),", "with the standardized feature vectors the network receives. The relevant one should score higher."] for t in triplets: L += [f"- test: {t['q']}", f" relevant ({t['pos_lab']}): {t['pos']} x = {t['xp']}", f" distractor ({t['neg_lab']}): {t['neg']} x = {t['xn']}"] L += ["", "Write the weights."] return "\n".join(L) def parse_mlp(text): o = P.last_json(text.replace('"W1"', '"weights_W1"')) if False else None 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 "W1" in obj: found = obj i = end except ValueError: i += 1 if not found: return None, "no JSON with W1" try: p = {"W1": np.array(found["W1"], float), "b1": np.array(found["b1"], float), "w2": np.array(found["w2"], float), "b2": np.array(found["b2"], float).reshape(-1)} except Exception as e: # noqa: BLE001 return None, f"bad arrays: {e}" ok = p["W1"].shape == (4, 5) and p["b1"].shape == (4,) and p["w2"].shape == (4,) and p["b2"].shape == (1,) and all(np.isfinite(v).all() for v in p.values()) return (p, found.get("rationale")) if ok else (None, "wrong shape or non-finite") # ---------------------------------------------------------------- evaluation def evaluate(its, F, scorer, exp, scale): """Per item metrics for one scorer in experiment A or B. scorer(Z, f) -> scores over the candidate rows.""" rows = [] for (c, sp, q, lab, mids, mlabs), f in zip(its, F): cand = order(f["bm25"], f["keys"])[:POOL_A] if exp == "A" else list(range(len(mids))) Z = (f["X"][cand] - scale["mu"]) / scale["sd"] s = scorer(Z, f, cand) top = [cand[i] for i in sorted(range(len(cand)), key=lambda i: (-s[i], f["keys"][cand[i]]))][:K] rel = [mlabs[i] == lab for i in top] first = next((r + 1 for r, x in enumerate(rel) if x), None) dcg = sum(1 / math.log2(r + 2) for r, x in enumerate(rel) if x); nrel = min(K, sum(l == lab for l in mlabs)); idcg = sum(1 / math.log2(r + 2) for r in range(nrel)) or 1 bm_top20 = order(f["bm25"], f["keys"])[:POOL_A] rows.append({"crop": c, "split": sp, "q": q, "hit": float(any(rel)), "mrr": 1 / first if first else 0.0, "ndcg": dcg / idcg, "ntrue": float(sum(rel)), "pool_recall": float(any(mlabs[i] == lab for i in bm_top20)), "eligible_has_rel": float(lab in mlabs), "recovered": float(any(rel) and not any(mlabs[i] == lab for i in bm_top20)), "top": [mids[i] for i in top]}) return rows def eq(rows, sp, m): by = defaultdict(list) for r in rows: if r["split"] == sp: by[r["crop"]].append(r[m]) return 100 * float(np.mean([np.mean(v) for v in by.values()])) if m != "ntrue" else float(np.mean([np.mean(v) for v in by.values()])) def paired_ci(ra, rb, sp, m="hit", n=2000): rng = np.random.default_rng(0); by = defaultdict(list) for a, b in zip(ra, rb): if a["split"] == sp: by[a["crop"]].append(a[m] - b[m]) arr = [np.array(v) for v in by.values()]; ds = [100 * np.mean([v[rng.integers(0, len(v), len(v))].mean() for v in arr]) for _ in range(n)] return [round(float(np.percentile(ds, 2.5)), 1), round(float(np.percentile(ds, 97.5)), 1)] # ---------------------------------------------------------------- main def main(): caps, dev, test, Et, idx_t = load() print(f"dev {len(dev):,} test {len(test):,}") Fd, Ft = featurize(dev, caps, Et, idx_t), featurize(test, caps, Et, idx_t) allX = np.vstack([f["X"] for f in Fd]); scale = {"mu": allX.mean(0), "sd": allX.std(0) + 1e-9} # BM25 reproduces the recorded P1 retrieval rec = {} for l in open(P.M10 / "P1" / "predictions.jsonl"): r = json.loads(l) if r["condition"] == "mace": rec[r["image_id"]] = [m[2:] for m in r["memory_ids"]] same = sum([mids[i] for i in order(f["bm25"], f["keys"])[:K]] == rec[q] for (c, sp, q, lab, mids, ml), f in zip(test, Ft)) print(f"BM25 reproduces recorded P1 retrieval: {same}/{len(test)}") # dev pairs: positives (same label) vs negatives (different label) within each dev query's BM25 top 20 and full memory rng = np.random.default_rng(0); Zp, Zn, trip_pool = [], [], [] for (c, sp, q, lab, mids, mlabs), f in zip(dev, Fd): Z = (f["X"] - scale["mu"]) / scale["sd"]; pos = [i for i, l in enumerate(mlabs) if l == lab]; neg = [i for i, l in enumerate(mlabs) if l != lab] if not pos or not neg: continue for _ in range(4): i, j = rng.choice(pos), rng.choice(neg); Zp.append(Z[i]); Zn.append(Z[j]) ob = order(f["bm25"], f["keys"]); hn = [j for j in ob[:POOL_A] if mlabs[j] != lab] if hn: # half hard examples (BM25's best positive vs its top distractor), half ordinary (random positive vs random # distractor); hard-only packs invert the signal: the top distractor out-scores a random positive on every feature hard = len(trip_pool) % 2 == 0 bp = next(j for j in ob if mlabs[j] == lab) trip_pool.append((c, q, lab, mids, mlabs, Z, bp if hard else rng.choice(pos), hn[0] if hard else rng.choice(neg))) Zp, Zn = np.array(Zp), np.array(Zn) def pack(seed): r = np.random.default_rng(100 + seed); bycrop = defaultdict(list) for t in trip_pool: bycrop[t[0]].append(t) crops = sorted(bycrop); trips = [] while len(trips) < 16: for c in crops: if len(trips) < 16: trips.append(bycrop[c][r.integers(len(bycrop[c]))]) caps_ex = []; rc = np.random.default_rng(200 + seed) for c in crops: t = bycrop[c][rc.integers(len(bycrop[c]))]; mids, mlabs = t[3], t[4] for i in rc.choice(len(mids), 2, replace=False): if len(caps_ex) < 16: caps_ex.append((mlabs[i], packet.caption_text(caps[mids[i]]))) T3 = [{"q": packet.caption_text(caps[t[1]]), "pos": packet.caption_text(caps[t[3][t[6]]]), "pos_lab": t[2], "neg": packet.caption_text(caps[t[3][t[7]]]), "neg_lab": t[4][t[7]], "xp": [round(float(v), 2) for v in t[5][t[6]]], "xn": [round(float(v), 2) for v in t[5][t[7]]], "Zp": t[5][t[6]], "Zn": t[5][t[7]]} for t in trips] return caps_ex, T3 packs = {s: pack(s) for s in range(3)} scorers = {"bm25": lambda Z, f, cand: f["bm25"][cand], "cosine": lambda Z, f, cand: f["X"][cand, 3]} def rrf(Z, f, cand): rb = {i: r for r, i in enumerate(sorted(cand, key=lambda i: (-f["bm25"][i], f["keys"][i])))} rc = {i: r for r, i in enumerate(sorted(cand, key=lambda i: (-f["X"][i, 3], f["keys"][i])))} return np.array([1 / (60 + rb[i] + 1) + 1 / (60 + rc[i] + 1) for i in cand]) scorers["rrf"] = rrf lin = fit_pairwise(Zp, Zn, "linear"); scorers["sup_linear"] = lambda Z, f, cand, p=lin: Z @ p["w"] full = fit_pairwise(Zp, Zn, "mlp"); scorers["sup_mlp_full"] = lambda Z, f, cand, p=full: mlp_score(p, Z) for s, (_, T3) in packs.items(): pm = fit_pairwise(np.array([t["Zp"] for t in T3]), np.array([t["Zn"] for t in T3]), "mlp", seed=s, epochs=300) scorers[f"sup_mlp_matched_p{s}"] = lambda Z, f, cand, p=pm: mlp_score(p, Z) llm.set_budget(llm.spent() + 3.0); gen_log = {} for cond in ("G0", "G1", "G2", "G3"): for s, (caps_ex, T3) in packs.items(): if cond == "G0" and s > 0: # G0 has no examples; three independent samples need distinct requests pass prompt = gen_prompt(cond, scale, caps_ex, T3) + ("" if cond != "G0" else f"\n(Independent draw {s + 1} of 3.)") r = llm.call(GEN_SYS, [{"type": "text", "text": prompt}], stage="retriever_plan_gen", tag=f"{cond}|p{s}", reserve_usd=0.2) p, why = parse_mlp(r.get("text", "") or "") gen_log[f"{cond}_p{s}"] = {"ok": p is not None, "note": why, "cost_usd": r.get("cost_usd"), "cache_hit": r.get("cache_hit"), "params": {k: v.tolist() for k, v in p.items()} if p else None} if p: scorers[f"gen_{cond}_p{s}"] = lambda Z, f, cand, p=p: mlp_score(p, Z) (OUT / "generated_weights.json").write_text(json.dumps({"generator": GEN_MODEL_NOTE, "scale": {k: v.tolist() for k, v in scale.items()}, "runs": gen_log}, indent=1)) (OUT / "packs.json").write_text(json.dumps({s: {"captions": ce, "triplets": [{k: v for k, v in t.items() if k not in ("Zp", "Zn")} for t in T3]} for s, (ce, T3) in packs.items()}, indent=1)) print("generator:", {k: (v["ok"], v["note"] if not v["ok"] else "") for k, v in gen_log.items()}, "USD", round(sum((v["cost_usd"] or 0) for v in gen_log.values()), 3)) # ---- development results, selection locked before test devres = {(n, e): evaluate(dev, Fd, sc, e, scale) for n, sc in scorers.items() for e in ("A", "B")} D = {f"{n}|{e}": {m: eq(r, "val", m) for m in ("hit", "mrr", "ndcg", "ntrue")} for (n, e), r in devres.items()} conds = {} for e in ("A", "B"): for cond in ("G0", "G1", "G2", "G3"): v = [D[f"gen_{cond}_p{s}|{e}"]["hit"] for s in range(3) if f"gen_{cond}_p{s}|{e}" in D] conds[f"{cond}|{e}"] = {"mean": float(np.mean(v)) if v else None, "min": min(v) if v else None, "max": max(v) if v else None, "n": len(v)} lock = {} for e in ("A", "B"): best_c = max((c for c in ("G0", "G1", "G2", "G3") if conds[f"{c}|{e}"]["n"]), key=lambda c: conds[f"{c}|{e}"]["mean"]) best_p = max((f"gen_{best_c}_p{s}" for s in range(3) if f"gen_{best_c}_p{s}|{e}" in D), key=lambda n: (D[f"{n}|{e}"]["hit"], D[f"{n}|{e}"]["mrr"])) simple = max(("cosine", "rrf", "sup_linear", "sup_mlp_full"), key=lambda n: (D[f"{n}|{e}"]["hit"], D[f"{n}|{e}"]["mrr"])) matched = max((f"sup_mlp_matched_p{s}" for s in range(3)), key=lambda n: (D[f"{n}|{e}"]["hit"], D[f"{n}|{e}"]["mrr"])) lock[e] = {"generator_condition": best_c, "generated_scorer": best_p, "strongest_simple": simple, "matched_supervised": matched} (OUT / "dev_results.json").write_text(json.dumps({"per_method": D, "generator_conditions": conds, "locked": lock}, indent=1)) print("LOCKED on dev:", json.dumps(lock)) # ---- test retrieval (one look) tres = {(n, e): evaluate(test, Ft, sc, e, scale) for n, sc in scorers.items() for e in ("A", "B")} md = [] for e in ("A", "B"): # one table per experiment md += [f"\n### Experiment {e} ({'rerank BM25 top 20' if e == 'A' else 'full memory'}), test, k = 4", "", "| Method | hit@4 IID | hit@4 held-out | MRR@4 IID | MRR@4 held-out | nDCG@4 IID | nDCG@4 held-out | true refs IID | dev hit@4 | hit@4 vs BM25 IID [95% CI] | held-out |", "|---|" + "---:|" * 10] names = ["bm25", "cosine", "rrf", "sup_linear", "sup_mlp_full"] + [f"sup_mlp_matched_p{s}" for s in range(3)] + sorted(n for n in scorers if n.startswith("gen_")) for n in names: r, b = tres[(n, e)], tres[("bm25", e)] tag = " **(locked)**" if n in (lock[e]["generated_scorer"], lock[e]["strongest_simple"], lock[e]["matched_supervised"]) else "" ci = lambda sp: "" if n == "bm25" else f"{eq(r, sp, 'hit') - eq(b, sp, 'hit'):+.1f} {paired_ci(r, b, sp)}" md.append(f"| {n}{tag} | {eq(r,'iid','hit'):.1f} | {eq(r,'ood','hit'):.1f} | {eq(r,'iid','mrr'):.1f} | {eq(r,'ood','mrr'):.1f} | {eq(r,'iid','ndcg'):.1f} | {eq(r,'ood','ndcg'):.1f} | " f"{eq(r,'iid','ntrue'):.2f} | {D[f'{n}|{e}']['hit']:.1f} | {ci('iid')} | {ci('ood')} |") b = tres[("bm25", e)] md.append(f"\nBM25 top-20 candidate recall: IID {eq(b,'iid','pool_recall'):.1f}, held-out {eq(b,'ood','pool_recall'):.1f}; eligible memory holds a relevant reference: IID {eq(b,'iid','eligible_has_rel'):.1f}, held-out {eq(b,'ood','eligible_has_rel'):.1f}.") if e == "B": for n in (lock["B"]["generated_scorer"], lock["B"]["strongest_simple"]): md.append(f"Recovered (relevant in top 4, none in BM25 top 20) by {n}: {int(sum(x['recovered'] for x in tres[(n, 'B')]))} queries.") md += ["", "Generator conditions on dev (hit@4 mean [min, max] over 3 packs):"] md += [f"- {k}: {v['mean']:.1f} [{v['min']:.1f}, {v['max']:.1f}] (n={v['n']})" for k, v in conds.items() if v["n"]] (OUT / "test_retrieval.md").write_text("\n".join(md) + "\n") (OUT / "test_retrieved.json").write_text(json.dumps({f"{n}|{e}": {x["q"]: x["top"] for x in r} for (n, e), r in tres.items() if n in ("bm25", lock[e]["generated_scorer"], lock[e]["strongest_simple"], lock[e]["matched_supervised"])})) print("\n".join(md)) if __name__ == "__main__": main()