mattbitzesty commited on
Commit
0884300
·
unverified ·
1 Parent(s): 4d413c0

feat(artifacts): add paper artifact generator with validation metrics and UMAP POM figure

Browse files

- scripts/generate_paper_artifacts.py: downloads checkpoint, runs validation pass,
extracts latent vectors for registry compounds, computes chiral pair distances,
and renders UMAP Principal Odor Map colored by boiling point.
- Adds matplotlib and umap-learn to project dependencies.

pyproject.toml CHANGED
@@ -19,6 +19,8 @@ dependencies = [
19
  "huggingface-hub>=0.24",
20
  "datasets>=2.20",
21
  "tensorboard>=2.15",
 
 
22
  ]
23
 
24
  [project.optional-dependencies]
 
19
  "huggingface-hub>=0.24",
20
  "datasets>=2.20",
21
  "tensorboard>=2.15",
22
+ "matplotlib>=3.8",
23
+ "umap-learn>=0.5",
24
  ]
25
 
26
  [project.optional-dependencies]
scripts/generate_paper_artifacts.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate paper-ready latent-space artifacts from a trained PINO checkpoint.
2
+
3
+ This script downloads the trained checkpoint and empirical dataset from the Hugging
4
+ Face Hub, runs the validation partition through the model to log final metrics,
5
+ extracts latent embeddings for every compound in the SQLite AromaRegistry, computes
6
+ geometric separation metrics for classic chiral enantiomer pairs, and renders a
7
+ UMAP-based Principal Odor Map figure.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import matplotlib.pyplot as plt
19
+ import numpy as np
20
+ import torch
21
+ import umap
22
+ from huggingface_hub import hf_hub_download, snapshot_download
23
+ from torch.utils.data import DataLoader
24
+
25
+ from pino.embeddings import OlfactoryEmbeddingEngine
26
+ from pino.heads import PIMTHeads
27
+ from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
28
+ from pino.registry import AromaRegistry
29
+ from pino.thermo.losses import AdaptiveLossBalancer
30
+ from pino.train import pad_trajectory_collate
31
+
32
+
33
+
34
+ def _get_hf_token() -> str | None:
35
+ return os.environ.get("HF_TOKEN")
36
+
37
+
38
+ def load_checkpoint_dir(checkpoint_dir: str, local_root: Path = Path("models")) -> Path:
39
+ """Resolve a checkpoint path, downloading from HF Hub if it is a repo ID."""
40
+ local_path = Path(checkpoint_dir)
41
+ if local_path.exists() and local_path.is_dir():
42
+ return local_path
43
+
44
+ print(f"📥 Downloading checkpoint from Hugging Face Hub: {checkpoint_dir}")
45
+ local_root.mkdir(parents=True, exist_ok=True)
46
+ downloaded = snapshot_download(
47
+ repo_id=checkpoint_dir,
48
+ local_dir=str(local_root),
49
+ token=_get_hf_token(),
50
+ )
51
+ return Path(downloaded)
52
+
53
+
54
+ def download_dataset(local_path: Path = Path("data/empirical_dataset_v1.jsonl")) -> Path:
55
+ """Download the empirical dataset from the canonical dataset repo if missing locally."""
56
+ if local_path.exists():
57
+ return local_path
58
+ token = _get_hf_token()
59
+ if not token:
60
+ raise RuntimeError("Dataset not found locally and HF_TOKEN is not set")
61
+ print(f"📥 Downloading empirical dataset from Hugging Face Hub...")
62
+ local_path.parent.mkdir(parents=True, exist_ok=True)
63
+ downloaded = hf_hub_download(
64
+ repo_id="mattbitzesty/pino-synthetic-dataset",
65
+ filename="empirical_dataset_v1.jsonl",
66
+ repo_type="dataset",
67
+ token=token,
68
+ local_dir=str(local_path.parent),
69
+ )
70
+ return Path(downloaded)
71
+
72
+
73
+ def build_validation_loader(
74
+ data_path: Path,
75
+ batch_size: int = 8,
76
+ workers: int = 0,
77
+ ) -> tuple[DataLoader, list[dict[str, Any]]]:
78
+ """Load the empirical dataset and build a validation-only DataLoader."""
79
+ from pino.upload_data import create_molecule_disjoint_split
80
+
81
+ with open(data_path) as f:
82
+ all_records = [json.loads(line) for line in f]
83
+
84
+ control_records = [r for r in all_records if r.get("is_control", False)]
85
+ mixture_records = [r for r in all_records if not r.get("is_control", False)]
86
+
87
+ split = create_molecule_disjoint_split(data_path, train_ratio=0.8, seed=42)
88
+ val_records = list(split["validation"]) + control_records # controls for reference only
89
+
90
+ genre_map = {
91
+ "citrus_cologne": 0,
92
+ "fougere": 1,
93
+ "floral_woody": 2,
94
+ "amber_oriental": 3,
95
+ "wildcard": 4,
96
+ }
97
+
98
+ val_dataset = FragranceTrajectoryDataset(
99
+ records=val_records,
100
+ use_embedding_fallback=True,
101
+ genre_map=genre_map,
102
+ )
103
+ val_loader = DataLoader(
104
+ val_dataset,
105
+ batch_size=batch_size,
106
+ shuffle=False,
107
+ num_workers=workers,
108
+ collate_fn=pad_trajectory_collate,
109
+ )
110
+ return val_loader, val_records
111
+
112
+
113
+ @torch.no_grad()
114
+ def validate(
115
+ model: PhysicsInformedMixtureTransformer,
116
+ heads: PIMTHeads,
117
+ val_loader: DataLoader,
118
+ device: torch.device,
119
+ loss_balancer: AdaptiveLossBalancer,
120
+ ) -> dict[str, float]:
121
+ """Run one validation pass and return aggregated loss metrics."""
122
+ model.eval()
123
+ heads.eval()
124
+
125
+ total_loss = 0.0
126
+ totals = {"obj": 0.0, "season": 0.0, "wear": 0.0, "alignment": 0.0}
127
+ count = 0
128
+
129
+ for batch in val_loader:
130
+ tokens = batch["tokens"].to(device)
131
+ physics = batch["physics"].to(device)
132
+ src_key_padding_mask = batch["src_key_padding_mask"].to(device)
133
+ target_obj = batch["target_obj"].to(device)
134
+ target_sub = {
135
+ "seasonality": batch["target_sub_seasonality"].to(device),
136
+ "gender_profile": batch["target_sub_gender"].to(device),
137
+ "wearability": batch["target_sub_wearability"].to(device),
138
+ }
139
+
140
+ latent = model(tokens, physics, src_key_padding_mask)
141
+ pred = heads(latent)
142
+
143
+ obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
144
+ obj_loss = torch.nn.functional.mse_loss(pred["objective"], target_obj, reduction="none")
145
+ obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
146
+
147
+ season_loss = torch.nn.functional.cross_entropy(
148
+ pred["subjective"]["seasonality"], target_sub["seasonality"].argmax(dim=-1)
149
+ )
150
+ gender_loss = torch.nn.functional.mse_loss(
151
+ pred["subjective"]["gender_profile"].squeeze(-1), target_sub["gender_profile"]
152
+ )
153
+ wear_loss = torch.nn.functional.binary_cross_entropy_with_logits(
154
+ pred["subjective"]["wearability"], target_sub["wearability"]
155
+ )
156
+ wear_loss = wear_loss + gender_loss
157
+
158
+ alignment_loss = 1.0 - torch.nn.functional.cosine_similarity(
159
+ pred["alignment"], target_obj.mean(dim=1), dim=-1
160
+ ).mean()
161
+
162
+ loss_payload = {
163
+ "obj": obj_loss,
164
+ "season": season_loss,
165
+ "wear": wear_loss,
166
+ "alignment": alignment_loss,
167
+ }
168
+ total = loss_balancer(loss_payload)
169
+
170
+ total_loss += total.item()
171
+ for k in totals:
172
+ totals[k] += loss_payload[k].item()
173
+ count += 1
174
+
175
+ return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
176
+
177
+
178
+ def print_validation_metrics(metrics: dict[str, float]) -> None:
179
+ """Print validation metrics in a paper-ready format."""
180
+ print("\n📊 Final Validation Metrics (Validation Partition)")
181
+ print(" " + "-" * 42)
182
+ print(f" {'Total Loss:':<25} {metrics['total']:.4f}")
183
+ print(f" {'Objective VLE Loss:':<25} {metrics['obj']:.4f}")
184
+ print(f" {'Seasonality Loss:':<25} {metrics['season']:.4f}")
185
+ print(f" {'Wearability Loss:':<25} {metrics['wear']:.4f}")
186
+ print(f" {'Alignment Loss:':<25} {metrics['alignment']:.4f}")
187
+ print(" " + "-" * 42)
188
+
189
+
190
+ def extract_latent_vectors(
191
+ model: PhysicsInformedMixtureTransformer,
192
+ engine: OlfactoryEmbeddingEngine,
193
+ chemicals: list[dict[str, Any]],
194
+ device: torch.device,
195
+ state_dim: int = 2,
196
+ ) -> tuple[np.ndarray, list[dict[str, Any]], list[float]]:
197
+ """Run the trained backbone over every registry compound and return latent vectors."""
198
+ latent_vectors: list[np.ndarray] = []
199
+ metadata_labels: list[dict[str, Any]] = []
200
+ color_values: list[float] = []
201
+
202
+ model.eval()
203
+ with torch.no_grad():
204
+ for chem in chemicals:
205
+ cas = chem["cas"]
206
+ smiles = chem.get("smiles", "")
207
+
208
+ input_token = engine.get_embedding(smiles, cas=cas)
209
+ token_tensor = torch.from_numpy(input_token).float().unsqueeze(0).unsqueeze(0).to(device)
210
+ # Single token, single timestep, dummy physical state.
211
+ states = torch.zeros(1, 1, 1, state_dim, dtype=torch.float32, device=device)
212
+
213
+ outputs = model(token_tensor, states)
214
+ latent_vec = outputs.squeeze().cpu().numpy()
215
+ if latent_vec.ndim > 1:
216
+ latent_vec = latent_vec.mean(axis=tuple(range(latent_vec.ndim - 1)))
217
+
218
+ latent_vectors.append(latent_vec)
219
+ metadata_labels.append(chem)
220
+ bp = chem.get("boiling_point_k") or 400.0
221
+ color_values.append(float(bp))
222
+
223
+ return np.array(latent_vectors), metadata_labels, color_values
224
+
225
+
226
+ def analyze_chiral_pairs(
227
+ latent_matrix: np.ndarray,
228
+ metadata_labels: list[dict[str, Any]],
229
+ chiral_pairs: dict[str, tuple[str, str]],
230
+ ) -> None:
231
+ """Print Euclidean and cosine metrics for key enantiomer pairs."""
232
+ cas_to_idx = {c["cas"]: i for i, c in enumerate(metadata_labels)}
233
+
234
+ print("\n🔬 Analyzing Chiral Separation Hemispheres...")
235
+ for label, (cas_r, cas_s) in chiral_pairs.items():
236
+ idx_r = cas_to_idx.get(cas_r)
237
+ idx_s = cas_to_idx.get(cas_s)
238
+
239
+ if idx_r is not None and idx_s is not None:
240
+ vec_r = latent_matrix[idx_r]
241
+ vec_s = latent_matrix[idx_s]
242
+
243
+ euclidean_dist = np.linalg.norm(vec_r - vec_s)
244
+ cosine_sim = np.dot(vec_r, vec_s) / (
245
+ np.linalg.norm(vec_r) * np.linalg.norm(vec_s) + 1e-9
246
+ )
247
+
248
+ print(f" - {label}:")
249
+ print(f" * Euclidean Distance: {euclidean_dist:.4f}")
250
+ print(f" * Cosine Similarity: {cosine_sim:.4f}")
251
+ else:
252
+ print(f" - ⚠️ Missing active registry nodes to evaluate chiral path for {label}")
253
+
254
+
255
+ def plot_umap(
256
+ latent_matrix: np.ndarray,
257
+ metadata_labels: list[dict[str, Any]],
258
+ color_values: list[float],
259
+ chiral_pairs: dict[str, tuple[str, str]],
260
+ output_path: Path,
261
+ ) -> None:
262
+ """Project latent vectors to 2D with UMAP and render the Principal Odor Map."""
263
+ print("\n🎨 Computing 2D UMAP projection embeddings for the map visualization...")
264
+ reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, metric="cosine", random_state=42)
265
+ embedding_2d = reducer.fit_transform(latent_matrix)
266
+
267
+ plt.figure(figsize=(10, 8), dpi=300)
268
+ scatter = plt.scatter(
269
+ embedding_2d[:, 0],
270
+ embedding_2d[:, 1],
271
+ c=color_values,
272
+ cmap="viridis",
273
+ s=25,
274
+ alpha=0.8,
275
+ edgecolors="none",
276
+ )
277
+
278
+ cbar = plt.colorbar(scatter)
279
+ cbar.set_label("Boiling Point (Kelvin) — Volatility Indicator", fontsize=12)
280
+
281
+ plt.title(
282
+ "PINO Principal Odor Map (POM) Latent Embedding Space",
283
+ fontsize=14,
284
+ fontweight="bold",
285
+ pad=15,
286
+ )
287
+ plt.xlabel("UMAP Coordinate 1", fontsize=11)
288
+ plt.ylabel("UMAP Coordinate 2", fontsize=11)
289
+ plt.grid(True, linestyle="--", alpha=0.3)
290
+
291
+ cas_to_idx = {c["cas"]: i for i, c in enumerate(metadata_labels)}
292
+ for label, (cas_r, cas_s) in chiral_pairs.items():
293
+ short_name = label.split()[0]
294
+ for cas, marker_text in [(cas_r, "R"), (cas_s, "S")]:
295
+ idx = cas_to_idx.get(cas)
296
+ if idx is not None:
297
+ plt.annotate(
298
+ f"{marker_text}-{short_name}",
299
+ (embedding_2d[idx, 0], embedding_2d[idx, 1]),
300
+ textcoords="offset points",
301
+ xytext=(0, 10),
302
+ ha="center",
303
+ fontsize=8,
304
+ fontweight="bold",
305
+ arrowprops=dict(arrowstyle="->", color="black", lw=0.5),
306
+ )
307
+
308
+ output_path.parent.mkdir(parents=True, exist_ok=True)
309
+ plt.savefig(output_path, bbox_inches="tight")
310
+ plt.close()
311
+ print(f"✅ Success: Publication-ready latent cluster map exported to {output_path}")
312
+
313
+
314
+ def generate_paper_artifacts(
315
+ checkpoint_dir: str,
316
+ output_image_path: str | Path,
317
+ data_path: str | Path | None = None,
318
+ batch_size: int = 8,
319
+ ) -> None:
320
+ output_image_path = Path(output_image_path)
321
+ print("⏳ Connecting to canonical SQLite registry and loading checkpoint...")
322
+
323
+ registry = AromaRegistry()
324
+ all_chemicals = list(registry.all_records().values())
325
+ valid_chemicals = [
326
+ c for c in all_chemicals
327
+ if c.get("openpom_embedding") and len(c.get("openpom_embedding", [])) > 0
328
+ ]
329
+
330
+ checkpoint_path = load_checkpoint_dir(checkpoint_dir)
331
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
332
+
333
+ model = PhysicsInformedMixtureTransformer(
334
+ embedding_dim=145,
335
+ state_dim=2,
336
+ hidden_dim=256,
337
+ num_heads=4,
338
+ num_layers=4,
339
+ ).to(device)
340
+ heads = PIMTHeads(hidden_dim=256, objective_dim=138).to(device)
341
+ loss_balancer = AdaptiveLossBalancer(num_tasks=4).to(device)
342
+
343
+ for checkpoint_name in ("pimt_v1.pt", "pytorch_model.bin", "model.pt"):
344
+ candidate = checkpoint_path / checkpoint_name
345
+ if candidate.exists():
346
+ checkpoint = torch.load(candidate, map_location=device)
347
+ model.load_state_dict(checkpoint.get("model_state_dict", checkpoint), strict=False)
348
+ heads.load_state_dict(checkpoint.get("heads_state_dict", {}), strict=False)
349
+ print(f"✅ Weights loaded successfully from {candidate}.")
350
+ break
351
+ else:
352
+ print(f"⚠️ No checkpoint file found in {checkpoint_path}. Running with raw backbone.")
353
+
354
+ if data_path is not None:
355
+ data_path = Path(data_path)
356
+ data_path = download_dataset(data_path)
357
+ val_loader, val_records = build_validation_loader(data_path, batch_size=batch_size)
358
+ metrics = validate(model, heads, val_loader, device, loss_balancer)
359
+ print_validation_metrics(metrics)
360
+
361
+ engine = OlfactoryEmbeddingEngine()
362
+
363
+ print(f"\n🧬 Extracting model hidden layer representations for {len(valid_chemicals)} compounds...")
364
+ latent_matrix, metadata_labels, color_values = extract_latent_vectors(
365
+ model, engine, valid_chemicals, device
366
+ )
367
+
368
+ chiral_pairs = {
369
+ "Limonene Enantiomers (Oranges vs Lemons)": ("5989-27-5", "5989-54-8"),
370
+ "Carvone Enantiomers (Spearmint vs Caraway)": ("6485-40-1", "2244-16-8"),
371
+ }
372
+
373
+ analyze_chiral_pairs(latent_matrix, metadata_labels, chiral_pairs)
374
+ plot_umap(latent_matrix, metadata_labels, color_values, chiral_pairs, output_image_path)
375
+
376
+
377
+ if __name__ == "__main__":
378
+ parser = argparse.ArgumentParser(description="Generate PINO paper artifacts and metrics")
379
+ parser.add_argument(
380
+ "--checkpoint-dir",
381
+ default="mattbitzesty/pino-pimt-checkpoint",
382
+ help="Local path or HF Hub repo ID for the trained checkpoint",
383
+ )
384
+ parser.add_argument(
385
+ "--output-image",
386
+ default="reports/figures/latent_space_umap.png",
387
+ help="Output path for the UMAP figure",
388
+ )
389
+ parser.add_argument(
390
+ "--dataset",
391
+ default="data/empirical_dataset_v1.jsonl",
392
+ help="Path to the empirical dataset JSONL",
393
+ )
394
+ parser.add_argument(
395
+ "--batch-size",
396
+ type=int,
397
+ default=8,
398
+ help="Batch size for validation metric collection",
399
+ )
400
+ args = parser.parse_args()
401
+ generate_paper_artifacts(
402
+ args.checkpoint_dir,
403
+ args.output_image,
404
+ data_path=args.dataset,
405
+ batch_size=args.batch_size,
406
+ )