mattbitzesty commited on
Commit
65da34a
·
verified ·
1 Parent(s): 376e3b9

Upload scripts/evaluate_substantivity.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/evaluate_substantivity.py +169 -0
scripts/evaluate_substantivity.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate a trained PIMT checkpoint on MEASURED Poucher substantivity.
2
+
3
+ This is the E1 metric. Substantivity (olfactive duration) is physics-causal —
4
+ it IS evaporation — and the Poucher coefficients are measured, i.e.
5
+ engine-independent (not UNIFAC-derived). A non-redundant physics channel
6
+ (gamma blend-interaction) should improve prediction of this target on
7
+ held-out molecules; a redundant one should not.
8
+
9
+ Method:
10
+ * Rebuild the exact molecule-disjoint train/val split (same seed + ratio as
11
+ training) and run the substantivity head over the VALIDATION records.
12
+ * Keep only records with a measured-Poucher target (mask == 1).
13
+ * Report masked-MSE, MAE, Pearson and Spearman correlation between predicted
14
+ log10 substantivity and the measured Poucher target, plus n.
15
+ * Compare physics_off vs physics_gamma arms on the same split/seed.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+ import torch
25
+
26
+ from pino.heads import PIMTHeads
27
+ from pino.pimt_model import (
28
+ FragranceTrajectoryDataset,
29
+ PhysicsInformedMixtureTransformer,
30
+ )
31
+ from pino.upload_data import create_molecule_disjoint_split_from_records
32
+
33
+
34
+ def load_model(ckpt_path: Path, objective_dim: int):
35
+ sd = torch.load(ckpt_path, map_location="cpu", weights_only=False)
36
+ state = sd.get("model_state_dict", sd.get("model", sd))
37
+ heads_state = sd.get("heads_state_dict", sd.get("heads", {}))
38
+ state_dim = int(state["gating.physics_scaler"].shape[0])
39
+ embedding_dim = int(state["input_proj.weight"].shape[1])
40
+ hidden_dim = int(state["input_proj.weight"].shape[0])
41
+ num_layers = sum(1 for k in state if k.endswith("self_attn.in_proj_weight"))
42
+ # num_heads is not directly stored; default to the train config value (4 for
43
+ # full runs, 2 for smoke). It does not affect load_state_dict correctness
44
+ # because attention weights are stored shape-complete; only num_layers/dims
45
+ # must match. Use 4 but rely on strict=False for safety.
46
+ model = PhysicsInformedMixtureTransformer(
47
+ embedding_dim=embedding_dim, state_dim=state_dim,
48
+ hidden_dim=hidden_dim, num_heads=4, num_layers=max(num_layers, 1),
49
+ )
50
+ model.load_state_dict(state, strict=False)
51
+ heads = PIMTHeads(hidden_dim=hidden_dim, objective_dim=objective_dim)
52
+ if heads_state:
53
+ heads.load_state_dict(heads_state, strict=False)
54
+ model.eval(); heads.eval()
55
+ return model, heads, {"embedding_dim": embedding_dim, "state_dim": state_dim,
56
+ "hidden_dim": hidden_dim, "num_layers": num_layers}
57
+
58
+
59
+ def pearson(x, y):
60
+ if len(x) < 3:
61
+ return float("nan")
62
+ return float(np.corrcoef(x, y)[0, 1])
63
+
64
+
65
+ def spearman(x, y):
66
+ if len(x) < 3:
67
+ return float("nan")
68
+ rx = np.argsort(np.argsort(x)); ry = np.argsort(np.argsort(y))
69
+ return float(np.corrcoef(rx, ry)[0, 1])
70
+
71
+
72
+ def main() -> int:
73
+ ap = argparse.ArgumentParser()
74
+ ap.add_argument("--checkpoint", required=True)
75
+ ap.add_argument("--data", required=True)
76
+ ap.add_argument("--structural-source", default="morgan")
77
+ ap.add_argument("--train-ratio", type=float, default=0.85)
78
+ ap.add_argument("--seed", type=int, default=42)
79
+ ap.add_argument("--arm-label", default=None)
80
+ ap.add_argument("--use-gamma", action="store_true")
81
+ ap.add_argument("--split", choices=["molecule", "formula"], default="formula",
82
+ help="molecule = strict molecule-disjoint holdout (clean but n~10 measured); "
83
+ "formula = random formula-level holdout (~460 measured, but molecules leak). "
84
+ "E1 uses formula-level for power and discloses the leakage.")
85
+ ap.add_argument("--output", required=True)
86
+ args = ap.parse_args()
87
+
88
+ objective_dim = 575 if args.structural_source == "pom_alltags" else 138
89
+ engine_source = "openpom_256" if args.structural_source == "pom_alltags" else args.structural_source
90
+
91
+ model, heads, dims = load_model(Path(args.checkpoint), objective_dim)
92
+ model_state_dim = dims["state_dim"]
93
+
94
+ with open(args.data) as f:
95
+ all_records = [json.loads(line) for line in f if line.strip()]
96
+
97
+ if args.split == "molecule":
98
+ split = create_molecule_disjoint_split_from_records(
99
+ all_records, train_ratio=args.train_ratio, seed=args.seed)
100
+ val_records = split["validation"]
101
+ split_note = "molecule-disjoint holdout (strict, low measured-n)"
102
+ else:
103
+ # formula-level random holdout: higher measured-Poucher n for power, at the
104
+ # cost of molecule leakage between train/val. Disclosed in the output.
105
+ # MUST match train.py's formula split exactly (same rng.permutation + seed).
106
+ rng = np.random.default_rng(args.seed)
107
+ n = len(all_records)
108
+ n_val = max(1, int(round(n * (1.0 - args.train_ratio))))
109
+ perm = rng.permutation(n)
110
+ val_idx = set(perm[:n_val].tolist())
111
+ val_records = [all_records[i] for i in sorted(val_idx)]
112
+ split_note = ("formula-level random holdout; molecules may leak between splits "
113
+ "(disclosed). Chosen for measured-Poucher power.")
114
+
115
+ ds = FragranceTrajectoryDataset(
116
+ records=val_records, use_embedding_fallback=True,
117
+ structural_source=engine_source, objective_dim=objective_dim,
118
+ use_gamma=args.use_gamma,
119
+ )
120
+
121
+ preds, targs = [], []
122
+ device = "cuda" if torch.cuda.is_available() else "cpu"
123
+ model.to(device); heads.to(device)
124
+ with torch.no_grad():
125
+ for i in range(len(ds)):
126
+ item = ds[i]
127
+ mask = float(item.get("target_substantivity_mask", 0.0))
128
+ if mask < 0.5:
129
+ continue
130
+ tokens = item["tokens"].unsqueeze(0).to(device) # (1,S,E)
131
+ physics = item["physics"].unsqueeze(0).to(device) # (1,T,S,C)
132
+ # match model state_dim
133
+ if physics.size(-1) != model_state_dim:
134
+ if physics.size(-1) < model_state_dim:
135
+ pad = torch.zeros(1, physics.size(1), physics.size(2), model_state_dim - physics.size(-1), device=device)
136
+ physics = torch.cat([physics, pad], dim=-1)
137
+ else:
138
+ physics = physics[..., :model_state_dim]
139
+ latent = model(tokens, physics)
140
+ out = heads(latent, physics)
141
+ sub = out["subjective"]["substantivity"]
142
+ pred = float(sub.reshape(-1)[0].cpu())
143
+ preds.append(pred)
144
+ targs.append(float(item["target_substantivity"]))
145
+
146
+ preds = np.array(preds); targs = np.array(targs)
147
+ result = {
148
+ "arm": args.arm_label or Path(args.checkpoint).stem,
149
+ "use_gamma": bool(args.use_gamma),
150
+ "seed": args.seed,
151
+ "model_dims": dims,
152
+ "task": "measured Poucher substantivity (engine-independent, physics-causal)",
153
+ "n_measured_val": int(len(preds)),
154
+ "mse": float(((preds - targs) ** 2).mean()) if len(preds) else None,
155
+ "mae": float(np.abs(preds - targs).mean()) if len(preds) else None,
156
+ "pearson": pearson(preds, targs),
157
+ "spearman": spearman(preds, targs),
158
+ "target_mean": float(targs.mean()) if len(targs) else None,
159
+ "target_std": float(targs.std()) if len(targs) else None,
160
+ "baseline_mse_predict_mean": float(((targs - targs.mean()) ** 2).mean()) if len(targs) else None,
161
+ }
162
+ out = Path(args.output); out.parent.mkdir(parents=True, exist_ok=True)
163
+ out.write_text(json.dumps(result, indent=2))
164
+ print(json.dumps({k: result[k] for k in ["arm", "use_gamma", "n_measured_val", "mse", "mae", "pearson", "spearman"]}, indent=2))
165
+ return 0
166
+
167
+
168
+ if __name__ == "__main__":
169
+ raise SystemExit(main())