midah commited on
Commit
d126496
·
verified ·
1 Parent(s): 6a3be6d

Reorganize: scripts/eval/retrieval_eval.py

Browse files
Files changed (1) hide show
  1. scripts/eval/retrieval_eval.py +271 -0
scripts/eval/retrieval_eval.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Figure completion retrieval benchmark.
2
+
3
+ Leave-one-out: for each patent, mask one view (by default the top plan view,
4
+ or the hardest available). Given embeddings of N-1 sibling views as context,
5
+ retrieve the correct masked view from a pool of 100 candidates.
6
+
7
+ Baselines:
8
+ random — chance (1%)
9
+ single — embed only the perspective view, retrieve
10
+ multi — average CLIP embeddings of all N-1 context views, retrieve
11
+ vlm — (future) use VLM to describe missing view, embed description
12
+
13
+ Usage:
14
+ python scripts/eval/retrieval_eval.py \
15
+ --embeddings data/embeddings/embeddings_2022_vitl14.parquet \
16
+ --enriched data/enriched/enriched_2022.parquet \
17
+ --n 500 \
18
+ --pool-size 100 \
19
+ --out results/retrieval_eval.json
20
+ """
21
+
22
+ import argparse
23
+ import json
24
+ import random
25
+ import re
26
+ from collections import defaultdict
27
+ from pathlib import Path
28
+
29
+ import faiss
30
+ import numpy as np
31
+ import pandas as pd
32
+ from tqdm import tqdm
33
+
34
+
35
+ # ── viewpoint helpers ─────────────────────────────────────────────────────────
36
+
37
+ def parse_viewpoint(drawing_desc: str, fig_num: int) -> str:
38
+ pat = re.compile(
39
+ rf"FIG\.\s*{fig_num + 1}\s+is\s+(?:a\s+|an\s+)?(.{{5,80}}?)\s*(?:view|thereof|;|\n|$)",
40
+ re.IGNORECASE,
41
+ )
42
+ m = pat.search(drawing_desc or "")
43
+ return m.group(1).strip().lower() if m else ""
44
+
45
+
46
+ TARGET_PRIORITY = [
47
+ # (label_fragment, difficulty)
48
+ ("cross-sectional", "very_hard"),
49
+ ("cross section", "very_hard"),
50
+ ("enlarged", "hard"),
51
+ ("detail", "hard"),
52
+ ("top plan", "hard"),
53
+ ("bottom plan", "medium"),
54
+ ("rear elevation", "medium"),
55
+ ("rear elev", "medium"),
56
+ ("side elev", "easy"),
57
+ ("front elev", "easy"),
58
+ ("perspective", "baseline"),
59
+ ]
60
+
61
+
62
+ def pick_target_view(viewpoints: list[str]) -> tuple[int, str]:
63
+ """Pick the highest-priority masking target. Returns (index, difficulty)."""
64
+ for frag, difficulty in TARGET_PRIORITY:
65
+ for i, vp in enumerate(viewpoints):
66
+ if frag in vp:
67
+ return i, difficulty
68
+ # Fallback: pick any non-first view
69
+ return 1 if len(viewpoints) > 1 else 0, "unknown"
70
+
71
+
72
+ # ── retrieval ─────────────────────────────────────────────────────────────────
73
+
74
+ def build_faiss_index(vectors: np.ndarray) -> faiss.IndexFlatIP:
75
+ """Build an inner-product FAISS index (cosine sim on L2-normed vectors)."""
76
+ dim = vectors.shape[1]
77
+ index = faiss.IndexFlatIP(dim)
78
+ index.add(vectors.astype(np.float32))
79
+ return index
80
+
81
+
82
+ def retrieve(
83
+ query_vec: np.ndarray, # (dim,)
84
+ candidate_indices: list[int], # indices into the full embedding matrix
85
+ all_vectors: np.ndarray,
86
+ correct_idx: int, # index into candidate_indices
87
+ ) -> dict:
88
+ """Score retrieval: rank correct candidate among candidates by cosine sim."""
89
+ cand_vecs = all_vectors[candidate_indices].astype(np.float32)
90
+ q = query_vec.astype(np.float32).reshape(1, -1)
91
+ sims = (cand_vecs @ q.T).squeeze()
92
+ ranks = np.argsort(-sims) # descending
93
+ rank_of_correct = int(np.where(ranks == correct_idx)[0][0]) + 1 # 1-indexed
94
+ return {
95
+ "rank": rank_of_correct,
96
+ "r1": int(rank_of_correct <= 1),
97
+ "r5": int(rank_of_correct <= 5),
98
+ "r10": int(rank_of_correct <= 10),
99
+ "sim_correct": float(sims[correct_idx]),
100
+ "sim_top1": float(sims[ranks[0]]),
101
+ }
102
+
103
+
104
+ # ── main eval ─────────────────────────────────────────────────────────────────
105
+
106
+ def run_eval(
107
+ embeddings_path: str,
108
+ enriched_path: str,
109
+ n: int,
110
+ pool_size: int,
111
+ out_path: str,
112
+ seed: int = 42,
113
+ ):
114
+ rng = random.Random(seed)
115
+
116
+ print("Loading embeddings...")
117
+ emb_df = pd.read_parquet(embeddings_path)
118
+ fig_id_to_idx = {fid: i for i, fid in enumerate(emb_df["figure_id"])}
119
+ all_vecs = np.vstack(emb_df["embedding"].tolist()).astype(np.float32)
120
+ # Ensure unit norm for cosine sim
121
+ norms = np.linalg.norm(all_vecs, axis=1, keepdims=True)
122
+ all_vecs = all_vecs / np.maximum(norms, 1e-8)
123
+ print(f"Embeddings: {all_vecs.shape}")
124
+
125
+ print("Loading enriched metadata...")
126
+ df = pd.read_parquet(enriched_path)
127
+ df["viewpoint_parsed"] = df.apply(
128
+ lambda r: parse_viewpoint(r.get("drawing_description", ""), r["figure_number"]),
129
+ axis=1,
130
+ )
131
+
132
+ # Keep only figures with embeddings
133
+ df = df[df["figure_id"].isin(fig_id_to_idx)].copy()
134
+ df["_vec_idx"] = df["figure_id"].map(fig_id_to_idx)
135
+
136
+ # Group by patent
137
+ patent_groups = {
138
+ pid: g.sort_values("figure_number")
139
+ for pid, g in df.groupby("patent_id")
140
+ if len(g) >= 3
141
+ }
142
+
143
+ # Build Locarno-class → figure_id list for distractor sampling
144
+ class_to_fids = defaultdict(list)
145
+ for _, row in df.iterrows():
146
+ cls = row.get("class") or row.get("locarno_class") or "unknown"
147
+ class_to_fids[str(cls)].append(row["figure_id"])
148
+
149
+ # Sample eligible patents
150
+ all_pids = list(patent_groups.keys())
151
+ rng.shuffle(all_pids)
152
+ eval_pids = all_pids[:n]
153
+ print(f"Evaluating {len(eval_pids)} patents (pool_size={pool_size})")
154
+
155
+ by_difficulty = defaultdict(lambda: {"r1": 0, "r5": 0, "r10": 0, "n": 0})
156
+ results = []
157
+
158
+ for pid in tqdm(eval_pids):
159
+ group = patent_groups[pid]
160
+ fids = group["figure_id"].tolist()
161
+ vps = group["viewpoint_parsed"].tolist()
162
+ vec_idxs = group["_vec_idx"].tolist()
163
+ cls = str(group["class"].iloc[0] if "class" in group.columns else "unknown")
164
+
165
+ # Pick target view to mask
166
+ target_pos, difficulty = pick_target_view(vps)
167
+ target_fid = fids[target_pos]
168
+ target_vec_idx = vec_idxs[target_pos]
169
+
170
+ context_idxs = [vi for i, vi in enumerate(vec_idxs) if i != target_pos]
171
+ if not context_idxs:
172
+ continue
173
+
174
+ # Build query: average of context embeddings
175
+ query_vec = all_vecs[context_idxs].mean(axis=0)
176
+ query_vec /= max(np.linalg.norm(query_vec), 1e-8)
177
+
178
+ # Build candidate pool: target + (pool_size - 1) distractors from same class
179
+ distractors_pool = [
180
+ f for f in class_to_fids.get(cls, [])
181
+ if f not in set(fids) and f in fig_id_to_idx
182
+ ]
183
+ rng.shuffle(distractors_pool)
184
+ distractors = distractors_pool[: pool_size - 1]
185
+ if len(distractors) < pool_size - 1:
186
+ # Fill from any other patent
187
+ other_fids = [
188
+ f for f in df["figure_id"].tolist()
189
+ if f not in set(fids) and f not in set(distractors) and f in fig_id_to_idx
190
+ ]
191
+ rng.shuffle(other_fids)
192
+ distractors += other_fids[: pool_size - 1 - len(distractors)]
193
+
194
+ if len(distractors) < 3:
195
+ continue
196
+
197
+ candidates = distractors[: pool_size - 1]
198
+ # Insert correct answer at random position
199
+ insert_pos = rng.randint(0, len(candidates))
200
+ candidates.insert(insert_pos, target_fid)
201
+ candidate_vec_idxs = [fig_id_to_idx[f] for f in candidates]
202
+
203
+ # Multi-view retrieval
204
+ score = retrieve(query_vec, candidate_vec_idxs, all_vecs, insert_pos)
205
+ # Single-view retrieval (perspective only, if available)
206
+ persp_pos = next((i for i, v in enumerate(vps) if "perspective" in v and i != target_pos), None)
207
+ if persp_pos is not None:
208
+ single_score = retrieve(all_vecs[vec_idxs[persp_pos]], candidate_vec_idxs, all_vecs, insert_pos)
209
+ else:
210
+ single_score = score # fallback
211
+
212
+ for bucket in [difficulty, "all"]:
213
+ by_difficulty[bucket]["r1"] += score["r1"]
214
+ by_difficulty[bucket]["r5"] += score["r5"]
215
+ by_difficulty[bucket]["r10"] += score["r10"]
216
+ by_difficulty[bucket]["n"] += 1
217
+
218
+ results.append({
219
+ "patent_id": pid,
220
+ "target_view": vps[target_pos],
221
+ "difficulty": difficulty,
222
+ "pool_size": len(candidates),
223
+ "multi_view": score,
224
+ "single_view": single_score,
225
+ })
226
+
227
+ # Summary
228
+ print("\n" + "=" * 60)
229
+ print("RETRIEVAL EVAL RESULTS")
230
+ print(f"{'Difficulty':<16} {'N':>5} {'R@1':>6} {'R@5':>6} {'R@10':>6} {'Chance R@1':>10}")
231
+ print("-" * 60)
232
+ for diff in ["all", "baseline", "easy", "medium", "hard", "very_hard"]:
233
+ b = by_difficulty[diff]
234
+ if b["n"] == 0:
235
+ continue
236
+ chance = 100.0 / pool_size
237
+ print(
238
+ f"{diff:<16} {b['n']:>5} "
239
+ f"{b['r1']/b['n']:>5.1%} "
240
+ f"{b['r5']/b['n']:>5.1%} "
241
+ f"{b['r10']/b['n']:>5.1%} "
242
+ f"{chance:>9.1f}%"
243
+ )
244
+
245
+ output = {
246
+ "summary": {d: {k: v/b["n"] if k != "n" else v for k, v in b.items()}
247
+ for d, b in by_difficulty.items()},
248
+ "pool_size": pool_size,
249
+ "n_patents": len(results),
250
+ "results": results,
251
+ }
252
+ Path(out_path).parent.mkdir(parents=True, exist_ok=True)
253
+ with open(out_path, "w") as f:
254
+ json.dump(output, f, indent=2)
255
+ print(f"\nFull results → {out_path}")
256
+
257
+
258
+ def main():
259
+ parser = argparse.ArgumentParser()
260
+ parser.add_argument("--embeddings", default="data/embeddings/embeddings_2022_vitl14.parquet")
261
+ parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet")
262
+ parser.add_argument("--n", type=int, default=500)
263
+ parser.add_argument("--pool-size", type=int, default=100)
264
+ parser.add_argument("--out", default="results/retrieval_eval.json")
265
+ parser.add_argument("--seed", type=int, default=42)
266
+ args = parser.parse_args()
267
+ run_eval(args.embeddings, args.enriched, args.n, args.pool_size, args.out, args.seed)
268
+
269
+
270
+ if __name__ == "__main__":
271
+ main()