mattbitzesty commited on
Commit
d027051
·
verified ·
1 Parent(s): 7d3c72d

R11 eval job: add evaluate_prospective_trainconsistent.py (train-consistent physics-on evals)

Browse files
scripts/evaluate_prospective_trainconsistent.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Prospective family-profile readout under TRAIN-CONSISTENT physics conditioning.
3
+
4
+ The paper's frozen-benchmarks evaluator (evaluate_frozen_benchmarks.py) scores the
5
+ 40 held-out prospective formulas with the physics tensor ZEROED at eval time — a
6
+ deliberately conservative "perceptual-only" readout (one molecule, one timestep,
7
+ zeroed physics). A review panel demands the same readout re-scored under the
8
+ physics conditioning the model was actually trained on: the full (T, S) formula
9
+ token grid with REAL time-resolved physical states from the Dortmund-UNIFAC engine.
10
+
11
+ For each prospective formula this script:
12
+ 1. Runs the cached Dortmund-UNIFAC evaporation engine on the FULL formula
13
+ (all ingredients together, as in training) to get per-(timestep, component)
14
+ states: [x_liquid, log10(OAV)].
15
+ 2. Builds the train-consistent input grid: tokens (S, E) from the arm-matched
16
+ embedding engine, physics (T, S, state_dim) from the engine trajectory.
17
+ 3. Forward through model + heads → objective tiers (3, 138) → mean over tiers.
18
+ 4. Projects the 138-dim prediction onto family tag-space → cosine vs the
19
+ sequestered intended family profile (SAME scoring code as the frozen eval).
20
+ 5. Also emits the ZEROED-physics full-grid cosine (sensitivity reference):
21
+ same grid, same forward, physics zeroed — isolating the physics contribution
22
+ at the full-grid architecture.
23
+
24
+ Engine trajectories are cached (artifacts/engine_traj_cache.json) so reruns are cheap.
25
+
26
+ Output JSON:
27
+ {arm, checkpoint sha256, n_formulas,
28
+ mean_family_profile_cosine_physics_on,
29
+ mean_family_profile_cosine_zeroed_fullgrid,
30
+ details: [{formula_id, genre, cosine_physics_on, cosine_zeroed_fullgrid, delta, ...}]}
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import hashlib
36
+ import json
37
+ import os
38
+ import sys
39
+ from pathlib import Path
40
+
41
+ import numpy as np
42
+ import torch
43
+ from scipy.spatial.distance import cosine
44
+
45
+ # Ensure src/ is importable
46
+ ROOT = Path(__file__).resolve().parents[1]
47
+ sys.path.insert(0, str(ROOT / "src"))
48
+ # Also make the scripts dir importable so we can reuse the frozen-eval scoring code
49
+ sys.path.insert(0, str(ROOT / "scripts"))
50
+
51
+ from pino.embeddings import OlfactoryEmbeddingEngine # noqa: E402
52
+ from pino.heads import PIMTHeads # noqa: E402
53
+ from pino.pimt_model import PhysicsInformedMixtureTransformer # noqa: E402
54
+
55
+ # Reuse the exact scoring code from the frozen-benchmarks evaluator
56
+ from evaluate_frozen_benchmarks import ( # noqa: E402
57
+ FAMS,
58
+ FAMILY_TAGS,
59
+ _family_projection,
60
+ infer_model_dims,
61
+ load_model,
62
+ sha256_file,
63
+ )
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Engine trajectory computation
68
+ # ---------------------------------------------------------------------------
69
+
70
+ def _load_verifier():
71
+ from pino.verifier import FragrancePipelineVerifier
72
+ return FragrancePipelineVerifier()
73
+
74
+
75
+ def _run_formula_trajectory(verifier, formula: dict, duration_seconds: float = 8 * 3600.0,
76
+ interval_seconds: float = 600.0) -> dict | None:
77
+ """Run the evaporation engine on a FULL prospective formula.
78
+
79
+ Returns a dict with:
80
+ species: [cas, ...] (resolved ingredient CAS order)
81
+ t_s: [times]
82
+ x_liquid: (T, S) array
83
+ log_oav: (T, S) array
84
+ or None if the engine could not solve the formula.
85
+ """
86
+ ings = []
87
+ for ing in formula["ingredients"]:
88
+ ings.append({
89
+ "cas": ing["cas"],
90
+ "smiles": ing.get("smiles", ""),
91
+ "weight_fraction": ing["weight_fraction"],
92
+ })
93
+
94
+ # Patch any registry records that have smiles=None but the formula provides
95
+ # a valid SMILES — otherwise _ingredient_from_record raises a TypeError that
96
+ # skip_unresolved does not catch (it's not an IngredientResolutionError).
97
+ for ing in ings:
98
+ cas = ing["cas"]
99
+ smiles = ing.get("smiles", "")
100
+ if not smiles:
101
+ continue
102
+ try:
103
+ rec = verifier.resolver.registry.get(cas)
104
+ if rec and not rec.get("smiles"):
105
+ verifier.resolver.registry.add({
106
+ **rec, "smiles": smiles, "cas": cas,
107
+ })
108
+ except Exception: # noqa: BLE001
109
+ pass
110
+
111
+ try:
112
+ sim = verifier.run_sim(ings, duration_seconds=duration_seconds,
113
+ interval_seconds=interval_seconds,
114
+ method="BDF", skip_ifra=True, skip_unresolved=True)
115
+ traj = sim.get("trajectory", [])
116
+ if not traj:
117
+ return None
118
+ # Determine the resolved species order from the first timestep
119
+ first = traj[0]
120
+ species = list(first["x_liquid"].keys())
121
+ T = len(traj)
122
+ S = len(species)
123
+ x_liquid = np.zeros((T, S), dtype=np.float32)
124
+ log_oav = np.zeros((T, S), dtype=np.float32)
125
+ times = []
126
+ for t, step in enumerate(traj):
127
+ times.append(step["t_s"])
128
+ for j, cas in enumerate(species):
129
+ x_liquid[t, j] = float(step["x_liquid"].get(cas, 0.0))
130
+ oav = float(step["OAV"].get(cas, 0.0))
131
+ log_oav[t, j] = np.log10(max(oav, 1e-10))
132
+ return {"species": species, "t_s": times,
133
+ "x_liquid": x_liquid.tolist(), "log_oav": log_oav.tolist()}
134
+ except Exception:
135
+ return None
136
+
137
+
138
+ def get_trajectory_cache(formula_id: str, verifier, formula: dict,
139
+ cache: dict, cache_path: Path) -> dict | None:
140
+ """Return cached trajectory for a formula, or compute + cache it."""
141
+ if formula_id in cache:
142
+ entry = cache[formula_id]
143
+ return entry if entry else None # empty dict = previously failed
144
+ traj = _run_formula_trajectory(verifier, formula)
145
+ if traj is None:
146
+ cache[formula_id] = {}
147
+ cache_path.write_text(json.dumps(cache))
148
+ return None
149
+ cache[formula_id] = traj
150
+ cache_path.write_text(json.dumps(cache))
151
+ return traj
152
+
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # Forward pass
156
+ # ---------------------------------------------------------------------------
157
+
158
+ def build_formula_grid(formula: dict, traj: dict, engine: OlfactoryEmbeddingEngine,
159
+ state_dim: int) -> tuple[torch.Tensor, torch.Tensor] | None:
160
+ """Build the (T, S, E) token grid and (T, S, state_dim) physics grid.
161
+
162
+ Returns (tokens, physics) ready for model(), or None on failure.
163
+ The engine trajectory may resolve fewer ingredients than the formula
164
+ (skip_unresolved=True). We align tokens to the resolved species.
165
+ """
166
+ species = traj["species"]
167
+ # Map resolved CAS back to the formula ingredients for embeddings
168
+ ing_by_cas = {}
169
+ for ing in formula["ingredients"]:
170
+ ing_by_cas[ing["cas"]] = ing
171
+
172
+ tokens_list = []
173
+ for cas in species:
174
+ ing = ing_by_cas.get(cas, {})
175
+ smiles = ing.get("smiles", "")
176
+ z = engine.get_embedding(smiles, cas=cas)
177
+ tokens_list.append(torch.from_numpy(z).float())
178
+
179
+ if not tokens_list:
180
+ return None
181
+
182
+ tokens = torch.stack(tokens_list, dim=0) # (S, E)
183
+ S = tokens.shape[0]
184
+ E = tokens.shape[1]
185
+ x_liquid = np.asarray(traj["x_liquid"], dtype=np.float32) # (T, S)
186
+ T = x_liquid.shape[0]
187
+
188
+ # Physics: (T, S, state_dim) — [x_liquid, log10(OAV)]
189
+ if state_dim < 2:
190
+ raise ValueError(f"state_dim must be >= 2 for physics-on eval, got {state_dim}")
191
+ physics = np.zeros((T, S, state_dim), dtype=np.float32)
192
+ physics[:, :, 0] = x_liquid
193
+ physics[:, :, 1] = np.asarray(traj["log_oav"], dtype=np.float32)
194
+ # If state_dim == 3 (gamma channel), leave it as zeros — gamma is not
195
+ # available from the prospective engine trajectory without P_sat lookup.
196
+ # This is documented in the script's output notes.
197
+ physics_tensor = torch.from_numpy(physics)
198
+
199
+ return tokens, physics_tensor
200
+
201
+
202
+ def forward_formula(model, heads, tokens_2d: torch.Tensor, physics_3d: torch.Tensor) -> np.ndarray:
203
+ """Full-grid forward: (S,E) + (T,S,state_dim) -> 138-dim prediction.
204
+
205
+ model expects tokens (B, S, E) and states (B, T, S, state_dim).
206
+ heads expects latent (B, T, S, H) and physics (B, T, S, state_dim).
207
+ """
208
+ S = tokens_2d.shape[0]
209
+ tokens = tokens_2d.unsqueeze(0) # (1, S, E)
210
+ physics = physics_3d.unsqueeze(0) # (1, T, S, state_dim)
211
+ mask = torch.zeros(1, S, dtype=torch.bool)
212
+ with torch.no_grad():
213
+ latent = model(tokens, physics) # (1, T, S, H)
214
+ out = heads(latent, physics, mask)
215
+ pyramid = out["objective"][0].cpu().numpy() # (3, 138)
216
+ return pyramid.mean(axis=0) # (138,)
217
+
218
+
219
+ def forward_formula_zeroed(model, heads, tokens_2d: torch.Tensor, physics_3d: torch.Tensor) -> np.ndarray:
220
+ """Same as forward_formula but with physics zeroed (sensitivity reference)."""
221
+ physics_zero = torch.zeros_like(physics_3d)
222
+ return forward_formula(model, heads, tokens_2d, physics_zero)
223
+
224
+
225
+ # ---------------------------------------------------------------------------
226
+ # Main evaluation
227
+ # ---------------------------------------------------------------------------
228
+
229
+ ARM_TO_STRUCTURAL_SOURCE = {
230
+ "morgan": "morgan",
231
+ "morgan_2048_rp": "morgan_2048_rp",
232
+ "morgan_2048_direct": "morgan_2048_direct",
233
+ "openpom_256": "openpom_256",
234
+ "disjoint_256": "disjoint_256",
235
+ }
236
+
237
+
238
+ def main() -> int:
239
+ ap = argparse.ArgumentParser(description=__doc__)
240
+ ap.add_argument("--checkpoint", required=True, help="Path to PIMT checkpoint .pt")
241
+ ap.add_argument("--arm", required=True,
242
+ choices=list(ARM_TO_STRUCTURAL_SOURCE),
243
+ help="A/B arm name (determines embedding engine structural_source)")
244
+ ap.add_argument("--max-formulas", type=int, default=None,
245
+ help="Limit to first N formulas (smoke testing)")
246
+ ap.add_argument("--output", required=True)
247
+ ap.add_argument("--cache", default=str(ROOT / "artifacts" / "engine_traj_cache.json"))
248
+ ap.add_argument("--vocab", default=str(ROOT / "data" / "pyrfume_vocabulary.json"))
249
+ ap.add_argument("--formulas",
250
+ default=str(ROOT / "data" / "benchmarks" / "prospective_formulas" / "formulas.jsonl"))
251
+ ap.add_argument("--labels",
252
+ default=str(ROOT / "data" / "benchmarks" / "prospective_formulas" / "labels.sequestered.json"))
253
+ ap.add_argument("--skip-download", action="store_true",
254
+ help="Don't download checkpoint from HF; use local --checkpoint path only")
255
+ args = ap.parse_args()
256
+
257
+ structural_source = ARM_TO_STRUCTURAL_SOURCE[args.arm]
258
+
259
+ # --- Load model ---
260
+ ckpt_path = Path(args.checkpoint)
261
+ if not ckpt_path.exists():
262
+ if args.skip_download:
263
+ print(f"ERROR: checkpoint not found: {ckpt_path}", file=sys.stderr)
264
+ return 1
265
+ print(f"Downloading checkpoint from HuggingFace: {args.checkpoint}")
266
+ from huggingface_hub import hf_hub_download
267
+ ckpt_path = Path(hf_hub_download(
268
+ repo_id="mattbitzesty/pino-pimt-representation-ab",
269
+ filename=ckpt_path.name,
270
+ ))
271
+
272
+ objective_dim = 138 # family projection is 138-vocab specific
273
+ model, heads, dims = load_model(ckpt_path, objective_dim=objective_dim)
274
+ state_dim = dims["state_dim"]
275
+ model.eval()
276
+ heads.eval()
277
+
278
+ # --- Load embedding engine ---
279
+ engine = OlfactoryEmbeddingEngine(structural_source=structural_source)
280
+
281
+ # --- Load data ---
282
+ vocab = json.loads(Path(args.vocab).read_text())["vocabulary"]
283
+ formulas = [json.loads(l) for l in Path(args.formulas).read_text().splitlines() if l.strip()]
284
+ if args.max_formulas:
285
+ formulas = formulas[:args.max_formulas]
286
+ labels_raw = json.loads(Path(args.labels).read_text())["labels"]
287
+ labels = {l["formula_id"]: l["target_family_profile"] for l in labels_raw}
288
+
289
+ # --- Cache ---
290
+ cache_path = Path(args.cache)
291
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
292
+ cache = json.loads(cache_path.read_text()) if cache_path.exists() else {}
293
+
294
+ # --- Verifier (lazy) ---
295
+ verifier = None
296
+
297
+ # --- Evaluate ---
298
+ sims_on, sims_off = [], []
299
+ details = []
300
+
301
+ for form in formulas:
302
+ fid = form["formula_id"]
303
+ if verifier is None:
304
+ verifier = _load_verifier()
305
+ traj = get_trajectory_cache(fid, verifier, form, cache, cache_path)
306
+ if traj is None:
307
+ print(f" [{fid}] engine trajectory failed — skipping", file=sys.stderr)
308
+ details.append({
309
+ "formula_id": fid, "genre": form["genre"],
310
+ "cosine_physics_on": None, "cosine_zeroed_fullgrid": None,
311
+ "delta": None, "n_engine_species": 0, "n_timesteps": 0,
312
+ "status": "engine_failed",
313
+ })
314
+ continue
315
+
316
+ grid = build_formula_grid(form, traj, engine, state_dim)
317
+ if grid is None:
318
+ details.append({
319
+ "formula_id": fid, "genre": form["genre"],
320
+ "cosine_physics_on": None, "cosine_zeroed_fullgrid": None,
321
+ "delta": None, "n_engine_species": 0, "n_timesteps": len(traj["t_s"]),
322
+ "status": "token_build_failed",
323
+ })
324
+ continue
325
+ tokens_2d, physics_3d = grid
326
+
327
+ # Physics ON (train-consistent)
328
+ pred_on = forward_formula(model, heads, tokens_2d, physics_3d)
329
+ # Physics OFF (zeroed, same full-grid architecture)
330
+ pred_off = forward_formula_zeroed(model, heads, tokens_2d, physics_3d)
331
+
332
+ tgt_profile = labels.get(fid, {})
333
+ tgt = np.array([tgt_profile.get(f, 0.0) for f in FAMS])
334
+
335
+ def _score(pred_138: np.ndarray) -> float:
336
+ fam_proj = _family_projection(vocab, pred_138)
337
+ if fam_proj.sum():
338
+ fam_proj = fam_proj / fam_proj.sum()
339
+ if pred_138.any() and tgt.any():
340
+ return float(1.0 - cosine(fam_proj, tgt))
341
+ return 0.0
342
+
343
+ sim_on = _score(pred_on)
344
+ sim_off = _score(pred_off)
345
+ sims_on.append(sim_on)
346
+ sims_off.append(sim_off)
347
+
348
+ details.append({
349
+ "formula_id": fid,
350
+ "genre": form["genre"],
351
+ "n_engine_species": len(traj["species"]),
352
+ "n_timesteps": len(traj["t_s"]),
353
+ "cosine_physics_on": round(sim_on, 4),
354
+ "cosine_zeroed_fullgrid": round(sim_off, 4),
355
+ "delta_on_minus_off": round(sim_on - sim_off, 4),
356
+ "status": "ok",
357
+ })
358
+ print(f" [{fid}] on={sim_on:.4f} off={sim_off:.4f} delta={sim_on-sim_off:+.4f}")
359
+
360
+ n_ok = len(sims_on)
361
+ result = {
362
+ "arm": args.arm,
363
+ "structural_source": structural_source,
364
+ "checkpoint": str(ckpt_path),
365
+ "checkpoint_sha256": sha256_file(ckpt_path),
366
+ "model_dims": dims,
367
+ "state_dim": state_dim,
368
+ "n_formulas": len(formulas),
369
+ "n_evaluated": n_ok,
370
+ "n_skipped": len(formulas) - n_ok,
371
+ "mean_family_profile_cosine_physics_on": round(float(np.mean(sims_on)), 4) if sims_on else None,
372
+ "mean_family_profile_cosine_zeroed_fullgrid": round(float(np.mean(sims_off)), 4) if sims_off else None,
373
+ "mean_delta_on_minus_off": round(float(np.mean(np.array(sims_on) - np.array(sims_off))), 4) if sims_on else None,
374
+ "conditioning": "train_consistent_full_grid_physics_on",
375
+ "notes": [
376
+ "Physics ON: real time-resolved [x_liquid, log10(OAV)] from Dortmund-UNIFAC engine on the full formula.",
377
+ "Zeroed full-grid: same (T,S) architecture, physics tensor zeroed (sensitivity reference isolating physics contribution).",
378
+ "State_dim=3 checkpoints have gamma channel zeroed (gamma not available from prospective trajectory without P_sat lookup).",
379
+ ],
380
+ "details": details,
381
+ }
382
+
383
+ out = Path(args.output)
384
+ out.parent.mkdir(parents=True, exist_ok=True)
385
+ out.write_text(json.dumps(result, indent=2))
386
+
387
+ print("\n" + "=" * 70)
388
+ print(f"PROSPECTIVE TRAIN-CONSISTENT EVAL — arm={args.arm}")
389
+ print("=" * 70)
390
+ print(f"Formulas: {len(formulas)} | evaluated: {n_ok} | skipped: {len(formulas) - n_ok}")
391
+ print(f"Mean cosine (physics ON): {result['mean_family_profile_cosine_physics_on']}")
392
+ print(f"Mean cosine (zeroed fullgrid): {result['mean_family_profile_cosine_zeroed_fullgrid']}")
393
+ print(f"Mean delta (on - off): {result['mean_delta_on_minus_off']}")
394
+ print(f"Output: {out}")
395
+ print("=" * 70)
396
+ return 0
397
+
398
+
399
+ if __name__ == "__main__":
400
+ raise SystemExit(main())