File size: 8,078 Bytes
874eec2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""Retriever tuning with a clean validation set, then ONE look at the 1,600 test queries.

Validation queries: training-fold images that are in the seed-0 K=16 memory of a crop and fold but not in its K=4 memory
and are never test queries. Each is scored against the K=4 memory of the same crop and fold (the memory MACE uses), so
no test image or test label is touched while tuning. Validation images come from the memory collections, so tuning can
only target the IID setting; held-out results are reported as they come.

Search space (every config scored the same way, top 4 kept, ties by memory id):
  text    BM25 over the whole caption with parameters k1, b and the organ repeat count (paper: 1.2, 0.75, 3)
  image   DINOv2 cosine between test and memory image, min-max scaled within the memory, added with weight alpha
  cap     at most `cap` entries per disease among the four (4 = no cap)
Objective on validation: hit@4 (equal-crop mean), then mean number of true-disease entries among the four.

  python -m experiments.retriever_pilot.tune
"""
from __future__ import annotations

import itertools
import json
import math
from collections import Counter, defaultdict

import numpy as np

from agmem import packet
from mace10 import jobs as JB
from . import pilot as P

OUT = P.OUT
K1S, BS, ORGS = (0.6, 1.2, 2.0), (0.3, 0.75, 1.0), (0, 1, 3, 6)
ALPHAS = (0, 0.25, 0.5, 1, 1.5, 2, 3, 5, 1e3)      # 1e3 = image similarity alone (text breaks ties)
CAPS = (4, 3, 2, 1)


def bm25(q, docs, k1, b):
    N = len(docs); df = Counter(t for d in docs for t in set(d)); avg = sum(map(len, docs)) / N; qc = Counter(q); out = []
    for d in docs:
        tf = Counter(d); s = 0.0
        for t in qc:
            if t in tf:
                s += math.log(1 + (N - df[t] + 0.5) / (df[t] + 0.5)) * tf[t] * (k1 + 1) / (tf[t] + k1 * (1 - b + b * len(d) / avg))
        out.append(s)
    m = max(out) or 1.0
    return np.array(out) / m


def items(P1, caps, E, idx):
    """Validation and test items: (crop, split, query id, true label, memory ids, memory labels)."""
    test = [(j["crop"], j["split"], j["image_id"], j["label"], [m["image_id"] for m in j["memory"]], [m["label"] for m in j["memory"]]) for j in P1]
    tq = set(JB.queries().image_id); val = []
    for c, r in sorted({(j["crop"], j["run"]) for j in P1}):
        m4 = JB.mem(c, 0, r, 4); ids4 = {m["image_id"] for m in m4}
        for m in JB.mem(c, 0, r, 16):
            i = m["image_id"]
            if i not in ids4 and i not in tq and i in caps and i in idx:
                val.append((c, "val", i, m["label"], [x["image_id"] for x in m4], [x["label"] for x in m4]))
    return val, test


def precompute(its, caps, E, idx):
    """Per item: text scores for every (k1, b, organ repeat) and the min-max scaled image similarity."""
    toks = {}
    def tk(i):
        if i not in toks:
            toks[i] = packet.tok(packet.caption_text(caps[i]))
        return toks[i]
    pre = []
    for c, sp, q, lab, mids, mlabs in its:
        docs = [tk(m) for m in mids]; organ = packet.tok(str(caps[q].get("organ", "")))
        T = {(k1, b, o): bm25(tk(q) + organ * o, docs, k1, b) for k1 in K1S for b in BS for o in ORGS}
        cos = E[[idx[m] for m in mids]] @ E[idx[q]]; img = (cos - cos.min()) / ((cos.max() - cos.min()) or 1.0)
        pre.append((T, img))
    return pre


def pick(score, mids, mlabs, cap):
    order = sorted(range(len(mids)), key=lambda i: (-score[i], "m_" + mids[i])); out, n = [], Counter()
    for i in order:
        if n[mlabs[i]] < cap:
            out.append(i); n[mlabs[i]] += 1
        if len(out) == 4:
            break
    return out


def evaluate(its, pre, cfg):
    (k1, b, o), a, cap = cfg; per = defaultdict(lambda: defaultdict(list))
    for (c, sp, q, lab, mids, mlabs), (T, img) in zip(its, pre):
        sel = pick(T[(k1, b, o)] + a * img, mids, mlabs, cap); 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 = per[(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); r["q"].append(q)
    return per


def summary(per, sp):
    crops = sorted(c for s, c in per if s == sp)
    return {m: 100 * float(np.mean([np.mean(per[(sp, c)][m]) for c in crops])) if m != "ntrue" else float(np.mean([np.mean(per[(sp, c)][m]) for c in crops]))
            for m in ("hit4", "ntrue", "vote", "top1")}


def paired_ci(pa, pb, sp, m="hit4", n=2000):
    rng = np.random.default_rng(0); crops = sorted(c for s, c in pa if s == sp); ds = []
    for _ in range(n):
        v = []
        for c in crops:
            a, b = np.array(pa[(sp, c)][m], float), np.array(pb[(sp, c)][m], float); k = rng.integers(0, len(a), len(a)); v.append((a[k] - b[k]).mean())
        ds.append(100 * np.mean(v))
    return [round(float(np.percentile(ds, 2.5)), 1), round(float(np.percentile(ds, 97.5)), 1)]


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 = items(P1, caps, E, idx)
    print(f"validation queries {len(val):,} ({len({v[0] for v in val})} crops); test queries {len(test):,}")
    pv = precompute(val, caps, E, idx)
    grid = list(itertools.product([(k1, b, o) for k1 in K1S for b in BS for o in ORGS], ALPHAS, CAPS))
    rows = []
    for cfg in grid:
        s = summary(evaluate(val, pv, cfg), "val"); rows.append((cfg, s))
    rows.sort(key=lambda r: (-round(r[1]["hit4"], 6), -r[1]["ntrue"]))
    base = ((1.2, 0.75, 3), 0, 4)
    sb = next(s for cfg, s in rows if cfg == base)
    print(f"validation: paper BM25 hit@4 {sb['hit4']:.1f}, true entries {sb['ntrue']:.2f}; {len(grid)} configs")
    for cfg, s in rows[:8]:
        print(f"  {cfg}  hit@4 {s['hit4']:.1f}  true entries {s['ntrue']:.2f}  vote {s['vote']:.1f}")
    best = rows[0][0]
    # best without the per-disease cap, so we can see what the image similarity alone adds
    best_nocap = next(cfg for cfg, s in rows if cfg[2] == 4)
    img_only = ((1.2, 0.75, 3), 1e3, 4)
    pt = precompute(test, caps, E, idx)
    named = {"BM25 (paper)": base, "Image only (DINOv2)": img_only, "Tuned, no cap": best_nocap, "Tuned (best on validation)": best}
    res = {n: evaluate(test, pt, c) for n, c in named.items()}
    lines = ["| Retriever | config (k1, b, organ x; alpha; cap) | hit@4 IID | hit@4 held-out | true entries IID | true entries held-out | vote IID | vote held-out | hit@4 vs BM25 IID [95% CI] | held-out |",
             "|---|---|" + "---:|" * 8]
    out = {"validation_n": len(val), "test_n": len(test), "selected": {n: list(map(str, c)) for n, c in named.items()}, "test": {}, "validation_top": [[str(c), s] for c, s in rows[:20]]}
    for n, c in named.items():
        si, so = summary(res[n], "iid"), summary(res[n], "ood"); out["test"][n] = {"iid": si, "ood": so}
        ci = "" if n == "BM25 (paper)" else f"{si['hit4'] - summary(res['BM25 (paper)'], 'iid')['hit4']:+.1f} {paired_ci(res[n], res['BM25 (paper)'], 'iid')}"
        co = "" if n == "BM25 (paper)" else f"{so['hit4'] - summary(res['BM25 (paper)'], 'ood')['hit4']:+.1f} {paired_ci(res[n], res['BM25 (paper)'], 'ood')}"
        lines.append(f"| {n} | {c[0]}; {c[1]:g}; {c[2]} | {si['hit4']:.1f} | {so['hit4']:.1f} | {si['ntrue']:.2f} | {so['ntrue']:.2f} | {si['vote']:.1f} | {so['vote']:.1f} | {ci} | {co} |")
    (OUT / "tune_table.md").write_text("\n".join(lines) + "\n"); (OUT / "tune_results.json").write_text(json.dumps(out, indent=1))
    # retrieved ids of the selected configs, so a diagnosis run can use them directly
    sel = {}
    for n, (cfgT, a, cap) in named.items():
        for (c, sp, q, lab, mids, mlabs), (T, img) in zip(test, pt):
            sel.setdefault(n, {})[q] = [mids[i] for i in pick(T[cfgT] + a * img, mids, mlabs, cap)]
    (OUT / "tune_retrieved.json").write_text(json.dumps(sel))
    print("\n".join(lines))


if __name__ == "__main__":
    main()