siddhm11 Claude Opus 5.5 commited on
Commit
3d3bf61
Β·
1 Parent(s): fd260fc

test(eval): user-centred persona suite and bake-off round 2

Browse files

persona_eval.py scores what readers experience: the "liked X, Y, Z -> what
next?" chain on real readers' time-ordered votes against a same-week
candidate pool, Semantic Scholar's dense + TF-IDF mix, and a newcomer
"start here" re-rank (plainly written, surveys, foundational papers) with
its relevance cost. encode_round2.py adds Qwen3-Embedding-0.6B,
gte-modernbert and nomic-embed to the model bake-off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012V6kQQzERfDwhxHuiBoFJ5

scripts/embedding_eval/encode_round2.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bake-off round 2: newer general-purpose embedding models (venv-specter).
2
+
3
+ Runs in the environment with transformers 4.57 (the production pin, 4.44, is too
4
+ old for Qwen3 and ModernBERT). Encodes a SUBSET of the round-1 universe so every
5
+ round-1 model can be re-scored on exactly the same papers:
6
+
7
+ * all Test A papers (citation triplets, lookalike traps)
8
+ * every paper rated by the first 300 of round 1's 600 sampled readers
9
+ * 10,000 of round 1's 30,000 random background papers (seed 42)
10
+
11
+ Models
12
+ qwen3_06b Qwen/Qwen3-Embedding-0.6B (Apache-2.0, 2025). Documents are
13
+ encoded without an instruction, as its model card specifies.
14
+ gte_modernbert Alibaba-NLP/gte-modernbert-base (Apache-2.0)
15
+ nomic_v15 nomic-ai/nomic-embed-text-v1.5, "search_document: " prefix
16
+ Not run: google/embeddinggemma-300m is gated and the HF token has no access.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+ import random
23
+ import sys
24
+ import time
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ from common import CACHE, SEED, log
30
+
31
+ BK = CACHE / "bakeoff"
32
+ MODELS = {
33
+ "qwen3_06b": {"hf": "Qwen/Qwen3-Embedding-0.6B", "prefix": "", "kw": {}},
34
+ "gte_modernbert": {"hf": "Alibaba-NLP/gte-modernbert-base", "prefix": "", "kw": {}},
35
+ "nomic_v15": {"hf": "nomic-ai/nomic-embed-text-v1.5", "prefix": "search_document: ",
36
+ "kw": {"trust_remote_code": True}},
37
+ }
38
+
39
+
40
+ def subset() -> list[str]:
41
+ path = BK / "round2_ids.json"
42
+ if path.exists():
43
+ return json.loads(path.read_text())
44
+ u = json.loads((BK / "universe.json").read_text())
45
+ users = u["real_users"][:300]
46
+ r = pd.read_csv(CACHE / "scholar_inbox" / "rated_papers.csv", dtype={"arxiv_id": str, "user_id": str})
47
+ real = set(r[r.user_id.isin(users)].arxiv_id) & set(u["ids"])
48
+ bg = sorted(random.Random(SEED).sample(u["background"], 10000))
49
+ ids = sorted(set(u["test_a"]) | real | set(bg))
50
+ path.write_text(json.dumps(ids))
51
+ (BK / "round2_meta.json").write_text(json.dumps({"users": users, "background": bg}))
52
+ log("round2", f"subset: {len(ids):,} papers ({len(real):,} rated by 300 readers, {len(bg):,} background)")
53
+ return ids
54
+
55
+
56
+ def main(name: str) -> None:
57
+ from sentence_transformers import SentenceTransformer
58
+ cfg = MODELS[name]
59
+ ids = subset()
60
+ u = json.loads((BK / "universe.json").read_text())
61
+ texts = [cfg["prefix"] + u["titles"].get(i, "") + ". " + u["abstracts"].get(i, "") for i in ids]
62
+ m = SentenceTransformer(cfg["hf"], device=os.getenv("EMBEVAL_BASELINE_DEVICE", "mps"), **cfg["kw"])
63
+ m.max_seq_length = 512 # same budget as the other models
64
+ t0 = time.time()
65
+ parts = []
66
+ for s in range(0, len(texts), 4000):
67
+ parts.append(m.encode(texts[s:s + 4000], batch_size=16, normalize_embeddings=True, convert_to_numpy=True))
68
+ log("round2", f"{name}: {s + len(parts[-1]):,}/{len(texts):,} ({time.time() - t0:.0f}s)")
69
+ np.save(BK / f"vec_{name}.npy", np.concatenate(parts).astype(np.float16))
70
+ (BK / f"ids_{name}.json").write_text(json.dumps(ids))
71
+ # CPU speed on 2 threads, the Space's vCPU count.
72
+ import torch
73
+ torch.set_num_threads(2)
74
+ mc = SentenceTransformer(cfg["hf"], device="cpu", **cfg["kw"])
75
+ mc.max_seq_length = 512
76
+ mc.encode(texts[:8])
77
+ t1 = time.time()
78
+ mc.encode(texts[8:72], batch_size=16)
79
+ speed = 64 / (time.time() - t1)
80
+ dims = int(parts[0].shape[1])
81
+ (BK / f"cost_{name}.json").write_text(json.dumps({"dims": dims, "cpu_docs_per_s_2threads": speed,
82
+ "gb_float16_1.85M": 1.853777e6 * dims * 2 / 1e9,
83
+ "gb_int8_1.85M": 1.853777e6 * dims / 1e9}))
84
+ log("round2", f"{name}: done; {dims} dims, {speed:.1f} papers/s on 2 CPU threads")
85
+
86
+
87
+ if __name__ == "__main__":
88
+ main(sys.argv[1])
scripts/embedding_eval/persona_eval.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """User-centred test suite: does the recommender serve real kinds of readers?
2
+
3
+ T1 UP NEXT (the "liked X, Y, Z -> what next?" chain), real readers.
4
+ Each reader's upvotes in time order. At up to 5 steps per reader (after at
5
+ least 5 upvotes), the target is their NEXT upvote; candidates are the target
6
+ plus 49 papers other readers rated within +/-14 days (a realistic same-week
7
+ pool, so recency cannot give the answer away). Strategies x models:
8
+ last_item similarity to the paper just liked
9
+ short short-term EWMA profile (app's ewma_update, alpha 0.40)
10
+ long long-term EWMA profile (alpha 0.03)
11
+ blend 0.40*unit(long) + 0.25*unit(short) (feed formula, no recency)
12
+ recent3 best similarity to any of the last 3 likes
13
+ Metric: hit@10 and MRR of the true next paper.
14
+ T2 DENSE + LEXICAL (Semantic Scholar's recipe), real readers.
15
+ Liked-vs-disliked AUC: dense profile, TF-IDF profile, and their average.
16
+ T3 NEWCOMER PATHWAY. A newcomer arrives on a paper (each Test A seed) and
17
+ asks "what should I read?". Compare plain relevance with a "start here"
18
+ re-rank that also rewards plainly written abstracts (app/readability.py),
19
+ surveys/tutorials and foundational papers (citations), and report what each
20
+ costs in relevance (citation-linked papers in the top 10).
21
+
22
+ Vectors come from the bake-off cache (round 1 and round 2 where present).
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import random
28
+ import re
29
+ import sqlite3
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+
34
+ from common import CACHE, OUT, SEED, SIDECAR, app_import_path, log
35
+
36
+ app_import_path()
37
+ BK = CACHE / "bakeoff"
38
+ STAGE = "persona"
39
+ import os
40
+ # Round 1 by default; add round-2 models with PERSONA_MODELS=... once encoded.
41
+ CANDIDATE_MODELS = os.getenv("PERSONA_MODELS", "bge_m3,specter2,scincl,gte_large,minilm").split(",")
42
+ SURVEY = re.compile(r"\b(survey|review|tutorial|overview|introduction to|primer|a gentle)\b", re.I)
43
+
44
+
45
+ def load_vecs(name):
46
+ p = BK / f"vec_{name}.npy"
47
+ if not p.exists():
48
+ return None
49
+ ids = json.loads((BK / f"ids_{name}.json").read_text())
50
+ M = np.load(p).astype(np.float32)
51
+ M /= np.linalg.norm(M, axis=1, keepdims=True)
52
+ return dict(zip(ids, M))
53
+
54
+
55
+ def unit(x):
56
+ lo, hi = x.min(), x.max()
57
+ return (x - lo) / (hi - lo) if hi - lo > 1e-12 else np.zeros_like(x)
58
+
59
+
60
+ def ci(x, rng, n=3000):
61
+ x = np.asarray(x, float)
62
+ m = x[rng.integers(0, len(x), (n, len(x)))].mean(axis=1)
63
+ return [float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5))]
64
+
65
+
66
+ def main() -> None:
67
+ from sklearn.feature_extraction.text import TfidfVectorizer
68
+ from sklearn.metrics import roc_auc_score
69
+ from app import readability
70
+ from app.recommend.profiles import ALPHA_LONG_TERM, ALPHA_SHORT_TERM, ewma_update
71
+ rng = np.random.default_rng(SEED)
72
+ u = json.loads((BK / "universe.json").read_text())
73
+ V = {m: v for m in CANDIDATE_MODELS if (v := load_vecs(m)) is not None}
74
+ common = set.intersection(*(set(v) for v in V.values()))
75
+ log(STAGE, f"models: {list(V)}; papers with every model: {len(common):,}")
76
+ res = {"models": list(V), "common_papers": len(common)}
77
+
78
+ ratings = pd.read_csv(CACHE / "scholar_inbox" / "rated_papers.csv", dtype={"arxiv_id": str, "user_id": str})
79
+ ratings["time"] = pd.to_datetime(ratings["time"], format="mixed")
80
+ users = [x for x in u["real_users"]]
81
+ r_all = ratings[ratings.arxiv_id.isin(common)]
82
+ sub = r_all[r_all.user_id.isin(users)].sort_values(["user_id", "time"])
83
+
84
+ # ── T1 up next ──
85
+ strategies = ("last_item", "short", "long", "blend", "recent3")
86
+ hits = {(m, s): [] for m in V for s in strategies}
87
+ mrr = {(m, s): [] for m in V for s in strategies}
88
+ rr = random.Random(SEED)
89
+ others_by_day = r_all.assign(day=r_all.time.dt.floor("D"))
90
+ n_cases = 0
91
+ for usr in users:
92
+ mine = sub[sub.user_id == usr]
93
+ ups = mine[mine.rating > 0]
94
+ if len(ups) < 8:
95
+ continue
96
+ rated = set(mine.arxiv_id)
97
+ steps = list(range(5, len(ups)))
98
+ rr.shuffle(steps)
99
+ for t in sorted(steps[:5]):
100
+ hist = list(ups.arxiv_id.iloc[:t])
101
+ target, when = ups.arxiv_id.iloc[t], ups.time.iloc[t]
102
+ win = others_by_day[(others_by_day.time - when).abs() <= pd.Timedelta(days=14)]
103
+ pool = sorted(set(win.arxiv_id) - rated - {target})
104
+ if len(pool) < 49:
105
+ continue
106
+ cands = [target] + rr.sample(pool, 49)
107
+ n_cases += 1
108
+ for m, vec in V.items():
109
+ X = np.stack([vec[c] for c in cands])
110
+ lt = st = None
111
+ for k, a in enumerate(hist):
112
+ lt = ewma_update(lt, vec[a], ALPHA_LONG_TERM, count=k, normalise=False)
113
+ st = ewma_update(st, vec[a], ALPHA_SHORT_TERM, count=k, normalise=False)
114
+ sl, ss = X @ (lt / np.linalg.norm(lt)), X @ (st / np.linalg.norm(st))
115
+ scores = {"last_item": X @ vec[hist[-1]], "short": ss, "long": sl,
116
+ "blend": 0.40 * unit(sl) + 0.25 * unit(ss),
117
+ "recent3": (X @ np.stack([vec[a] for a in hist[-3:]]).T).max(axis=1)}
118
+ for s, sc in scores.items():
119
+ rank = int((sc > sc[0]).sum())
120
+ hits[(m, s)].append(float(rank < 10))
121
+ mrr[(m, s)].append(1.0 / (rank + 1))
122
+ t1 = {f"{m}|{s}": {"hit@10": float(np.mean(hits[(m, s)])), "hit@10_ci": ci(hits[(m, s)], rng),
123
+ "MRR": float(np.mean(mrr[(m, s)]))} for (m, s) in hits}
124
+ res["T1_up_next"] = {"n_cases": n_cases, "random_hit@10": 10 / 50, "by": t1}
125
+ best = max(t1, key=lambda k: t1[k]["hit@10"])
126
+ log(STAGE, f"T1 cases {n_cases}; best {best} {t1[best]['hit@10']:.3f}; "
127
+ + " ".join(f"{m}:{t1[m + '|blend']['hit@10']:.3f}" for m in V))
128
+
129
+ # ── T2 dense + lexical ──
130
+ texts = {i: u["titles"].get(i, "") + " " + u["abstracts"].get(i, "") for i in common}
131
+ ids_all = sorted(texts)
132
+ tf = TfidfVectorizer(sublinear_tf=True, min_df=2, max_features=200000, stop_words="english")
133
+ T = tf.fit_transform([texts[i] for i in ids_all])
134
+ row = {a: k for k, a in enumerate(ids_all)}
135
+ best_dense = max(V, key=lambda m: t1[f"{m}|blend"]["hit@10"])
136
+ auc = {"dense:" + best_dense: [], "dense:bge_m3": [], "tfidf": [], "avg:" + best_dense + "+tfidf": [],
137
+ "avg:bge_m3+tfidf": []}
138
+ for usr in users:
139
+ mine = sub[sub.user_id == usr]
140
+ cut = int(len(mine) * 0.7)
141
+ tr, te = mine.iloc[:cut], mine.iloc[cut:]
142
+ if tr.rating.gt(0).sum() < 5 or te.rating.nunique() < 2:
143
+ continue
144
+ y = (te.rating > 0).astype(int).values
145
+ pos = list(tr.arxiv_id[tr.rating > 0])
146
+ tcen = np.asarray(T[[row[a] for a in pos]].mean(axis=0)).ravel()
147
+ ttest = T[[row[a] for a in te.arxiv_id]] @ tcen
148
+ out = {"tfidf": np.asarray(ttest).ravel()}
149
+ for m in {best_dense, "bge_m3"}:
150
+ cen = np.mean([V[m][a] for a in pos], axis=0)
151
+ out["dense:" + m] = np.stack([V[m][a] for a in te.arxiv_id]) @ cen
152
+ out["avg:" + best_dense + "+tfidf"] = 0.5 * unit(out["dense:" + best_dense]) + 0.5 * unit(out["tfidf"])
153
+ out["avg:bge_m3+tfidf"] = 0.5 * unit(out["dense:bge_m3"]) + 0.5 * unit(out["tfidf"])
154
+ for k in auc:
155
+ auc[k].append(roc_auc_score(y, out[k]))
156
+ res["T2_dense_lexical"] = {k: {"auc": float(np.mean(v)), "ci": ci(v, rng)} for k, v in auc.items()}
157
+ res["T2_dense_lexical"]["n_readers"] = len(auc["tfidf"])
158
+ log(STAGE, "T2 " + json.dumps({k: round(v["auc"], 4) for k, v in res["T2_dense_lexical"].items() if k != "n_readers"}))
159
+
160
+ # ── T3 newcomer pathway ──
161
+ sc = sqlite3.connect(f"file:{SIDECAR}?mode=ro", uri=True)
162
+ cit = {a: c or 0 for a, c in sc.execute("SELECT arxiv_id, citation_count FROM papers")}
163
+ pool_ids = sorted(common & (set(u["background"]) | set(u["test_a"])))
164
+ lvl = {a: readability.level(u["abstracts"].get(a, "")) for a in pool_ids}
165
+ is_survey = {a: bool(SURVEY.search(u["titles"].get(a, ""))) for a in pool_ids}
166
+ M = np.stack([V[best_dense][a] for a in pool_ids])
167
+ idx = {a: k for k, a in enumerate(pool_ids)}
168
+ logc = np.log1p(np.array([cit.get(a, 0) for a in pool_ids], float))
169
+ acc = np.array([1.0 if lvl[a] == "accessible" else 0.0 for a in pool_ids])
170
+ surv = np.array([1.0 if is_survey[a] else 0.0 for a in pool_ids])
171
+ rows = {"relevance": [], "start_here": []}
172
+ examples = []
173
+ for s in u["seeds"]:
174
+ if s not in idx:
175
+ continue
176
+ linked = {x for x in u["links"][s]["refs"] + u["links"][s]["cits"] if x in idx}
177
+ if len(linked) < 3:
178
+ continue
179
+ rel = M @ V[best_dense][s]
180
+ rel[idx[s]] = -9
181
+ top100 = np.argsort(-rel)[:100] # newcomer re-rank only reorders relevant candidates
182
+ r_unit = unit(rel[top100])
183
+ newcomer = 0.55 * r_unit + 0.15 * acc[top100] + 0.15 * surv[top100] + 0.15 * unit(logc[top100])
184
+ for name, order in (("relevance", top100[:10]), ("start_here", top100[np.argsort(-newcomer)[:10]])):
185
+ ids10 = [pool_ids[j] for j in order]
186
+ rows[name].append({"linked": np.mean([i in linked for i in ids10]),
187
+ "accessible": np.mean([lvl[i] == "accessible" for i in ids10]),
188
+ "survey": np.mean([is_survey[i] for i in ids10]),
189
+ "median_citations": float(np.median([cit.get(i, 0) for i in ids10]))})
190
+ if len(examples) < 3:
191
+ examples.append({"seed": u["titles"].get(s, ""), "relevance": [u["titles"].get(pool_ids[j], "")[:100] for j in top100[:6]],
192
+ "start_here": [{"title": u["titles"].get(pool_ids[j], "")[:100], "accessible": lvl[pool_ids[j]] == "accessible",
193
+ "survey": is_survey[pool_ids[j]], "citations": cit.get(pool_ids[j], 0)}
194
+ for j in top100[np.argsort(-newcomer)[:6]]]})
195
+ res["T3_newcomer"] = {"model": best_dense, "n_seeds": len(rows["relevance"]),
196
+ "weights": "0.55 relevance + 0.15 plainly written + 0.15 survey/tutorial + 0.15 log citations",
197
+ **{n: {k: float(np.mean([x[k] for x in v])) for k in v[0]} for n, v in rows.items()},
198
+ "examples": examples}
199
+ log(STAGE, "T3 " + json.dumps({n: res["T3_newcomer"][n] for n in rows}))
200
+ (OUT / "persona_eval.json").write_text(json.dumps(res, indent=1, default=float))
201
+ log(STAGE, f"wrote {OUT / 'persona_eval.json'}")
202
+
203
+
204
+ if __name__ == "__main__":
205
+ main()