mattbitzesty commited on
Commit
1289050
·
verified ·
1 Parent(s): b8be6fc

Upload scripts/evaluate_drydown_physics.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/evaluate_drydown_physics.py +169 -0
scripts/evaluate_drydown_physics.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IDEA 3: does the PIMT transformer itself exploit the physics channel to predict
2
+ the time-evolved (pyramid) descriptor profile?
3
+
4
+ Idea 2 showed (with GBM/linear probes on hand-built features) that the physics
5
+ trajectory DOUBLES explained variance on the drydown profile. This evaluator
6
+ tests the same claim end-to-end in the trained model: for each held-out formula,
7
+ run the objective head with the REAL physics tensor vs a ZEROED physics tensor
8
+ (physics-off ablation at inference), and score the predicted 3-tier pyramid
9
+ against the stored pyramid target -- per tier (top/mid/base) and overall.
10
+
11
+ If physics carries non-redundant signal for the time-evolved profile, physics-on
12
+ should beat physics-off, with the largest gain on the BASE tier (drydown).
13
+
14
+ Metric: per-descriptor binary cross-entropy (the training objective) and mean
15
+ cosine similarity between predicted and target tier profiles. Lower BCE / higher
16
+ cosine with physics-on than physics-off = physics helps.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import json
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+ import torch
26
+
27
+ from pino.heads import PIMTHeads
28
+ from pino.pimt_model import (
29
+ FragranceTrajectoryDataset,
30
+ PhysicsInformedMixtureTransformer,
31
+ objective_targets_to_pyramid,
32
+ )
33
+ from pino.upload_data import create_molecule_disjoint_split_from_records
34
+
35
+
36
+ def load_model(ckpt_path: Path, objective_dim: int):
37
+ sd = torch.load(ckpt_path, map_location="cpu", weights_only=False)
38
+ state = sd.get("model_state_dict", sd.get("model", sd))
39
+ heads_state = sd.get("heads_state_dict", sd.get("heads", {}))
40
+ state_dim = int(state["gating.physics_scaler"].shape[0])
41
+ embedding_dim = int(state["input_proj.weight"].shape[1])
42
+ hidden_dim = int(state["input_proj.weight"].shape[0])
43
+ num_layers = sum(1 for k in state if k.endswith("self_attn.in_proj_weight"))
44
+ model = PhysicsInformedMixtureTransformer(
45
+ embedding_dim=embedding_dim, state_dim=state_dim,
46
+ hidden_dim=hidden_dim, num_heads=4, num_layers=max(num_layers, 1),
47
+ )
48
+ model.load_state_dict(state, strict=False)
49
+ heads = PIMTHeads(hidden_dim=hidden_dim, objective_dim=objective_dim)
50
+ if heads_state:
51
+ heads.load_state_dict(heads_state, strict=False)
52
+ model.eval(); heads.eval()
53
+ return model, heads, {"embedding_dim": embedding_dim, "state_dim": state_dim,
54
+ "hidden_dim": hidden_dim, "num_layers": num_layers}
55
+
56
+
57
+ def tier_cosine(pred, targ):
58
+ # pred/targ: (3, 138); cosine per tier
59
+ out = []
60
+ for t in range(3):
61
+ a = pred[t]; b = targ[t]
62
+ na = np.linalg.norm(a); nb = np.linalg.norm(b)
63
+ out.append(float(np.dot(a, b) / (na * nb)) if na > 0 and nb > 0 else 0.0)
64
+ return out # [top, mid, base]
65
+
66
+
67
+ def main() -> int:
68
+ ap = argparse.ArgumentParser()
69
+ ap.add_argument("--checkpoint", required=True)
70
+ ap.add_argument("--data", required=True)
71
+ ap.add_argument("--structural-source", default="morgan")
72
+ ap.add_argument("--train-ratio", type=float, default=0.85)
73
+ ap.add_argument("--seed", type=int, default=42)
74
+ ap.add_argument("--split", choices=["molecule", "formula"], default="formula")
75
+ ap.add_argument("--arm-label", default=None)
76
+ ap.add_argument("--use-gamma", action="store_true")
77
+ ap.add_argument("--max-eval", type=int, default=400)
78
+ ap.add_argument("--output", required=True)
79
+ args = ap.parse_args()
80
+
81
+ objective_dim = 575 if args.structural_source == "pom_alltags" else 138
82
+ engine_source = "openpom_256" if args.structural_source == "pom_alltags" else args.structural_source
83
+ model, heads, dims = load_model(Path(args.checkpoint), objective_dim)
84
+ state_dim = dims["state_dim"]
85
+
86
+ with open(args.data) as f:
87
+ all_records = [json.loads(line) for line in f if line.strip()]
88
+
89
+ if args.split == "molecule":
90
+ split = create_molecule_disjoint_split_from_records(all_records, train_ratio=args.train_ratio, seed=args.seed)
91
+ val_records = split["validation"]
92
+ else:
93
+ rng = np.random.default_rng(args.seed)
94
+ n = len(all_records)
95
+ n_val = max(1, int(round(n * (1.0 - args.train_ratio))))
96
+ perm = rng.permutation(n)
97
+ val_records = [all_records[i] for i in sorted(set(perm[:n_val].tolist()))]
98
+
99
+ # restrict to blends with a real trajectory + pyramid target
100
+ blends = [r for r in val_records if not r.get("is_control") and len(r.get("formula", [])) >= 3
101
+ and r.get("objective_targets") and len(r.get("trajectory", [])) > 1]
102
+ blends = blends[: args.max_eval]
103
+ ds = FragranceTrajectoryDataset(records=blends, use_embedding_fallback=True,
104
+ structural_source=engine_source, objective_dim=objective_dim,
105
+ use_gamma=args.use_gamma)
106
+ device = "cuda" if torch.cuda.is_available() else "cpu"
107
+ model.to(device); heads.to(device)
108
+
109
+ bce_on, bce_off = [], []
110
+ cos_on = np.zeros(3); cos_off = np.zeros(3)
111
+ used = 0
112
+ bce = torch.nn.functional.binary_cross_entropy
113
+ with torch.no_grad():
114
+ for i in range(len(ds)):
115
+ item = ds[i]
116
+ tokens = item["tokens"].unsqueeze(0).to(device)
117
+ physics = item["physics"].unsqueeze(0).to(device)
118
+ if physics.size(-1) != state_dim:
119
+ if physics.size(-1) < state_dim:
120
+ pad = torch.zeros(1, physics.size(1), physics.size(2), state_dim - physics.size(-1), device=device)
121
+ physics = torch.cat([physics, pad], dim=-1)
122
+ else:
123
+ physics = physics[..., :state_dim]
124
+ # mask: all real tokens present in a single (unpadded) item
125
+ S = tokens.size(1)
126
+ mask = torch.zeros(1, S, dtype=torch.bool, device=device)
127
+ # target_obj is already the (3,138) pyramid for this dataset
128
+ target = item["target_obj"].clamp(0.0, 1.0).to(device) # (3,138)
129
+
130
+ # physics ON
131
+ lat_on = model(tokens, physics)
132
+ pyr_on = heads(lat_on, physics, mask)["objective"][0] # (3,138)
133
+ # physics OFF (zeroed)
134
+ phys_zero = torch.zeros_like(physics)
135
+ lat_off = model(tokens, phys_zero)
136
+ pyr_off = heads(lat_off, phys_zero, mask)["objective"][0]
137
+
138
+ bce_on.append(float(bce(pyr_on, target).cpu()))
139
+ bce_off.append(float(bce(pyr_off, target).cpu()))
140
+ c_on = tier_cosine(pyr_on.cpu().numpy(), target.cpu().numpy())
141
+ c_off = tier_cosine(pyr_off.cpu().numpy(), target.cpu().numpy())
142
+ cos_on += np.array(c_on); cos_off += np.array(c_off)
143
+ used += 1
144
+
145
+ cos_on /= max(used, 1); cos_off /= max(used, 1)
146
+ result = {
147
+ "arm": args.arm_label or Path(args.checkpoint).stem,
148
+ "use_gamma": bool(args.use_gamma), "seed": args.seed, "model_dims": dims,
149
+ "task": "3-tier descriptor pyramid (top/mid/base); physics-on vs physics-off inference ablation",
150
+ "n_eval": used,
151
+ "bce_physics_on": float(np.mean(bce_on)),
152
+ "bce_physics_off": float(np.mean(bce_off)),
153
+ "bce_delta_off_minus_on": float(np.mean(bce_off) - np.mean(bce_on)),
154
+ "cosine_top_on": float(cos_on[0]), "cosine_mid_on": float(cos_on[1]), "cosine_base_on": float(cos_on[2]),
155
+ "cosine_top_off": float(cos_off[0]), "cosine_mid_off": float(cos_off[1]), "cosine_base_off": float(cos_off[2]),
156
+ "cosine_base_delta_on_minus_off": float(cos_on[2] - cos_off[2]),
157
+ "cosine_mean_on": float(cos_on.mean()), "cosine_mean_off": float(cos_off.mean()),
158
+ "verdict": ("physics helps (on beats off)" if np.mean(bce_on) < np.mean(bce_off) else "physics does not help"),
159
+ }
160
+ out = Path(args.output); out.parent.mkdir(parents=True, exist_ok=True)
161
+ out.write_text(json.dumps(result, indent=2))
162
+ print(json.dumps({k: result[k] for k in ["arm", "n_eval", "bce_physics_on", "bce_physics_off",
163
+ "bce_delta_off_minus_on", "cosine_base_on", "cosine_base_off",
164
+ "cosine_base_delta_on_minus_off", "verdict"]}, indent=2))
165
+ return 0
166
+
167
+
168
+ if __name__ == "__main__":
169
+ raise SystemExit(main())