Matthew Ford commited on
Commit ·
7cc735d
1
Parent(s): 44e3198
feat: prepare v7 HF training and evaluation
Browse filesFormer-commit-id: aec44c64d9612890c7e63a88ef3a1d15cca1ea7e
Former-commit-id: db28bcd21a6d7e1d96a1446cf8594facbd367e9b
- hf_job.yaml +4 -3
- scripts/hf_train_job.py +8 -5
- src/pino/evaluate.py +84 -68
- src/pino/train.py +2 -1
hf_job.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
-
# HF Jobs cluster configuration for PINO
|
| 2 |
# Mounts the source code as a model volume and the v3 dataset as a dataset volume
|
| 3 |
# to avoid git clone inside the container.
|
| 4 |
-
name: pino-
|
| 5 |
image: python:3.11
|
| 6 |
command:
|
| 7 |
- bash
|
|
@@ -13,13 +13,14 @@ command:
|
|
| 13 |
pip install torch --index-url https://download.pytorch.org/whl/cu121
|
| 14 |
echo "Installing pino package and dependencies..."
|
| 15 |
pip install -e .
|
| 16 |
-
echo "Starting
|
| 17 |
python -u scripts/hf_train_job.py
|
| 18 |
flavor: t4-small
|
| 19 |
secrets:
|
| 20 |
HF_TOKEN: ${HF_TOKEN}
|
| 21 |
env:
|
| 22 |
HF_DATA_PATH: /data/empirical_dataset_v4.jsonl
|
|
|
|
| 23 |
volumes:
|
| 24 |
- hf://mattbitzesty/pino-source-code:/workspace/pino
|
| 25 |
- hf://datasets/mattbitzesty/pino-synthetic-dataset-v3:/data
|
|
|
|
| 1 |
+
# HF Jobs cluster configuration for PINO v7 5-epoch GPU training
|
| 2 |
# Mounts the source code as a model volume and the v3 dataset as a dataset volume
|
| 3 |
# to avoid git clone inside the container.
|
| 4 |
+
name: pino-v7-5epoch-pyramid
|
| 5 |
image: python:3.11
|
| 6 |
command:
|
| 7 |
- bash
|
|
|
|
| 13 |
pip install torch --index-url https://download.pytorch.org/whl/cu121
|
| 14 |
echo "Installing pino package and dependencies..."
|
| 15 |
pip install -e .
|
| 16 |
+
echo "Starting v7 pyramid training job..."
|
| 17 |
python -u scripts/hf_train_job.py
|
| 18 |
flavor: t4-small
|
| 19 |
secrets:
|
| 20 |
HF_TOKEN: ${HF_TOKEN}
|
| 21 |
env:
|
| 22 |
HF_DATA_PATH: /data/empirical_dataset_v4.jsonl
|
| 23 |
+
PINO_MODEL_VERSION: v7
|
| 24 |
volumes:
|
| 25 |
- hf://mattbitzesty/pino-source-code:/workspace/pino
|
| 26 |
- hf://datasets/mattbitzesty/pino-synthetic-dataset-v3:/data
|
scripts/hf_train_job.py
CHANGED
|
@@ -8,7 +8,7 @@ import time
|
|
| 8 |
import traceback
|
| 9 |
from pathlib import Path
|
| 10 |
|
| 11 |
-
# HF Job entrypoint for the
|
| 12 |
# Uses snapshot_download to pull fresh source and dataset into a writable
|
| 13 |
# workspace, avoiding stale/cached model-volume mounts.
|
| 14 |
|
|
@@ -22,7 +22,9 @@ WORKSPACE = Path("/workspace")
|
|
| 22 |
SOURCE_DIR = WORKSPACE / "pino-fresh"
|
| 23 |
DATASET_DIR = WORKSPACE / "pino-dataset"
|
| 24 |
OUTPUT_DIR = WORKSPACE / "models"
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
DIAG_LOG = WORKSPACE / "hf_train.log"
|
| 27 |
|
| 28 |
SRC_DIR = SOURCE_DIR / "src"
|
|
@@ -179,9 +181,10 @@ sys.argv = [
|
|
| 179 |
"--workers", "0",
|
| 180 |
"--output-dir", str(OUTPUT_DIR),
|
| 181 |
"--log-dir", str(LOG_DIR),
|
|
|
|
| 182 |
]
|
| 183 |
|
| 184 |
-
_log("🚀 HF Job: starting PINO 5-epoch
|
| 185 |
_log(f" Device: {'cuda' if torch.cuda.is_available() else 'cpu'}")
|
| 186 |
_log(f" Args: {' '.join(sys.argv[1:])}")
|
| 187 |
|
|
@@ -197,7 +200,7 @@ _log(f"✅ Training complete. Checkpoint: {checkpoint_path}")
|
|
| 197 |
|
| 198 |
if TOKEN and checkpoint_path and Path(checkpoint_path).exists():
|
| 199 |
repo_id = "mattbitzesty/pino-pimt-checkpoint"
|
| 200 |
-
_log(f"[HF-JOB] Uploading {checkpoint_path} to {repo_id} as
|
| 201 |
try:
|
| 202 |
# Monkey-patch / bypass Xet to avoid a hf_xet/huggingface_hub bug that
|
| 203 |
# crashes large-file uploads in the HF Jobs image.
|
|
@@ -219,7 +222,7 @@ if TOKEN and checkpoint_path and Path(checkpoint_path).exists():
|
|
| 219 |
create_repo(repo_id, private=True, token=TOKEN, exist_ok=True)
|
| 220 |
HfApi(token=TOKEN).upload_file(
|
| 221 |
path_or_fileobj=str(checkpoint_path),
|
| 222 |
-
path_in_repo=
|
| 223 |
repo_id=repo_id,
|
| 224 |
repo_type="model",
|
| 225 |
)
|
|
|
|
| 8 |
import traceback
|
| 9 |
from pathlib import Path
|
| 10 |
|
| 11 |
+
# HF Job entrypoint for the v7 pyramid training run.
|
| 12 |
# Uses snapshot_download to pull fresh source and dataset into a writable
|
| 13 |
# workspace, avoiding stale/cached model-volume mounts.
|
| 14 |
|
|
|
|
| 22 |
SOURCE_DIR = WORKSPACE / "pino-fresh"
|
| 23 |
DATASET_DIR = WORKSPACE / "pino-dataset"
|
| 24 |
OUTPUT_DIR = WORKSPACE / "models"
|
| 25 |
+
MODEL_VERSION = os.environ.get("PINO_MODEL_VERSION", "v7")
|
| 26 |
+
CHECKPOINT_NAME = f"pimt_{MODEL_VERSION}.pt"
|
| 27 |
+
LOG_DIR = WORKSPACE / "runs" / f"hf_job_{MODEL_VERSION}"
|
| 28 |
DIAG_LOG = WORKSPACE / "hf_train.log"
|
| 29 |
|
| 30 |
SRC_DIR = SOURCE_DIR / "src"
|
|
|
|
| 181 |
"--workers", "0",
|
| 182 |
"--output-dir", str(OUTPUT_DIR),
|
| 183 |
"--log-dir", str(LOG_DIR),
|
| 184 |
+
"--checkpoint-name", CHECKPOINT_NAME,
|
| 185 |
]
|
| 186 |
|
| 187 |
+
_log(f"🚀 HF Job: starting PINO 5-epoch {MODEL_VERSION} concentration-aware convergence pass")
|
| 188 |
_log(f" Device: {'cuda' if torch.cuda.is_available() else 'cpu'}")
|
| 189 |
_log(f" Args: {' '.join(sys.argv[1:])}")
|
| 190 |
|
|
|
|
| 200 |
|
| 201 |
if TOKEN and checkpoint_path and Path(checkpoint_path).exists():
|
| 202 |
repo_id = "mattbitzesty/pino-pimt-checkpoint"
|
| 203 |
+
_log(f"[HF-JOB] Uploading {checkpoint_path} to {repo_id} as {CHECKPOINT_NAME}")
|
| 204 |
try:
|
| 205 |
# Monkey-patch / bypass Xet to avoid a hf_xet/huggingface_hub bug that
|
| 206 |
# crashes large-file uploads in the HF Jobs image.
|
|
|
|
| 222 |
create_repo(repo_id, private=True, token=TOKEN, exist_ok=True)
|
| 223 |
HfApi(token=TOKEN).upload_file(
|
| 224 |
path_or_fileobj=str(checkpoint_path),
|
| 225 |
+
path_in_repo=CHECKPOINT_NAME,
|
| 226 |
repo_id=repo_id,
|
| 227 |
repo_type="model",
|
| 228 |
)
|
src/pino/evaluate.py
CHANGED
|
@@ -14,81 +14,50 @@ from scipy.stats import spearmanr
|
|
| 14 |
from torch.utils.data import DataLoader
|
| 15 |
|
| 16 |
from pino.heads import PIMTHeads
|
| 17 |
-
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
|
|
|
|
| 18 |
|
| 19 |
logger = logging.getLogger("pino.evaluate")
|
| 20 |
|
| 21 |
|
| 22 |
-
def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
| 23 |
-
"""Minimal collate for evaluation: pads tokens, physics, and targets."""
|
| 24 |
-
max_molecules = max(item["tokens"].size(0) for item in batch)
|
| 25 |
-
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 26 |
-
bsz = len(batch)
|
| 27 |
-
|
| 28 |
-
tokens = torch.zeros(bsz, max_molecules, DEFAULT_EMBEDDING_DIM, dtype=torch.float32)
|
| 29 |
-
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 30 |
-
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 31 |
-
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
| 32 |
-
target_sub_seasonality = torch.zeros(bsz, 4, dtype=torch.float32)
|
| 33 |
-
target_sub_gender = torch.zeros(bsz, dtype=torch.float32)
|
| 34 |
-
target_sub_wearability = torch.zeros(bsz, 2, dtype=torch.float32)
|
| 35 |
-
genre_labels = torch.zeros(bsz, dtype=torch.int64)
|
| 36 |
-
genres: list[str] = []
|
| 37 |
-
|
| 38 |
-
for i, item in enumerate(batch):
|
| 39 |
-
n_mol = item["tokens"].size(0)
|
| 40 |
-
t_steps = item["physics"].size(0)
|
| 41 |
-
tokens[i, :n_mol] = item["tokens"]
|
| 42 |
-
physics[i, :t_steps, :n_mol] = item["physics"]
|
| 43 |
-
src_key_padding_mask[i, :n_mol] = False
|
| 44 |
-
target_obj[i, :t_steps] = item["target_obj"]
|
| 45 |
-
sub = item["target_sub"]
|
| 46 |
-
target_sub_seasonality[i] = sub[[0,1,2,3]]
|
| 47 |
-
target_sub_gender[i] = sub[4]
|
| 48 |
-
target_sub_wearability[i] = sub[[5,6]]
|
| 49 |
-
genre_labels[i] = item.get("genre_label", 0)
|
| 50 |
-
genres.append(item.get("genre", "wildcard"))
|
| 51 |
-
|
| 52 |
-
return {
|
| 53 |
-
"tokens": tokens,
|
| 54 |
-
"physics": physics,
|
| 55 |
-
"src_key_padding_mask": src_key_padding_mask,
|
| 56 |
-
"target_obj": target_obj,
|
| 57 |
-
"target_sub_seasonality": target_sub_seasonality,
|
| 58 |
-
"target_sub_gender": target_sub_gender,
|
| 59 |
-
"target_sub_wearability": target_sub_wearability,
|
| 60 |
-
"genre_label": genre_labels,
|
| 61 |
-
"genre": genres,
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
|
| 65 |
@torch.no_grad()
|
| 66 |
def extract_embeddings(
|
| 67 |
model: nn.Module,
|
| 68 |
heads: nn.Module,
|
| 69 |
loader: DataLoader,
|
| 70 |
device: torch.device,
|
| 71 |
-
) -> tuple[np.ndarray, np.ndarray,
|
| 72 |
-
"""Return
|
| 73 |
model.eval()
|
| 74 |
heads.eval()
|
| 75 |
-
|
| 76 |
targets: list[np.ndarray] = []
|
| 77 |
-
|
|
|
|
| 78 |
for batch in loader:
|
| 79 |
tokens = batch["tokens"].to(device)
|
| 80 |
physics = batch["physics"].to(device)
|
| 81 |
src_key_padding_mask = batch["src_key_padding_mask"].to(device)
|
| 82 |
target_obj = batch["target_obj"].to(device)
|
| 83 |
latent = model(tokens, physics, src_key_padding_mask)
|
| 84 |
-
pred = heads(latent)
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
|
| 94 |
def spearman_distance_correlation(embeddings: np.ndarray, targets: np.ndarray) -> dict[str, float]:
|
|
@@ -140,10 +109,40 @@ def mean_average_precision(embeddings: np.ndarray, labels: np.ndarray, k: int |
|
|
| 140 |
}
|
| 141 |
|
| 142 |
|
| 143 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
"""Load a checkpoint and run perceptual evaluation metrics."""
|
| 145 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 146 |
checkpoint = torch.load(checkpoint_path, map_location=device)
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
all_genres = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 149 |
genre_map = {genre: idx for idx, genre in enumerate(all_genres)}
|
|
@@ -151,32 +150,49 @@ def evaluate(checkpoint_path: str, data_path: str, batch_size: int = 16, hidden_
|
|
| 151 |
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, collate_fn=pad_trajectory_collate)
|
| 152 |
|
| 153 |
model = PhysicsInformedMixtureTransformer(
|
| 154 |
-
embedding_dim=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
).to(device)
|
| 156 |
-
heads = PIMTHeads(hidden_dim=hidden_dim, objective_dim=138).to(device)
|
| 157 |
model.load_state_dict(checkpoint["model_state_dict"])
|
| 158 |
heads.load_state_dict(checkpoint["heads_state_dict"])
|
| 159 |
|
| 160 |
-
|
| 161 |
-
genre_labels = np.array([genre_map.get(g, 0) for g in genres], dtype=np.int64)
|
| 162 |
|
| 163 |
-
spearman_metrics = spearman_distance_correlation(
|
| 164 |
-
map_metrics = mean_average_precision(
|
|
|
|
|
|
|
| 165 |
|
| 166 |
metrics = {
|
| 167 |
"spearman": spearman_metrics,
|
| 168 |
"retrieval_mAP": map_metrics,
|
| 169 |
-
"
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
}
|
| 172 |
|
| 173 |
logger.info("=" * 50)
|
| 174 |
logger.info("PERCEPTUAL EVALUATION RESULTS")
|
| 175 |
logger.info("=" * 50)
|
| 176 |
-
logger.info("Spearman distance correlation: rho=%.4f | p=%.4e | n_pairs=%d",
|
| 177 |
spearman_metrics["spearman_rho"], spearman_metrics["spearman_p_value"], spearman_metrics["n_pairs"])
|
| 178 |
-
logger.info("Retrieval mAP@all: %.4f +/- %.4f | n_queries=%d",
|
| 179 |
map_metrics["mAP"], map_metrics["AP_std"], map_metrics["n_queries"])
|
|
|
|
| 180 |
logger.info("=" * 50)
|
| 181 |
return metrics
|
| 182 |
|
|
@@ -186,7 +202,7 @@ if __name__ == "__main__":
|
|
| 186 |
parser.add_argument("--checkpoint", default="models/pimt_v1.pt", help="Path to trained checkpoint")
|
| 187 |
parser.add_argument("--data", default="data/synthetic_dataset_v2.jsonl", help="Dataset JSON-L")
|
| 188 |
parser.add_argument("--batch-size", type=int, default=16, help="Evaluation batch size")
|
| 189 |
-
parser.add_argument("--hidden-dim", type=int, default=
|
| 190 |
parser.add_argument("--output", default="metrics.json", help="Path to write JSON metrics")
|
| 191 |
parser.add_argument("--log-level", default="INFO")
|
| 192 |
args = parser.parse_args()
|
|
|
|
| 14 |
from torch.utils.data import DataLoader
|
| 15 |
|
| 16 |
from pino.heads import PIMTHeads
|
| 17 |
+
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
|
| 18 |
+
from pino.train import pad_trajectory_collate
|
| 19 |
|
| 20 |
logger = logging.getLogger("pino.evaluate")
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
@torch.no_grad()
|
| 24 |
def extract_embeddings(
|
| 25 |
model: nn.Module,
|
| 26 |
heads: nn.Module,
|
| 27 |
loader: DataLoader,
|
| 28 |
device: torch.device,
|
| 29 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
| 30 |
+
"""Return predicted/target descriptor profiles plus genre labels."""
|
| 31 |
model.eval()
|
| 32 |
heads.eval()
|
| 33 |
+
predictions: list[np.ndarray] = []
|
| 34 |
targets: list[np.ndarray] = []
|
| 35 |
+
genre_labels: list[np.ndarray] = []
|
| 36 |
+
tier_predictions: list[np.ndarray] = []
|
| 37 |
for batch in loader:
|
| 38 |
tokens = batch["tokens"].to(device)
|
| 39 |
physics = batch["physics"].to(device)
|
| 40 |
src_key_padding_mask = batch["src_key_padding_mask"].to(device)
|
| 41 |
target_obj = batch["target_obj"].to(device)
|
| 42 |
latent = model(tokens, physics, src_key_padding_mask)
|
| 43 |
+
pred = heads(latent, physics, src_key_padding_mask)
|
| 44 |
+
|
| 45 |
+
tier_pred = pred["objective"].cpu().numpy()
|
| 46 |
+
tier_target = target_obj.cpu().numpy()
|
| 47 |
+
tier_predictions.append(tier_pred)
|
| 48 |
+
|
| 49 |
+
# Collapse the top/middle/base pyramid into one perceptual descriptor
|
| 50 |
+
# profile for retrieval/distance metrics.
|
| 51 |
+
predictions.append(tier_pred.mean(axis=1))
|
| 52 |
+
targets.append(tier_target.mean(axis=1))
|
| 53 |
+
genre_labels.append(batch["genre_label"].cpu().numpy())
|
| 54 |
+
|
| 55 |
+
return (
|
| 56 |
+
np.vstack(predictions),
|
| 57 |
+
np.vstack(targets),
|
| 58 |
+
np.concatenate(genre_labels),
|
| 59 |
+
np.concatenate(tier_predictions, axis=0),
|
| 60 |
+
)
|
| 61 |
|
| 62 |
|
| 63 |
def spearman_distance_correlation(embeddings: np.ndarray, targets: np.ndarray) -> dict[str, float]:
|
|
|
|
| 109 |
}
|
| 110 |
|
| 111 |
|
| 112 |
+
def _infer_checkpoint_config(checkpoint: dict[str, Any]) -> dict[str, int]:
|
| 113 |
+
"""Infer architecture knobs saved by the current trainer."""
|
| 114 |
+
model_state = checkpoint["model_state_dict"]
|
| 115 |
+
input_proj = model_state["input_proj.weight"]
|
| 116 |
+
hidden_dim = int(input_proj.shape[0])
|
| 117 |
+
embedding_dim = int(input_proj.shape[1])
|
| 118 |
+
state_dim = int(model_state["gating.physics_scaler"].shape[0])
|
| 119 |
+
|
| 120 |
+
layer_prefixes = {
|
| 121 |
+
key.split(".")[2]
|
| 122 |
+
for key in model_state
|
| 123 |
+
if key.startswith("encoder.layers.") and key.endswith("self_attn.in_proj_weight")
|
| 124 |
+
}
|
| 125 |
+
num_layers = len(layer_prefixes) or 4
|
| 126 |
+
|
| 127 |
+
# num_heads is not represented in the state dict. Current HF training uses
|
| 128 |
+
# four heads; fall back to the largest common divisor up to 8 for older runs.
|
| 129 |
+
num_heads = 4 if hidden_dim % 4 == 0 else next(h for h in (8, 2, 1) if hidden_dim % h == 0)
|
| 130 |
+
return {
|
| 131 |
+
"hidden_dim": hidden_dim,
|
| 132 |
+
"embedding_dim": embedding_dim,
|
| 133 |
+
"state_dim": state_dim,
|
| 134 |
+
"num_layers": num_layers,
|
| 135 |
+
"num_heads": num_heads,
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def evaluate(checkpoint_path: str, data_path: str, batch_size: int = 16, hidden_dim: int | None = None) -> dict[str, Any]:
|
| 140 |
"""Load a checkpoint and run perceptual evaluation metrics."""
|
| 141 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 142 |
checkpoint = torch.load(checkpoint_path, map_location=device)
|
| 143 |
+
cfg = _infer_checkpoint_config(checkpoint)
|
| 144 |
+
if hidden_dim is not None and hidden_dim != cfg["hidden_dim"]:
|
| 145 |
+
logger.warning("Ignoring --hidden-dim=%d; checkpoint requires hidden_dim=%d", hidden_dim, cfg["hidden_dim"])
|
| 146 |
|
| 147 |
all_genres = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 148 |
genre_map = {genre: idx for idx, genre in enumerate(all_genres)}
|
|
|
|
| 150 |
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, collate_fn=pad_trajectory_collate)
|
| 151 |
|
| 152 |
model = PhysicsInformedMixtureTransformer(
|
| 153 |
+
embedding_dim=cfg["embedding_dim"],
|
| 154 |
+
state_dim=cfg["state_dim"],
|
| 155 |
+
hidden_dim=cfg["hidden_dim"],
|
| 156 |
+
num_heads=cfg["num_heads"],
|
| 157 |
+
num_layers=cfg["num_layers"],
|
| 158 |
).to(device)
|
| 159 |
+
heads = PIMTHeads(hidden_dim=cfg["hidden_dim"], objective_dim=138).to(device)
|
| 160 |
model.load_state_dict(checkpoint["model_state_dict"])
|
| 161 |
heads.load_state_dict(checkpoint["heads_state_dict"])
|
| 162 |
|
| 163 |
+
predictions, targets, genre_labels, tier_predictions = extract_embeddings(model, heads, loader, device)
|
|
|
|
| 164 |
|
| 165 |
+
spearman_metrics = spearman_distance_correlation(predictions, targets)
|
| 166 |
+
map_metrics = mean_average_precision(predictions, genre_labels)
|
| 167 |
+
mse = float(np.mean((predictions - targets) ** 2))
|
| 168 |
+
mae = float(np.mean(np.abs(predictions - targets)))
|
| 169 |
|
| 170 |
metrics = {
|
| 171 |
"spearman": spearman_metrics,
|
| 172 |
"retrieval_mAP": map_metrics,
|
| 173 |
+
"prediction": {
|
| 174 |
+
"profile_mse": mse,
|
| 175 |
+
"profile_mae": mae,
|
| 176 |
+
"prediction_variance": float(np.var(predictions)),
|
| 177 |
+
"tier_prediction_variance": float(np.var(tier_predictions)),
|
| 178 |
+
},
|
| 179 |
+
"n_samples": len(predictions),
|
| 180 |
+
"embedding_dim": predictions.shape[1],
|
| 181 |
+
"checkpoint": {
|
| 182 |
+
"epoch": checkpoint.get("epoch"),
|
| 183 |
+
"val_loss": checkpoint.get("val_loss"),
|
| 184 |
+
**cfg,
|
| 185 |
+
},
|
| 186 |
}
|
| 187 |
|
| 188 |
logger.info("=" * 50)
|
| 189 |
logger.info("PERCEPTUAL EVALUATION RESULTS")
|
| 190 |
logger.info("=" * 50)
|
| 191 |
+
logger.info("Spearman distance correlation: rho=%.4f | p=%.4e | n_pairs=%d",
|
| 192 |
spearman_metrics["spearman_rho"], spearman_metrics["spearman_p_value"], spearman_metrics["n_pairs"])
|
| 193 |
+
logger.info("Retrieval mAP@all: %.4f +/- %.4f | n_queries=%d",
|
| 194 |
map_metrics["mAP"], map_metrics["AP_std"], map_metrics["n_queries"])
|
| 195 |
+
logger.info("Profile prediction: mse=%.4f | mae=%.4f | variance=%.6f", mse, mae, metrics["prediction"]["prediction_variance"])
|
| 196 |
logger.info("=" * 50)
|
| 197 |
return metrics
|
| 198 |
|
|
|
|
| 202 |
parser.add_argument("--checkpoint", default="models/pimt_v1.pt", help="Path to trained checkpoint")
|
| 203 |
parser.add_argument("--data", default="data/synthetic_dataset_v2.jsonl", help="Dataset JSON-L")
|
| 204 |
parser.add_argument("--batch-size", type=int, default=16, help="Evaluation batch size")
|
| 205 |
+
parser.add_argument("--hidden-dim", type=int, default=None, help="Deprecated; architecture is inferred from checkpoint")
|
| 206 |
parser.add_argument("--output", default="metrics.json", help="Path to write JSON metrics")
|
| 207 |
parser.add_argument("--log-level", default="INFO")
|
| 208 |
args = parser.parse_args()
|
src/pino/train.py
CHANGED
|
@@ -247,6 +247,7 @@ def main():
|
|
| 247 |
parser.add_argument("--seed", type=int, default=2026)
|
| 248 |
parser.add_argument("--output-dir", default="models")
|
| 249 |
parser.add_argument("--log-dir", default="runs")
|
|
|
|
| 250 |
parser.add_argument("--train-ratio", type=float, default=0.6, help="Molecule-disjoint train molecule ratio")
|
| 251 |
parser.add_argument("--smoke-test", action="store_true", help="Run lightweight CPU smoke test")
|
| 252 |
args = parser.parse_args()
|
|
@@ -273,7 +274,7 @@ def main():
|
|
| 273 |
"max_batches_per_epoch": None,
|
| 274 |
"lr": args.lr,
|
| 275 |
"weight_decay": 1e-2,
|
| 276 |
-
"checkpoint_name":
|
| 277 |
}
|
| 278 |
logger.info("Configuration: %s", cfg)
|
| 279 |
|
|
|
|
| 247 |
parser.add_argument("--seed", type=int, default=2026)
|
| 248 |
parser.add_argument("--output-dir", default="models")
|
| 249 |
parser.add_argument("--log-dir", default="runs")
|
| 250 |
+
parser.add_argument("--checkpoint-name", default="pimt_v6.pt", help="Filename for the best checkpoint")
|
| 251 |
parser.add_argument("--train-ratio", type=float, default=0.6, help="Molecule-disjoint train molecule ratio")
|
| 252 |
parser.add_argument("--smoke-test", action="store_true", help="Run lightweight CPU smoke test")
|
| 253 |
args = parser.parse_args()
|
|
|
|
| 274 |
"max_batches_per_epoch": None,
|
| 275 |
"lr": args.lr,
|
| 276 |
"weight_decay": 1e-2,
|
| 277 |
+
"checkpoint_name": args.checkpoint_name,
|
| 278 |
}
|
| 279 |
logger.info("Configuration: %s", cfg)
|
| 280 |
|