feat(embeddings): expand input token from 145-D to 151-D with physical-functional payload
Browse files- OlfactoryEmbeddingEngine now emits 151-D tokens:
138-D structural + 7-D 3D shape + 2-D physics (MW, LogP) + 4-D functional flags.
- Functional flags derived from Dortmund-UNIFAC subgroup IDs:
ester (21-23), alcohol (14-16), ketone (18-19), aldehyde (20).
- Updated model inits, collate padding, and docs in train.py, evaluate.py,
train_hf.py, pimt_model.py, pimt_model_hf.py, predict.py, inference.py,
and generate_paper_artifacts.py.
- scripts/generate_paper_artifacts.py +2 -2
- src/pino/embeddings.py +110 -10
- src/pino/evaluate.py +3 -3
- src/pino/inference.py +1 -1
- src/pino/pimt_model.py +8 -4
- src/pino/pimt_model_hf.py +5 -5
- src/pino/predict.py +1 -1
- src/pino/train.py +3 -3
- src/pino/train_hf.py +4 -4
scripts/generate_paper_artifacts.py
CHANGED
|
@@ -24,7 +24,7 @@ from torch.utils.data import DataLoader
|
|
| 24 |
|
| 25 |
from pino.embeddings import OlfactoryEmbeddingEngine
|
| 26 |
from pino.heads import PIMTHeads
|
| 27 |
-
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer
|
| 28 |
from pino.registry import AromaRegistry
|
| 29 |
from pino.thermo.losses import AdaptiveLossBalancer
|
| 30 |
from pino.train import pad_trajectory_collate
|
|
@@ -331,7 +331,7 @@ def generate_paper_artifacts(
|
|
| 331 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 332 |
|
| 333 |
model = PhysicsInformedMixtureTransformer(
|
| 334 |
-
embedding_dim=
|
| 335 |
state_dim=2,
|
| 336 |
hidden_dim=256,
|
| 337 |
num_heads=4,
|
|
|
|
| 24 |
|
| 25 |
from pino.embeddings import OlfactoryEmbeddingEngine
|
| 26 |
from pino.heads import PIMTHeads
|
| 27 |
+
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer, DEFAULT_EMBEDDING_DIM
|
| 28 |
from pino.registry import AromaRegistry
|
| 29 |
from pino.thermo.losses import AdaptiveLossBalancer
|
| 30 |
from pino.train import pad_trajectory_collate
|
|
|
|
| 331 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 332 |
|
| 333 |
model = PhysicsInformedMixtureTransformer(
|
| 334 |
+
embedding_dim=DEFAULT_EMBEDDING_DIM,
|
| 335 |
state_dim=2,
|
| 336 |
hidden_dim=256,
|
| 337 |
num_heads=4,
|
src/pino/embeddings.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import logging
|
| 4 |
from typing import Any
|
| 5 |
|
|
@@ -14,33 +15,98 @@ from .thermo.naturals import OPENPOM_DIM, SHAPE_DIM, resolve_natural_oil_vectors
|
|
| 14 |
logger = logging.getLogger("pino.embeddings")
|
| 15 |
|
| 16 |
STRUCTURAL_DIM = OPENPOM_DIM # 138
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Mute RDKit's internal C++ warning streams globally.
|
| 20 |
rd_logger = RDLogger.logger()
|
| 21 |
rd_logger.setLevel(RDLogger.CRITICAL)
|
| 22 |
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
class OlfactoryEmbeddingEngine:
|
| 25 |
"""
|
| 26 |
-
Write-through cached embedding engine for
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
computes them once, writes them back to the database permanently, and
|
| 31 |
-
returns them. Empty or invalid inputs short-circuit to a zero fallback
|
| 32 |
-
without invoking RDKit.
|
| 33 |
"""
|
| 34 |
|
| 35 |
-
def __init__(self, use_fallback: bool = True) -> None:
|
| 36 |
self.use_fallback = use_fallback
|
| 37 |
self.structural_dim = STRUCTURAL_DIM
|
| 38 |
self.shape_dim = SHAPE_DIM
|
|
|
|
|
|
|
| 39 |
self.embedding_dim = COMBINED_DIM
|
| 40 |
self.registry = AromaRegistry()
|
|
|
|
| 41 |
if not self.use_fallback:
|
| 42 |
self._initialize_real_openpom()
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
def _initialize_real_openpom(self) -> None:
|
| 45 |
# Placeholder for future on-disk GNN model loading.
|
| 46 |
logger.warning("Real OpenPOM model not available; enabling fallback automatically")
|
|
@@ -55,11 +121,45 @@ class OlfactoryEmbeddingEngine:
|
|
| 55 |
s = smiles.strip()
|
| 56 |
return bool(s) and s != "None" and not s.startswith("SMILES:") and not s.startswith("NATURAL:")
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
def get_embedding(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 59 |
-
"""Main entry point. Returns a
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
structural = self._compute_structural_embedding(smiles, cas)
|
| 61 |
shape = self._compute_shape_features(smiles, cas)
|
| 62 |
-
|
|
|
|
|
|
|
| 63 |
norm = np.linalg.norm(combined)
|
| 64 |
return combined / norm if norm > 0 else combined
|
| 65 |
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import json
|
| 4 |
import logging
|
| 5 |
from typing import Any
|
| 6 |
|
|
|
|
| 15 |
logger = logging.getLogger("pino.embeddings")
|
| 16 |
|
| 17 |
STRUCTURAL_DIM = OPENPOM_DIM # 138
|
| 18 |
+
SHAPE_DIM = SHAPE_DIM # 7
|
| 19 |
+
PHYSICAL_DIM = 2 # molecular_weight, logp
|
| 20 |
+
FUNCTIONAL_DIM = 4 # ester, alcohol, ketone, aldehyde
|
| 21 |
+
COMBINED_DIM = STRUCTURAL_DIM + SHAPE_DIM + PHYSICAL_DIM + FUNCTIONAL_DIM # 151
|
| 22 |
|
| 23 |
# Mute RDKit's internal C++ warning streams globally.
|
| 24 |
rd_logger = RDLogger.logger()
|
| 25 |
rd_logger.setLevel(RDLogger.CRITICAL)
|
| 26 |
|
| 27 |
|
| 28 |
+
# UNIFAC subgroup ID mapping to functional families (Dortmund-UNIFAC convention).
|
| 29 |
+
# These IDs are stable in the thermo.unifac DOUFSG parameter set.
|
| 30 |
+
FUNCTIONAL_GROUP_IDS = {
|
| 31 |
+
"ester": {21, 22, 23},
|
| 32 |
+
"alcohol": {14, 15, 16},
|
| 33 |
+
"ketone": {18, 19},
|
| 34 |
+
"aldehyde": {20},
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _functional_group_flags(unifac_groups: dict[str, Any] | str | None) -> np.ndarray:
|
| 39 |
+
"""Return a 4-D binary vector for ester, alcohol, ketone, aldehyde."""
|
| 40 |
+
flags = np.zeros(FUNCTIONAL_DIM, dtype=np.float32)
|
| 41 |
+
if not unifac_groups:
|
| 42 |
+
return flags
|
| 43 |
+
|
| 44 |
+
if isinstance(unifac_groups, str):
|
| 45 |
+
try:
|
| 46 |
+
unifac_groups = json.loads(unifac_groups)
|
| 47 |
+
except Exception:
|
| 48 |
+
return flags
|
| 49 |
+
|
| 50 |
+
group_ids = set()
|
| 51 |
+
for key in unifac_groups:
|
| 52 |
+
try:
|
| 53 |
+
group_ids.add(int(key))
|
| 54 |
+
except ValueError:
|
| 55 |
+
# If keys are textual names (legacy), look for matching subgroup names.
|
| 56 |
+
k = str(key).lower()
|
| 57 |
+
if "coo" in k or "ester" in k:
|
| 58 |
+
flags[0] = 1.0
|
| 59 |
+
if "oh" in k:
|
| 60 |
+
flags[1] = 1.0
|
| 61 |
+
if "ketone" in k or "co" == k:
|
| 62 |
+
flags[2] = 1.0
|
| 63 |
+
if "cho" in k or "aldehyde" in k:
|
| 64 |
+
flags[3] = 1.0
|
| 65 |
+
return flags
|
| 66 |
+
|
| 67 |
+
if group_ids & FUNCTIONAL_GROUP_IDS["ester"]:
|
| 68 |
+
flags[0] = 1.0
|
| 69 |
+
if group_ids & FUNCTIONAL_GROUP_IDS["alcohol"]:
|
| 70 |
+
flags[1] = 1.0
|
| 71 |
+
if group_ids & FUNCTIONAL_GROUP_IDS["ketone"]:
|
| 72 |
+
flags[2] = 1.0
|
| 73 |
+
if group_ids & FUNCTIONAL_GROUP_IDS["aldehyde"]:
|
| 74 |
+
flags[3] = 1.0
|
| 75 |
+
return flags
|
| 76 |
+
|
| 77 |
+
|
| 78 |
class OlfactoryEmbeddingEngine:
|
| 79 |
"""
|
| 80 |
+
Write-through cached embedding engine for 151-D olfactory molecule tokens.
|
| 81 |
+
|
| 82 |
+
Combines a 138-D OpenPOM-style structural vector, a 7-D 3D shape/chirality
|
| 83 |
+
descriptor, and a 6-D physical-functional payload (molecular weight, LogP,
|
| 84 |
+
ester/alcohol/ketone/aldehyde flags) from the SQLite AromaRegistry.
|
| 85 |
|
| 86 |
+
Missing 3D features are computed once and written back to the registry.
|
| 87 |
+
Empty or invalid inputs short-circuit to a zero fallback without invoking RDKit.
|
|
|
|
|
|
|
|
|
|
| 88 |
"""
|
| 89 |
|
| 90 |
+
def __init__(self, use_fallback: bool = True, global_median_logp: float = 2.15) -> None:
|
| 91 |
self.use_fallback = use_fallback
|
| 92 |
self.structural_dim = STRUCTURAL_DIM
|
| 93 |
self.shape_dim = SHAPE_DIM
|
| 94 |
+
self.physical_dim = PHYSICAL_DIM
|
| 95 |
+
self.functional_dim = FUNCTIONAL_DIM
|
| 96 |
self.embedding_dim = COMBINED_DIM
|
| 97 |
self.registry = AromaRegistry()
|
| 98 |
+
self.global_median_logp = self._compute_median_logp() if global_median_logp is None else global_median_logp
|
| 99 |
if not self.use_fallback:
|
| 100 |
self._initialize_real_openpom()
|
| 101 |
|
| 102 |
+
def _compute_median_logp(self) -> float:
|
| 103 |
+
rows = self.registry._conn.execute(
|
| 104 |
+
"SELECT logp FROM aroma_chemicals WHERE logp IS NOT NULL AND logp != 0"
|
| 105 |
+
).fetchall()
|
| 106 |
+
if not rows:
|
| 107 |
+
return 2.15
|
| 108 |
+
return float(np.median([r[0] for r in rows]))
|
| 109 |
+
|
| 110 |
def _initialize_real_openpom(self) -> None:
|
| 111 |
# Placeholder for future on-disk GNN model loading.
|
| 112 |
logger.warning("Real OpenPOM model not available; enabling fallback automatically")
|
|
|
|
| 121 |
s = smiles.strip()
|
| 122 |
return bool(s) and s != "None" and not s.startswith("SMILES:") and not s.startswith("NATURAL:")
|
| 123 |
|
| 124 |
+
def get_combined_structural_token(self, cas: str, smiles: str) -> np.ndarray:
|
| 125 |
+
"""Main entry point. Returns a 151-dimensional float32 array."""
|
| 126 |
+
return self.get_embedding(smiles, cas=cas)
|
| 127 |
+
|
| 128 |
+
def _extract_physical_features(self, record: dict[str, Any]) -> np.ndarray:
|
| 129 |
+
"""Return a 2-D normalized [MW, LogP] vector."""
|
| 130 |
+
mw = float(record.get("molecular_weight", 150.0))
|
| 131 |
+
logp_raw = record.get("logp")
|
| 132 |
+
logp = float(logp_raw) if logp_raw is not None else self.global_median_logp
|
| 133 |
+
return np.array([mw / 300.0, logp / 5.0], dtype=np.float32)
|
| 134 |
+
|
| 135 |
+
def _extract_functional_features(self, record: dict[str, Any]) -> np.ndarray:
|
| 136 |
+
"""Return a 4-D binary flag vector for ester/alcohol/ketone/aldehyde."""
|
| 137 |
+
return _functional_group_flags(record.get("unifac_groups"))
|
| 138 |
+
|
| 139 |
def get_embedding(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 140 |
+
"""Main entry point. Returns a 151-dimensional float32 array."""
|
| 141 |
+
normalized_cas = self._normalized_cas(cas)
|
| 142 |
+
|
| 143 |
+
if normalized_cas:
|
| 144 |
+
try:
|
| 145 |
+
record = self.registry.get(normalized_cas)
|
| 146 |
+
if record:
|
| 147 |
+
structural = np.asarray(record.get("openpom_embedding", [0.0] * STRUCTURAL_DIM), dtype=np.float32)
|
| 148 |
+
shape = np.asarray(record.get("shape_3d_features", [0.0] * SHAPE_DIM), dtype=np.float32)
|
| 149 |
+
physical = self._extract_physical_features(record)
|
| 150 |
+
functional = self._extract_functional_features(record)
|
| 151 |
+
combined = np.concatenate([structural, shape, physical, functional]).astype(np.float32)
|
| 152 |
+
norm = np.linalg.norm(combined)
|
| 153 |
+
return combined / norm if norm > 0 else combined
|
| 154 |
+
except Exception as exc:
|
| 155 |
+
logger.debug("Registry lookup failed for %s: %s", normalized_cas, exc)
|
| 156 |
+
|
| 157 |
+
# Fallback: compute structural/shape features on the fly.
|
| 158 |
structural = self._compute_structural_embedding(smiles, cas)
|
| 159 |
shape = self._compute_shape_features(smiles, cas)
|
| 160 |
+
physical = np.array([0.5, self.global_median_logp / 5.0], dtype=np.float32) # 150/300=0.5
|
| 161 |
+
functional = _functional_group_flags(None)
|
| 162 |
+
combined = np.concatenate([structural, shape, physical, functional]).astype(np.float32)
|
| 163 |
norm = np.linalg.norm(combined)
|
| 164 |
return combined / norm if norm > 0 else combined
|
| 165 |
|
src/pino/evaluate.py
CHANGED
|
@@ -14,7 +14,7 @@ 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 |
|
|
@@ -25,7 +25,7 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 25 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 26 |
bsz = len(batch)
|
| 27 |
|
| 28 |
-
tokens = torch.zeros(bsz, max_molecules,
|
| 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)
|
|
@@ -151,7 +151,7 @@ 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"])
|
|
|
|
| 14 |
from torch.utils.data import DataLoader
|
| 15 |
|
| 16 |
from pino.heads import PIMTHeads
|
| 17 |
+
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer, DEFAULT_EMBEDDING_DIM
|
| 18 |
|
| 19 |
logger = logging.getLogger("pino.evaluate")
|
| 20 |
|
|
|
|
| 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)
|
|
|
|
| 151 |
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, collate_fn=pad_trajectory_collate)
|
| 152 |
|
| 153 |
model = PhysicsInformedMixtureTransformer(
|
| 154 |
+
embedding_dim=DEFAULT_EMBEDDING_DIM, state_dim=2, hidden_dim=hidden_dim, num_heads=4, num_layers=4
|
| 155 |
).to(device)
|
| 156 |
heads = PIMTHeads(hidden_dim=hidden_dim, objective_dim=138).to(device)
|
| 157 |
model.load_state_dict(checkpoint["model_state_dict"])
|
src/pino/inference.py
CHANGED
|
@@ -31,7 +31,7 @@ class FragranceInferenceEngine:
|
|
| 31 |
},
|
| 32 |
"raw_predictions": {
|
| 33 |
"subjective_logits": [0.85, 0.12, 0.05, 0.01, 0.01, 0.01, 0.01],
|
| 34 |
-
"objective_trajectory_shape": [1, 49,
|
| 35 |
},
|
| 36 |
"review_text": "Mocked validation profile: High volatile top-note distribution detected.",
|
| 37 |
}
|
|
|
|
| 31 |
},
|
| 32 |
"raw_predictions": {
|
| 33 |
"subjective_logits": [0.85, 0.12, 0.05, 0.01, 0.01, 0.01, 0.01],
|
| 34 |
+
"objective_trajectory_shape": [1, 49, 151],
|
| 35 |
},
|
| 36 |
"review_text": "Mocked validation profile: High volatile top-note distribution detected.",
|
| 37 |
}
|
src/pino/pimt_model.py
CHANGED
|
@@ -16,14 +16,18 @@ logger = logging.getLogger("pino.pimt_model")
|
|
| 16 |
|
| 17 |
DEFAULT_DATASET = Path(__file__).parent.parent.parent / "data" / "synthetic_dataset_v2.jsonl"
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
class FragranceTrajectoryDataset(Dataset):
|
| 21 |
"""
|
| 22 |
Streaming PyTorch dataset over the PINO synthetic trajectory corpus.
|
| 23 |
|
| 24 |
Each record is parsed line-by-line from the JSON-L file. For every
|
| 25 |
-
ingredient we look up a static
|
| 26 |
-
+ 7-D 3D shape) and combine it with the time-resolved physical state
|
| 27 |
vectors to build a token tensor.
|
| 28 |
"""
|
| 29 |
|
|
@@ -32,7 +36,7 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 32 |
data_path: str | Path | None = DEFAULT_DATASET,
|
| 33 |
records: list[dict[str, Any]] | None = None,
|
| 34 |
max_ingredients: int = 32,
|
| 35 |
-
embedding_dim: int =
|
| 36 |
state_dim: int = 4,
|
| 37 |
use_embedding_fallback: bool = True,
|
| 38 |
label_noise: bool = True,
|
|
@@ -188,7 +192,7 @@ class PhysicsInformedMixtureTransformer(torch.nn.Module):
|
|
| 188 |
|
| 189 |
def __init__(
|
| 190 |
self,
|
| 191 |
-
embedding_dim: int =
|
| 192 |
state_dim: int = 4,
|
| 193 |
hidden_dim: int = 256,
|
| 194 |
num_heads: int = 4,
|
|
|
|
| 16 |
|
| 17 |
DEFAULT_DATASET = Path(__file__).parent.parent.parent / "data" / "synthetic_dataset_v2.jsonl"
|
| 18 |
|
| 19 |
+
# The default token dimension is 151-D: 138-D structural + 7-D 3D shape + 2-D physics +
|
| 20 |
+
# 4-D functional-group flags.
|
| 21 |
+
DEFAULT_EMBEDDING_DIM = 151
|
| 22 |
+
|
| 23 |
|
| 24 |
class FragranceTrajectoryDataset(Dataset):
|
| 25 |
"""
|
| 26 |
Streaming PyTorch dataset over the PINO synthetic trajectory corpus.
|
| 27 |
|
| 28 |
Each record is parsed line-by-line from the JSON-L file. For every
|
| 29 |
+
ingredient we look up a static 151-D molecular embedding (138-D structural
|
| 30 |
+
+ 7-D 3D shape + 2-D physics + 4-D functional-group flags) and combine it with the time-resolved physical state
|
| 31 |
vectors to build a token tensor.
|
| 32 |
"""
|
| 33 |
|
|
|
|
| 36 |
data_path: str | Path | None = DEFAULT_DATASET,
|
| 37 |
records: list[dict[str, Any]] | None = None,
|
| 38 |
max_ingredients: int = 32,
|
| 39 |
+
embedding_dim: int = DEFAULT_EMBEDDING_DIM,
|
| 40 |
state_dim: int = 4,
|
| 41 |
use_embedding_fallback: bool = True,
|
| 42 |
label_noise: bool = True,
|
|
|
|
| 192 |
|
| 193 |
def __init__(
|
| 194 |
self,
|
| 195 |
+
embedding_dim: int = DEFAULT_EMBEDDING_DIM,
|
| 196 |
state_dim: int = 4,
|
| 197 |
hidden_dim: int = 256,
|
| 198 |
num_heads: int = 4,
|
src/pino/pimt_model_hf.py
CHANGED
|
@@ -7,8 +7,8 @@ import torch.nn as nn
|
|
| 7 |
import torch.nn.functional as F
|
| 8 |
from transformers import PretrainedConfig, PreTrainedModel
|
| 9 |
from transformers.modeling_outputs import SequenceClassifierOutput
|
| 10 |
-
|
| 11 |
-
from .heads import PIMTHeads
|
| 12 |
|
| 13 |
|
| 14 |
class PIMTConfig(PretrainedConfig):
|
|
@@ -20,7 +20,7 @@ class PIMTConfig(PretrainedConfig):
|
|
| 20 |
|
| 21 |
def __init__(
|
| 22 |
self,
|
| 23 |
-
embedding_dim: int =
|
| 24 |
state_dim: int = 2,
|
| 25 |
hidden_dim: int = 256,
|
| 26 |
num_heads: int = 8,
|
|
@@ -99,7 +99,7 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
|
| 99 |
)
|
| 100 |
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=config.num_layers)
|
| 101 |
self.text_proj = nn.Linear(config.text_embedding_dim, config.hidden_dim)
|
| 102 |
-
# Objective output vocabulary stays 138-D; structural input is
|
| 103 |
objective_dim = getattr(config, "objective_dim", 138)
|
| 104 |
self.heads = PIMTHeads(
|
| 105 |
hidden_dim=config.hidden_dim,
|
|
@@ -146,7 +146,7 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
|
| 146 |
physics: (B, T, S, state_dim)
|
| 147 |
src_key_padding_mask: (B, S) bool, True for padding positions.
|
| 148 |
text_embedding: (B, 384) sentence-transformer embedding for conditioning.
|
| 149 |
-
labels: fused (B, T,
|
| 150 |
"""
|
| 151 |
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 152 |
|
|
|
|
| 7 |
import torch.nn.functional as F
|
| 8 |
from transformers import PretrainedConfig, PreTrainedModel
|
| 9 |
from transformers.modeling_outputs import SequenceClassifierOutput
|
| 10 |
+
from pino.pimt_model import DEFAULT_EMBEDDING_DIM
|
| 11 |
+
from pino.heads import PIMTHeads
|
| 12 |
|
| 13 |
|
| 14 |
class PIMTConfig(PretrainedConfig):
|
|
|
|
| 20 |
|
| 21 |
def __init__(
|
| 22 |
self,
|
| 23 |
+
embedding_dim: int = DEFAULT_EMBEDDING_DIM,
|
| 24 |
state_dim: int = 2,
|
| 25 |
hidden_dim: int = 256,
|
| 26 |
num_heads: int = 8,
|
|
|
|
| 99 |
)
|
| 100 |
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=config.num_layers)
|
| 101 |
self.text_proj = nn.Linear(config.text_embedding_dim, config.hidden_dim)
|
| 102 |
+
# Objective output vocabulary stays 138-D; structural input is 151-D.
|
| 103 |
objective_dim = getattr(config, "objective_dim", 138)
|
| 104 |
self.heads = PIMTHeads(
|
| 105 |
hidden_dim=config.hidden_dim,
|
|
|
|
| 146 |
physics: (B, T, S, state_dim)
|
| 147 |
src_key_padding_mask: (B, S) bool, True for padding positions.
|
| 148 |
text_embedding: (B, 384) sentence-transformer embedding for conditioning.
|
| 149 |
+
labels: fused (B, T, 151) tensor of objective + subjective labels (legacy HF shape).
|
| 150 |
"""
|
| 151 |
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 152 |
|
src/pino/predict.py
CHANGED
|
@@ -34,7 +34,7 @@ def predict(
|
|
| 34 |
"""
|
| 35 |
Run inference on a single formulation.
|
| 36 |
|
| 37 |
-
tokens: (S,
|
| 38 |
physics: (T, S, 2) or (B, T, S, 2)
|
| 39 |
src_key_padding_mask: (S,) or (B, S)
|
| 40 |
Returns: {"objective": (B, T, 138), "subjective": (B, 7)}
|
|
|
|
| 34 |
"""
|
| 35 |
Run inference on a single formulation.
|
| 36 |
|
| 37 |
+
tokens: (S, 151) or (B, S, 151)
|
| 38 |
physics: (T, S, 2) or (B, T, S, 2)
|
| 39 |
src_key_padding_mask: (S,) or (B, S)
|
| 40 |
Returns: {"objective": (B, T, 138), "subjective": (B, 7)}
|
src/pino/train.py
CHANGED
|
@@ -17,7 +17,7 @@ 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_records
|
| 23 |
|
|
@@ -47,7 +47,7 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 47 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 48 |
bsz = len(batch)
|
| 49 |
|
| 50 |
-
tokens = torch.zeros(bsz, max_molecules,
|
| 51 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 52 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 53 |
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
|
@@ -327,7 +327,7 @@ def main():
|
|
| 327 |
)
|
| 328 |
|
| 329 |
model = PhysicsInformedMixtureTransformer(
|
| 330 |
-
embedding_dim=
|
| 331 |
state_dim=2,
|
| 332 |
hidden_dim=cfg["hidden_dim"],
|
| 333 |
num_heads=cfg["num_heads"],
|
|
|
|
| 17 |
from torch.utils.tensorboard import SummaryWriter
|
| 18 |
|
| 19 |
from pino.heads import PIMTHeads
|
| 20 |
+
from pino.pimt_model import FragranceTrajectoryDataset, PhysicsInformedMixtureTransformer, DEFAULT_EMBEDDING_DIM
|
| 21 |
from pino.thermo.losses import AdaptiveLossBalancer
|
| 22 |
from pino.upload_data import create_formula_disjoint_split_from_records
|
| 23 |
|
|
|
|
| 47 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 48 |
bsz = len(batch)
|
| 49 |
|
| 50 |
+
tokens = torch.zeros(bsz, max_molecules, DEFAULT_EMBEDDING_DIM, dtype=torch.float32)
|
| 51 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 52 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 53 |
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
|
|
|
| 327 |
)
|
| 328 |
|
| 329 |
model = PhysicsInformedMixtureTransformer(
|
| 330 |
+
embedding_dim=DEFAULT_EMBEDDING_DIM,
|
| 331 |
state_dim=2,
|
| 332 |
hidden_dim=cfg["hidden_dim"],
|
| 333 |
num_heads=cfg["num_heads"],
|
src/pino/train_hf.py
CHANGED
|
@@ -14,7 +14,7 @@ from datasets import load_dataset
|
|
| 14 |
from sentence_transformers import SentenceTransformer
|
| 15 |
from transformers import Trainer, TrainingArguments
|
| 16 |
|
| 17 |
-
from pino.pimt_model import FragranceTrajectoryDataset
|
| 18 |
from pino.pimt_model_hf import PIMTConfig, PhysicsInformedMixtureTransformer
|
| 19 |
|
| 20 |
logger = logging.getLogger("pino.train_hf")
|
|
@@ -45,7 +45,7 @@ def pad_trajectory_collate(batch: list) -> dict:
|
|
| 45 |
max_molecules = max(item["tokens"].size(0) for item in batch)
|
| 46 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 47 |
bsz = len(batch)
|
| 48 |
-
tokens = torch.zeros(bsz, max_molecules,
|
| 49 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 50 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 51 |
labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
|
@@ -75,7 +75,7 @@ def pad_trajectory_collate(batch: list) -> dict:
|
|
| 75 |
emb = text_encoder.encode(item["text_conditioning"], convert_to_numpy=True)
|
| 76 |
text_embeddings[i] = torch.from_numpy(emb).float()
|
| 77 |
|
| 78 |
-
# Fuse objective and subjective labels into a single (B, T,
|
| 79 |
labels_sub_t = labels_sub.unsqueeze(1).expand(-1, max_timesteps, -1)
|
| 80 |
labels = torch.cat([labels_obj, labels_sub_t], dim=-1)
|
| 81 |
|
|
@@ -178,7 +178,7 @@ def main() -> None:
|
|
| 178 |
val_ds = FragranceTrajectoryDataset(records=val_records, use_embedding_fallback=True)
|
| 179 |
|
| 180 |
config = PIMTConfig(
|
| 181 |
-
embedding_dim=
|
| 182 |
objective_dim=138,
|
| 183 |
state_dim=2,
|
| 184 |
hidden_dim=256,
|
|
|
|
| 14 |
from sentence_transformers import SentenceTransformer
|
| 15 |
from transformers import Trainer, TrainingArguments
|
| 16 |
|
| 17 |
+
from pino.pimt_model import FragranceTrajectoryDataset, DEFAULT_EMBEDDING_DIM
|
| 18 |
from pino.pimt_model_hf import PIMTConfig, PhysicsInformedMixtureTransformer
|
| 19 |
|
| 20 |
logger = logging.getLogger("pino.train_hf")
|
|
|
|
| 45 |
max_molecules = max(item["tokens"].size(0) for item in batch)
|
| 46 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 47 |
bsz = len(batch)
|
| 48 |
+
tokens = torch.zeros(bsz, max_molecules, DEFAULT_EMBEDDING_DIM, dtype=torch.float32)
|
| 49 |
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 50 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 51 |
labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
|
|
|
| 75 |
emb = text_encoder.encode(item["text_conditioning"], convert_to_numpy=True)
|
| 76 |
text_embeddings[i] = torch.from_numpy(emb).float()
|
| 77 |
|
| 78 |
+
# Fuse objective and subjective labels into a single (B, T, 151) tensor for HF Trainer (legacy shape).
|
| 79 |
labels_sub_t = labels_sub.unsqueeze(1).expand(-1, max_timesteps, -1)
|
| 80 |
labels = torch.cat([labels_obj, labels_sub_t], dim=-1)
|
| 81 |
|
|
|
|
| 178 |
val_ds = FragranceTrajectoryDataset(records=val_records, use_embedding_fallback=True)
|
| 179 |
|
| 180 |
config = PIMTConfig(
|
| 181 |
+
embedding_dim=DEFAULT_EMBEDDING_DIM,
|
| 182 |
objective_dim=138,
|
| 183 |
state_dim=2,
|
| 184 |
hidden_dim=256,
|