Matthew Ford commited on
Commit
e6555ec
·
1 Parent(s): 19ac1ec

feat: preregistered frozen-benchmark evaluator (substitution triplets + prospective)

Browse files

Scores discordant substitution triplets in the model's learned odor-pyramid
space (preferred must be perceptually closer to target than the structural
distractor) and prospective formulas by projecting the model-predicted pyramid
onto family tag-space vs sequestered labels. Single once-only readout per arm;
reports all outcomes including negative.


Former-commit-id: 1c8a0f18a93d2ae3aeba08cb2bea557e70fddf90
Former-commit-id: 8f77d1adff6ab1a31902d5f34f511f545c90e779

Files changed (1) hide show
  1. scripts/evaluate_frozen_benchmarks.py +187 -0
scripts/evaluate_frozen_benchmarks.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate a trained PIMT checkpoint ONCE on the frozen benchmarks.
3
+
4
+ Benchmarks (all label_access=evaluation_only, never used in training/selection):
5
+ 1. Discordant substitution triplets: the model should rank the perceptually
6
+ preferred substitute CLOSER to the target than the structurally-closer
7
+ distractor. Scored in the model's learned odor space.
8
+ 2. Prospective formulas: predicted family profile vs sequestered intended
9
+ profile (cosine similarity per formula).
10
+
11
+ Reports every outcome including negative/inconclusive. This is the single,
12
+ preregistered readout for the two-arm representation A/B.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import hashlib
18
+ import json
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+ import torch
24
+ from scipy.spatial.distance import cosine
25
+
26
+ from pino.embeddings import OlfactoryEmbeddingEngine
27
+ from pino.heads import PIMTHeads
28
+ from pino.pimt_model import PhysicsInformedMixtureTransformer
29
+
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
+
36
+
37
+ def infer_model_dims(state_dict: dict[str, torch.Tensor]) -> dict[str, int]:
38
+ hidden_dim, embedding_dim = state_dict["input_proj.weight"].shape
39
+ state_dim = state_dict["gating.physics_scaler"].shape[0]
40
+ num_layers = max(
41
+ int(k.split(".")[2]) for k in state_dict
42
+ if k.startswith("encoder.layers.") and k.endswith(".self_attn.in_proj_weight")
43
+ ) + 1
44
+ num_heads = 8 if hidden_dim % 8 == 0 and hidden_dim >= 512 else 4
45
+ return {"embedding_dim": int(embedding_dim), "state_dim": int(state_dim),
46
+ "hidden_dim": int(hidden_dim), "num_heads": num_heads, "num_layers": int(num_layers)}
47
+
48
+
49
+ def load_model(ckpt_path: Path):
50
+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
51
+ dims = infer_model_dims(ckpt["model_state_dict"])
52
+ model = PhysicsInformedMixtureTransformer(**dims)
53
+ model.load_state_dict(ckpt["model_state_dict"])
54
+ model.eval()
55
+ heads = PIMTHeads(hidden_dim=dims["hidden_dim"], objective_dim=138)
56
+ heads.load_state_dict(ckpt["heads_state_dict"], strict=False)
57
+ heads.eval()
58
+ return model, heads, dims
59
+
60
+
61
+ def odor_pyramid(model, heads, engine, smiles: str, cas: str) -> np.ndarray:
62
+ """Encode one molecule to the model's 138-dim odor pyramid (mean of tiers).
63
+
64
+ This is the learned perceptual space used for triplet ranking."""
65
+ z = torch.from_numpy(engine.get_embedding(smiles, cas=cas)).float()
66
+ tokens = z.unsqueeze(0).unsqueeze(0) # (1, T=1, S=1, E)
67
+ physics = torch.zeros(1, 1, 1, 2) # (1, T=1, S=1, 2)
68
+ with torch.no_grad():
69
+ latent = model(tokens, physics) # (1, T, S, H)
70
+ out = heads(latent, physics)
71
+ pyramid = out["objective"].squeeze(0).numpy() # (3, 138)
72
+ return pyramid.mean(axis=0) # (138,)
73
+
74
+
75
+ def eval_triplets(model, heads, engine) -> dict[str, Any]:
76
+ f = ROOT / "data/benchmarks/substitution_triplets/triplets.jsonl"
77
+ rows = [json.loads(l) for l in f.read_text().splitlines() if l.strip()]
78
+ correct, details = 0, []
79
+ for r in rows:
80
+ # Triplets store CAS/SMILES: keys; the engine resolves structure via CAS.
81
+ t_emb = odor_pyramid(model, heads, engine, "", r["target_cas"])
82
+ p_emb = odor_pyramid(model, heads, engine, "", r["preferred_cas"])
83
+ d_emb = odor_pyramid(model, heads, engine, "", r["structural_distractor_cas"])
84
+ d_pref = cosine(t_emb, p_emb)
85
+ d_dist = cosine(t_emb, d_emb)
86
+ ok = bool(d_pref < d_dist) # preferred should be perceptually closer
87
+ correct += int(ok)
88
+ details.append({"triplet_id": r["triplet_id"], "target": r["target"],
89
+ "cos_dist_preferred": round(float(d_pref), 4),
90
+ "cos_dist_distractor": round(float(d_dist), 4), "correct": ok})
91
+ n = len(rows)
92
+ return {"n_triplets": n, "n_correct": correct,
93
+ "accuracy": round(correct / n, 4) if n else None,
94
+ "chance": 0.5, "details": details}
95
+
96
+
97
+ # Family -> Pyrfume 138 tags that belong to that olfactory family. Used to project
98
+ # the model's predicted pyramid onto a family profile.
99
+ FAMILY_TAGS = {
100
+ "citrus_fresh": ["citrus", "lemon", "orange", "grapefruit", "fresh", "ozone", "terpenic", "bergamot"],
101
+ "aromatic_herbal": ["herbal", "lavender", "chamomile", "camphoreous", "mentholic", "mint", "minty", "aromatic"],
102
+ "floral_sweet": ["floral", "rose", "jasmin", "jasmine", "muguet", "violet", "hyacinth", "lily", "geranium", "sweet"],
103
+ "woody_amber": ["woody", "cedar", "pine", "amber", "sandalwood", "vetiver", "patchouli", "mossy"],
104
+ "gourmand": ["vanilla", "chocolate", "caramellic", "honey", "cocoa", "coffee", "nutty", "coumarinic", "lactonic", "creamy", "balsamic"],
105
+ "musk_clean": ["musk", "clean", "powdery", "soapy", "aldehydic", "animal"],
106
+ "green": ["green", "grassy", "leafy", "cucumber", "vegetable", "hay", "weedy"],
107
+ }
108
+ FAMS = list(FAMILY_TAGS)
109
+
110
+
111
+ def _family_projection(vocab: list[str], pyramid: np.ndarray) -> np.ndarray:
112
+ """Project a predicted 138-dim pyramid onto family mass via tag membership."""
113
+ idx = {t: i for i, t in enumerate(vocab)}
114
+ prof = np.zeros(len(FAMS))
115
+ for fi, fam in enumerate(FAMS):
116
+ for tag in FAMILY_TAGS[fam]:
117
+ if tag in idx:
118
+ prof[fi] += pyramid[idx[tag]]
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:
154
+ ap = argparse.ArgumentParser()
155
+ ap.add_argument("--checkpoint", required=True)
156
+ ap.add_argument("--structural-source", choices=["morgan", "openpom_256"], required=True)
157
+ ap.add_argument("--arm-label", default=None)
158
+ ap.add_argument("--output", required=True)
159
+ args = ap.parse_args()
160
+
161
+ ckpt = Path(args.checkpoint)
162
+ model, heads, dims = load_model(ckpt)
163
+ engine = OlfactoryEmbeddingEngine(structural_source=args.structural_source)
164
+
165
+ result = {
166
+ "arm": args.arm_label or args.structural_source,
167
+ "structural_source": args.structural_source,
168
+ "checkpoint": {"path": str(ckpt), "sha256": sha256_file(ckpt)},
169
+ "model_dims": dims,
170
+ "input_embedding_dim": engine.embedding_dim,
171
+ "substitution_triplets": eval_triplets(model, heads, engine),
172
+ "prospective_formulas": eval_prospective(model, heads, engine),
173
+ "label_access": "evaluation_only; results reported for all outcomes incl. negative",
174
+ }
175
+ out = Path(args.output)
176
+ out.parent.mkdir(parents=True, exist_ok=True)
177
+ out.write_text(json.dumps(result, indent=2))
178
+ print(json.dumps({k: result[k] for k in
179
+ ["arm", "input_embedding_dim"]}, indent=2))
180
+ print("triplets:", result["substitution_triplets"]["accuracy"],
181
+ f"({result['substitution_triplets']['n_correct']}/{result['substitution_triplets']['n_triplets']})")
182
+ print("prospective mean cosine:", result["prospective_formulas"]["mean_family_profile_cosine"])
183
+ return 0
184
+
185
+
186
+ if __name__ == "__main__":
187
+ raise SystemExit(main())