mattbitzesty commited on
Commit
7ea9f42
·
verified ·
1 Parent(s): 3ae77c2

review-response: upload scripts/evaluate_frozen_benchmarks.py

Browse files
scripts/evaluate_frozen_benchmarks.py CHANGED
@@ -14,6 +14,7 @@ preregistered readout for the two-arm representation A/B.
14
  from __future__ import annotations
15
 
16
  import argparse
 
17
  import hashlib
18
  import json
19
  from pathlib import Path
@@ -30,6 +31,29 @@ from pino.pimt_model import PhysicsInformedMixtureTransformer
30
  ROOT = Path(__file__).resolve().parents[1]
31
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  def sha256_file(path: Path) -> str:
34
  return hashlib.sha256(path.read_bytes()).hexdigest()
35
 
@@ -119,35 +143,58 @@ def _family_projection(vocab: list[str], pyramid: np.ndarray) -> np.ndarray:
119
  return prof
120
 
121
 
122
- def eval_prospective(model, heads, engine) -> dict[str, Any]:
123
  vocab = json.loads((ROOT / "data/pyrfume_vocabulary.json").read_text())["vocabulary"]
124
  ff = ROOT / "data/benchmarks/prospective_formulas/formulas.jsonl"
125
  lf = ROOT / "data/benchmarks/prospective_formulas/labels.sequestered.json"
126
  formulas = [json.loads(l) for l in ff.read_text().splitlines() if l.strip()]
127
  labels = {l["formula_id"]: l["target_family_profile"]
128
  for l in json.loads(lf.read_text())["labels"]}
 
129
 
130
- sims, details = [], []
131
  for form in formulas:
132
  # Model prediction: weight-average each ingredient's predicted pyramid by
133
  # the model's concentration-normalised contribution (weight_fraction here
134
  # as the physical dose), then project onto family tag-space.
135
  blend = np.zeros(138)
 
136
  for ing in form["ingredients"]:
137
  emb = odor_pyramid(model, heads, engine, ing.get("smiles", ""), ing.get("cas") or "")
138
  blend += ing["weight_fraction"] * emb
 
139
  pred = _family_projection(vocab, blend)
140
  pred = pred / pred.sum() if pred.sum() else pred
141
  tgt = np.array([labels[form["formula_id"]].get(f, 0.0) for f in FAMS])
142
  tgt = tgt / tgt.sum() if tgt.sum() else tgt
143
  sim = 1.0 - cosine(pred, tgt) if (pred.any() and tgt.any()) else 0.0
 
 
 
 
 
144
  sims.append(sim)
145
- details.append({"formula_id": form["formula_id"], "genre": form["genre"],
146
- "family_profile_cosine": round(float(sim), 4)})
147
- return {"n_formulas": len(formulas),
148
- "mean_family_profile_cosine": round(float(np.mean(sims)), 4) if sims else None,
149
- "note": "model-predicted pyramid projected onto family tag-space vs sequestered intended profile",
150
- "details": details}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
 
153
  def main() -> int:
@@ -163,6 +210,7 @@ def main() -> int:
163
  engine_source = "openpom_256" if args.structural_source == "pom_alltags" else args.structural_source
164
  model, heads, dims = load_model(ckpt, objective_dim=objective_dim)
165
  engine = OlfactoryEmbeddingEngine(structural_source=engine_source)
 
166
 
