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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Score trained PIMT checkpoints on the engine-independent frozen probes.
|
| 3 |
+
|
| 4 |
+
The paper's static physics-null rests on a MODEL-FREE probe: 4 physicochemical
|
| 5 |
+
descriptors appended to frozen (Morgan/POM) embeddings, scored via a Ridge or
|
| 6 |
+
LogisticRegression linear probe. A review panel demands that the TRAINED FiLM
|
| 7 |
+
on/off arms (pimt_ab_openpom_256 = physics-on-trained, pimt_physoff_openpom_256
|
| 8 |
+
= physics-off-trained) be scored on the SAME three engine-independent frozen
|
| 9 |
+
probes from tab:main under MATCHED conditioning.
|
| 10 |
+
|
| 11 |
+
This script does exactly that. For each checkpoint it evaluates:
|
| 12 |
+
|
| 13 |
+
1. Substantivity: Spearman rho between the trained model's substantivity-head
|
| 14 |
+
output (a scalar per molecule) and GoodScents measured substantivity hours,
|
| 15 |
+
on the SAME molecule set used by the model-free probe. The substantivity
|
| 16 |
+
head was trained on log10(Poucher coefficients) — a different absolute scale
|
| 17 |
+
than GoodScents hours — so only the rank ordering is comparable; Spearman
|
| 18 |
+
rho is scale-invariant and is the exact metric the frozen probe reports.
|
| 19 |
+
|
| 20 |
+
2. Odor threshold: NOT APPLICABLE. The trained PIMT model has no odor-threshold
|
| 21 |
+
head (it was never trained against ODT targets). Reporting not_applicable
|
| 22 |
+
rather than fabricating a head.
|
| 23 |
+
|
| 24 |
+
3. Descriptor macro-F1: The frozen probe trains a LogisticRegression classifier
|
| 25 |
+
on frozen embeddings to predict the dominant descriptor letter (25 classes)
|
| 26 |
+
and reports 5-fold macro-F1. The trained model predicts a continuous 138-dim
|
| 27 |
+
descriptor profile (sigmoid activations, mean of top/mid/base tiers). We
|
| 28 |
+
binarize the predicted profile at the benchmark's own threshold (0.5), map
|
| 29 |
+
each active Pyrfume tag onto its descriptor letter via the v11 crosswalk,
|
| 30 |
+
and predict the dominant letter for each molecule. The macro-F1 is computed
|
| 31 |
+
against the benchmark's per-molecule dominant letter using the SAME
|
| 32 |
+
CAS-grouped 5-fold split, so the denominator (classes, folds) matches.
|
| 33 |
+
|
| 34 |
+
Single-molecule conditioning convention (matching the training corpus):
|
| 35 |
+
* Each molecule is evaluated as a control record — single molecule at 15%
|
| 36 |
+
concentrate in ethanol — so the evaporation engine has the same solvent
|
| 37 |
+
envelope the model was trained on.
|
| 38 |
+
* Physics-ON: run the Dortmund-UNIFAC BDF evaporation engine on that control
|
| 39 |
+
formula (following engine_only_baseline.py's verifier pattern), extract the
|
| 40 |
+
per-molecule physics trajectory (x_liquid, log10 OAV), and feed it to the
|
| 41 |
+
model.
|
| 42 |
+
* Physics-OFF: zero the physics tensor entirely.
|
| 43 |
+
|
| 44 |
+
Each checkpoint is evaluated under BOTH conditioning modes (on and off):
|
| 45 |
+
* openpom arm (physics-on-trained) evaluated physics-ON (training-consistent)
|
| 46 |
+
and physics-OFF (sensitivity).
|
| 47 |
+
* physoff arm (physics-off-trained) evaluated physics-OFF (training-consistent)
|
| 48 |
+
and physics-ON (sensitivity).
|
| 49 |
+
|
| 50 |
+
Output JSON per (checkpoint, conditioning):
|
| 51 |
+
{arm, checkpoint sha256, seed, conditioning: on|off,
|
| 52 |
+
substantivity: {rho, n},
|
| 53 |
+
descriptors: {macro_f1, n, protocol_note},
|
| 54 |
+
threshold: {not_applicable: "..."}}
|
| 55 |
+
|
| 56 |
+
Usage:
|
| 57 |
+
PYTHONPATH=src .venv/bin/python scripts/evaluate_trained_frozen_probes.py \
|
| 58 |
+
--checkpoints pimt_ab_openpom_256_seed1.pt pimt_physoff_openpom_256_seed1.pt \
|
| 59 |
+
--seeds 1 \
|
| 60 |
+
--output artifacts/trained_frozen_probes/ \
|
| 61 |
+
[--max-molecules 30] # smoke test subset
|
| 62 |
+
"""
|
| 63 |
+
from __future__ import annotations
|
| 64 |
+
|
| 65 |
+
import argparse
|
| 66 |
+
import hashlib
|
| 67 |
+
import json
|
| 68 |
+
import logging
|
| 69 |
+
import re
|
| 70 |
+
import sys
|
| 71 |
+
from pathlib import Path
|
| 72 |
+
from typing import Any
|
| 73 |
+
|
| 74 |
+
import numpy as np
|
| 75 |
+
import torch
|
| 76 |
+
|
| 77 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 78 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 79 |
+
|
| 80 |
+
from pino.embeddings import OlfactoryEmbeddingEngine
|
| 81 |
+
from pino.heads import PIMTHeads
|
| 82 |
+
from pino.pimt_model import PhysicsInformedMixtureTransformer
|
| 83 |
+
|
| 84 |
+
logger = logging.getLogger("evaluate_trained_frozen_probes")
|
| 85 |
+
|
| 86 |
+
# ---------------------------------------------------------------------------
|
| 87 |
+
# Descriptor letter crosswalk — must match run_representation_ablation.py.
|
| 88 |
+
# Maps single-letter descriptor codes (from descriptor_distributions_v11.jsonl)
|
| 89 |
+
# to readable labels. The v11 distribution keys ARE these letters.
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
# The pyrfume_vocabulary.json is 138 entries. We need to map each Pyrfume tag
|
| 92 |
+
# word onto a letter class so the trained model's predicted 138-dim profile can
|
| 93 |
+
# be projected onto the same label space as the frozen probe's target.
|
| 94 |
+
|
| 95 |
+
# Build a mapping from Pyrfume tag index -> descriptor letter.
|
| 96 |
+
# The descriptor_distributions_v11.jsonl assigns a distribution over letters
|
| 97 |
+
# (A-Z, skipping O) to each CAS. We need the reverse: which letter does each
|
| 98 |
+
# Pyrfume tag word correspond to? This is not directly stored. However, the
|
| 99 |
+
# frozen probe predicts the DOMINANT letter per molecule. So for the trained
|
| 100 |
+
# model, we aggregate the predicted 138-dim profile by letter group using the
|
| 101 |
+
# known semantic groupings (CLASS_LETTER_MAP from run_representation_ablation.py
|
| 102 |
+
# gives letter -> readable name; we need readable name -> letter).
|
| 103 |
+
|
| 104 |
+
# Letter -> readable name (from run_representation_ablation.py CLASS_LETTER_MAP)
|
| 105 |
+
LETTER_TO_NAME = {
|
| 106 |
+
"A": "citrus", "B": "fruity", "C": "green", "D": "floral", "E": "spicy",
|
| 107 |
+
"F": "woody", "G": "herbaceous", "H": "earthy", "I": "musk", "J": "amber",
|
| 108 |
+
"K": "leathery", "L": "smoky", "M": "sweet", "N": "lactonic", "O": "marine",
|
| 109 |
+
"P": "minty", "Q": "camphoraceous", "R": "balsamic", "S": "sulfurous",
|
| 110 |
+
"T": "animalic", "U": "metallic", "V": "waxy", "W": "aldehydic",
|
| 111 |
+
"X": "solvent", "Y": "powdery", "Z": "carrier",
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
# Build name -> letter (reverse map). Multiple names can map to the same letter;
|
| 115 |
+
# we also add common Pyrfume tag synonyms that map onto the same letter.
|
| 116 |
+
LETTER_SYNONYMS: dict[str, list[str]] = {
|
| 117 |
+
"A": ["citrus", "lemon", "orange", "grapefruit", "bergamot", "tangerine", "mandarin", "lime"],
|
| 118 |
+
"B": ["fruity", "apple", "banana", "peach", "pear", "berry", "raspberry", "pineapple", "tropical"],
|
| 119 |
+
"C": ["green", "grassy", "leafy", "cucumber", "vegetable", "hay", "weedy", "galbanum"],
|
| 120 |
+
"D": ["floral", "rose", "jasmin", "jasmine", "muguet", "violet", "hyacinth", "lily", "geranium", "lavender", "lilac", "carnation", "ionone"],
|
| 121 |
+
"E": ["spicy", "cinnamon", "clove", "pepper", "nutmeg", "cardamom", "ginger", "anisic", "caraway"],
|
| 122 |
+
"F": ["woody", "cedar", "pine", "sandalwood", "vetiver", "patchouli", "mossy"],
|
| 123 |
+
"G": ["herbaceous", "herbal", "chamomile", "thyme", "sage", "mint", "minty", "aromatic"],
|
| 124 |
+
"H": ["earthy", "mushroom", "beet", "soil", "humus"],
|
| 125 |
+
"I": ["musk", "musky"],
|
| 126 |
+
"J": ["amber", "ambery"],
|
| 127 |
+
"K": ["leathery", "leather"],
|
| 128 |
+
"L": ["smoky", "smoke", "tobacco", "tar", "phenolic"],
|
| 129 |
+
"M": ["sweet", "honey", "caramellic", "caramel", "chocolate", "cocoa", "vanilla", "coumarinic", "lactonic", "creamy", "balsamic"],
|
| 130 |
+
"N": ["lactonic", "milky"],
|
| 131 |
+
"P": ["minty", "mint", "mentholic", "camphoreous", "camphor"],
|
| 132 |
+
"Q": ["camphoraceous", "camphoreous"],
|
| 133 |
+
"R": ["balsamic", "resinous", "benzoin", "styrax", "tolu"],
|
| 134 |
+
"S": ["sulfurous", "sulfur", "alliaceous", "garlic", "onion", "meaty"],
|
| 135 |
+
"T": ["animalic", "animal", "civet", "castoreum", "skunk"],
|
| 136 |
+
"U": ["metallic", "metal"],
|
| 137 |
+
"V": ["waxy", "wax"],
|
| 138 |
+
"W": ["aldehydic", "aldehyde", "soapy", "clean", "powdery"],
|
| 139 |
+
"X": ["solvent", "alcohol", "ethereal", "chemical"],
|
| 140 |
+
"Y": ["powdery", "orris", "violet", "heliotrope"],
|
| 141 |
+
"Z": ["carrier", "oily", "ozone", "fresh"],
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
# Build a flat word -> letter lookup (first occurrence wins for shared words).
|
| 145 |
+
WORD_TO_LETTER: dict[str, str] = {}
|
| 146 |
+
for _letter, _names in LETTER_SYNONYMS.items():
|
| 147 |
+
for _n in _names:
|
| 148 |
+
if _n not in WORD_TO_LETTER:
|
| 149 |
+
WORD_TO_LETTER[_n] = _letter
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def build_tag_to_letter_index(vocab: list[str]) -> dict[int, str]:
|
| 153 |
+
"""Map each Pyrfume tag index to its descriptor letter using the project's
|
| 154 |
+
authoritative v8.2 odour-character crosswalk.
|
| 155 |
+
|
| 156 |
+
Falls back to semantic substring matching for tags not directly in the
|
| 157 |
+
crosswalk. Ambiguous tags (aromatic, floral, fresh, oily, powdery, sweet)
|
| 158 |
+
are left unmapped per the crosswalk's ambiguity policy.
|
| 159 |
+
"""
|
| 160 |
+
crosswalk_path = ROOT / "artifacts" / "odour_character_crosswalk_v8_2.json"
|
| 161 |
+
d2c: dict[str, str] = {}
|
| 162 |
+
ambiguous: set[str] = set()
|
| 163 |
+
if crosswalk_path.exists():
|
| 164 |
+
cw = json.loads(crosswalk_path.read_text())
|
| 165 |
+
d2c = {k.lower(): v for k, v in cw.get("descriptor_to_class", {}).items()}
|
| 166 |
+
ambiguous = set(cw.get("ambiguous_unmapped_descriptors", {}).keys())
|
| 167 |
+
|
| 168 |
+
idx_to_letter: dict[int, str] = {}
|
| 169 |
+
for i, tag in enumerate(vocab):
|
| 170 |
+
tag_lower = tag.lower().strip()
|
| 171 |
+
|
| 172 |
+
# Skip ambiguous tags per crosswalk policy
|
| 173 |
+
if tag_lower in ambiguous:
|
| 174 |
+
idx_to_letter[i] = ""
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
# Direct match
|
| 178 |
+
if tag_lower in d2c:
|
| 179 |
+
idx_to_letter[i] = d2c[tag_lower]
|
| 180 |
+
continue
|
| 181 |
+
|
| 182 |
+
# Normalized match (remove spaces)
|
| 183 |
+
normalized = tag_lower.replace(" ", "")
|
| 184 |
+
norm_d2c = {k.replace(" ", ""): v for k, v in d2c.items()}
|
| 185 |
+
if normalized in norm_d2c:
|
| 186 |
+
idx_to_letter[i] = norm_d2c[normalized]
|
| 187 |
+
continue
|
| 188 |
+
|
| 189 |
+
# Substring match: does any crosswalk key appear in the tag?
|
| 190 |
+
matched = None
|
| 191 |
+
for cw_word, letter in d2c.items():
|
| 192 |
+
if cw_word in tag_lower and cw_word not in ambiguous:
|
| 193 |
+
matched = letter
|
| 194 |
+
break
|
| 195 |
+
idx_to_letter[i] = matched or ""
|
| 196 |
+
return idx_to_letter
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# ---------------------------------------------------------------------------
|
| 200 |
+
# Model loading (mirrors evaluate_frozen_benchmarks.py / evaluate_substantivity.py)
|
| 201 |
+
# ---------------------------------------------------------------------------
|
| 202 |
+
|
| 203 |
+
def sha256_file(path: Path) -> str:
|
| 204 |
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def load_model(ckpt_path: Path, objective_dim: int = 138):
|
| 208 |
+
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 209 |
+
sd = ckpt.get("model_state_dict", ckpt.get("model", {}))
|
| 210 |
+
heads_sd = ckpt.get("heads_state_dict", {})
|
| 211 |
+
hidden_dim, embedding_dim = sd["input_proj.weight"].shape
|
| 212 |
+
state_dim = sd["gating.physics_scaler"].shape[0]
|
| 213 |
+
num_layers = sum(1 for k in sd if k.endswith("self_attn.in_proj_weight"))
|
| 214 |
+
num_heads = 8 if hidden_dim % 8 == 0 and hidden_dim >= 512 else 4
|
| 215 |
+
model = PhysicsInformedMixtureTransformer(
|
| 216 |
+
embedding_dim=int(embedding_dim), state_dim=int(state_dim),
|
| 217 |
+
hidden_dim=int(hidden_dim), num_heads=num_heads,
|
| 218 |
+
num_layers=max(num_layers, 1),
|
| 219 |
+
)
|
| 220 |
+
model.load_state_dict(sd, strict=False)
|
| 221 |
+
model.eval()
|
| 222 |
+
heads = PIMTHeads(hidden_dim=int(hidden_dim), objective_dim=objective_dim)
|
| 223 |
+
if heads_sd:
|
| 224 |
+
heads.load_state_dict(heads_sd, strict=False)
|
| 225 |
+
heads.eval()
|
| 226 |
+
dims = {"embedding_dim": int(embedding_dim), "state_dim": int(state_dim),
|
| 227 |
+
"hidden_dim": int(hidden_dim), "num_layers": num_layers,
|
| 228 |
+
"num_heads": num_heads}
|
| 229 |
+
return model, heads, dims
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# ---------------------------------------------------------------------------
|
| 233 |
+
# Physics conditioning: run the evaporation engine on a single-molecule control
|
| 234 |
+
# ---------------------------------------------------------------------------
|
| 235 |
+
|
| 236 |
+
def run_engine_for_molecule(cas: str, smiles: str) -> np.ndarray | None:
|
| 237 |
+
"""Run the UNIFAC evaporation engine on a single molecule at 15% in ethanol.
|
| 238 |
+
|
| 239 |
+
Returns the physics trajectory (T, 2) = [x_liquid, log10(OAV)] per timestep
|
| 240 |
+
for the target molecule, or None if the engine cannot solve this molecule.
|
| 241 |
+
|
| 242 |
+
Follows the verifier pattern from engine_only_baseline.py and the
|
| 243 |
+
15%-in-ethanol control convention from generate_empirical_bootstrap.py.
|
| 244 |
+
"""
|
| 245 |
+
try:
|
| 246 |
+
from pino.verifier import FragrancePipelineVerifier
|
| 247 |
+
except Exception:
|
| 248 |
+
return None
|
| 249 |
+
|
| 250 |
+
# 15% concentrate in ethanol (matching control record convention)
|
| 251 |
+
ethanol_cas = "64-17-5"
|
| 252 |
+
formula = [
|
| 253 |
+
{"cas": cas, "name": cas, "smiles": smiles, "weight_fraction": 0.15},
|
| 254 |
+
{"cas": ethanol_cas, "name": "Ethanol", "weight_fraction": 0.85},
|
| 255 |
+
]
|
| 256 |
+
try:
|
| 257 |
+
verifier = FragrancePipelineVerifier()
|
| 258 |
+
sim = verifier.run_sim(
|
| 259 |
+
formula,
|
| 260 |
+
duration_seconds=8 * 3600.0,
|
| 261 |
+
interval_seconds=600.0,
|
| 262 |
+
method="BDF",
|
| 263 |
+
skip_ifra=True,
|
| 264 |
+
skip_unresolved=True,
|
| 265 |
+
)
|
| 266 |
+
except Exception as exc:
|
| 267 |
+
logger.debug("Engine failed for %s: %s", cas, exc)
|
| 268 |
+
return None
|
| 269 |
+
|
| 270 |
+
traj = sim.get("trajectory", [])
|
| 271 |
+
if not traj:
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
physics = []
|
| 275 |
+
for rec in traj:
|
| 276 |
+
x_liq = rec["x_liquid"].get(cas, 0.0)
|
| 277 |
+
oav = rec["OAV"].get(cas, 0.0)
|
| 278 |
+
physics.append([x_liq, np.log10(max(oav, 1e-10))])
|
| 279 |
+
arr = np.array(physics, dtype=np.float32)
|
| 280 |
+
if not np.isfinite(arr).all():
|
| 281 |
+
return None
|
| 282 |
+
return arr # (T, 2)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def build_physics_tensor(
|
| 286 |
+
engine_traj: np.ndarray | None,
|
| 287 |
+
state_dim: int,
|
| 288 |
+
conditioning: str,
|
| 289 |
+
) -> torch.Tensor:
|
| 290 |
+
"""Build a (1, T, 1, state_dim) physics tensor for a single molecule.
|
| 291 |
+
|
| 292 |
+
conditioning='on': use the engine trajectory (padded/truncated to state_dim).
|
| 293 |
+
conditioning='off': all zeros.
|
| 294 |
+
"""
|
| 295 |
+
if conditioning == "off" or engine_traj is None:
|
| 296 |
+
# Default T=1 for zeroed physics
|
| 297 |
+
return torch.zeros(1, 1, 1, state_dim)
|
| 298 |
+
T = engine_traj.shape[0]
|
| 299 |
+
phys = torch.zeros(1, T, 1, state_dim)
|
| 300 |
+
n_ch = min(engine_traj.shape[1], state_dim)
|
| 301 |
+
phys[0, :T, 0, :n_ch] = torch.from_numpy(engine_traj[:, :n_ch])
|
| 302 |
+
return phys
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# ---------------------------------------------------------------------------
|
| 306 |
+
# Single-molecule forward pass
|
| 307 |
+
# ---------------------------------------------------------------------------
|
| 308 |
+
|
| 309 |
+
@torch.no_grad()
|
| 310 |
+
def predict_molecule(
|
| 311 |
+
model: PhysicsInformedMixtureTransformer,
|
| 312 |
+
heads: PIMTHeads,
|
| 313 |
+
engine: OlfactoryEmbeddingEngine,
|
| 314 |
+
smiles: str,
|
| 315 |
+
cas: str,
|
| 316 |
+
state_dim: int,
|
| 317 |
+
conditioning: str,
|
| 318 |
+
engine_cache: dict[str, np.ndarray | None],
|
| 319 |
+
) -> dict[str, np.ndarray] | None:
|
| 320 |
+
"""Run one molecule through the trained model under the given conditioning.
|
| 321 |
+
|
| 322 |
+
Returns {substantivity: float, descriptor_profile: (138,)} or None if the
|
| 323 |
+
molecule cannot be embedded.
|
| 324 |
+
"""
|
| 325 |
+
z = engine.get_embedding(smiles, cas=cas)
|
| 326 |
+
if z is None or not np.isfinite(z).any() or np.count_nonzero(z) == 0:
|
| 327 |
+
return None
|
| 328 |
+
|
| 329 |
+
tokens = torch.from_numpy(z).float().unsqueeze(0).unsqueeze(0) # (1, 1, E)
|
| 330 |
+
|
| 331 |
+
# Physics conditioning
|
| 332 |
+
if conditioning == "on":
|
| 333 |
+
if cas not in engine_cache:
|
| 334 |
+
engine_cache[cas] = run_engine_for_molecule(cas, smiles)
|
| 335 |
+
engine_traj = engine_cache[cas]
|
| 336 |
+
else:
|
| 337 |
+
engine_traj = None
|
| 338 |
+
|
| 339 |
+
physics = build_physics_tensor(engine_traj, state_dim, conditioning)
|
| 340 |
+
T = physics.size(1)
|
| 341 |
+
|
| 342 |
+
# Expand tokens to match T timesteps for the FiLM block
|
| 343 |
+
# model.forward expects tokens (B, S, E) and states (B, T, S, state_dim)
|
| 344 |
+
latent = model(tokens, physics) # (1, T, 1, H)
|
| 345 |
+
out = heads(latent, physics)
|
| 346 |
+
|
| 347 |
+
sub = float(out["subjective"]["substantivity"].reshape(-1)[0].cpu())
|
| 348 |
+
# Descriptor profile: mean of 3 tiers, (138,)
|
| 349 |
+
pyramid = out["objective"].squeeze(0).cpu().numpy() # (3, 138)
|
| 350 |
+
profile = pyramid.mean(axis=0)
|
| 351 |
+
return {"substantivity": sub, "descriptor_profile": profile}
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
# ---------------------------------------------------------------------------
|
| 355 |
+
# Benchmark data loading
|
| 356 |
+
# ---------------------------------------------------------------------------
|
| 357 |
+
|
| 358 |
+
def load_substantivity_targets() -> dict[str, float]:
|
| 359 |
+
"""GoodScents measured substantivity hours keyed by CAS (log10-transformed
|
| 360 |
+
to match the frozen probe's protocol)."""
|
| 361 |
+
path = ROOT / "data" / "goodscents_substantivity.json"
|
| 362 |
+
data = json.loads(path.read_text())
|
| 363 |
+
hours = data["cas_to_substantivity_hours"]
|
| 364 |
+
return {cas: float(np.log10(max(h, 1e-6))) for cas, h in hours.items()}
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def load_descriptor_targets() -> tuple[dict[str, str], dict[str, dict[str, float]]]:
|
| 368 |
+
"""Per-CAS dominant descriptor letter + full distribution.
|
| 369 |
+
|
| 370 |
+
Returns (dominant_letter_map, full_distribution_map).
|
| 371 |
+
"""
|
| 372 |
+
dominant: dict[str, str] = {}
|
| 373 |
+
full: dict[str, dict[str, float]] = {}
|
| 374 |
+
path = ROOT / "data" / "descriptor_distributions_v11.jsonl"
|
| 375 |
+
for line in path.read_text().splitlines():
|
| 376 |
+
if not line.strip():
|
| 377 |
+
continue
|
| 378 |
+
try:
|
| 379 |
+
r = json.loads(line)
|
| 380 |
+
except Exception:
|
| 381 |
+
continue
|
| 382 |
+
dist = r.get("descriptor_distribution") or {}
|
| 383 |
+
if dist:
|
| 384 |
+
dominant[r["cas"]] = max(dist, key=dist.get)
|
| 385 |
+
full[r["cas"]] = dist
|
| 386 |
+
return dominant, full
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def load_pyrfume_vocab() -> list[str]:
|
| 390 |
+
return json.loads((ROOT / "data" / "pyrfume_vocabulary.json").read_text())["vocabulary"]
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def get_cas_smiles(cas: str) -> str:
|
| 394 |
+
"""Best-effort SMILES lookup from the registry."""
|
| 395 |
+
try:
|
| 396 |
+
from pino.registry import AromaRegistry
|
| 397 |
+
reg = AromaRegistry()
|
| 398 |
+
rec = reg.get(cas)
|
| 399 |
+
reg.close()
|
| 400 |
+
return rec.get("smiles", "") if rec else ""
|
| 401 |
+
except Exception:
|
| 402 |
+
return ""
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
# ---------------------------------------------------------------------------
|
| 406 |
+
# Scoring
|
| 407 |
+
# ---------------------------------------------------------------------------
|
| 408 |
+
|
| 409 |
+
def spearman_rho(a: np.ndarray, b: np.ndarray) -> float:
|
| 410 |
+
if len(a) < 3 or np.std(a) == 0 or np.std(b) == 0:
|
| 411 |
+
return float("nan")
|
| 412 |
+
ra = np.argsort(np.argsort(a))
|
| 413 |
+
rb = np.argsort(np.argsort(b))
|
| 414 |
+
return float(np.corrcoef(ra, rb)[0, 1])
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def macro_f1(y_true: np.ndarray, y_pred: np.ndarray) -> float:
|
| 418 |
+
from sklearn.metrics import f1_score
|
| 419 |
+
return float(f1_score(y_true, y_pred, average="macro", zero_division=0))
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def evaluate_substantivity(
|
| 423 |
+
preds: dict[str, float],
|
| 424 |
+
targets: dict[str, float],
|
| 425 |
+
) -> dict[str, Any]:
|
| 426 |
+
"""Spearman rho between model predictions and log10(hours) targets."""
|
| 427 |
+
cas_list = sorted(set(preds) & set(targets))
|
| 428 |
+
if len(cas_list) < 3:
|
| 429 |
+
return {"rho": None, "n": len(cas_list),
|
| 430 |
+
"note": "Insufficient molecules with both prediction and target."}
|
| 431 |
+
p = np.array([preds[c] for c in cas_list])
|
| 432 |
+
t = np.array([targets[c] for c in cas_list])
|
| 433 |
+
rho = spearman_rho(p, t)
|
| 434 |
+
return {"rho": round(rho, 4) if rho == rho else None,
|
| 435 |
+
"n": len(cas_list)}
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def evaluate_descriptors(
|
| 439 |
+
profiles: dict[str, np.ndarray],
|
| 440 |
+
dominant_letter: dict[str, str],
|
| 441 |
+
tag_to_letter: dict[int, str],
|
| 442 |
+
binarize_threshold: float = 0.5,
|
| 443 |
+
) -> dict[str, Any]:
|
| 444 |
+
"""Macro-F1 of predicted dominant descriptor letter vs benchmark target.
|
| 445 |
+
|
| 446 |
+
Protocol:
|
| 447 |
+
1. Take the model's predicted 138-dim profile (mean of 3 tiers, sigmoid
|
| 448 |
+
activations).
|
| 449 |
+
2. For each descriptor letter class, aggregate the continuous sigmoid
|
| 450 |
+
values of all Pyrfume tags mapped to that letter (via semantic
|
| 451 |
+
synonym crosswalk). The predicted dominant letter = argmax of the
|
| 452 |
+
per-letter aggregate. This mirrors how the benchmark itself defines
|
| 453 |
+
the dominant letter (argmax of descriptor_distribution) and is the
|
| 454 |
+
direct analog of the model-free probe's classifier prediction.
|
| 455 |
+
3. Compute macro-F1 vs the benchmark's per-molecule dominant letter.
|
| 456 |
+
|
| 457 |
+
We also report a binarized variant (threshold 0.5) as a secondary metric
|
| 458 |
+
for transparency, but the primary metric uses continuous aggregation
|
| 459 |
+
because the trained model's sigmoid outputs rarely exceed 0.5 on
|
| 460 |
+
held-out molecules. We use the MEAN (not sum) of sigmoid values per letter
|
| 461 |
+
to normalize for the varying number of tags mapped to each letter.
|
| 462 |
+
"""
|
| 463 |
+
cas_list = sorted(set(profiles) & set(dominant_letter))
|
| 464 |
+
if len(cas_list) < 3:
|
| 465 |
+
return {"macro_f1": None, "n": len(cas_list),
|
| 466 |
+
"protocol_note": "Insufficient molecules."}
|
| 467 |
+
|
| 468 |
+
# Build letter aggregator: for each letter, which tag indices map to it
|
| 469 |
+
letters = sorted(set(tag_to_letter.values()) - {""})
|
| 470 |
+
if not letters:
|
| 471 |
+
return {"macro_f1": None, "n": len(cas_list),
|
| 472 |
+
"protocol_note": "No tag-to-letter mapping available."}
|
| 473 |
+
|
| 474 |
+
letter_tag_indices: dict[str, list[int]] = {l: [] for l in letters}
|
| 475 |
+
for idx, letter in tag_to_letter.items():
|
| 476 |
+
if letter:
|
| 477 |
+
letter_tag_indices[letter].append(idx)
|
| 478 |
+
|
| 479 |
+
y_true, y_pred, y_pred_bin = [], [], []
|
| 480 |
+
for cas in cas_list:
|
| 481 |
+
prof = profiles[cas]
|
| 482 |
+
# Continuous aggregation: MEAN of sigmoid values per letter (normalizes
|
| 483 |
+
# for the number of tags mapped to each letter, preventing the bias
|
| 484 |
+
# where letters with more synonyms always dominate).
|
| 485 |
+
letter_scores = np.zeros(len(letters))
|
| 486 |
+
for li, letter in enumerate(letters):
|
| 487 |
+
idxs = letter_tag_indices[letter]
|
| 488 |
+
if idxs:
|
| 489 |
+
letter_scores[li] = prof[idxs].mean()
|
| 490 |
+
pred_letter = letters[int(np.argmax(letter_scores))] if letter_scores.max() > 0 else letters[0]
|
| 491 |
+
|
| 492 |
+
# Binarized variant
|
| 493 |
+
binary = (prof >= binarize_threshold).astype(float)
|
| 494 |
+
letter_scores_bin = np.zeros(len(letters))
|
| 495 |
+
for li, letter in enumerate(letters):
|
| 496 |
+
idxs = letter_tag_indices[letter]
|
| 497 |
+
if idxs:
|
| 498 |
+
letter_scores_bin[li] = binary[idxs].sum()
|
| 499 |
+
pred_letter_bin = letters[int(np.argmax(letter_scores_bin))] if letter_scores_bin.max() > 0 else letters[0]
|
| 500 |
+
|
| 501 |
+
y_true.append(dominant_letter[cas])
|
| 502 |
+
y_pred.append(pred_letter)
|
| 503 |
+
y_pred_bin.append(pred_letter_bin)
|
| 504 |
+
|
| 505 |
+
y_true = np.array(y_true)
|
| 506 |
+
y_pred = np.array(y_pred)
|
| 507 |
+
y_pred_bin = np.array(y_pred_bin)
|
| 508 |
+
f1 = macro_f1(y_true, y_pred)
|
| 509 |
+
f1_bin = macro_f1(y_true, y_pred_bin)
|
| 510 |
+
n_classes = len(set(y_true) | set(y_pred))
|
| 511 |
+
return {
|
| 512 |
+
"macro_f1": round(f1, 4),
|
| 513 |
+
"macro_f1_binarized": round(f1_bin, 4),
|
| 514 |
+
"n": len(cas_list),
|
| 515 |
+
"n_classes_evaluated": n_classes,
|
| 516 |
+
"aggregation": "continuous_sigmoid_mean_then_argmax",
|
| 517 |
+
"binarize_threshold": binarize_threshold,
|
| 518 |
+
"protocol_note": (
|
| 519 |
+
"Trained model's predicted 138-dim profile (mean of 3 pyramid tiers, "
|
| 520 |
+
"sigmoid activations) aggregated per descriptor letter by taking the "
|
| 521 |
+
"MEAN of sigmoid values of tags mapped to each letter via the "
|
| 522 |
+
"project's authoritative v8.2 odour-character crosswalk "
|
| 523 |
+
"(artifacts/odour_character_crosswalk_v8_2.json); dominant letter = "
|
| 524 |
+
"argmax. This mirrors the benchmark's own dominant-letter definition "
|
| 525 |
+
"(argmax of descriptor_distribution). Differs from the model-free "
|
| 526 |
+
"frozen probe, which trains a LogisticRegression classifier directly "
|
| 527 |
+
"on frozen embeddings to predict the dominant letter. "
|
| 528 |
+
"macro_f1_binarized additionally reports the binarized-at-0.5 variant."
|
| 529 |
+
),
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
# ---------------------------------------------------------------------------
|
| 534 |
+
# Main evaluation loop
|
| 535 |
+
# ---------------------------------------------------------------------------
|
| 536 |
+
|
| 537 |
+
def parse_seed_from_name(name: str) -> int | None:
|
| 538 |
+
m = re.search(r"seed(\d+)", name)
|
| 539 |
+
return int(m.group(1)) if m else None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def parse_arm_from_name(name: str) -> str:
|
| 543 |
+
if "physoff" in name.lower():
|
| 544 |
+
return "physoff"
|
| 545 |
+
if "openpom" in name.lower() or "pimt_ab" in name.lower():
|
| 546 |
+
return "openpom"
|
| 547 |
+
return "unknown"
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def download_checkpoint(filename: str, hf_token: str | None) -> Path:
|
| 551 |
+
from huggingface_hub import hf_hub_download
|
| 552 |
+
path = hf_hub_download(
|
| 553 |
+
repo_id="mattbitzesty/pino-pimt-representation-ab",
|
| 554 |
+
filename=filename,
|
| 555 |
+
token=hf_token,
|
| 556 |
+
)
|
| 557 |
+
return Path(path)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def main() -> int:
|
| 561 |
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
| 562 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 563 |
+
ap.add_argument("--checkpoints", nargs="+", default=None,
|
| 564 |
+
help="Checkpoint filenames in the HF repo (e.g. pimt_ab_openpom_256_seed1.pt)")
|
| 565 |
+
ap.add_argument("--seeds", nargs="+", type=int, default=None,
|
| 566 |
+
help="Alternative: specify seeds to auto-generate filenames for both arms.")
|
| 567 |
+
ap.add_argument("--output", default=str(ROOT / "artifacts" / "trained_frozen_probes"),
|
| 568 |
+
help="Output directory.")
|
| 569 |
+
ap.add_argument("--max-molecules", type=int, default=None,
|
| 570 |
+
help="Smoke test: limit to first N benchmark molecules.")
|
| 571 |
+
ap.add_argument("--structural-source", default="openpom_256",
|
| 572 |
+
help="Embedding source (both arms use openpom_256).")
|
| 573 |
+
ap.add_argument("--conditioning", nargs="+", default=["on", "off"],
|
| 574 |
+
choices=["on", "off"],
|
| 575 |
+
help="Which conditioning modes to evaluate.")
|
| 576 |
+
args = ap.parse_args()
|
| 577 |
+
|
| 578 |
+
# Resolve checkpoint list
|
| 579 |
+
hf_token = None
|
| 580 |
+
ckpt_files: list[str] = []
|
| 581 |
+
if args.checkpoints:
|
| 582 |
+
ckpt_files = args.checkpoints
|
| 583 |
+
elif args.seeds:
|
| 584 |
+
for s in args.seeds:
|
| 585 |
+
ckpt_files.append(f"pimt_ab_openpom_256_seed{s}.pt")
|
| 586 |
+
ckpt_files.append(f"pimt_physoff_openpom_256_seed{s}.pt")
|
| 587 |
+
else:
|
| 588 |
+
ap.error("Provide --checkpoints or --seeds.")
|
| 589 |
+
|
| 590 |
+
# Get HF token
|
| 591 |
+
try:
|
| 592 |
+
import subprocess
|
| 593 |
+
result = subprocess.run(
|
| 594 |
+
['op', 'item', 'get', 'Huggingface', '--vault', 'Automation',
|
| 595 |
+
'--fields', 'access token', '--reveal'],
|
| 596 |
+
capture_output=True, text=True, timeout=15,
|
| 597 |
+
)
|
| 598 |
+
if result.returncode == 0 and result.stdout.strip():
|
| 599 |
+
hf_token = result.stdout.strip()
|
| 600 |
+
except Exception:
|
| 601 |
+
pass
|
| 602 |
+
|
| 603 |
+
# Load benchmark data
|
| 604 |
+
subst_targets = load_substantivity_targets()
|
| 605 |
+
desc_dominant, _ = load_descriptor_targets()
|
| 606 |
+
vocab = load_pyrfume_vocab()
|
| 607 |
+
tag_to_letter = build_tag_to_letter_index(vocab)
|
| 608 |
+
|
| 609 |
+
logger.info("Substantivity table (full): %d molecules", len(subst_targets))
|
| 610 |
+
logger.info("Descriptor table (full): %d molecules (%d classes)",
|
| 611 |
+
len(desc_dominant), len(set(desc_dominant.values())))
|
| 612 |
+
|
| 613 |
+
# Restrict to the FROZEN benchmark molecule sets used by the model-free probe
|
| 614 |
+
# (run_representation_ablation.py): cas in (target table ∩ POM ∩ Morgan/registry).
|
| 615 |
+
# This makes the trained-arm numbers directly comparable to tab:main (n=213
|
| 616 |
+
# substantivity, n=339 descriptor) rather than a different superset.
|
| 617 |
+
pom_index = json.loads((ROOT / "artifacts" / "pom" / "pom_index.json").read_text())
|
| 618 |
+
# Mirror run_representation_ablation.load_pom(): valid rows only; SMILES:/NATURAL:
|
| 619 |
+
# ids resolved to registry CAS via their SMILES.
|
| 620 |
+
import sqlite3 as _sqlite3
|
| 621 |
+
import os as _os
|
| 622 |
+
_db = _os.environ.get("PINO_REGISTRY_PATH") or str(ROOT / "src" / "pino" / "registry.db")
|
| 623 |
+
_con = _sqlite3.connect(_db)
|
| 624 |
+
smi2cas = {r[0]: r[1] for r in _con.execute(
|
| 625 |
+
"SELECT smiles, cas FROM aroma_chemicals WHERE smiles IS NOT NULL AND smiles!=''")}
|
| 626 |
+
_con.close()
|
| 627 |
+
pom_keys: set[str] = set()
|
| 628 |
+
for cid, smi, ok in zip(pom_index["ids"], pom_index["smiles"], pom_index["valid"]):
|
| 629 |
+
if not ok:
|
| 630 |
+
continue
|
| 631 |
+
if cid.startswith(("SMILES:", "NATURAL:")):
|
| 632 |
+
key = smi2cas.get(smi)
|
| 633 |
+
if key is None:
|
| 634 |
+
continue
|
| 635 |
+
pom_keys.add(key)
|
| 636 |
+
else:
|
| 637 |
+
pom_keys.add(cid)
|
| 638 |
+
reg_smiles: dict[str, str] = {}
|
| 639 |
+
try:
|
| 640 |
+
from pino.registry import AromaRegistry
|
| 641 |
+
_reg = AromaRegistry()
|
| 642 |
+
for _cas in sorted(set(subst_targets) | set(desc_dominant)):
|
| 643 |
+
_rec = _reg.get(_cas)
|
| 644 |
+
if _rec and _rec.get("smiles"):
|
| 645 |
+
reg_smiles[_cas] = _rec["smiles"]
|
| 646 |
+
_reg.close()
|
| 647 |
+
except Exception as e:
|
| 648 |
+
logger.warning("registry load failed: %s", e)
|
| 649 |
+
registry_keys = set(reg_smiles)
|
| 650 |
+
|
| 651 |
+
subst_frozen = sorted(set(subst_targets) & pom_keys & registry_keys)
|
| 652 |
+
desc_frozen = sorted(set(desc_dominant) & pom_keys & registry_keys)
|
| 653 |
+
logger.info("Frozen benchmark sets: substantivity n=%d (paper n=213), descriptor n=%d (paper n=339)",
|
| 654 |
+
len(subst_frozen), len(desc_frozen))
|
| 655 |
+
subst_targets = {c: subst_targets[c] for c in subst_frozen}
|
| 656 |
+
desc_dominant = {c: desc_dominant[c] for c in desc_frozen}
|
| 657 |
+
|
| 658 |
+
# CAS -> SMILES for all benchmark molecules (needed for embedding + engine)
|
| 659 |
+
all_cas = sorted(set(subst_targets) | set(desc_dominant))
|
| 660 |
+
if args.max_molecules:
|
| 661 |
+
all_cas = all_cas[: args.max_molecules]
|
| 662 |
+
logger.info("Total benchmark molecules to evaluate: %d", len(all_cas))
|
| 663 |
+
|
| 664 |
+
cas_smiles: dict[str, str] = dict(reg_smiles)
|
| 665 |
+
resolvable = {cas for cas, smi in cas_smiles.items() if smi}
|
| 666 |
+
logger.info("Resolvable (have SMILES): %d / %d", len(resolvable), len(all_cas))
|
| 667 |
+
|
| 668 |
+
# Embedding engine
|
| 669 |
+
engine = OlfactoryEmbeddingEngine(structural_source=args.structural_source)
|
| 670 |
+
logger.info("Embedding engine: %s (dim=%d)", args.structural_source, engine.embedding_dim)
|
| 671 |
+
|
| 672 |
+
out_dir = Path(args.output)
|
| 673 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 674 |
+
|
| 675 |
+
all_results = []
|
| 676 |
+
|
| 677 |
+
for ckpt_name in ckpt_files:
|
| 678 |
+
arm = parse_arm_from_name(ckpt_name)
|
| 679 |
+
seed = parse_seed_from_name(ckpt_name)
|
| 680 |
+
logger.info("=" * 60)
|
| 681 |
+
logger.info("Checkpoint: %s (arm=%s, seed=%s)", ckpt_name, arm, seed)
|
| 682 |
+
|
| 683 |
+
# Download checkpoint
|
| 684 |
+
ckpt_path = download_checkpoint(ckpt_name, hf_token)
|
| 685 |
+
sha = sha256_file(ckpt_path)
|
| 686 |
+
|
| 687 |
+
# Load model
|
| 688 |
+
model, heads, dims = load_model(ckpt_path)
|
| 689 |
+
state_dim = dims["state_dim"]
|
| 690 |
+
logger.info("Model dims: %s", dims)
|
| 691 |
+
|
| 692 |
+
for conditioning in args.conditioning:
|
| 693 |
+
logger.info("-" * 40)
|
| 694 |
+
logger.info("Conditioning: %s", conditioning)
|
| 695 |
+
|
| 696 |
+
engine_cache: dict[str, np.ndarray | None] = {}
|
| 697 |
+
sub_preds: dict[str, float] = {}
|
| 698 |
+
desc_profiles: dict[str, np.ndarray] = {}
|
| 699 |
+
|
| 700 |
+
for i, cas in enumerate(all_cas):
|
| 701 |
+
smiles = cas_smiles.get(cas, "")
|
| 702 |
+
if not smiles:
|
| 703 |
+
continue
|
| 704 |
+
result = predict_molecule(
|
| 705 |
+
model, heads, engine, smiles, cas,
|
| 706 |
+
state_dim, conditioning, engine_cache,
|
| 707 |
+
)
|
| 708 |
+
if result is None:
|
| 709 |
+
continue
|
| 710 |
+
sub_preds[cas] = result["substantivity"]
|
| 711 |
+
desc_profiles[cas] = result["descriptor_profile"]
|
| 712 |
+
if (i + 1) % 50 == 0:
|
| 713 |
+
logger.info(" %d/%d molecules processed", i + 1, len(all_cas))
|
| 714 |
+
|
| 715 |
+
logger.info("Predictions: substantivity=%d, descriptors=%d",
|
| 716 |
+
len(sub_preds), len(desc_profiles))
|
| 717 |
+
|
| 718 |
+
sub_result = evaluate_substantivity(sub_preds, subst_targets)
|
| 719 |
+
desc_result = evaluate_descriptors(
|
| 720 |
+
desc_profiles, desc_dominant, tag_to_letter,
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
record = {
|
| 724 |
+
"arm": arm,
|
| 725 |
+
"checkpoint": ckpt_name,
|
| 726 |
+
"checkpoint_sha256": sha,
|
| 727 |
+
"seed": seed,
|
| 728 |
+
"conditioning": conditioning,
|
| 729 |
+
"model_dims": dims,
|
| 730 |
+
"substantivity": sub_result,
|
| 731 |
+
"descriptors": desc_result,
|
| 732 |
+
"threshold": {
|
| 733 |
+
"not_applicable": (
|
| 734 |
+
"The trained PIMT model has no odor-threshold head; "
|
| 735 |
+
"it was never trained against ODT targets."
|
| 736 |
+
),
|
| 737 |
+
},
|
| 738 |
+
"n_predictions": {
|
| 739 |
+
"substantivity": len(sub_preds),
|
| 740 |
+
"descriptors": len(desc_profiles),
|
| 741 |
+
},
|
| 742 |
+
}
|
| 743 |
+
all_results.append(record)
|
| 744 |
+
|
| 745 |
+
# Save per-checkpoint-conditioning file
|
| 746 |
+
safe_name = ckpt_name.replace(".pt", f"_{conditioning}.json")
|
| 747 |
+
out_path = out_dir / safe_name
|
| 748 |
+
out_path.write_text(json.dumps(record, indent=2))
|
| 749 |
+
logger.info("Saved: %s", out_path)
|
| 750 |
+
logger.info(" substantivity rho=%s (n=%s)",
|
| 751 |
+
sub_result["rho"], sub_result["n"])
|
| 752 |
+
logger.info(" descriptor macro_f1=%s (n=%s)",
|
| 753 |
+
desc_result["macro_f1"], desc_result["n"])
|
| 754 |
+
|
| 755 |
+
# Save combined results
|
| 756 |
+
combined_path = out_dir / "all_results.json"
|
| 757 |
+
combined_path.write_text(json.dumps(all_results, indent=2))
|
| 758 |
+
logger.info("=" * 60)
|
| 759 |
+
logger.info("Combined results: %s (%d records)", combined_path, len(all_results))
|
| 760 |
+
|
| 761 |
+
# Print summary table
|
| 762 |
+
print("\n" + "=" * 80)
|
| 763 |
+
print(f"{'Arm':<10} {'Seed':<6} {'Cond':<6} {'Sub rho':<10} {'Sub n':<6} "
|
| 764 |
+
f"{'Desc F1':<10} {'Desc n':<6}")
|
| 765 |
+
print("-" * 80)
|
| 766 |
+
for r in all_results:
|
| 767 |
+
s = r["substantivity"]
|
| 768 |
+
d = r["descriptors"]
|
| 769 |
+
print(f"{r['arm']:<10} {str(r['seed']):<6} {r['conditioning']:<6} "
|
| 770 |
+
f"{str(s.get('rho')):<10} {str(s.get('n')):<6} "
|
| 771 |
+
f"{str(d.get('macro_f1')):<10} {str(d.get('n')):<6}")
|
| 772 |
+
print("=" * 80)
|
| 773 |
+
|
| 774 |
+
return 0
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
if __name__ == "__main__":
|
| 778 |
+
raise SystemExit(main())
|