tirtho149's picture
Add retriever study (code, predictions, one-pager), refresh response cache
874eec2 verified
Raw History Blame Contribute Delete
5.84 kB
"""Shreyan's retriever with the image feature: Sonnet writes the weights of a small linear scoring network over the 16
caption features of pilot.py plus DINOv2 image similarity (min-max scaled within the memory).
Two contexts, one Sonnet call per crop each: 'schema' (feature definitions, crop, disease list) and 'memory' (the same
plus the crop's memory captions and labels). The context is chosen on the validation set of tune.py (hit@4, then true
entries); the test queries are scored once, and the chosen retriever's test retrieval is written for full.py.
python -m experiments.retriever_pilot.llm_image
"""
from __future__ import annotations
import json
from collections import Counter, defaultdict
import numpy as np
from agmem import llm, packet
from . import pilot as P, tune as T
FEATS = P.FEATS + ["image_sim"]
DOC = {**P.FEAT_DOC, "image_sim": "Visual similarity of the two images (DINOv2 image-embedding cosine), scaled so the most similar memory image is 1 and the least similar is 0. It does not use the captions."}
def 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 image/caption and one memory entry):"]
lines += [f"- {k}: {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 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]))
r = llm.call(P.LLM_SYS, [{"type": "text", "text": prompt(crop, sorted({l for _, l in bank}), bank, caps, with_memory)}],
stage="retriever_pilot_img", tag=f"{'memory' if with_memory else 'schema'}|{crop}", reserve_usd=0.15)
p = 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], "missing": [k for k in FEATS if k not in w], "rationale": p.get("rationale"), "cost_usd": r.get("cost_usd")}
return out
def score_items(its, caps, E, idx, W):
"""Per item: top-4 indices under the crop's weights; plus BM25 and tuned text+image for reference."""
res = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
picks = defaultdict(dict)
for c, sp, q, lab, mids, mlabs in its:
F = P.features(caps[q], mids, caps)
cos = E[[idx[m] for m in mids]] @ E[idx[q]]; img = (cos - cos.min()) / ((cos.max() - cos.min()) or 1.0)
F = np.hstack([F, img[:, None]])
for name, w in W.items():
sel = T.pick(F @ np.array(w[c]["w"]), mids, mlabs, 4); labs = [mlabs[i] for i in sel]
cnt = Counter(labs); best = max(cnt.values()); vote = next(l for l in labs if cnt[l] == best)
r = res[name][(sp, c)]; r["hit4"].append(lab in labs); r["ntrue"].append(labs.count(lab)); r["vote"].append(vote == lab); r["top1"].append(labs[0] == lab)
picks[name][q] = [mids[i] for i in sel]
return res, picks
def main():
caps, P1, _ = P.load()
d = np.load(P.M10 / "dinov2_embeddings.npz"); E = d["E"].astype(np.float32); E /= np.linalg.norm(E, axis=1, keepdims=True); idx = {k: i for i, k in enumerate(d["ids"])}
val, test = T.items(P1, caps, E, idx)
llm.set_budget(llm.spent() + 2.0)
W = {"llm_img_schema": weights(P1, caps, False), "llm_img_memory": weights(P1, caps, True)}
print("missing weights:", {k: sum(len(x["missing"]) for x in v.values()) for k, v in W.items()},
"USD:", round(sum((x["cost_usd"] or 0) for v in W.values() for x in v.values()), 3))
(P.OUT / "llm_image_weights.json").write_text(json.dumps({k: {c: {**x, "features": FEATS} for c, x in v.items()} for k, v in W.items()}, indent=1))
vres, _ = score_items(val, caps, E, idx, W)
pv = T.precompute(val, caps, E, idx)
ref = {"BM25 (paper)": ((1.2, 0.75, 3), 0, 4), "Tuned text + image": ((2.0, 0.3, 0), 1.5, 4)}
print("validation (equal-crop):")
for n, cfg in ref.items():
s = T.summary(T.evaluate(val, pv, cfg), "val"); print(f" {n:<22} hit@4 {s['hit4']:.1f} true entries {s['ntrue']:.2f} vote {s['vote']:.1f}")
vs = {n: T.summary(vres[n], "val") for n in W}
for n, s in vs.items():
print(f" {n:<22} hit@4 {s['hit4']:.1f} true entries {s['ntrue']:.2f} vote {s['vote']:.1f}")
chosen = max(vs, key=lambda n: (round(vs[n]["hit4"], 6), vs[n]["ntrue"]))
print("chosen on validation:", chosen)
tres, picks = score_items(test, caps, E, idx, {chosen: W[chosen]})
for sp in ("iid", "ood"):
s = T.summary(tres[chosen], sp); print(f"test {sp}: hit@4 {s['hit4']:.1f} true entries {s['ntrue']:.2f} vote {s['vote']:.1f}")
(P.OUT / "llm_image_retrieved.json").write_text(json.dumps({"chosen": chosen, "retrieved": picks[chosen]}))
(P.OUT / "llm_image_results.json").write_text(json.dumps({"validation": vs, "chosen": chosen, "test": {sp: T.summary(tres[chosen], sp) for sp in ("iid", "ood")}}, indent=1))
if __name__ == "__main__":
main()