167
  result = {
168
  "arm": args.arm_label or args.structural_source,
@@ -171,10 +219,11 @@ def main() -> int:
171
  "checkpoint": {"path": str(ckpt), "sha256": sha256_file(ckpt)},
172
  "model_dims": dims,
173
  "input_embedding_dim": engine.embedding_dim,
 
174
  "substitution_triplets": eval_triplets(model, heads, engine),
175
  # Prospective family-profile projection is defined over the 138-dim
176
  # Pyrfume vocabulary; not comparable for the 575-dim all-tags arm.
177
- "prospective_formulas": (eval_prospective(model, heads, engine)
178
  if objective_dim == 138
179
  else {"not_applicable": "575-dim tag target; family projection is 138-vocab specific"}),
180
  "label_access": "evaluation_only; results reported for all outcomes incl. negative",
 
14
  from __future__ import annotations
15
 
16
  import argparse
17
+ import csv
18
  import hashlib
19
  import json
20
  from pathlib import Path
 
31
  ROOT = Path(__file__).resolve().parents[1]
32
 
33
 
34
+ def _canon_smiles(smiles: str) -> str | None:
35
+ try:
36
+ from rdkit import Chem
37
+ m = Chem.MolFromSmiles(smiles or "")
38
+ return Chem.MolToSmiles(m, isomericSmiles=False) if m else None
39
+ except Exception: # noqa: BLE001
40
+ return None
41
+
42
+
43
+ def _load_openpom_proxy() -> set[str]:
44
+ """Public GoodScents+Leffingwell corpus OpenPOM was trained on (proxy bound)."""
45
+ f = ROOT / "data/openpom_curated_4983.csv"
46
+ keys: set[str] = set()
47
+ if not f.exists():
48
+ return keys
49
+ with open(f, newline="") as fh:
50
+ for row in csv.DictReader(fh):
51
+ k = _canon_smiles(row.get("nonStereoSMILES", ""))
52
+ if k:
53
+ keys.add(k)
54
+ return keys
55
+
56
+
57
  def sha256_file(path: Path) -> str:
58
  return hashlib.sha256(path.read_bytes()).hexdigest()
59
 
 
143
  return prof
144
 
145
 
146
+ def eval_prospective(model, heads, engine, openpom_proxy: set[str] | None = None) -> dict[str, Any]:
147
  vocab = json.loads((ROOT / "data/pyrfume_vocabulary.json").read_text())["vocabulary"]
148
  ff = ROOT / "data/benchmarks/prospective_formulas/formulas.jsonl"
149
  lf = ROOT / "data/benchmarks/prospective_formulas/labels.sequestered.json"
150
  formulas = [json.loads(l) for l in ff.read_text().splitlines() if l.strip()]
151
  labels = {l["formula_id"]: l["target_family_profile"]
152
  for l in json.loads(lf.read_text())["labels"]}
153
+ proxy = openpom_proxy if openpom_proxy is not None else set()
154
 
155
+ sims, weights, details = [], [], []
156
  for form in formulas:
157
  # Model prediction: weight-average each ingredient's predicted pyramid by
158
  # the model's concentration-normalised contribution (weight_fraction here
159
  # as the physical dose), then project onto family tag-space.
160
  blend = np.zeros(138)
161
+ ing_keys = []
162
  for ing in form["ingredients"]:
163
  emb = odor_pyramid(model, heads, engine, ing.get("smiles", ""), ing.get("cas") or "")
164
  blend += ing["weight_fraction"] * emb
165
+ ing_keys.append(_canon_smiles(ing.get("smiles", "")))
166
  pred = _family_projection(vocab, blend)
167
  pred = pred / pred.sum() if pred.sum() else pred
168
  tgt = np.array([labels[form["formula_id"]].get(f, 0.0) for f in FAMS])
169
  tgt = tgt / tgt.sum() if tgt.sum() else tgt
170
  sim = 1.0 - cosine(pred, tgt) if (pred.any() and tgt.any()) else 0.0
171
+ # Novelty weight: fraction of ingredients absent from OpenPOM's public training
172
+ # corpus. On this benchmark overlap is near-total, so this bounds the honest,
173
+ # overlap-free agreement. 1.0 when no proxy is available (unweighted).
174
+ valid = [k for k in ing_keys if k]
175
+ novelty = (sum(1 for k in valid if k not in proxy) / len(valid)) if valid and proxy else 1.0
176
  sims.append(sim)
177
+ weights.append(novelty)
178
+ details.append({**{"formula_id": form["formula_id"], "genre": form["genre"],
179
+ "family_profile_cosine": round(float(sim), 4),
180
+ "novelty_weight": round(float(novelty), 4)}})
181
+ w = np.array(weights)
182
+ s = np.array(sims)
183
+ wmean = float((w * s).sum() / w.sum()) if w.sum() > 0 else None
184
+ result = {"n_formulas": len(formulas),
185
+ "mean_family_profile_cosine": round(float(np.mean(sims)), 4) if sims else None,
186
+ "note": "model-predicted pyramid projected onto family tag-space vs sequestered intended profile",
187
+ "details": details}
188
+ if proxy:
189
+ result["openpom_overlap"] = {
190
+ "novelty_weighted_mean_cosine": round(wmean, 4) if wmean is not None else None,
191
+ "n_formulas_with_any_novelty": int((w > 0).sum()),
192
+ "mean_novelty_weight": round(float(w.mean()), 4),
193
+ "note": ("novelty_weight = fraction of ingredients NOT in OpenPOM's public training corpus; "
194
+ "the novelty-weighted cosine is the honest overlap-bounded readout (unweighted mean is "
195
+ "an upper bound inflated by pretraining memorization)."),
196
+ }
197
+ return result
198
 
199
 
200
  def main() -> int:
 
210
  engine_source = "openpom_256" if args.structural_source == "pom_alltags" else args.structural_source
211
  model, heads, dims = load_model(ckpt, objective_dim=objective_dim)
212
  engine = OlfactoryEmbeddingEngine(structural_source=engine_source)
213
+ openpom_proxy = _load_openpom_proxy()
214
 
215
  result = {
216
  "arm": args.arm_label or args.structural_source,
 
219
  "checkpoint": {"path": str(ckpt), "sha256": sha256_file(ckpt)},
220
  "model_dims": dims,
221
  "input_embedding_dim": engine.embedding_dim,
222
+ "openpom_overlap_proxy_corpus_size": len(openpom_proxy),
223
  "substitution_triplets": eval_triplets(model, heads, engine),
224
  # Prospective family-profile projection is defined over the 138-dim
225
  # Pyrfume vocabulary; not comparable for the 575-dim all-tags arm.
226
+ "prospective_formulas": (eval_prospective(model, heads, engine, openpom_proxy)
227
  if objective_dim == 138
228
  else {"not_applicable": "575-dim tag target; family projection is 138-vocab specific"}),
229
  "label_access": "evaluation_only; results reported for all outcomes incl. negative",