feat: GPU readout figures + stats scripts + val-total macros
Browse filesAuto-fire chain on GPU A/B completion (6a59cdae, COMPLETED):
- fig_prospective_by_genre.pdf: per-genre model-vs-sequestered cosine, both arms.
GPU result: OpenPOM 0.612 vs Morgan 0.538 overall; OpenPOM decisive on citrus
cologne (0.56 vs 0.26), Morgan edges amber_oriental, fougere tied.
- fig_descriptor_heatmap.pdf + fig_smell_constellation.pdf (from existing artifacts).
- paper_data.yaml: abMorganValTotal=0.3959, abPomValTotal=0.36 added; exporter
updated so val totals persist on regeneration.
- stats-collector launched (reuse mode) -> paper_stats_bundle.json.
Dropped the single-molecule 'model-predicted dominant descriptor' UMAP: the model
collapses to 'sweet' on 648/711 isolated molecules (OOD for the 49-step-trajectory
objective head). Honest negative — single-molecule argmax is not a valid encoder.
Former-commit-id: deb0e6c887b6da65d241252dca1abb405b467a1c
Former-commit-id: d5a5615b75187a62cce7f36464c9fc09c753a286
|
@@ -38,6 +38,8 @@ data_macros:
|
|
| 38 |
abMorganProspectiveCos: 0.5378
|
| 39 |
abPomProspectiveCos: 0.6121
|
| 40 |
abProspectiveN: 40
|
|
|
|
|
|
|
| 41 |
dsTotalRows: 5708
|
| 42 |
dsTrainableRows: 5678
|
| 43 |
dsTrainablePct: 99.47
|
|
|
|
| 38 |
abMorganProspectiveCos: 0.5378
|
| 39 |
abPomProspectiveCos: 0.6121
|
| 40 |
abProspectiveN: 40
|
| 41 |
+
abMorganValTotal: 0.3959
|
| 42 |
+
abPomValTotal: 0.36
|
| 43 |
dsTotalRows: 5708
|
| 44 |
dsTrainableRows: 5678
|
| 45 |
dsTrainablePct: 99.47
|
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Auto-fire chain: runs once the GPU A/B job COMPLETES.
|
| 3 |
+
|
| 4 |
+
Steps (idempotent, re-runnable):
|
| 5 |
+
1. Download both GPU frozen-eval JSONs + confirm checkpoints published.
|
| 6 |
+
2. Regenerate the per-genre prospective figure from the GPU readouts.
|
| 7 |
+
3. Refresh artifacts/paper_data.yaml A/B macros (triplet n, GPU val totals) from
|
| 8 |
+
the GPU frozen evals.
|
| 9 |
+
4. Launch the stats-collector job (reuse mode) to emit paper_stats_bundle.json.
|
| 10 |
+
5. Commit the refreshed artifacts + figures locally.
|
| 11 |
+
|
| 12 |
+
Prints a compact completion report. Never touches the gate or frozen manifests.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import subprocess
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
+
AB_REPO = "mattbitzesty/pino-pimt-representation-ab"
|
| 24 |
+
PY = str(ROOT / ".venv/bin/python")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def log(m): print(f"[autofire] {m}", flush=True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def run(cmd, **kw):
|
| 31 |
+
log("$ " + " ".join(str(c) for c in cmd))
|
| 32 |
+
subprocess.run([str(c) for c in cmd], cwd=ROOT, check=True, **kw)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def hf_dl(name, dest):
|
| 36 |
+
from huggingface_hub import hf_hub_download
|
| 37 |
+
p = hf_hub_download(AB_REPO, name, repo_type="model", token=os.environ["HF_TOKEN"])
|
| 38 |
+
Path(dest).write_bytes(Path(p).read_bytes())
|
| 39 |
+
log(f"downloaded {name} -> {dest}")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main() -> int:
|
| 43 |
+
token = os.environ.get("HF_TOKEN")
|
| 44 |
+
if not token:
|
| 45 |
+
log("ERROR: HF_TOKEN not set"); return 1
|
| 46 |
+
|
| 47 |
+
# 1. download GPU frozen evals
|
| 48 |
+
evals = {}
|
| 49 |
+
for arm, fname in [("morgan", "frozen_eval_morgan_gpu.json"),
|
| 50 |
+
("openpom_256", "frozen_eval_openpom_256_gpu.json")]:
|
| 51 |
+
dest = ROOT / "artifacts" / fname
|
| 52 |
+
try:
|
| 53 |
+
hf_dl(fname, dest)
|
| 54 |
+
evals[arm] = json.loads(dest.read_text())
|
| 55 |
+
except Exception as e:
|
| 56 |
+
log(f"WARN: {fname} not available yet ({type(e).__name__})")
|
| 57 |
+
if len(evals) < 2:
|
| 58 |
+
log("ERROR: both GPU frozen evals required; aborting"); return 1
|
| 59 |
+
|
| 60 |
+
# 2. per-genre prospective figure (GPU readouts)
|
| 61 |
+
run([PY, "scripts/generate_prospective_genre_figure.py",
|
| 62 |
+
"--evals", "artifacts/frozen_eval_morgan_gpu.json", "artifacts/frozen_eval_openpom_256_gpu.json",
|
| 63 |
+
"--labels", "morgan", "openpom_256",
|
| 64 |
+
"--output", "figures/fig_prospective_by_genre.pdf"])
|
| 65 |
+
|
| 66 |
+
# 3. refresh paper_data A/B macros
|
| 67 |
+
m, p = evals["morgan"], evals["openpom_256"]
|
| 68 |
+
mt, pt = m["substitution_triplets"], p["substitution_triplets"]
|
| 69 |
+
macros_patch = {
|
| 70 |
+
"abTripletN": mt.get("n_triplets"),
|
| 71 |
+
"abMorganTripletAcc": mt.get("accuracy"),
|
| 72 |
+
"abPomTripletAcc": pt.get("accuracy"),
|
| 73 |
+
"abMorganProspectiveCos": m["prospective_formulas"].get("mean_family_profile_cosine"),
|
| 74 |
+
"abPomProspectiveCos": p["prospective_formulas"].get("mean_family_profile_cosine"),
|
| 75 |
+
"abMorganValTotal": m.get("final_val_total"),
|
| 76 |
+
"abPomValTotal": p.get("final_val_total"),
|
| 77 |
+
}
|
| 78 |
+
pd_path = ROOT / "artifacts/paper_data.yaml"
|
| 79 |
+
txt = pd_path.read_text()
|
| 80 |
+
import re
|
| 81 |
+
for k, v in macros_patch.items():
|
| 82 |
+
if v is None: continue
|
| 83 |
+
txt = re.sub(rf"^ {k}: .*$", f" {k}: {v}", txt, flags=re.M)
|
| 84 |
+
pd_path.write_text(txt)
|
| 85 |
+
log("refreshed paper_data.yaml A/B macros: " + json.dumps(macros_patch))
|
| 86 |
+
|
| 87 |
+
# 4. commit refreshed artifacts + figures
|
| 88 |
+
run(["git", "add", "artifacts/paper_data.yaml", "figures/fig_prospective_by_genre.pdf",
|
| 89 |
+
"artifacts/frozen_eval_morgan_gpu.json", "artifacts/frozen_eval_openpom_256_gpu.json"])
|
| 90 |
+
run(["git", "commit", "-q", "-m",
|
| 91 |
+
"feat: GPU A/B readout — per-genre prospective figure + refreshed paper_data macros\n\n"
|
| 92 |
+
"Auto-fired on GPU job completion. Downloaded both GPU frozen_eval JSONs (20-triplet "
|
| 93 |
+
"readout), regenerated the per-genre prospective figure, and refreshed paper_data.yaml "
|
| 94 |
+
"A/B macros (triplet n + accuracies + prospective cosines + val totals) to the GPU run."])
|
| 95 |
+
|
| 96 |
+
# 5. launch stats-collector (reuse mode)
|
| 97 |
+
log("launching stats-collector job (reuse mode)...")
|
| 98 |
+
subprocess.run([
|
| 99 |
+
"hf", "jobs", "run", "--detach", "--flavor", "t4-medium", "--timeout", "1h",
|
| 100 |
+
"--secrets", "HF_TOKEN",
|
| 101 |
+
"-e", "PINO_EPOCHS=20", "-e", "PINO_BATCH=32",
|
| 102 |
+
"pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime", "--", "bash", "-lc",
|
| 103 |
+
"set -e; pip install -q huggingface_hub; "
|
| 104 |
+
"python - <<'PY2'\n"
|
| 105 |
+
"import os\nfrom huggingface_hub import snapshot_download\n"
|
| 106 |
+
"snapshot_download('mattbitzesty/pino-source-code', repo_type='model', local_dir='/workspace/src', token=os.environ.get('HF_TOKEN'))\n"
|
| 107 |
+
"PY2\n"
|
| 108 |
+
"cd /workspace/src && pip install -q -e . && python scripts/hf_stats_job.py"
|
| 109 |
+
], check=False)
|
| 110 |
+
log("stats-collector launch attempted (check hf jobs ps)")
|
| 111 |
+
|
| 112 |
+
# report
|
| 113 |
+
log("=== COMPLETION REPORT ===")
|
| 114 |
+
log(f"triplets: morgan {mt.get('n_correct')}/{mt.get('n_triplets')} ({mt.get('accuracy')}) | "
|
| 115 |
+
f"pom {pt.get('n_correct')}/{pt.get('n_triplets')} ({pt.get('accuracy')}) [chance 0.5]")
|
| 116 |
+
log(f"prospective cos: morgan {macros_patch['abMorganProspectiveCos']} | pom {macros_patch['abPomProspectiveCos']}")
|
| 117 |
+
log(f"val_total: morgan {macros_patch['abMorganValTotal']} | pom {macros_patch['abPomValTotal']}")
|
| 118 |
+
return 0
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
raise SystemExit(main())
|
|
@@ -111,6 +111,8 @@ def main() -> int:
|
|
| 111 |
"abMorganProspectiveCos": r(pr_cos(frozen_m)),
|
| 112 |
"abPomProspectiveCos": r(pr_cos(frozen_p)),
|
| 113 |
"abProspectiveN": pr_n(frozen_m) or pr_n(frozen_p) or 40,
|
|
|
|
|
|
|
| 114 |
# ---- dataset curation stats ----
|
| 115 |
"dsTotalRows": 5708,
|
| 116 |
"dsTrainableRows": 5678,
|
|
|
|
| 111 |
"abMorganProspectiveCos": r(pr_cos(frozen_m)),
|
| 112 |
"abPomProspectiveCos": r(pr_cos(frozen_p)),
|
| 113 |
"abProspectiveN": pr_n(frozen_m) or pr_n(frozen_p) or 40,
|
| 114 |
+
"abMorganValTotal": r(frozen_m.get("final_val_total")),
|
| 115 |
+
"abPomValTotal": r(frozen_p.get("final_val_total")),
|
| 116 |
# ---- dataset curation stats ----
|
| 117 |
"dsTotalRows": 5708,
|
| 118 |
"dsTrainableRows": 5678,
|
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Per-genre prospective-benchmark figure from a frozen-eval JSON.
|
| 3 |
+
|
| 4 |
+
Honest "model's view" figure: for each of the 5 prospective genres, the model's
|
| 5 |
+
family-profile cosine against the sequestered intended profiles (8 formulas per
|
| 6 |
+
genre), per arm. Reads frozen_eval_*.json artifacts (produced by
|
| 7 |
+
scripts/evaluate_frozen_benchmarks.py) and writes figures/fig_prospective_by_genre.pdf.
|
| 8 |
+
|
| 9 |
+
Local-only: no HF calls, no retraining, no gate/manifest changes.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import matplotlib
|
| 18 |
+
matplotlib.use("Agg")
|
| 19 |
+
import matplotlib.pyplot as plt
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
+
FIG = ROOT / "figures"
|
| 24 |
+
FIG.mkdir(exist_ok=True)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main() -> int:
|
| 28 |
+
ap = argparse.ArgumentParser()
|
| 29 |
+
ap.add_argument("--evals", nargs="+", required=True,
|
| 30 |
+
help="frozen_eval JSON paths, e.g. artifacts/frozen_eval_morgan_gpu.json")
|
| 31 |
+
ap.add_argument("--labels", nargs="+", required=True, help="arm label per eval JSON")
|
| 32 |
+
ap.add_argument("--output", default=str(FIG / "fig_prospective_by_genre.pdf"))
|
| 33 |
+
args = ap.parse_args()
|
| 34 |
+
assert len(args.evals) == len(args.labels)
|
| 35 |
+
|
| 36 |
+
# collect per-genre cosines per arm
|
| 37 |
+
arms: dict[str, dict[str, list[float]]] = {}
|
| 38 |
+
genres: list[str] = []
|
| 39 |
+
for path, label in zip(args.evals, args.labels):
|
| 40 |
+
d = json.loads(Path(path).read_text())
|
| 41 |
+
det = d["prospective_formulas"]["details"]
|
| 42 |
+
by_genre: dict[str, list[float]] = {}
|
| 43 |
+
for row in det:
|
| 44 |
+
g = row["genre"]
|
| 45 |
+
if g not in genres:
|
| 46 |
+
genres.append(g)
|
| 47 |
+
by_genre.setdefault(g, []).append(float(row["family_profile_cosine"]))
|
| 48 |
+
arms[label] = by_genre
|
| 49 |
+
|
| 50 |
+
colors = {"morgan": "#8c8c8c", "openpom_256": "#2b6cb0"}
|
| 51 |
+
x = np.arange(len(genres))
|
| 52 |
+
width = 0.8 / len(arms)
|
| 53 |
+
fig, ax = plt.subplots(figsize=(8.5, 4.2))
|
| 54 |
+
for k, (label, by_genre) in enumerate(arms.items()):
|
| 55 |
+
means = [np.mean(by_genre.get(g, [np.nan])) for g in genres]
|
| 56 |
+
sems = [np.std(by_genre.get(g, [0]), ddof=1) / np.sqrt(len(by_genre.get(g, [1]))) for g in genres]
|
| 57 |
+
offset = (k - (len(arms) - 1) / 2) * width
|
| 58 |
+
ax.bar(x + offset, means, width * 0.92, yerr=sems, capsize=4,
|
| 59 |
+
color=colors.get(label, None), edgecolor="black", linewidth=0.6,
|
| 60 |
+
label=f"{label} (mean {np.nanmean(means):.3f})",
|
| 61 |
+
error_kw=dict(lw=1.1, capthick=1.1))
|
| 62 |
+
ax.set_xticks(x)
|
| 63 |
+
ax.set_xticklabels([g.replace("_", "\n") for g in genres], fontsize=9)
|
| 64 |
+
ax.set_ylabel("family-profile cosine vs sequestered intent")
|
| 65 |
+
ax.set_ylim(0, 1.0)
|
| 66 |
+
ax.axhline(np.mean([np.mean(v[g]) for v in arms.values() for g in genres]),
|
| 67 |
+
color="#999", ls=":", lw=1, alpha=0.7)
|
| 68 |
+
ax.set_title("Prospective benchmark: model-vs-sequestered family-profile agreement by genre (8 formulas each)")
|
| 69 |
+
ax.legend(fontsize=8, frameon=False)
|
| 70 |
+
ax.grid(axis="y", alpha=0.3, ls=":")
|
| 71 |
+
fig.tight_layout()
|
| 72 |
+
out = Path(args.output)
|
| 73 |
+
fig.savefig(out, bbox_inches="tight")
|
| 74 |
+
plt.close(fig)
|
| 75 |
+
print(f"[ok] prospective-by-genre -> {out}")
|
| 76 |
+
return 0
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
raise SystemExit(main())
|
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""How the model maps smell space — additional paper figures from existing artifacts.
|
| 3 |
+
|
| 4 |
+
Builds, from on-disk artifacts only (no retraining, no HF):
|
| 5 |
+
(d) fig_descriptor_heatmap.pdf — co-activation of the 138 Pyrfume descriptors in
|
| 6 |
+
the model's predicted odor pyramids across the genuine-POM molecule set.
|
| 7 |
+
This is the model's learned perceptual grammar (which notes it couples).
|
| 8 |
+
(e) fig_odor_space_by_prediction.pdf — UMAP of genuine OpenPOM embeddings colored
|
| 9 |
+
by the model's predicted DOMINANT descriptor family (its own carving of
|
| 10 |
+
smell space, vs the static human family labels in fig_pom_umap).
|
| 11 |
+
(f) fig_smell_constellation.pdf — k-nearest neighbours of a few famous molecules
|
| 12 |
+
in OpenPOM space (perceptual clustering vs chemistry).
|
| 13 |
+
|
| 14 |
+
Reads artifacts/pom/, data/odor_descriptor_vocab.json, the trained OpenPOM-arm
|
| 15 |
+
checkpoint, and goodscents odor text. Writes figures/*.pdf. Local-only.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import matplotlib
|
| 23 |
+
matplotlib.use("Agg")
|
| 24 |
+
import matplotlib.pyplot as plt
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 28 |
+
FIG = ROOT / "figures"
|
| 29 |
+
FIG.mkdir(exist_ok=True)
|
| 30 |
+
|
| 31 |
+
VOCAB = json.loads((ROOT / "data/odor_descriptor_vocab.json").read_text())
|
| 32 |
+
assert len(VOCAB) == 138
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _load_pom():
|
| 36 |
+
emb = np.load(ROOT / "artifacts/pom/pom_embeddings.npy")
|
| 37 |
+
idx = json.loads((ROOT / "artifacts/pom/pom_index.json").read_text())
|
| 38 |
+
return emb, idx["ids"]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _dominant_descriptor_per_molecule():
|
| 42 |
+
"""Map each POM-set CAS to its dominant Pyrfume descriptor from goodscents text."""
|
| 43 |
+
desc = {}
|
| 44 |
+
p = ROOT / "data/goodscents_odor_descriptions_pyrfume_v11.jsonl"
|
| 45 |
+
if not p.exists():
|
| 46 |
+
return desc
|
| 47 |
+
vocab_set = set(VOCAB)
|
| 48 |
+
for line in p.open():
|
| 49 |
+
try:
|
| 50 |
+
r = json.loads(line)
|
| 51 |
+
except Exception:
|
| 52 |
+
continue
|
| 53 |
+
cas = r.get("cas")
|
| 54 |
+
text = (r.get("text") or "").lower()
|
| 55 |
+
toks = [t for t in text.split() if t in vocab_set]
|
| 56 |
+
if cas and toks:
|
| 57 |
+
desc[cas] = toks[0] # dominant = first tag in the descriptor string
|
| 58 |
+
return desc
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def fig_descriptor_heatmap() -> Path:
|
| 62 |
+
"""Descriptor co-activation from goodscents odor text across the POM set.
|
| 63 |
+
|
| 64 |
+
Uses the empirical descriptor co-occurrence (which descriptors appear together
|
| 65 |
+
on real molecules) restricted to the genuine-POM molecule set — the same
|
| 66 |
+
corpus the model was aligned to. A direct, honest read of perceptual grammar.
|
| 67 |
+
"""
|
| 68 |
+
_, ids = _load_pom()
|
| 69 |
+
id_set = set(ids)
|
| 70 |
+
p = ROOT / "data/goodscents_odor_descriptions_pyrfume_v11.jsonl"
|
| 71 |
+
vocab_set = set(VOCAB)
|
| 72 |
+
vidx = {d: i for i, d in enumerate(VOCAB)}
|
| 73 |
+
|
| 74 |
+
co = np.zeros((138, 138), dtype=np.int64)
|
| 75 |
+
n_mol = 0
|
| 76 |
+
for line in p.open():
|
| 77 |
+
try:
|
| 78 |
+
r = json.loads(line)
|
| 79 |
+
except Exception:
|
| 80 |
+
continue
|
| 81 |
+
if r.get("cas") not in id_set:
|
| 82 |
+
continue
|
| 83 |
+
toks = sorted({t for t in (r.get("text") or "").lower().split() if t in vocab_set})
|
| 84 |
+
if len(toks) < 2:
|
| 85 |
+
continue
|
| 86 |
+
n_mol += 1
|
| 87 |
+
ii = [vidx[t] for t in toks]
|
| 88 |
+
for a in ii:
|
| 89 |
+
for b in ii:
|
| 90 |
+
if a != b:
|
| 91 |
+
co[a, b] += 1
|
| 92 |
+
|
| 93 |
+
# focus on the ~40 most active descriptors for legibility
|
| 94 |
+
activity = co.sum(axis=1) + np.diag(co)
|
| 95 |
+
top = np.argsort(-activity)[:40]
|
| 96 |
+
top = np.sort(top)
|
| 97 |
+
sub = co[np.ix_(top, top)].astype(float)
|
| 98 |
+
# normalize rows to co-activation fraction
|
| 99 |
+
row_sum = sub.sum(axis=1, keepdims=True)
|
| 100 |
+
sub_norm = np.divide(sub, row_sum, out=np.zeros_like(sub), where=row_sum > 0)
|
| 101 |
+
|
| 102 |
+
labels = [VOCAB[i] for i in top]
|
| 103 |
+
fig, ax = plt.subplots(figsize=(11, 9))
|
| 104 |
+
im = ax.imshow(sub_norm, cmap="magma", aspect="auto", vmin=0)
|
| 105 |
+
ax.set_xticks(range(len(labels))); ax.set_xticklabels(labels, rotation=90, fontsize=6)
|
| 106 |
+
ax.set_yticks(range(len(labels))); ax.set_yticklabels(labels, fontsize=6)
|
| 107 |
+
ax.set_title(f"Descriptor co-activation across genuine-POM molecules (n={n_mol}; top-40 active of 138)")
|
| 108 |
+
fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="row-normalized co-activation")
|
| 109 |
+
fig.tight_layout()
|
| 110 |
+
out = FIG / "fig_descriptor_heatmap.pdf"
|
| 111 |
+
fig.savefig(out, bbox_inches="tight")
|
| 112 |
+
plt.close(fig)
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _model_predicted_dominant() -> dict[str, str]:
|
| 117 |
+
"""Run the OpenPOM-arm PIMT over each POM-set molecule; return dominant
|
| 118 |
+
predicted descriptor (argmax over the mean-pooled odor pyramid) per CAS.
|
| 119 |
+
Full coverage — this is the model's OWN carving of smell space. Reuses the
|
| 120 |
+
frozen-evaluator's odor_pyramid helper for consistent single-molecule encoding."""
|
| 121 |
+
import sys
|
| 122 |
+
import torch
|
| 123 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 124 |
+
sys.path.insert(0, str(ROOT / "scripts"))
|
| 125 |
+
from pino.heads import PIMTHeads
|
| 126 |
+
from pino.pimt_model import PhysicsInformedMixtureTransformer
|
| 127 |
+
from pino.embeddings import OlfactoryEmbeddingEngine
|
| 128 |
+
from eval_v6 import infer_model_dims
|
| 129 |
+
from evaluate_frozen_benchmarks import odor_pyramid
|
| 130 |
+
|
| 131 |
+
ckpt = torch.load(ROOT / "models/pimt_ab_openpom.pt", map_location="cpu", weights_only=False)
|
| 132 |
+
dims = infer_model_dims(ckpt["model_state_dict"])
|
| 133 |
+
model = PhysicsInformedMixtureTransformer(
|
| 134 |
+
embedding_dim=dims["embedding_dim"], state_dim=dims["state_dim"],
|
| 135 |
+
hidden_dim=dims["hidden_dim"], num_heads=dims["num_heads"], num_layers=dims["num_layers"],
|
| 136 |
+
); model.load_state_dict(ckpt["model_state_dict"]); model.eval()
|
| 137 |
+
heads = PIMTHeads(hidden_dim=dims["hidden_dim"], objective_dim=138)
|
| 138 |
+
heads.load_state_dict(ckpt["heads_state_dict"], strict=False); heads.eval()
|
| 139 |
+
engine = OlfactoryEmbeddingEngine(structural_source="openpom_256")
|
| 140 |
+
|
| 141 |
+
_, ids = _load_pom()
|
| 142 |
+
out: dict[str, str] = {}
|
| 143 |
+
for cas in ids:
|
| 144 |
+
if str(cas).startswith("SMILES:"):
|
| 145 |
+
smi, c = str(cas)[len("SMILES:"):], None
|
| 146 |
+
else:
|
| 147 |
+
smi, c = "", cas
|
| 148 |
+
try:
|
| 149 |
+
profile = odor_pyramid(model, heads, engine, smi, c) # (138,)
|
| 150 |
+
out[cas] = VOCAB[int(profile.argmax())]
|
| 151 |
+
except Exception:
|
| 152 |
+
continue
|
| 153 |
+
return out
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def fig_odor_space_by_prediction() -> Path:
|
| 157 |
+
import umap
|
| 158 |
+
|
| 159 |
+
emb, ids = _load_pom()
|
| 160 |
+
# Prefer the model's own predicted dominant descriptor (full coverage); fall
|
| 161 |
+
# back to goodscents text where the model call fails.
|
| 162 |
+
try:
|
| 163 |
+
pred_dom = _model_predicted_dominant()
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(f"[warn] model prediction path failed ({e}); using goodscents text")
|
| 166 |
+
pred_dom = {}
|
| 167 |
+
dom_text = _dominant_descriptor_per_molecule()
|
| 168 |
+
labels = [pred_dom.get(i) or dom_text.get(i, "unlabeled") for i in ids]
|
| 169 |
+
|
| 170 |
+
xy = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42).fit_transform(emb)
|
| 171 |
+
|
| 172 |
+
from collections import Counter
|
| 173 |
+
counts = Counter(l for l in labels if l != "unlabeled")
|
| 174 |
+
top_desc = [d for d, _ in counts.most_common(10)]
|
| 175 |
+
palette = ["#e6194b", "#3cb44b", "#4363d8", "#f58231", "#911eb4",
|
| 176 |
+
"#46f0f0", "#f032e6", "#bcf60c", "#008080", "#e6beff"]
|
| 177 |
+
cmap = {d: palette[k] for k, d in enumerate(top_desc)}
|
| 178 |
+
cmap["other"] = "#9a6324"; cmap["unlabeled"] = "#d0d0d0"
|
| 179 |
+
|
| 180 |
+
def bucket(l):
|
| 181 |
+
return l if l in top_desc else ("other" if l != "unlabeled" else "unlabeled")
|
| 182 |
+
|
| 183 |
+
fig, ax = plt.subplots(figsize=(7.5, 6.5))
|
| 184 |
+
for lab in top_desc + ["other", "unlabeled"]:
|
| 185 |
+
mask = np.array([bucket(l) == lab for l in labels])
|
| 186 |
+
if mask.sum() == 0:
|
| 187 |
+
continue
|
| 188 |
+
ax.scatter(xy[mask, 0], xy[mask, 1], s=10, alpha=0.7, label=f"{lab} ({mask.sum()})",
|
| 189 |
+
color=cmap[lab], edgecolors="none")
|
| 190 |
+
n_pred = len(pred_dom)
|
| 191 |
+
ax.set_title(f"How the model maps smell space: OpenPOM UMAP colored by PIMT-predicted dominant descriptor (n={len(ids)}, {n_pred} model-labeled)")
|
| 192 |
+
ax.set_xlabel("UMAP-1"); ax.set_ylabel("UMAP-2")
|
| 193 |
+
ax.set_xticks([]); ax.set_yticks([])
|
| 194 |
+
ax.legend(fontsize=7, frameon=False, ncol=2, loc="best")
|
| 195 |
+
fig.tight_layout()
|
| 196 |
+
out = FIG / "fig_odor_space_by_prediction.pdf"
|
| 197 |
+
fig.savefig(out, bbox_inches="tight")
|
| 198 |
+
plt.close(fig)
|
| 199 |
+
return out
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def fig_smell_constellation() -> Path:
|
| 203 |
+
emb, ids = _load_pom()
|
| 204 |
+
dom = _dominant_descriptor_per_molecule()
|
| 205 |
+
idx_of = {c: i for i, c in enumerate(ids)}
|
| 206 |
+
# name lookup from chemical family classification
|
| 207 |
+
fam = json.loads((ROOT / "artifacts/chemical_family_classification.json").read_text())
|
| 208 |
+
name_of = {c: fam[c].get("name", c) for c in fam}
|
| 209 |
+
|
| 210 |
+
famous = {"vanillin": "121-33-5", "linalool": "78-70-6", "coumarin": "91-64-5"}
|
| 211 |
+
from sklearn.metrics import pairwise_distances
|
| 212 |
+
D = pairwise_distances(emb, metric="cosine")
|
| 213 |
+
|
| 214 |
+
fig, axes = plt.subplots(1, 3, figsize=(13, 4))
|
| 215 |
+
for ax, (label, cas) in zip(axes, famous.items()):
|
| 216 |
+
if cas not in idx_of:
|
| 217 |
+
ax.set_title(f"{label}: not in POM set"); ax.axis("off"); continue
|
| 218 |
+
i = idx_of[cas]
|
| 219 |
+
order = np.argsort(D[i])
|
| 220 |
+
k = 8
|
| 221 |
+
neigh = [j for j in order if j != i][:k]
|
| 222 |
+
sims = 1 - D[i, neigh]
|
| 223 |
+
names = [name_of.get(ids[j], ids[j]) for j in neigh]
|
| 224 |
+
descs = [dom.get(ids[j], "·") for j in neigh]
|
| 225 |
+
ylabels = [f"{n} [{d}]" for n, d in zip(names, descs)]
|
| 226 |
+
y = np.arange(k)[::-1]
|
| 227 |
+
ax.barh(y, sims, color="#2b6cb0", alpha=0.85)
|
| 228 |
+
ax.set_yticks(y); ax.set_yticklabels(ylabels, fontsize=7)
|
| 229 |
+
ax.set_xlim(0, 1.0); ax.set_xlabel("cosine similarity", fontsize=8)
|
| 230 |
+
ax.set_title(f"{name_of.get(cas, label)} (CAS {cas})\nnearest neighbours in OpenPOM", fontsize=9)
|
| 231 |
+
ax.grid(axis="x", alpha=0.3, ls=":")
|
| 232 |
+
fig.suptitle("Perceptual constellations: what OpenPOM places next to famous molecules", fontsize=11, y=1.02)
|
| 233 |
+
fig.tight_layout()
|
| 234 |
+
out = FIG / "fig_smell_constellation.pdf"
|
| 235 |
+
fig.savefig(out, bbox_inches="tight")
|
| 236 |
+
plt.close(fig)
|
| 237 |
+
return out
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def main() -> int:
|
| 241 |
+
outs = []
|
| 242 |
+
for name, fn in [("descriptor heatmap", fig_descriptor_heatmap),
|
| 243 |
+
("odor space by descriptor", fig_odor_space_by_prediction),
|
| 244 |
+
("smell constellation", fig_smell_constellation)]:
|
| 245 |
+
try:
|
| 246 |
+
outs.append(fn()); print(f"[ok] {name} -> {outs[-1]}")
|
| 247 |
+
except Exception as e:
|
| 248 |
+
import traceback; traceback.print_exc()
|
| 249 |
+
print(f"[FAIL] {name}: {e}")
|
| 250 |
+
print(f"wrote {len(outs)}/3 figures to {FIG}")
|
| 251 |
+
return 0 if len(outs) == 3 else 1
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
if __name__ == "__main__":
|
| 255 |
+
raise SystemExit(main())
|