feat(train): pin 597 single-molecule controls exclusively to training
Browse files- Separate empirical controls from mixture records before splitting.
- Apply formula-disjoint split only to the 5,000 mixture records.
- Append all pure single-molecule anchors to the training pool.
- Add create_formula_disjoint_split_from_dataset helper for in-memory Dataset splits.
- src/pino/train.py +26 -12
- src/pino/upload_data.py +36 -24
src/pino/train.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import argparse
|
|
|
|
| 4 |
import logging
|
| 5 |
import random
|
| 6 |
from pathlib import Path
|
|
@@ -11,13 +12,14 @@ 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 |
from pino.thermo.losses import AdaptiveLossBalancer
|
| 20 |
-
from pino.upload_data import
|
| 21 |
|
| 22 |
logger = logging.getLogger("pino.train")
|
| 23 |
|
|
@@ -261,11 +263,23 @@ def main():
|
|
| 261 |
}
|
| 262 |
logger.info("Configuration: %s", cfg)
|
| 263 |
|
| 264 |
-
# Ingest and
|
| 265 |
-
#
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
# Verify no identical formula fingerprint (ingredients + weights) appears in both splits.
|
| 271 |
def _formula_fingerprint(r):
|
|
@@ -275,26 +289,26 @@ def main():
|
|
| 275 |
)
|
| 276 |
return "".join(f"{c.get('cas', '')}_{c.get('weight_fraction', 0):.4f}" for c in components)
|
| 277 |
|
| 278 |
-
train_fps = {_formula_fingerprint(r) for r in
|
| 279 |
-
val_fps = {_formula_fingerprint(r) for r in
|
| 280 |
overlap = train_fps & val_fps
|
| 281 |
print(f"🔒 Formula isolation check: {len(overlap)} identical recipes shared between splits.")
|
| 282 |
assert len(overlap) == 0, f"Formula leakage detected: {overlap}"
|
| 283 |
|
| 284 |
-
total_rows = len(
|
| 285 |
-
print(f"📊 Dataset fully loaded. Total rows: {total_rows} | Training samples: {len(
|
| 286 |
|
| 287 |
# Use the genre column for both stratification and the contrastive loss.
|
| 288 |
all_genres = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 289 |
genre_map = {genre: idx for idx, genre in enumerate(all_genres)}
|
| 290 |
|
| 291 |
train_dataset = FragranceTrajectoryDataset(
|
| 292 |
-
records=
|
| 293 |
use_embedding_fallback=True,
|
| 294 |
genre_map=genre_map,
|
| 295 |
)
|
| 296 |
val_dataset = FragranceTrajectoryDataset(
|
| 297 |
-
records=
|
| 298 |
use_embedding_fallback=True,
|
| 299 |
genre_map=genre_map,
|
| 300 |
)
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import argparse
|
| 4 |
+
import json
|
| 5 |
import logging
|
| 6 |
import random
|
| 7 |
from pathlib import Path
|
|
|
|
| 12 |
import torch.nn as nn
|
| 13 |
import torch.nn.functional as F
|
| 14 |
import torch.optim as optim
|
| 15 |
+
from datasets import Dataset
|
| 16 |
from torch.utils.data import DataLoader
|
| 17 |
from torch.utils.tensorboard import SummaryWriter
|
| 18 |
|
| 19 |
from pino.heads import PIMTHeads
|
| 20 |
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
|
| 21 |
from pino.thermo.losses import AdaptiveLossBalancer
|
| 22 |
+
from pino.upload_data import create_formula_disjoint_split_from_dataset
|
| 23 |
|
| 24 |
logger = logging.getLogger("pino.train")
|
| 25 |
|
|
|
|
| 263 |
}
|
| 264 |
logger.info("Configuration: %s", cfg)
|
| 265 |
|
| 266 |
+
# Ingest and splice the dataset: controls are pinned to training, while
|
| 267 |
+
# empirical mixture formulas are split with a strict formula-disjoint rule.
|
| 268 |
+
print("⏳ Splicing empirical bootstrap data streams...")
|
| 269 |
+
with open(args.data, "r") as f:
|
| 270 |
+
all_records = [json.loads(line) for line in f]
|
| 271 |
+
|
| 272 |
+
control_records = [r for r in all_records if r.get("is_control", False)]
|
| 273 |
+
mixture_records = [r for r in all_records if not r.get("is_control", False)]
|
| 274 |
+
print(f"📊 Extracted {len(control_records)} pure single-molecule anchors.")
|
| 275 |
+
|
| 276 |
+
# Apply formula-disjoint split only to mixture records.
|
| 277 |
+
mixture_dataset = Dataset.from_list(mixture_records)
|
| 278 |
+
mixture_split = create_formula_disjoint_split_from_dataset(mixture_dataset, train_ratio=0.8)
|
| 279 |
+
|
| 280 |
+
# Pin all control records to the training pool.
|
| 281 |
+
train_records = mixture_split["train"].to_list() + control_records
|
| 282 |
+
val_records = mixture_split["validation"].to_list()
|
| 283 |
|
| 284 |
# Verify no identical formula fingerprint (ingredients + weights) appears in both splits.
|
| 285 |
def _formula_fingerprint(r):
|
|
|
|
| 289 |
)
|
| 290 |
return "".join(f"{c.get('cas', '')}_{c.get('weight_fraction', 0):.4f}" for c in components)
|
| 291 |
|
| 292 |
+
train_fps = {_formula_fingerprint(r) for r in train_records}
|
| 293 |
+
val_fps = {_formula_fingerprint(r) for r in val_records}
|
| 294 |
overlap = train_fps & val_fps
|
| 295 |
print(f"🔒 Formula isolation check: {len(overlap)} identical recipes shared between splits.")
|
| 296 |
assert len(overlap) == 0, f"Formula leakage detected: {overlap}"
|
| 297 |
|
| 298 |
+
total_rows = len(train_records) + len(val_records)
|
| 299 |
+
print(f"📊 Dataset fully loaded. Total rows: {total_rows} | Training samples: {len(train_records)} | Validation samples: {len(val_records)}")
|
| 300 |
|
| 301 |
# Use the genre column for both stratification and the contrastive loss.
|
| 302 |
all_genres = ["citrus_cologne", "fougere", "floral_woody", "amber_oriental", "wildcard"]
|
| 303 |
genre_map = {genre: idx for idx, genre in enumerate(all_genres)}
|
| 304 |
|
| 305 |
train_dataset = FragranceTrajectoryDataset(
|
| 306 |
+
records=train_records,
|
| 307 |
use_embedding_fallback=True,
|
| 308 |
genre_map=genre_map,
|
| 309 |
)
|
| 310 |
val_dataset = FragranceTrajectoryDataset(
|
| 311 |
+
records=val_records,
|
| 312 |
use_embedding_fallback=True,
|
| 313 |
genre_map=genre_map,
|
| 314 |
)
|
src/pino/upload_data.py
CHANGED
|
@@ -8,7 +8,7 @@ import os
|
|
| 8 |
from pathlib import Path
|
| 9 |
from typing import Any
|
| 10 |
|
| 11 |
-
from datasets import ClassLabel, DatasetDict, load_dataset
|
| 12 |
|
| 13 |
logger = logging.getLogger("pino.upload_data")
|
| 14 |
|
|
@@ -29,37 +29,33 @@ def _active_cas_set(record: dict[str, Any], solvent_cas: str | None = None) -> s
|
|
| 29 |
}
|
| 30 |
|
| 31 |
|
| 32 |
-
def
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
train_ratio: float = 0.8,
|
| 35 |
) -> DatasetDict:
|
| 36 |
"""
|
| 37 |
-
Partition a
|
| 38 |
|
| 39 |
Guarantees that exact ingredient combinations and weight-fraction distributions
|
| 40 |
do not cross the train/validation boundary, while preserving the full molecular
|
| 41 |
-
vocabulary across both splits.
|
| 42 |
-
molecule-disjoint isolation on densely-overlapping corpora.
|
| 43 |
"""
|
| 44 |
-
jsonl_path = Path(jsonl_path)
|
| 45 |
-
logger.info("Loading raw corpus from %s", jsonl_path)
|
| 46 |
-
raw_dataset = load_dataset("json", data_files=str(jsonl_path), split="train")
|
| 47 |
-
|
| 48 |
train_indices = []
|
| 49 |
val_indices = []
|
| 50 |
|
| 51 |
-
for idx, r in enumerate(
|
| 52 |
-
|
| 53 |
-
# Sorting ensures identical ingredient combinations hash identically
|
| 54 |
-
# regardless of component order.
|
| 55 |
-
components = sorted(
|
| 56 |
-
r.get("metadata", {}).get("initial_components") or r.get("formula", []),
|
| 57 |
-
key=lambda x: x.get("cas", ""),
|
| 58 |
-
)
|
| 59 |
-
formula_string = "".join(
|
| 60 |
-
f"{c.get('cas', '')}_{c.get('weight_fraction', 0):.4f}" for c in components
|
| 61 |
-
)
|
| 62 |
-
|
| 63 |
hash_val = int(hashlib.sha256(formula_string.encode("utf-8")).hexdigest(), 16)
|
| 64 |
if (hash_val % 100) < (train_ratio * 100):
|
| 65 |
train_indices.append(idx)
|
|
@@ -71,11 +67,27 @@ def create_formula_disjoint_split(
|
|
| 71 |
print(f" - Validation Recipes: {len(val_indices)}")
|
| 72 |
|
| 73 |
return DatasetDict({
|
| 74 |
-
"train":
|
| 75 |
-
"validation":
|
| 76 |
})
|
| 77 |
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def create_molecule_disjoint_split(
|
| 80 |
jsonl_path: str | Path,
|
| 81 |
train_ratio: float = 0.8,
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
from typing import Any
|
| 10 |
|
| 11 |
+
from datasets import ClassLabel, Dataset, DatasetDict, load_dataset
|
| 12 |
|
| 13 |
logger = logging.getLogger("pino.upload_data")
|
| 14 |
|
|
|
|
| 29 |
}
|
| 30 |
|
| 31 |
|
| 32 |
+
def _formula_fingerprint(record: dict[str, Any]) -> str:
|
| 33 |
+
"""Deterministic structural fingerprint from a recipe record."""
|
| 34 |
+
components = sorted(
|
| 35 |
+
record.get("metadata", {}).get("initial_components") or record.get("formula", []),
|
| 36 |
+
key=lambda x: x.get("cas", ""),
|
| 37 |
+
)
|
| 38 |
+
return "".join(
|
| 39 |
+
f"{c.get('cas', '')}_{c.get('weight_fraction', 0):.4f}" for c in components
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def create_formula_disjoint_split_from_dataset(
|
| 44 |
+
dataset: Dataset,
|
| 45 |
train_ratio: float = 0.8,
|
| 46 |
) -> DatasetDict:
|
| 47 |
"""
|
| 48 |
+
Partition a Hugging Face Dataset of formula records at the formula level.
|
| 49 |
|
| 50 |
Guarantees that exact ingredient combinations and weight-fraction distributions
|
| 51 |
do not cross the train/validation boundary, while preserving the full molecular
|
| 52 |
+
vocabulary across both splits.
|
|
|
|
| 53 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
train_indices = []
|
| 55 |
val_indices = []
|
| 56 |
|
| 57 |
+
for idx, r in enumerate(dataset):
|
| 58 |
+
formula_string = _formula_fingerprint(r)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
hash_val = int(hashlib.sha256(formula_string.encode("utf-8")).hexdigest(), 16)
|
| 60 |
if (hash_val % 100) < (train_ratio * 100):
|
| 61 |
train_indices.append(idx)
|
|
|
|
| 67 |
print(f" - Validation Recipes: {len(val_indices)}")
|
| 68 |
|
| 69 |
return DatasetDict({
|
| 70 |
+
"train": dataset.select(train_indices),
|
| 71 |
+
"validation": dataset.select(val_indices),
|
| 72 |
})
|
| 73 |
|
| 74 |
|
| 75 |
+
def create_formula_disjoint_split(
|
| 76 |
+
jsonl_path: str | Path,
|
| 77 |
+
train_ratio: float = 0.8,
|
| 78 |
+
) -> DatasetDict:
|
| 79 |
+
"""
|
| 80 |
+
Partition a JSON-L formulation corpus at the formula level.
|
| 81 |
+
|
| 82 |
+
Thin wrapper around :func:`create_formula_disjoint_split_from_dataset` that
|
| 83 |
+
loads the JSON-L file first.
|
| 84 |
+
"""
|
| 85 |
+
jsonl_path = Path(jsonl_path)
|
| 86 |
+
logger.info("Loading raw corpus from %s", jsonl_path)
|
| 87 |
+
raw_dataset = load_dataset("json", data_files=str(jsonl_path), split="train")
|
| 88 |
+
return create_formula_disjoint_split_from_dataset(raw_dataset, train_ratio=train_ratio)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
def create_molecule_disjoint_split(
|
| 92 |
jsonl_path: str | Path,
|
| 93 |
train_ratio: float = 0.8,
|