Matthew Ford commited on
Commit ·
3383ed6
1
Parent(s): 7cc735d
feat: harden v7 HF training and eval
Browse filesFormer-commit-id: 8e6a16a45ace09def4aa25308b4ee416421d4b8d
Former-commit-id: 261e5a6603049d6ef1c30783164aad87286806b2
- metrics_v6_current.json +195 -0
- scripts/eval_v6.py +247 -100
- scripts/hf_train_job.py +26 -1
metrics_v6_current.json
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checkpoint": {
|
| 3 |
+
"path": "models/pimt_v6.pt",
|
| 4 |
+
"epoch": 2,
|
| 5 |
+
"val_loss": 0.484091709347537,
|
| 6 |
+
"hidden_dim": 256,
|
| 7 |
+
"embedding_dim": 151,
|
| 8 |
+
"state_dim": 2,
|
| 9 |
+
"num_layers": 4,
|
| 10 |
+
"num_heads": 4
|
| 11 |
+
},
|
| 12 |
+
"data": {
|
| 13 |
+
"path": "data/empirical_dataset_v8.jsonl",
|
| 14 |
+
"n_records": 6078,
|
| 15 |
+
"n_validation_samples": 1089
|
| 16 |
+
},
|
| 17 |
+
"prediction": {
|
| 18 |
+
"profile_mse": 0.01670854724943638,
|
| 19 |
+
"profile_mae": 0.08257085829973221,
|
| 20 |
+
"profile_prediction_variance": 0.003912549465894699,
|
| 21 |
+
"tier_prediction_variance": 0.009843787178397179,
|
| 22 |
+
"tier_metrics": {
|
| 23 |
+
"top": {
|
| 24 |
+
"mse": 0.03479713946580887,
|
| 25 |
+
"mae": 0.06280406564474106,
|
| 26 |
+
"prediction_variance": 0.0011337018804624677,
|
| 27 |
+
"target_variance": 0.03625021129846573,
|
| 28 |
+
"mean_pairwise_cosine_similarity": 0.9688117237632773,
|
| 29 |
+
"mean_spearman_rho": 0.21981701217589275
|
| 30 |
+
},
|
| 31 |
+
"middle": {
|
| 32 |
+
"mse": 0.020692989230155945,
|
| 33 |
+
"mae": 0.0404493473470211,
|
| 34 |
+
"prediction_variance": 0.0006535974680446088,
|
| 35 |
+
"target_variance": 0.02135564014315605,
|
| 36 |
+
"mean_pairwise_cosine_similarity": 0.9567461467957046,
|
| 37 |
+
"mean_spearman_rho": 0.20025567720380308
|
| 38 |
+
},
|
| 39 |
+
"base": {
|
| 40 |
+
"mse": 0.09510858356952667,
|
| 41 |
+
"mae": 0.1818365752696991,
|
| 42 |
+
"prediction_variance": 0.021325431764125824,
|
| 43 |
+
"target_variance": 0.11628847569227219,
|
| 44 |
+
"mean_pairwise_cosine_similarity": 0.9431027251998285,
|
| 45 |
+
"mean_spearman_rho": 0.32991390136684196
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
},
|
| 49 |
+
"spearman": {
|
| 50 |
+
"flat_spearman_rho": 0.27788543250229925,
|
| 51 |
+
"flat_spearman_p_value": 0.0,
|
| 52 |
+
"profile_spearman_rho": 0.3537687699618818,
|
| 53 |
+
"profile_spearman_p_value": 0.0
|
| 54 |
+
},
|
| 55 |
+
"top_descriptors": {
|
| 56 |
+
"top": {
|
| 57 |
+
"predicted": [
|
| 58 |
+
{
|
| 59 |
+
"descriptor": "fresh",
|
| 60 |
+
"score": 0.1774865686893463
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"descriptor": "sulfurous",
|
| 64 |
+
"score": 0.1653631627559662
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"descriptor": "fishy",
|
| 68 |
+
"score": 0.13863913714885712
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"descriptor": "fatty",
|
| 72 |
+
"score": 0.1347414255142212
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"descriptor": "earthy",
|
| 76 |
+
"score": 0.130441352725029
|
| 77 |
+
}
|
| 78 |
+
],
|
| 79 |
+
"target": [
|
| 80 |
+
{
|
| 81 |
+
"descriptor": "fresh",
|
| 82 |
+
"score": 0.2029384821653366
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"descriptor": "sulfurous",
|
| 86 |
+
"score": 0.18824610114097595
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"descriptor": "fishy",
|
| 90 |
+
"score": 0.15518824756145477
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"descriptor": "earthy",
|
| 94 |
+
"score": 0.1515151560306549
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"descriptor": "popcorn",
|
| 98 |
+
"score": 0.127640038728714
|
| 99 |
+
}
|
| 100 |
+
]
|
| 101 |
+
},
|
| 102 |
+
"middle": {
|
| 103 |
+
"predicted": [
|
| 104 |
+
{
|
| 105 |
+
"descriptor": "fresh",
|
| 106 |
+
"score": 0.15246763825416565
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"descriptor": "sulfurous",
|
| 110 |
+
"score": 0.1356164962053299
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"descriptor": "grassy",
|
| 114 |
+
"score": 0.09715040773153305
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"descriptor": "fishy",
|
| 118 |
+
"score": 0.07722806930541992
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"descriptor": "earthy",
|
| 122 |
+
"score": 0.0631425753235817
|
| 123 |
+
}
|
| 124 |
+
],
|
| 125 |
+
"target": [
|
| 126 |
+
{
|
| 127 |
+
"descriptor": "fresh",
|
| 128 |
+
"score": 0.1873278170824051
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"descriptor": "sulfurous",
|
| 132 |
+
"score": 0.15059687197208405
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"descriptor": "earthy",
|
| 136 |
+
"score": 0.09182736277580261
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"descriptor": "grassy",
|
| 140 |
+
"score": 0.09182736277580261
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"descriptor": "fishy",
|
| 144 |
+
"score": 0.07346189022064209
|
| 145 |
+
}
|
| 146 |
+
]
|
| 147 |
+
},
|
| 148 |
+
"base": {
|
| 149 |
+
"predicted": [
|
| 150 |
+
{
|
| 151 |
+
"descriptor": "sulfurous",
|
| 152 |
+
"score": 0.8006615042686462
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"descriptor": "fresh",
|
| 156 |
+
"score": 0.663232147693634
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"descriptor": "fermented",
|
| 160 |
+
"score": 0.5910075306892395
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"descriptor": "waxy",
|
| 164 |
+
"score": 0.5055632591247559
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"descriptor": "grassy",
|
| 168 |
+
"score": 0.4854605197906494
|
| 169 |
+
}
|
| 170 |
+
],
|
| 171 |
+
"target": [
|
| 172 |
+
{
|
| 173 |
+
"descriptor": "sulfurous",
|
| 174 |
+
"score": 0.8126721978187561
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"descriptor": "fermented",
|
| 178 |
+
"score": 0.6391184329986572
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"descriptor": "fresh",
|
| 182 |
+
"score": 0.6391184329986572
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"descriptor": "waxy",
|
| 186 |
+
"score": 0.5325987339019775
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"descriptor": "balsamic",
|
| 190 |
+
"score": 0.5307621955871582
|
| 191 |
+
}
|
| 192 |
+
]
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
}
|
scripts/eval_v6.py
CHANGED
|
@@ -1,107 +1,254 @@
|
|
|
|
|
|
|
|
| 1 |
|
| 2 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from torch.utils.data import DataLoader
|
| 4 |
-
|
| 5 |
from pino.heads import PIMTHeads
|
| 6 |
-
from pino.
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
ckpt = torch.load("models/pimt_v6.pt", map_location="cpu", weights_only=False)
|
| 10 |
-
sd = ckpt["model_state_dict"]
|
| 11 |
-
emb_dim = sd["input_proj.weight"].shape[1]
|
| 12 |
-
hidden_dim = sd["input_proj.weight"].shape[0]
|
| 13 |
-
state_dim = sd["gating.physics_scaler"].shape[0]
|
| 14 |
|
| 15 |
-
|
| 16 |
-
embedding_dim=emb_dim, state_dim=state_dim, hidden_dim=hidden_dim,
|
| 17 |
-
num_heads=8, num_layers=4
|
| 18 |
-
)
|
| 19 |
-
model.load_state_dict(ckpt["model_state_dict"])
|
| 20 |
-
model.eval()
|
| 21 |
|
| 22 |
-
heads = PIMTHeads(hidden_dim=hidden_dim, objective_dim=138)
|
| 23 |
-
heads.load_state_dict(ckpt["heads_state_dict"])
|
| 24 |
-
heads.eval()
|
| 25 |
|
| 26 |
-
|
| 27 |
-
"
|
| 28 |
-
|
| 29 |
-
)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from scipy.spatial.distance import pdist
|
| 12 |
+
from scipy.stats import spearmanr
|
| 13 |
from torch.utils.data import DataLoader
|
| 14 |
+
|
| 15 |
from pino.heads import PIMTHeads
|
| 16 |
+
from pino.pimt_model import (
|
| 17 |
+
DEFAULT_EMBEDDING_DIM,
|
| 18 |
+
FragranceTrajectoryDataset,
|
| 19 |
+
PhysicsInformedMixtureTransformer,
|
| 20 |
+
)
|
| 21 |
+
from pino.train import pad_trajectory_collate
|
| 22 |
+
from pino.upload_data import create_formula_disjoint_split_from_records
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
DEFAULT_GENRES = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
def parse_args() -> argparse.Namespace:
|
| 29 |
+
parser = argparse.ArgumentParser(description="Evaluate a PINO PIMT checkpoint.")
|
| 30 |
+
parser.add_argument("--checkpoint", default="models/pimt_v6.pt", help="Local checkpoint path.")
|
| 31 |
+
parser.add_argument("--data", default="data/empirical_dataset_v8.jsonl", help="Evaluation dataset JSONL.")
|
| 32 |
+
parser.add_argument("--batch-size", type=int, default=8)
|
| 33 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 34 |
+
parser.add_argument("--output", default="metrics_v6_current.json", help="Metrics JSON output path.")
|
| 35 |
+
parser.add_argument(
|
| 36 |
+
"--hf-repo",
|
| 37 |
+
default=None,
|
| 38 |
+
help="Optional HF model repo to download --hf-filename from before evaluation.",
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument("--hf-filename", default=None, help="Checkpoint filename in --hf-repo.")
|
| 41 |
+
parser.add_argument("--hf-token", default=None, help="HF token override; defaults to cached auth/env.")
|
| 42 |
+
return parser.parse_args()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def resolve_checkpoint(args: argparse.Namespace) -> Path:
|
| 46 |
+
checkpoint = Path(args.checkpoint)
|
| 47 |
+
if checkpoint.exists():
|
| 48 |
+
return checkpoint
|
| 49 |
+
if not args.hf_repo:
|
| 50 |
+
raise FileNotFoundError(f"Checkpoint not found: {checkpoint}")
|
| 51 |
+
|
| 52 |
+
from huggingface_hub import hf_hub_download
|
| 53 |
+
|
| 54 |
+
filename = args.hf_filename or checkpoint.name
|
| 55 |
+
downloaded = hf_hub_download(
|
| 56 |
+
repo_id=args.hf_repo,
|
| 57 |
+
filename=filename,
|
| 58 |
+
token=args.hf_token,
|
| 59 |
+
)
|
| 60 |
+
return Path(downloaded)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def read_records(path: str | Path) -> list[dict[str, Any]]:
|
| 64 |
+
with Path(path).open("r", encoding="utf-8") as f:
|
| 65 |
+
return [json.loads(line) for line in f if line.strip()]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def make_validation_dataset(records: list[dict[str, Any]]) -> FragranceTrajectoryDataset:
|
| 69 |
+
control_records = [r for r in records if r.get("is_control", False)]
|
| 70 |
+
mixture_records = [r for r in records if not r.get("is_control", False)]
|
| 71 |
+
_, mixture_val = create_formula_disjoint_split_from_records(mixture_records, train_ratio=0.8)
|
| 72 |
+
genre_map = {genre: idx for idx, genre in enumerate(DEFAULT_GENRES)}
|
| 73 |
+
return FragranceTrajectoryDataset(
|
| 74 |
+
records=mixture_val,
|
| 75 |
+
use_embedding_fallback=True,
|
| 76 |
+
genre_map=genre_map,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def load_vocab(path: str | Path = "data/pyrfume_vocabulary.json") -> list[str]:
|
| 81 |
+
with Path(path).open("r", encoding="utf-8") as f:
|
| 82 |
+
raw = json.load(f)
|
| 83 |
+
if isinstance(raw, dict) and isinstance(raw.get("vocabulary"), list):
|
| 84 |
+
return [str(v) for v in raw["vocabulary"]]
|
| 85 |
+
if isinstance(raw, dict):
|
| 86 |
+
return [str(raw[k]) for k in sorted(raw)]
|
| 87 |
+
if isinstance(raw, list):
|
| 88 |
+
return [str(v) for v in raw]
|
| 89 |
+
return []
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def infer_model_dims(state_dict: dict[str, torch.Tensor]) -> dict[str, int]:
|
| 93 |
+
input_weight = state_dict["input_proj.weight"]
|
| 94 |
+
hidden_dim, embedding_dim = input_weight.shape
|
| 95 |
+
state_dim = state_dict["gating.physics_scaler"].shape[0]
|
| 96 |
+
num_layers = max(
|
| 97 |
+
int(k.split(".")[2])
|
| 98 |
+
for k in state_dict
|
| 99 |
+
if k.startswith("encoder.layers.") and k.endswith(".self_attn.in_proj_weight")
|
| 100 |
+
) + 1
|
| 101 |
+
in_proj_rows = state_dict["encoder.layers.0.self_attn.in_proj_weight"].shape[0]
|
| 102 |
+
num_heads = 8 if hidden_dim % 8 == 0 and hidden_dim >= 512 else 4
|
| 103 |
+
if in_proj_rows != hidden_dim * 3:
|
| 104 |
+
raise ValueError("Unexpected transformer attention weight shape")
|
| 105 |
+
return {
|
| 106 |
+
"hidden_dim": hidden_dim,
|
| 107 |
+
"embedding_dim": embedding_dim,
|
| 108 |
+
"state_dim": state_dim,
|
| 109 |
+
"num_layers": num_layers,
|
| 110 |
+
"num_heads": num_heads,
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def evaluate(args: argparse.Namespace) -> dict[str, Any]:
|
| 115 |
+
torch.manual_seed(args.seed)
|
| 116 |
+
np.random.seed(args.seed)
|
| 117 |
+
|
| 118 |
+
checkpoint_path = resolve_checkpoint(args)
|
| 119 |
+
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
| 120 |
+
model_state = ckpt["model_state_dict"]
|
| 121 |
+
dims = infer_model_dims(model_state)
|
| 122 |
+
|
| 123 |
+
model = PhysicsInformedMixtureTransformer(
|
| 124 |
+
embedding_dim=dims["embedding_dim"],
|
| 125 |
+
state_dim=dims["state_dim"],
|
| 126 |
+
hidden_dim=dims["hidden_dim"],
|
| 127 |
+
num_heads=dims["num_heads"],
|
| 128 |
+
num_layers=dims["num_layers"],
|
| 129 |
+
)
|
| 130 |
+
model.load_state_dict(model_state)
|
| 131 |
+
model.eval()
|
| 132 |
+
|
| 133 |
+
heads = PIMTHeads(hidden_dim=dims["hidden_dim"], objective_dim=138)
|
| 134 |
+
heads.load_state_dict(ckpt["heads_state_dict"])
|
| 135 |
+
heads.eval()
|
| 136 |
+
|
| 137 |
+
records = read_records(args.data)
|
| 138 |
+
val_dataset = make_validation_dataset(records)
|
| 139 |
+
val_loader = DataLoader(
|
| 140 |
+
val_dataset,
|
| 141 |
+
batch_size=args.batch_size,
|
| 142 |
+
shuffle=False,
|
| 143 |
+
collate_fn=pad_trajectory_collate,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
all_preds: list[np.ndarray] = []
|
| 147 |
+
all_targets: list[np.ndarray] = []
|
| 148 |
+
with torch.no_grad():
|
| 149 |
+
for batch in val_loader:
|
| 150 |
+
latent = model(
|
| 151 |
+
batch["tokens"],
|
| 152 |
+
batch["physics"],
|
| 153 |
+
src_key_padding_mask=batch["src_key_padding_mask"],
|
| 154 |
+
)
|
| 155 |
+
output = heads(latent, batch["physics"], batch["src_key_padding_mask"])
|
| 156 |
+
all_preds.append(output["objective"].numpy())
|
| 157 |
+
all_targets.append(batch["target_obj"].numpy())
|
| 158 |
+
|
| 159 |
+
preds = np.concatenate(all_preds, axis=0)
|
| 160 |
+
targets = np.concatenate(all_targets, axis=0)
|
| 161 |
+
|
| 162 |
+
tier_names = ["top", "middle", "base"]
|
| 163 |
+
tier_metrics: dict[str, Any] = {}
|
| 164 |
+
for tier_idx, tier_name in enumerate(tier_names):
|
| 165 |
+
pred_tier = preds[:, tier_idx, :]
|
| 166 |
+
target_tier = targets[:, tier_idx, :]
|
| 167 |
+
sims = 1.0 - pdist(pred_tier, metric="cosine")
|
| 168 |
+
rho_list = []
|
| 169 |
+
for idx in range(len(pred_tier)):
|
| 170 |
+
rho, _ = spearmanr(pred_tier[idx], target_tier[idx])
|
| 171 |
+
if rho is not None and not np.isnan(rho):
|
| 172 |
+
rho_list.append(float(rho))
|
| 173 |
+
tier_metrics[tier_name] = {
|
| 174 |
+
"mse": float(((pred_tier - target_tier) ** 2).mean()),
|
| 175 |
+
"mae": float(np.abs(pred_tier - target_tier).mean()),
|
| 176 |
+
"prediction_variance": float(pred_tier.var()),
|
| 177 |
+
"target_variance": float(target_tier.var()),
|
| 178 |
+
"mean_pairwise_cosine_similarity": float(sims.mean()) if len(sims) else None,
|
| 179 |
+
"mean_spearman_rho": float(np.mean(rho_list)) if rho_list else None,
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
flat_rho, flat_p = spearmanr(preds.reshape(-1), targets.reshape(-1))
|
| 183 |
+
profile_pred = preds.mean(axis=1)
|
| 184 |
+
profile_target = targets.mean(axis=1)
|
| 185 |
+
profile_rho, profile_p = spearmanr(profile_pred.reshape(-1), profile_target.reshape(-1))
|
| 186 |
+
|
| 187 |
+
vocab = load_vocab()
|
| 188 |
+
top_descriptors: dict[str, Any] = {}
|
| 189 |
+
for tier_idx, tier_name in enumerate(tier_names):
|
| 190 |
+
pred_mean = preds[:, tier_idx, :].mean(axis=0)
|
| 191 |
+
target_mean = targets[:, tier_idx, :].mean(axis=0)
|
| 192 |
+
pred_top = np.argsort(pred_mean)[-5:][::-1]
|
| 193 |
+
target_top = np.argsort(target_mean)[-5:][::-1]
|
| 194 |
+
top_descriptors[tier_name] = {
|
| 195 |
+
"predicted": [
|
| 196 |
+
{"descriptor": vocab[i] if i < len(vocab) else f"d{i}", "score": float(pred_mean[i])}
|
| 197 |
+
for i in pred_top
|
| 198 |
+
],
|
| 199 |
+
"target": [
|
| 200 |
+
{"descriptor": vocab[i] if i < len(vocab) else f"d{i}", "score": float(target_mean[i])}
|
| 201 |
+
for i in target_top
|
| 202 |
+
],
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
return {
|
| 206 |
+
"checkpoint": {
|
| 207 |
+
"path": str(checkpoint_path),
|
| 208 |
+
"epoch": ckpt.get("epoch"),
|
| 209 |
+
"val_loss": ckpt.get("val_loss"),
|
| 210 |
+
**dims,
|
| 211 |
+
},
|
| 212 |
+
"data": {
|
| 213 |
+
"path": args.data,
|
| 214 |
+
"n_records": len(records),
|
| 215 |
+
"n_validation_samples": len(val_dataset),
|
| 216 |
+
},
|
| 217 |
+
"prediction": {
|
| 218 |
+
"profile_mse": float(((profile_pred - profile_target) ** 2).mean()),
|
| 219 |
+
"profile_mae": float(np.abs(profile_pred - profile_target).mean()),
|
| 220 |
+
"profile_prediction_variance": float(profile_pred.var()),
|
| 221 |
+
"tier_prediction_variance": float(preds.var()),
|
| 222 |
+
"tier_metrics": tier_metrics,
|
| 223 |
+
},
|
| 224 |
+
"spearman": {
|
| 225 |
+
"flat_spearman_rho": float(flat_rho),
|
| 226 |
+
"flat_spearman_p_value": float(flat_p),
|
| 227 |
+
"profile_spearman_rho": float(profile_rho),
|
| 228 |
+
"profile_spearman_p_value": float(profile_p),
|
| 229 |
+
},
|
| 230 |
+
"top_descriptors": top_descriptors,
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def main() -> None:
|
| 235 |
+
args = parse_args()
|
| 236 |
+
metrics = evaluate(args)
|
| 237 |
+
output = Path(args.output)
|
| 238 |
+
output.write_text(json.dumps(metrics, indent=2), encoding="utf-8")
|
| 239 |
+
|
| 240 |
+
print(f"Checkpoint: {metrics['checkpoint']['path']}")
|
| 241 |
+
print(f"Validation samples: {metrics['data']['n_validation_samples']}")
|
| 242 |
+
print(f"Profile MSE: {metrics['prediction']['profile_mse']:.6f}")
|
| 243 |
+
print(f"Profile Spearman rho: {metrics['spearman']['profile_spearman_rho']:.4f}")
|
| 244 |
+
for tier, vals in metrics["prediction"]["tier_metrics"].items():
|
| 245 |
+
print(
|
| 246 |
+
f"{tier.title():<7} MSE={vals['mse']:.4f} "
|
| 247 |
+
f"MAE={vals['mae']:.4f} Var(pred)={vals['prediction_variance']:.6f} "
|
| 248 |
+
f"rho={vals['mean_spearman_rho']:.4f}"
|
| 249 |
+
)
|
| 250 |
+
print(f"Wrote {output}")
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
main()
|
scripts/hf_train_job.py
CHANGED
|
@@ -62,7 +62,9 @@ def _upload_log() -> None:
|
|
| 62 |
|
| 63 |
_log("[HF-JOB] hf_train_job.py started")
|
| 64 |
|
| 65 |
-
# Install
|
|
|
|
|
|
|
| 66 |
_log("[HF-JOB] Installing huggingface_hub")
|
| 67 |
try:
|
| 68 |
subprocess.check_call(
|
|
@@ -77,6 +79,29 @@ except Exception as exc:
|
|
| 77 |
_upload_log()
|
| 78 |
sys.exit(1)
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
# Download fresh source and dataset into writable workspace.
|
| 81 |
try:
|
| 82 |
from huggingface_hub import snapshot_download
|
|
|
|
| 62 |
|
| 63 |
_log("[HF-JOB] hf_train_job.py started")
|
| 64 |
|
| 65 |
+
# Install runtime dependencies needed before pino imports. The project
|
| 66 |
+
# deliberately does not pin torch in pyproject.toml because local CPU, CUDA, and
|
| 67 |
+
# HF Jobs images need different wheels.
|
| 68 |
_log("[HF-JOB] Installing huggingface_hub")
|
| 69 |
try:
|
| 70 |
subprocess.check_call(
|
|
|
|
| 79 |
_upload_log()
|
| 80 |
sys.exit(1)
|
| 81 |
|
| 82 |
+
_log("[HF-JOB] Installing CUDA torch")
|
| 83 |
+
try:
|
| 84 |
+
subprocess.check_call(
|
| 85 |
+
[
|
| 86 |
+
sys.executable,
|
| 87 |
+
"-m",
|
| 88 |
+
"pip",
|
| 89 |
+
"install",
|
| 90 |
+
"--quiet",
|
| 91 |
+
"torch",
|
| 92 |
+
"--index-url",
|
| 93 |
+
"https://download.pytorch.org/whl/cu121",
|
| 94 |
+
],
|
| 95 |
+
stdout=sys.stdout,
|
| 96 |
+
stderr=sys.stderr,
|
| 97 |
+
)
|
| 98 |
+
_log("[HF-JOB] torch installed")
|
| 99 |
+
except Exception as exc:
|
| 100 |
+
_log(f"[HF-JOB] torch install failed: {exc}")
|
| 101 |
+
traceback.print_exc()
|
| 102 |
+
_upload_log()
|
| 103 |
+
sys.exit(1)
|
| 104 |
+
|
| 105 |
# Download fresh source and dataset into writable workspace.
|
| 106 |
try:
|
| 107 |
from huggingface_hub import snapshot_download
|