Download scripts/generate_paper_artifacts.py from mattbitzesty/pino-source-code: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/mattbitzesty/pino-source-code/resolve/ca7335cf129a10dadc60e243c8a6c196cbf48345/scripts/generate_paper_artifacts.py
- Command line
-
hf download hf://mattbitzesty/pino-source-code@ca7335cf129a10dadc60e243c8a6c196cbf48345/scripts/generate_paper_artifacts.py
-
curl -L -o generate_paper_artifacts.py https://huggingface.co/mattbitzesty/pino-source-code/resolve/ca7335cf129a10dadc60e243c8a6c196cbf48345/scripts/generate_paper_artifacts.py
14.6 kB
| """Generate paper-ready latent-space artifacts from a trained PINO checkpoint. | |
| This script downloads the trained checkpoint and empirical dataset from the Hugging | |
| Face Hub, runs the validation partition through the model to log final metrics, | |
| extracts latent embeddings for every compound in the SQLite AromaRegistry, computes | |
| geometric separation metrics for classic chiral enantiomer pairs, and renders a | |
| UMAP-based Principal Odor Map figure. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| from typing import Any | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import torch | |
| import umap | |
| from huggingface_hub import hf_hub_download, snapshot_download | |
| from torch.utils.data import DataLoader | |
| from pino.embeddings import OlfactoryEmbeddingEngine | |
| from pino.heads import PIMTHeads | |
| from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer, DEFAULT_EMBEDDING_DIM | |
| from pino.registry import AromaRegistry | |
| from pino.thermo.losses import AdaptiveLossBalancer | |
| from pino.train import pad_trajectory_collate | |
| def _get_hf_token() -> str | None: | |
| return os.environ.get("HF_TOKEN") | |
| def load_checkpoint_dir(checkpoint_dir: str, local_root: Path = Path("models")) -> Path: | |
| """Resolve a checkpoint path, downloading from HF Hub if it is a repo ID.""" | |
| local_path = Path(checkpoint_dir) | |
| if local_path.exists() and local_path.is_dir(): | |
| return local_path | |
| print(f"📥 Downloading checkpoint from Hugging Face Hub: {checkpoint_dir}") | |
| local_root.mkdir(parents=True, exist_ok=True) | |
| downloaded = snapshot_download( | |
| repo_id=checkpoint_dir, | |
| local_dir=str(local_root), | |
| token=_get_hf_token(), | |
| ) | |
| return Path(downloaded) | |
| def download_dataset(local_path: Path = Path("data/empirical_dataset_v1.jsonl")) -> Path: | |
| """Download the empirical dataset from the canonical dataset repo if missing locally.""" | |
| if local_path.exists(): | |
| return local_path | |
| token = _get_hf_token() | |
| if not token: | |
| raise RuntimeError("Dataset not found locally and HF_TOKEN is not set") | |
| print(f"📥 Downloading empirical dataset from Hugging Face Hub...") | |
| local_path.parent.mkdir(parents=True, exist_ok=True) | |
| downloaded = hf_hub_download( | |
| repo_id="mattbitzesty/pino-synthetic-dataset", | |
| filename="empirical_dataset_v1.jsonl", | |
| repo_type="dataset", | |
| token=token, | |
| local_dir=str(local_path.parent), | |
| ) | |
| return Path(downloaded) | |
| def build_validation_loader( | |
| data_path: Path, | |
| batch_size: int = 8, | |
| workers: int = 0, | |
| ) -> tuple[DataLoader, list[dict[str, Any]]]: | |
| """Load the empirical dataset and build a validation-only DataLoader.""" | |
| from pino.upload_data import DEFAULT_TRAIN_RATIO, create_molecule_disjoint_split | |
| split = create_molecule_disjoint_split(data_path, train_ratio=DEFAULT_TRAIN_RATIO, seed=42) | |
| val_records = list(split["validation"]) | |
| genre_map = { | |
| "citrus_cologne": 0, | |
| "fougere": 1, | |
| "floral_woody": 2, | |
| "amber_oriental": 3, | |
| "wildcard": 4, | |
| } | |
| val_dataset = FragranceTrajectoryDataset( | |
| records=val_records, | |
| use_embedding_fallback=True, | |
| genre_map=genre_map, | |
| ) | |
| val_loader = DataLoader( | |
| val_dataset, | |
| batch_size=batch_size, | |
| shuffle=False, | |
| num_workers=workers, | |
| collate_fn=pad_trajectory_collate, | |
| ) | |
| return val_loader, val_records | |
| def validate( | |
| model: PhysicsInformedMixtureTransformer, | |
| heads: PIMTHeads, | |
| val_loader: DataLoader, | |
| device: torch.device, | |
| loss_balancer: AdaptiveLossBalancer, | |
| ) -> dict[str, float]: | |
| """Run one validation pass and return aggregated loss metrics.""" | |
| model.eval() | |
| heads.eval() | |
| total_loss = 0.0 | |
| totals = {"obj": 0.0, "season": 0.0, "wear": 0.0, "alignment": 0.0} | |
| count = 0 | |
| for batch in val_loader: | |
| tokens = batch["tokens"].to(device) | |
| physics = batch["physics"].to(device) | |
| src_key_padding_mask = batch["src_key_padding_mask"].to(device) | |
| target_obj = batch["target_obj"].to(device) | |
| target_sub = { | |
| "seasonality": batch["target_sub_seasonality"].to(device), | |
| "gender_profile": batch["target_sub_gender"].to(device), | |
| "wearability": batch["target_sub_wearability"].to(device), | |
| } | |
| latent = model(tokens, physics, src_key_padding_mask) | |
| pred = heads(latent) | |
| obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1) | |
| obj_loss = torch.nn.functional.mse_loss(pred["objective"], target_obj, reduction="none") | |
| obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0) | |
| season_loss = torch.nn.functional.cross_entropy( | |
| pred["subjective"]["seasonality"], target_sub["seasonality"].argmax(dim=-1) | |
| ) | |
| gender_loss = torch.nn.functional.mse_loss( | |
| pred["subjective"]["gender_profile"].squeeze(-1), target_sub["gender_profile"] | |
| ) | |
| wear_loss = torch.nn.functional.binary_cross_entropy_with_logits( | |
| pred["subjective"]["wearability"], target_sub["wearability"] | |
| ) | |
| wear_loss = wear_loss + gender_loss | |
| alignment_loss = 1.0 - torch.nn.functional.cosine_similarity( | |
| pred["alignment"], target_obj.mean(dim=1), dim=-1 | |
| ).mean() | |
| loss_payload = { | |
| "obj": obj_loss, | |
| "season": season_loss, | |
| "wear": wear_loss, | |
| "alignment": alignment_loss, | |
| } | |
| total = loss_balancer(loss_payload) | |
| total_loss += total.item() | |
| for k in totals: | |
| totals[k] += loss_payload[k].item() | |
| count += 1 | |
| return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()} | |
| def print_validation_metrics(metrics: dict[str, float]) -> None: | |
| """Print validation metrics in a paper-ready format.""" | |
| print("\n📊 Final Validation Metrics (Validation Partition)") | |
| print(" " + "-" * 42) | |
| print(f" {'Total Loss:':<25} {metrics['total']:.4f}") | |
| print(f" {'Objective VLE Loss:':<25} {metrics['obj']:.4f}") | |
| print(f" {'Seasonality Loss:':<25} {metrics['season']:.4f}") | |
| print(f" {'Wearability Loss:':<25} {metrics['wear']:.4f}") | |
| print(f" {'Alignment Loss:':<25} {metrics['alignment']:.4f}") | |
| print(" " + "-" * 42) | |
| def extract_latent_vectors( | |
| model: PhysicsInformedMixtureTransformer, | |
| engine: OlfactoryEmbeddingEngine, | |
| chemicals: list[dict[str, Any]], | |
| device: torch.device, | |
| state_dim: int = 2, | |
| ) -> tuple[np.ndarray, list[dict[str, Any]], list[float]]: | |
| """Run the trained backbone over every registry compound and return latent vectors.""" | |
| latent_vectors: list[np.ndarray] = [] | |
| metadata_labels: list[dict[str, Any]] = [] | |
| color_values: list[float] = [] | |
| model.eval() | |
| with torch.no_grad(): | |
| for chem in chemicals: | |
| cas = chem["cas"] | |
| smiles = chem.get("smiles", "") | |
| input_token = engine.get_embedding(smiles, cas=cas) | |
| token_tensor = torch.from_numpy(input_token).float().unsqueeze(0).unsqueeze(0).to(device) | |
| # Single token, single timestep, dummy physical state. | |
| states = torch.zeros(1, 1, 1, state_dim, dtype=torch.float32, device=device) | |
| outputs = model(token_tensor, states) | |
| latent_vec = outputs.squeeze().cpu().numpy() | |
| if latent_vec.ndim > 1: | |
| latent_vec = latent_vec.mean(axis=tuple(range(latent_vec.ndim - 1))) | |
| latent_vectors.append(latent_vec) | |
| metadata_labels.append(chem) | |
| bp = chem.get("boiling_point_k") or 400.0 | |
| color_values.append(float(bp)) | |
| return np.array(latent_vectors), metadata_labels, color_values | |
| def analyze_chiral_pairs( | |
| latent_matrix: np.ndarray, | |
| metadata_labels: list[dict[str, Any]], | |
| chiral_pairs: dict[str, tuple[str, str]], | |
| ) -> None: | |
| """Print Euclidean and cosine metrics for key enantiomer pairs.""" | |
| cas_to_idx = {c["cas"]: i for i, c in enumerate(metadata_labels)} | |
| print("\n🔬 Analyzing Chiral Separation Hemispheres...") | |
| for label, (cas_r, cas_s) in chiral_pairs.items(): | |
| idx_r = cas_to_idx.get(cas_r) | |
| idx_s = cas_to_idx.get(cas_s) | |
| if idx_r is not None and idx_s is not None: | |
| vec_r = latent_matrix[idx_r] | |
| vec_s = latent_matrix[idx_s] | |
| euclidean_dist = np.linalg.norm(vec_r - vec_s) | |
| cosine_sim = np.dot(vec_r, vec_s) / ( | |
| np.linalg.norm(vec_r) * np.linalg.norm(vec_s) + 1e-9 | |
| ) | |
| print(f" - {label}:") | |
| print(f" * Euclidean Distance: {euclidean_dist:.4f}") | |
| print(f" * Cosine Similarity: {cosine_sim:.4f}") | |
| else: | |
| print(f" - ⚠️ Missing active registry nodes to evaluate chiral path for {label}") | |
| def plot_umap( | |
| latent_matrix: np.ndarray, | |
| metadata_labels: list[dict[str, Any]], | |
| color_values: list[float], | |
| chiral_pairs: dict[str, tuple[str, str]], | |
| output_path: Path, | |
| ) -> None: | |
| """Project latent vectors to 2D with UMAP and render the Principal Odor Map.""" | |
| print("\n🎨 Computing 2D UMAP projection embeddings for the map visualization...") | |
| reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, metric="cosine", random_state=42) | |
| embedding_2d = reducer.fit_transform(latent_matrix) | |
| plt.figure(figsize=(10, 8), dpi=300) | |
| scatter = plt.scatter( | |
| embedding_2d[:, 0], | |
| embedding_2d[:, 1], | |
| c=color_values, | |
| cmap="viridis", | |
| s=25, | |
| alpha=0.8, | |
| edgecolors="none", | |
| ) | |
| cbar = plt.colorbar(scatter) | |
| cbar.set_label("Boiling Point (Kelvin) — Volatility Indicator", fontsize=12) | |
| plt.title( | |
| "PINO Principal Odor Map (POM) Latent Embedding Space", | |
| fontsize=14, | |
| fontweight="bold", | |
| pad=15, | |
| ) | |
| plt.xlabel("UMAP Coordinate 1", fontsize=11) | |
| plt.ylabel("UMAP Coordinate 2", fontsize=11) | |
| plt.grid(True, linestyle="--", alpha=0.3) | |
| cas_to_idx = {c["cas"]: i for i, c in enumerate(metadata_labels)} | |
| for label, (cas_r, cas_s) in chiral_pairs.items(): | |
| short_name = label.split()[0] | |
| for cas, marker_text in [(cas_r, "R"), (cas_s, "S")]: | |
| idx = cas_to_idx.get(cas) | |
| if idx is not None: | |
| plt.annotate( | |
| f"{marker_text}-{short_name}", | |
| (embedding_2d[idx, 0], embedding_2d[idx, 1]), | |
| textcoords="offset points", | |
| xytext=(0, 10), | |
| ha="center", | |
| fontsize=8, | |
| fontweight="bold", | |
| arrowprops=dict(arrowstyle="->", color="black", lw=0.5), | |
| ) | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| plt.savefig(output_path, bbox_inches="tight") | |
| plt.close() | |
| print(f"✅ Success: Publication-ready latent cluster map exported to {output_path}") | |
| def generate_paper_artifacts( | |
| checkpoint_dir: str, | |
| output_image_path: str | Path, | |
| data_path: str | Path | None = None, | |
| batch_size: int = 8, | |
| ) -> None: | |
| output_image_path = Path(output_image_path) | |
| print("⏳ Connecting to canonical SQLite registry and loading checkpoint...") | |
| registry = AromaRegistry() | |
| all_chemicals = list(registry.all_records().values()) | |
| valid_chemicals = [ | |
| c for c in all_chemicals | |
| if c.get("openpom_embedding") and len(c.get("openpom_embedding", [])) > 0 | |
| ] | |
| checkpoint_path = load_checkpoint_dir(checkpoint_dir) | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| model = PhysicsInformedMixtureTransformer( | |
| embedding_dim=DEFAULT_EMBEDDING_DIM, | |
| state_dim=2, | |
| hidden_dim=256, | |
| num_heads=4, | |
| num_layers=4, | |
| ).to(device) | |
| heads = PIMTHeads(hidden_dim=256, objective_dim=138).to(device) | |
| loss_balancer = AdaptiveLossBalancer(num_tasks=4).to(device) | |
| for checkpoint_name in ("pimt_v1.pt", "pytorch_model.bin", "model.pt"): | |
| candidate = checkpoint_path / checkpoint_name | |
| if candidate.exists(): | |
| checkpoint = torch.load(candidate, map_location=device) | |
| model.load_state_dict(checkpoint.get("model_state_dict", checkpoint), strict=False) | |
| heads.load_state_dict(checkpoint.get("heads_state_dict", {}), strict=False) | |
| print(f"✅ Weights loaded successfully from {candidate}.") | |
| break | |
| else: | |
| print(f"⚠️ No checkpoint file found in {checkpoint_path}. Running with raw backbone.") | |
| if data_path is not None: | |
| data_path = Path(data_path) | |
| data_path = download_dataset(data_path) | |
| val_loader, val_records = build_validation_loader(data_path, batch_size=batch_size) | |
| metrics = validate(model, heads, val_loader, device, loss_balancer) | |
| print_validation_metrics(metrics) | |
| engine = OlfactoryEmbeddingEngine() | |
| print(f"\n🧬 Extracting model hidden layer representations for {len(valid_chemicals)} compounds...") | |
| latent_matrix, metadata_labels, color_values = extract_latent_vectors( | |
| model, engine, valid_chemicals, device | |
| ) | |
| chiral_pairs = { | |
| "Limonene Enantiomers (Oranges vs Lemons)": ("5989-27-5", "5989-54-8"), | |
| "Carvone Enantiomers (Spearmint vs Caraway)": ("6485-40-1", "2244-16-8"), | |
| } | |
| analyze_chiral_pairs(latent_matrix, metadata_labels, chiral_pairs) | |
| plot_umap(latent_matrix, metadata_labels, color_values, chiral_pairs, output_image_path) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Generate PINO paper artifacts and metrics") | |
| parser.add_argument( | |
| "--checkpoint-dir", | |
| default="mattbitzesty/pino-pimt-checkpoint", | |
| help="Local path or HF Hub repo ID for the trained checkpoint", | |
| ) | |
| parser.add_argument( | |
| "--output-image", | |
| default="reports/figures/latent_space_umap.png", | |
| help="Output path for the UMAP figure", | |
| ) | |
| parser.add_argument( | |
| "--dataset", | |
| default="data/empirical_dataset_v1.jsonl", | |
| help="Path to the empirical dataset JSONL", | |
| ) | |
| parser.add_argument( | |
| "--batch-size", | |
| type=int, | |
| default=8, | |
| help="Batch size for validation metric collection", | |
| ) | |
| args = parser.parse_args() | |
| generate_paper_artifacts( | |
| args.checkpoint_dir, | |
| args.output_image, | |
| data_path=args.dataset, | |
| batch_size=args.batch_size, | |
| ) | |