feat(upload,train): directive-compliant molecule-disjoint split
Browse filesAdd create_molecule_disjoint_split() using metadata.initial_components
with fallback to formula. Integrate splitter into train.py so training
and validation sets share zero molecules. Verify zero overlap at runtime.
- src/pino/train.py +17 -9
- src/pino/upload_data.py +67 -2
src/pino/train.py
CHANGED
|
@@ -11,11 +11,12 @@ import torch
|
|
| 11 |
import torch.nn as nn
|
| 12 |
import torch.nn.functional as F
|
| 13 |
import torch.optim as optim
|
| 14 |
-
from torch.utils.data import DataLoader,
|
| 15 |
from torch.utils.tensorboard import SummaryWriter
|
| 16 |
|
| 17 |
from pino.heads import PIMTHeads
|
| 18 |
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
|
|
|
|
| 19 |
|
| 20 |
logger = logging.getLogger("pino.train")
|
| 21 |
|
|
@@ -289,15 +290,22 @@ def main():
|
|
| 289 |
# Use the genre column for both stratification and the contrastive loss.
|
| 290 |
all_genres = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 291 |
genre_map = {genre: idx for idx, genre in enumerate(all_genres)}
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
|
|
|
|
|
|
| 300 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
|
| 302 |
train_loader = DataLoader(
|
| 303 |
train_ds, batch_size=cfg["batch_size"], shuffle=True, num_workers=args.workers, collate_fn=pad_trajectory_collate
|
|
|
|
| 11 |
import torch.nn as nn
|
| 12 |
import torch.nn.functional as F
|
| 13 |
import torch.optim as optim
|
| 14 |
+
from torch.utils.data import DataLoader, Subset
|
| 15 |
from torch.utils.tensorboard import SummaryWriter
|
| 16 |
|
| 17 |
from pino.heads import PIMTHeads
|
| 18 |
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
|
| 19 |
+
from pino.upload_data import create_molecule_disjoint_split
|
| 20 |
|
| 21 |
logger = logging.getLogger("pino.train")
|
| 22 |
|
|
|
|
| 290 |
# Use the genre column for both stratification and the contrastive loss.
|
| 291 |
all_genres = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 292 |
genre_map = {genre: idx for idx, genre in enumerate(all_genres)}
|
| 293 |
+
|
| 294 |
+
# Molecule-disjoint partition: no compound in a training formula may appear
|
| 295 |
+
# in any validation formula. This guarantees a true generalization test.
|
| 296 |
+
dataset_dict = create_molecule_disjoint_split(
|
| 297 |
+
args.data, train_ratio=0.8, seed=args.seed, solvent_cas="64-17-5"
|
| 298 |
+
)
|
| 299 |
+
full_dataset = FragranceTrajectoryDataset(
|
| 300 |
+
records=dataset_dict["train"].to_list() + dataset_dict["validation"].to_list(),
|
| 301 |
+
use_embedding_fallback=True,
|
| 302 |
+
genre_map=genre_map,
|
| 303 |
)
|
| 304 |
+
train_indices = list(range(len(dataset_dict["train"])))
|
| 305 |
+
val_indices = list(range(len(dataset_dict["train"]), len(full_dataset)))
|
| 306 |
+
train_ds = Subset(full_dataset, train_indices)
|
| 307 |
+
val_ds = Subset(full_dataset, val_indices)
|
| 308 |
+
test_ds = val_ds # No hidden test split for this verification pass
|
| 309 |
|
| 310 |
train_loader = DataLoader(
|
| 311 |
train_ds, batch_size=cfg["batch_size"], shuffle=True, num_workers=args.workers, collate_fn=pad_trajectory_collate
|
src/pino/upload_data.py
CHANGED
|
@@ -13,15 +13,80 @@ logger = logging.getLogger("pino.upload_data")
|
|
| 13 |
|
| 14 |
|
| 15 |
def _active_cas_set(record: dict[str, Any], solvent_cas: str | None = None) -> set[str]:
|
| 16 |
-
"""Return the set of active (non-solvent) CAS numbers in a formula record.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
solvent = solvent_cas or record.get("metadata", {}).get("solvent_cas", "64-17-5")
|
|
|
|
| 18 |
return {
|
| 19 |
comp["cas"]
|
| 20 |
-
for comp in
|
| 21 |
if comp.get("cas") and comp["cas"] != solvent
|
| 22 |
}
|
| 23 |
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
def molecule_disjoint_split(
|
| 26 |
jsonl_path: str | Path,
|
| 27 |
val_ratio: float = 0.2,
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def _active_cas_set(record: dict[str, Any], solvent_cas: str | None = None) -> set[str]:
|
| 16 |
+
"""Return the set of active (non-solvent) CAS numbers in a formula record.
|
| 17 |
+
|
| 18 |
+
The directive format stores the canonical ingredient list in
|
| 19 |
+
``metadata.initial_components``. Older records fall back to the top-level
|
| 20 |
+
``formula`` field.
|
| 21 |
+
"""
|
| 22 |
solvent = solvent_cas or record.get("metadata", {}).get("solvent_cas", "64-17-5")
|
| 23 |
+
components = record.get("metadata", {}).get("initial_components") or record.get("formula", [])
|
| 24 |
return {
|
| 25 |
comp["cas"]
|
| 26 |
+
for comp in components
|
| 27 |
if comp.get("cas") and comp["cas"] != solvent
|
| 28 |
}
|
| 29 |
|
| 30 |
|
| 31 |
+
def create_molecule_disjoint_split(
|
| 32 |
+
jsonl_path: str | Path,
|
| 33 |
+
train_ratio: float = 0.8,
|
| 34 |
+
seed: int = 42,
|
| 35 |
+
solvent_cas: str = "64-17-5",
|
| 36 |
+
) -> DatasetDict:
|
| 37 |
+
"""
|
| 38 |
+
Partition a JSON-L formulation corpus into molecule-disjoint train/validation sets.
|
| 39 |
+
|
| 40 |
+
A recipe containing even one molecule assigned to the validation tier is pushed
|
| 41 |
+
to the holdout validation set. The solvent (default ethanol) is ignored because
|
| 42 |
+
it appears in every formula. Returns a Hugging Face DatasetDict.
|
| 43 |
+
"""
|
| 44 |
+
import random
|
| 45 |
+
|
| 46 |
+
random.seed(seed)
|
| 47 |
+
jsonl_path = Path(jsonl_path)
|
| 48 |
+
logger.info("Loading raw corpus from %s", jsonl_path)
|
| 49 |
+
raw_dataset = load_dataset("json", data_files=str(jsonl_path), split="train")
|
| 50 |
+
|
| 51 |
+
all_records = list(raw_dataset)
|
| 52 |
+
record_cas_sets = [_active_cas_set(rec, solvent_cas) for rec in all_records]
|
| 53 |
+
|
| 54 |
+
all_molecules = sorted({cas for cas_set in record_cas_sets for cas in cas_set})
|
| 55 |
+
random.shuffle(all_molecules)
|
| 56 |
+
logger.info("Found %d unique active molecules across %d records", len(all_molecules), len(all_records))
|
| 57 |
+
|
| 58 |
+
split_idx = int(len(all_molecules) * train_ratio)
|
| 59 |
+
train_molecules = set(all_molecules[:split_idx])
|
| 60 |
+
|
| 61 |
+
train_indices = []
|
| 62 |
+
val_indices = []
|
| 63 |
+
for idx, cas_set in enumerate(record_cas_sets):
|
| 64 |
+
if not cas_set:
|
| 65 |
+
continue
|
| 66 |
+
# If any recipe ingredient is held out, the whole recipe goes to validation.
|
| 67 |
+
if cas_set.issubset(train_molecules):
|
| 68 |
+
train_indices.append(idx)
|
| 69 |
+
else:
|
| 70 |
+
val_indices.append(idx)
|
| 71 |
+
|
| 72 |
+
logger.info(
|
| 73 |
+
"Disjoint Split Complete. Train Formulas: %d | Val Formulas: %d",
|
| 74 |
+
len(train_indices),
|
| 75 |
+
len(val_indices),
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
train_cas = {cas for idx in train_indices for cas in record_cas_sets[idx]}
|
| 79 |
+
val_cas = {cas for idx in val_indices for cas in record_cas_sets[idx]}
|
| 80 |
+
overlap = train_cas & val_cas
|
| 81 |
+
if overlap:
|
| 82 |
+
raise RuntimeError(f"Molecule leakage detected: {overlap}")
|
| 83 |
+
|
| 84 |
+
return DatasetDict({
|
| 85 |
+
"train": raw_dataset.select(train_indices),
|
| 86 |
+
"validation": raw_dataset.select(val_indices),
|
| 87 |
+
})
|
| 88 |
+
|
| 89 |
+
|
| 90 |
def molecule_disjoint_split(
|
| 91 |
jsonl_path: str | Path,
|
| 92 |
val_ratio: float = 0.2,
|