fix(training): update hf_train_job to run from cloned repo, add text conditioning, fix dataset viewer
Browse files- scripts/augment_dataset_text.py +116 -0
- scripts/flatten_literature_for_hub.py +42 -0
- scripts/hf_train_job.py +52 -0
- scripts/pino_literature_dataset_builder.py +45 -0
- src/pino/pimt_model_hf.py +25 -28
- src/pino/registry.py +5 -2
- src/pino/train_hf.py +34 -3
scripts/augment_dataset_text.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import itertools
|
| 5 |
+
import json
|
| 6 |
+
import random
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from sentence_transformers import SentenceTransformer
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load_descriptions_by_genre(literature_path: Path, arctander_path: Path | None) -> dict[str, list[str]]:
|
| 14 |
+
"""Build a genre-keyed pool of perfume text descriptions."""
|
| 15 |
+
descriptions: dict[str, list[str]] = {}
|
| 16 |
+
|
| 17 |
+
# Genre keywords for classifying free-form odor text
|
| 18 |
+
genre_keywords = {
|
| 19 |
+
"citrus_cologne": ["citrus", "lemon", "lime", "bergamot", "orange", "grapefruit", "cologne", "fresh", "zesty"],
|
| 20 |
+
"floral_woody": ["rose", "jasmine", "floral", "lily", "ylang", "neroli", "flower", "wood", "sandalwood", "cedar"],
|
| 21 |
+
"fougere": ["fougere", "lavender", "coumarin", "oakmoss", "herbal", "green", "moss"],
|
| 22 |
+
"amber_oriental": ["amber", "oriental", "vanilla", "spice", "cinnamon", "incense", "resin", "balsamic", "sweet"],
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
def classify(text: str) -> str | None:
|
| 26 |
+
text_lower = text.lower()
|
| 27 |
+
scores = {genre: sum(1 for kw in keywords if kw in text_lower) for genre, keywords in genre_keywords.items()}
|
| 28 |
+
best = max(scores, key=scores.get)
|
| 29 |
+
return best if scores[best] > 0 else None
|
| 30 |
+
|
| 31 |
+
# Collect descriptions from literature formulas
|
| 32 |
+
if literature_path.exists():
|
| 33 |
+
data = json.loads(literature_path.read_text())
|
| 34 |
+
for rec in data:
|
| 35 |
+
genre = rec.get("expected_profile")
|
| 36 |
+
text = rec.get("name", "")
|
| 37 |
+
if genre and text:
|
| 38 |
+
descriptions.setdefault(genre, []).append(text)
|
| 39 |
+
|
| 40 |
+
# Collect descriptions from Arctander monographs
|
| 41 |
+
if arctander_path and arctander_path.exists():
|
| 42 |
+
for line in arctander_path.read_text().strip().splitlines():
|
| 43 |
+
rec = json.loads(line)
|
| 44 |
+
text = rec.get("odor_description") or rec.get("raw_text", "")
|
| 45 |
+
if not text:
|
| 46 |
+
continue
|
| 47 |
+
genre = classify(text)
|
| 48 |
+
if genre:
|
| 49 |
+
descriptions.setdefault(genre, []).append(text)
|
| 50 |
+
|
| 51 |
+
# Ensure every genre has a fallback pool
|
| 52 |
+
for genre in genre_keywords:
|
| 53 |
+
descriptions.setdefault(genre, [f"A classic {genre.replace('_', ' ')} fragrance"])
|
| 54 |
+
|
| 55 |
+
return descriptions
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def augment_dataset(
|
| 59 |
+
input_path: Path,
|
| 60 |
+
output_path: Path,
|
| 61 |
+
descriptions: dict[str, list[str]],
|
| 62 |
+
seed: int = 42,
|
| 63 |
+
) -> None:
|
| 64 |
+
"""Attach a sampled text description and its 384-D embedding to every record."""
|
| 65 |
+
random.seed(seed)
|
| 66 |
+
|
| 67 |
+
print("Loading sentence transformer...")
|
| 68 |
+
text_encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 69 |
+
|
| 70 |
+
# Pre-shuffle cyclical iterators per genre so sampling is deterministic
|
| 71 |
+
iterators: dict[str, itertools.cycle] = {}
|
| 72 |
+
for genre, pool in descriptions.items():
|
| 73 |
+
shuffled = pool[:]
|
| 74 |
+
random.shuffle(shuffled)
|
| 75 |
+
iterators[genre] = itertools.cycle(shuffled)
|
| 76 |
+
|
| 77 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
total = 0
|
| 79 |
+
|
| 80 |
+
with input_path.open("r", encoding="utf-8") as fin, output_path.open("w", encoding="utf-8") as fout:
|
| 81 |
+
for line in fin:
|
| 82 |
+
record = json.loads(line)
|
| 83 |
+
genre = record.get("genre")
|
| 84 |
+
if not genre or genre not in iterators:
|
| 85 |
+
genre = "citrus_cologne" # fallback
|
| 86 |
+
|
| 87 |
+
text = next(iterators[genre])
|
| 88 |
+
embedding = text_encoder.encode(text, convert_to_numpy=True)
|
| 89 |
+
|
| 90 |
+
record["text_conditioning"] = text
|
| 91 |
+
record["text_embedding"] = embedding.tolist()
|
| 92 |
+
fout.write(json.dumps(record, ensure_ascii=False) + "\n")
|
| 93 |
+
total += 1
|
| 94 |
+
|
| 95 |
+
print(f"Augmented {total} records with text conditioning -> {output_path}")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main() -> int:
|
| 99 |
+
parser = argparse.ArgumentParser(description="Augment PINO synthetic dataset with text conditioning")
|
| 100 |
+
parser.add_argument("--input", default="data/synthetic_dataset_v2.jsonl", help="Input JSONL")
|
| 101 |
+
parser.add_argument("--output", default="data/synthetic_dataset_v2_text.jsonl", help="Output JSONL")
|
| 102 |
+
parser.add_argument("--literature", default="data/literature_formulas.json", help="Literature blueprint")
|
| 103 |
+
parser.add_argument("--arctander", default="/home/hermes/fragrance-research/extracted/arctander_monographs.jsonl", help="Arctander monographs")
|
| 104 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed")
|
| 105 |
+
args = parser.parse_args()
|
| 106 |
+
|
| 107 |
+
descriptions = load_descriptions_by_genre(Path(args.literature), Path(args.arctander))
|
| 108 |
+
for genre, pool in descriptions.items():
|
| 109 |
+
print(f" {genre}: {len(pool)} descriptions")
|
| 110 |
+
|
| 111 |
+
augment_dataset(Path(args.input), Path(args.output), descriptions, seed=args.seed)
|
| 112 |
+
return 0
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
raise SystemExit(main())
|
scripts/flatten_literature_for_hub.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pyarrow as pa
|
| 7 |
+
from datasets import Dataset, DatasetDict, Features, Value
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def convert_mixed_jsonl_to_records(repo_dir: str, output_dir: str) -> dict[str, int]:
|
| 11 |
+
"""
|
| 12 |
+
Convert each JSONL file in repo_dir to a uniform schema where every row is
|
| 13 |
+
{"record": <original_json_string>}. This avoids Hub viewer CastError when
|
| 14 |
+
files have incompatible schemas.
|
| 15 |
+
"""
|
| 16 |
+
repo_dir = Path(repo_dir)
|
| 17 |
+
output_dir = Path(output_dir)
|
| 18 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 19 |
+
|
| 20 |
+
features = Features({"record": Value("string")})
|
| 21 |
+
counts: dict[str, int] = {}
|
| 22 |
+
|
| 23 |
+
for path in sorted(repo_dir.glob("*.jsonl")):
|
| 24 |
+
records = []
|
| 25 |
+
with path.open("r", encoding="utf-8") as f:
|
| 26 |
+
for line in f:
|
| 27 |
+
record = json.loads(line)
|
| 28 |
+
records.append({"record": json.dumps(record, ensure_ascii=False)})
|
| 29 |
+
ds = Dataset.from_list(records, features=features)
|
| 30 |
+
out_path = output_dir / path.name
|
| 31 |
+
ds.to_json(out_path)
|
| 32 |
+
counts[path.stem] = len(records)
|
| 33 |
+
|
| 34 |
+
return counts
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if __name__ == "__main__":
|
| 38 |
+
counts = convert_mixed_jsonl_to_records(
|
| 39 |
+
repo_dir="/home/hermes/fragrance-research/extracted",
|
| 40 |
+
output_dir="/home/hermes/pino/data/literature_flat",
|
| 41 |
+
)
|
| 42 |
+
print(counts)
|
scripts/hf_train_job.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Standalone training entrypoint for Hugging Face compute jobs.
|
| 3 |
+
|
| 4 |
+
This script is designed to run from inside the cloned pino-source repository.
|
| 5 |
+
It installs dependencies and starts training from the local source code.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import subprocess
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def install_deps() -> None:
|
| 15 |
+
"""Install runtime dependencies in the job container."""
|
| 16 |
+
subprocess.run(
|
| 17 |
+
[sys.executable, "-m", "pip", "install", "--quiet", "--upgrade"]
|
| 18 |
+
+ [
|
| 19 |
+
"rdkit",
|
| 20 |
+
"thermo",
|
| 21 |
+
"scipy",
|
| 22 |
+
"sentence-transformers",
|
| 23 |
+
"datasets",
|
| 24 |
+
"transformers>=4.41.0,<4.50.0",
|
| 25 |
+
"accelerate",
|
| 26 |
+
"huggingface-hub",
|
| 27 |
+
"tensorboard",
|
| 28 |
+
],
|
| 29 |
+
check=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main() -> int:
|
| 34 |
+
print("[pino-job] Installing dependencies...")
|
| 35 |
+
install_deps()
|
| 36 |
+
|
| 37 |
+
# This script is run from inside the cloned repo, e.g. /tmp/pino-source
|
| 38 |
+
source_dir = Path(__file__).resolve().parent
|
| 39 |
+
sys.path.insert(0, str(source_dir / "src"))
|
| 40 |
+
print(f"[pino-job] Using source directory: {source_dir}")
|
| 41 |
+
|
| 42 |
+
print("[pino-job] Starting training...")
|
| 43 |
+
from pino.train_hf import main as train_main
|
| 44 |
+
|
| 45 |
+
train_main()
|
| 46 |
+
return 0
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
from pathlib import Path
|
| 51 |
+
|
| 52 |
+
raise SystemExit(main())
|
scripts/pino_literature_dataset_builder.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import datasets as ds
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class PinoLiteratureDataset(ds.GeneratorBasedBuilder):
|
| 10 |
+
"""
|
| 11 |
+
Load the mixed-schema PINO literature corpus as separate splits.
|
| 12 |
+
Each record is wrapped as a single JSON string to avoid schema conflicts.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
VERSION = ds.Version("1.0.0")
|
| 16 |
+
|
| 17 |
+
def _info(self) -> ds.DatasetInfo:
|
| 18 |
+
return ds.DatasetInfo(
|
| 19 |
+
description="Mixed literature extracts for the PINO fragrance pipeline.",
|
| 20 |
+
features=ds.Features({"record": ds.Value("string")}),
|
| 21 |
+
homepage="https://huggingface.co/datasets/mattbitzesty/pino-literature-data",
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
def _split_generators(self, dl_manager):
|
| 25 |
+
data_dir = Path(dl_manager.download_and_extract(self.config.data_dir))
|
| 26 |
+
splits = []
|
| 27 |
+
for filename, split_name in [
|
| 28 |
+
("literature_pages.jsonl", "literature_pages"),
|
| 29 |
+
("arctander_monographs.jsonl", "arctander_monographs"),
|
| 30 |
+
("poucher_formulas.jsonl", "poucher_formulas"),
|
| 31 |
+
("literature_formulas_filtered.jsonl", "literature_formulas_filtered"),
|
| 32 |
+
]:
|
| 33 |
+
path = data_dir / filename
|
| 34 |
+
if path.exists():
|
| 35 |
+
splits.append(
|
| 36 |
+
ds.SplitGenerator(name=split_name, gen_kwargs={"path": str(path)})
|
| 37 |
+
)
|
| 38 |
+
return splits
|
| 39 |
+
|
| 40 |
+
def _generate_examples(self, path):
|
| 41 |
+
path = Path(path)
|
| 42 |
+
with path.open("r", encoding="utf-8") as f:
|
| 43 |
+
for i, line in enumerate(f):
|
| 44 |
+
record = json.loads(line)
|
| 45 |
+
yield f"{path.stem}_{i}", {"record": json.dumps(record, ensure_ascii=False)}
|
src/pino/pimt_model_hf.py
CHANGED
|
@@ -4,6 +4,7 @@ from typing import Optional, Tuple, Union
|
|
| 4 |
|
| 5 |
import torch
|
| 6 |
import torch.nn as nn
|
|
|
|
| 7 |
from transformers import PretrainedConfig, PreTrainedModel
|
| 8 |
from transformers.modeling_outputs import SequenceClassifierOutput
|
| 9 |
|
|
@@ -13,8 +14,6 @@ from .heads import PIMTHeads
|
|
| 13 |
class PIMTConfig(PretrainedConfig):
|
| 14 |
"""
|
| 15 |
Hugging Face PretrainedConfig for the Physics-Informed Mixture Transformer.
|
| 16 |
-
Defaults to returning tuples so the Trainer can capture both objective and
|
| 17 |
-
subjective head outputs for multi-task metric reporting.
|
| 18 |
"""
|
| 19 |
|
| 20 |
model_type = "pimt"
|
|
@@ -29,6 +28,7 @@ class PIMTConfig(PretrainedConfig):
|
|
| 29 |
dropout: float = 0.1,
|
| 30 |
max_ingredients: int = 32,
|
| 31 |
num_classes_sub: int = 7,
|
|
|
|
| 32 |
**kwargs,
|
| 33 |
) -> None:
|
| 34 |
self.embedding_dim = embedding_dim
|
|
@@ -39,6 +39,7 @@ class PIMTConfig(PretrainedConfig):
|
|
| 39 |
self.dropout = dropout
|
| 40 |
self.max_ingredients = max_ingredients
|
| 41 |
self.num_classes_sub = num_classes_sub
|
|
|
|
| 42 |
kwargs.setdefault("return_dict", True)
|
| 43 |
super().__init__(**kwargs)
|
| 44 |
|
|
@@ -46,8 +47,6 @@ class PIMTConfig(PretrainedConfig):
|
|
| 46 |
class PhysicsInformedGatingBlock(nn.Module):
|
| 47 |
"""
|
| 48 |
Modulate a static token embedding with a time-varying physical state vector.
|
| 49 |
-
No positional encoding is used, so the sequence is permutation-invariant
|
| 50 |
-
with respect to ingredient order.
|
| 51 |
"""
|
| 52 |
|
| 53 |
def __init__(self, embedding_dim: int, state_dim: int, hidden_dim: int = 64) -> None:
|
|
@@ -62,11 +61,6 @@ class PhysicsInformedGatingBlock(nn.Module):
|
|
| 62 |
)
|
| 63 |
|
| 64 |
def forward(self, tokens: torch.Tensor, states: torch.Tensor) -> torch.Tensor:
|
| 65 |
-
"""
|
| 66 |
-
tokens: (B, S, E)
|
| 67 |
-
states: (B, T, S, state_dim)
|
| 68 |
-
Returns: (B, T, S, E)
|
| 69 |
-
"""
|
| 70 |
b, seq_len, e = tokens.shape
|
| 71 |
t_steps = states.size(1)
|
| 72 |
tokens_t = tokens.unsqueeze(1).expand(b, t_steps, seq_len, e)
|
|
@@ -77,12 +71,9 @@ class PhysicsInformedGatingBlock(nn.Module):
|
|
| 77 |
|
| 78 |
class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
| 79 |
"""
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
Forward accepts keywords matching the dataset output: tokens, physics,
|
| 84 |
-
src_key_padding_mask, labels_obj, labels_sub. Returns a
|
| 85 |
-
SequenceClassifierOutput containing the pooled multi-task loss and logits.
|
| 86 |
"""
|
| 87 |
|
| 88 |
config_class = PIMTConfig
|
|
@@ -107,7 +98,12 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
|
| 107 |
batch_first=True,
|
| 108 |
)
|
| 109 |
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=config.num_layers)
|
| 110 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
self.post_init()
|
| 113 |
|
|
@@ -122,13 +118,12 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
|
| 122 |
weights = {"obj": 1.0, "sub": 0.5}
|
| 123 |
|
| 124 |
obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
|
| 125 |
-
obj_loss =
|
| 126 |
obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
|
| 127 |
|
| 128 |
-
# pred_sub is (B, 7), target_sub is (B, 7) or (B, T, 7); use mean over time if needed.
|
| 129 |
if target_sub.dim() == 3:
|
| 130 |
target_sub = target_sub.mean(dim=1)
|
| 131 |
-
sub_loss =
|
| 132 |
|
| 133 |
total = weights["obj"] * obj_loss + weights["sub"] * sub_loss
|
| 134 |
return total
|
|
@@ -138,6 +133,7 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
|
| 138 |
tokens: torch.Tensor,
|
| 139 |
physics: torch.Tensor,
|
| 140 |
src_key_padding_mask: Optional[torch.Tensor] = None,
|
|
|
|
| 141 |
labels: Optional[torch.Tensor] = None,
|
| 142 |
labels_obj: Optional[torch.Tensor] = None,
|
| 143 |
labels_sub: Optional[torch.Tensor] = None,
|
|
@@ -147,10 +143,8 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
|
| 147 |
tokens: (B, S, E)
|
| 148 |
physics: (B, T, S, state_dim)
|
| 149 |
src_key_padding_mask: (B, S) bool, True for padding positions.
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
labels_sub (last 7 dims) for multi-task loss.
|
| 153 |
-
labels_obj / labels_sub: explicit optional labels, used if labels is None.
|
| 154 |
"""
|
| 155 |
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 156 |
|
|
@@ -162,7 +156,6 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
|
| 162 |
b, t, s, e = gated.shape
|
| 163 |
x = self.input_proj(gated) # (B, T, S, H)
|
| 164 |
|
| 165 |
-
# Transformer expects (B, S, H); process each timestep independently.
|
| 166 |
x = x.reshape(b * t, s, self.hidden_dim)
|
| 167 |
if src_key_padding_mask is not None:
|
| 168 |
mask_bt = src_key_padding_mask.unsqueeze(1).expand(-1, t, -1).reshape(b * t, s)
|
|
@@ -171,12 +164,16 @@ class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
|
| 171 |
x = self.encoder(x)
|
| 172 |
x = x.reshape(b, t, s, self.hidden_dim)
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
logits = self.heads(x) # {"objective": (B, T, 138), "subjective": (B, 7)}
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
subjective_expanded = logits["subjective"].unsqueeze(1).expand(-1, t, -1) # (B, T, 7)
|
| 179 |
-
fused_logits = torch.cat([logits["objective"], subjective_expanded], dim=-1) # (B, T, 145)
|
| 180 |
|
| 181 |
loss = None
|
| 182 |
if labels_obj is not None and labels_sub is not None:
|
|
|
|
| 4 |
|
| 5 |
import torch
|
| 6 |
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 |
|
|
|
|
| 14 |
class PIMTConfig(PretrainedConfig):
|
| 15 |
"""
|
| 16 |
Hugging Face PretrainedConfig for the Physics-Informed Mixture Transformer.
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
|
| 19 |
model_type = "pimt"
|
|
|
|
| 28 |
dropout: float = 0.1,
|
| 29 |
max_ingredients: int = 32,
|
| 30 |
num_classes_sub: int = 7,
|
| 31 |
+
text_embedding_dim: int = 384,
|
| 32 |
**kwargs,
|
| 33 |
) -> None:
|
| 34 |
self.embedding_dim = embedding_dim
|
|
|
|
| 39 |
self.dropout = dropout
|
| 40 |
self.max_ingredients = max_ingredients
|
| 41 |
self.num_classes_sub = num_classes_sub
|
| 42 |
+
self.text_embedding_dim = text_embedding_dim
|
| 43 |
kwargs.setdefault("return_dict", True)
|
| 44 |
super().__init__(**kwargs)
|
| 45 |
|
|
|
|
| 47 |
class PhysicsInformedGatingBlock(nn.Module):
|
| 48 |
"""
|
| 49 |
Modulate a static token embedding with a time-varying physical state vector.
|
|
|
|
|
|
|
| 50 |
"""
|
| 51 |
|
| 52 |
def __init__(self, embedding_dim: int, state_dim: int, hidden_dim: int = 64) -> None:
|
|
|
|
| 61 |
)
|
| 62 |
|
| 63 |
def forward(self, tokens: torch.Tensor, states: torch.Tensor) -> torch.Tensor:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
b, seq_len, e = tokens.shape
|
| 65 |
t_steps = states.size(1)
|
| 66 |
tokens_t = tokens.unsqueeze(1).expand(b, t_steps, seq_len, e)
|
|
|
|
| 71 |
|
| 72 |
class PhysicsInformedMixtureTransformer(PreTrainedModel):
|
| 73 |
"""
|
| 74 |
+
Text-controllable, permutation-invariant transformer encoder for fragrance
|
| 75 |
+
dry-down trajectories. Accepts a 384-D sentence-transformer embedding to
|
| 76 |
+
gate the trajectory representation.
|
|
|
|
|
|
|
|
|
|
| 77 |
"""
|
| 78 |
|
| 79 |
config_class = PIMTConfig
|
|
|
|
| 98 |
batch_first=True,
|
| 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 |
+
self.heads = PIMTHeads(
|
| 103 |
+
hidden_dim=config.hidden_dim,
|
| 104 |
+
objective_dim=config.embedding_dim,
|
| 105 |
+
num_classes_sub=getattr(config, "num_classes_sub", 7),
|
| 106 |
+
)
|
| 107 |
|
| 108 |
self.post_init()
|
| 109 |
|
|
|
|
| 118 |
weights = {"obj": 1.0, "sub": 0.5}
|
| 119 |
|
| 120 |
obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
|
| 121 |
+
obj_loss = F.mse_loss(pred_obj, target_obj, reduction="none")
|
| 122 |
obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
|
| 123 |
|
|
|
|
| 124 |
if target_sub.dim() == 3:
|
| 125 |
target_sub = target_sub.mean(dim=1)
|
| 126 |
+
sub_loss = F.mse_loss(pred_sub, target_sub)
|
| 127 |
|
| 128 |
total = weights["obj"] * obj_loss + weights["sub"] * sub_loss
|
| 129 |
return total
|
|
|
|
| 133 |
tokens: torch.Tensor,
|
| 134 |
physics: torch.Tensor,
|
| 135 |
src_key_padding_mask: Optional[torch.Tensor] = None,
|
| 136 |
+
text_embedding: Optional[torch.Tensor] = None,
|
| 137 |
labels: Optional[torch.Tensor] = None,
|
| 138 |
labels_obj: Optional[torch.Tensor] = None,
|
| 139 |
labels_sub: Optional[torch.Tensor] = None,
|
|
|
|
| 143 |
tokens: (B, S, E)
|
| 144 |
physics: (B, T, S, state_dim)
|
| 145 |
src_key_padding_mask: (B, S) bool, True for padding positions.
|
| 146 |
+
text_embedding: (B, 384) sentence-transformer embedding for conditioning.
|
| 147 |
+
labels: fused (B, T, 145) tensor of objective + subjective labels.
|
|
|
|
|
|
|
| 148 |
"""
|
| 149 |
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 150 |
|
|
|
|
| 156 |
b, t, s, e = gated.shape
|
| 157 |
x = self.input_proj(gated) # (B, T, S, H)
|
| 158 |
|
|
|
|
| 159 |
x = x.reshape(b * t, s, self.hidden_dim)
|
| 160 |
if src_key_padding_mask is not None:
|
| 161 |
mask_bt = src_key_padding_mask.unsqueeze(1).expand(-1, t, -1).reshape(b * t, s)
|
|
|
|
| 164 |
x = self.encoder(x)
|
| 165 |
x = x.reshape(b, t, s, self.hidden_dim)
|
| 166 |
|
| 167 |
+
# Project text embedding and use it as a global conditioning gate.
|
| 168 |
+
if text_embedding is not None:
|
| 169 |
+
text_hidden = self.text_proj(text_embedding) # (B, H)
|
| 170 |
+
text_gate = F.sigmoid(text_hidden).view(b, 1, 1, self.hidden_dim) # (B, 1, 1, H)
|
| 171 |
+
x = x * text_gate
|
| 172 |
+
|
| 173 |
logits = self.heads(x) # {"objective": (B, T, 138), "subjective": (B, 7)}
|
| 174 |
|
| 175 |
+
subjective_expanded = logits["subjective"].unsqueeze(1).expand(-1, t, -1)
|
| 176 |
+
fused_logits = torch.cat([logits["objective"], subjective_expanded], dim=-1)
|
|
|
|
|
|
|
| 177 |
|
| 178 |
loss = None
|
| 179 |
if labels_obj is not None and labels_sub is not None:
|
src/pino/registry.py
CHANGED
|
@@ -6,8 +6,7 @@ import sqlite3
|
|
| 6 |
from pathlib import Path
|
| 7 |
from typing import Any
|
| 8 |
|
| 9 |
-
import
|
| 10 |
-
import ugropy
|
| 11 |
|
| 12 |
from . import unifac_mapping
|
| 13 |
from .models import IngredientResolutionError
|
|
@@ -247,6 +246,8 @@ class AromaRegistry:
|
|
| 247 |
def resolve_pubchem(identifier: str, identifier_type: str = "cas") -> dict[str, Any]:
|
| 248 |
"""Resolve a molecule to canonical name, SMILES, and MW via PubChem."""
|
| 249 |
try:
|
|
|
|
|
|
|
| 250 |
if identifier_type == "cas":
|
| 251 |
compounds = pcp.get_compounds(identifier, "name")
|
| 252 |
else:
|
|
@@ -286,6 +287,8 @@ class AromaRegistry:
|
|
| 286 |
"""Run ugropy and return thermo-compatible integer subgroup IDs."""
|
| 287 |
from thermo.unifac import DOUFSG
|
| 288 |
|
|
|
|
|
|
|
| 289 |
name_to_id = {str(v.group): k for k, v in DOUFSG.items()}
|
| 290 |
try:
|
| 291 |
groups_obj = ugropy.Groups(identifier, identifier_type=identifier_type)
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
from typing import Any
|
| 8 |
|
| 9 |
+
import numpy as np
|
|
|
|
| 10 |
|
| 11 |
from . import unifac_mapping
|
| 12 |
from .models import IngredientResolutionError
|
|
|
|
| 246 |
def resolve_pubchem(identifier: str, identifier_type: str = "cas") -> dict[str, Any]:
|
| 247 |
"""Resolve a molecule to canonical name, SMILES, and MW via PubChem."""
|
| 248 |
try:
|
| 249 |
+
import pubchempy as pcp
|
| 250 |
+
|
| 251 |
if identifier_type == "cas":
|
| 252 |
compounds = pcp.get_compounds(identifier, "name")
|
| 253 |
else:
|
|
|
|
| 287 |
"""Run ugropy and return thermo-compatible integer subgroup IDs."""
|
| 288 |
from thermo.unifac import DOUFSG
|
| 289 |
|
| 290 |
+
import ugropy
|
| 291 |
+
|
| 292 |
name_to_id = {str(v.group): k for k, v in DOUFSG.items()}
|
| 293 |
try:
|
| 294 |
groups_obj = ugropy.Groups(identifier, identifier_type=identifier_type)
|
src/pino/train_hf.py
CHANGED
|
@@ -4,13 +4,14 @@ import json
|
|
| 4 |
import logging
|
| 5 |
import os
|
| 6 |
import random
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Any
|
| 9 |
|
| 10 |
import numpy as np
|
| 11 |
import torch
|
| 12 |
-
import torch.nn.functional as F
|
| 13 |
from datasets import load_dataset
|
|
|
|
| 14 |
from transformers import Trainer, TrainingArguments
|
| 15 |
|
| 16 |
from pino.pimt_model import FragranceTrajectoryDataset
|
|
@@ -19,6 +20,16 @@ from pino.pimt_model_hf import PIMTConfig, PhysicsInformedMixtureTransformer
|
|
| 19 |
logger = logging.getLogger("pino.train_hf")
|
| 20 |
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
def seed_everything(seed: int = 42) -> None:
|
| 23 |
"""Lock all RNGs for fully reproducible training runs."""
|
| 24 |
random.seed(seed)
|
|
@@ -30,7 +41,7 @@ def seed_everything(seed: int = 42) -> None:
|
|
| 30 |
|
| 31 |
|
| 32 |
def pad_trajectory_collate(batch: list) -> dict:
|
| 33 |
-
"""Custom collate for variable-length ingredient formulations."""
|
| 34 |
max_molecules = max(item["tokens"].size(0) for item in batch)
|
| 35 |
max_timesteps = max(item["physics"].size(0) for item in batch)
|
| 36 |
bsz = len(batch)
|
|
@@ -41,6 +52,12 @@ def pad_trajectory_collate(batch: list) -> dict:
|
|
| 41 |
labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
| 42 |
labels_sub = torch.zeros(bsz, 7, dtype=torch.float32)
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
for i, item in enumerate(batch):
|
| 45 |
n_mol = item["tokens"].size(0)
|
| 46 |
t_steps = item["physics"].size(0)
|
|
@@ -50,6 +67,14 @@ def pad_trajectory_collate(batch: list) -> dict:
|
|
| 50 |
labels_obj[i, :t_steps] = item["target_obj"]
|
| 51 |
labels_sub[i] = item["target_sub"]
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
# Fuse objective and subjective labels into a single (B, T, 145) tensor for HF Trainer.
|
| 54 |
labels_sub_t = labels_sub.unsqueeze(1).expand(-1, max_timesteps, -1)
|
| 55 |
labels = torch.cat([labels_obj, labels_sub_t], dim=-1)
|
|
@@ -58,6 +83,7 @@ def pad_trajectory_collate(batch: list) -> dict:
|
|
| 58 |
"tokens": tokens,
|
| 59 |
"physics": physics,
|
| 60 |
"src_key_padding_mask": src_key_padding_mask,
|
|
|
|
| 61 |
"labels": labels,
|
| 62 |
}
|
| 63 |
|
|
@@ -127,6 +153,12 @@ def run_training() -> None:
|
|
| 127 |
|
| 128 |
|
| 129 |
def main() -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
logging.basicConfig(
|
| 131 |
level=logging.INFO,
|
| 132 |
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
|
@@ -158,7 +190,6 @@ def main() -> None:
|
|
| 158 |
|
| 159 |
training_args = TrainingArguments(
|
| 160 |
output_dir="./models/pino_publication_run",
|
| 161 |
-
overwrite_output_dir=True,
|
| 162 |
do_train=True,
|
| 163 |
do_eval=True,
|
| 164 |
evaluation_strategy="epoch",
|
|
|
|
| 4 |
import logging
|
| 5 |
import os
|
| 6 |
import random
|
| 7 |
+
import torch.multiprocessing as mp
|
| 8 |
from pathlib import Path
|
| 9 |
from typing import Any
|
| 10 |
|
| 11 |
import numpy as np
|
| 12 |
import torch
|
|
|
|
| 13 |
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
|
|
|
|
| 20 |
logger = logging.getLogger("pino.train_hf")
|
| 21 |
|
| 22 |
|
| 23 |
+
_TEXT_ENCODER: SentenceTransformer | None = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_text_encoder() -> SentenceTransformer:
|
| 27 |
+
global _TEXT_ENCODER
|
| 28 |
+
if _TEXT_ENCODER is None:
|
| 29 |
+
_TEXT_ENCODER = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 30 |
+
return _TEXT_ENCODER
|
| 31 |
+
|
| 32 |
+
|
| 33 |
def seed_everything(seed: int = 42) -> None:
|
| 34 |
"""Lock all RNGs for fully reproducible training runs."""
|
| 35 |
random.seed(seed)
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
def pad_trajectory_collate(batch: list) -> dict:
|
| 44 |
+
"""Custom collate for variable-length ingredient formulations with text conditioning."""
|
| 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)
|
|
|
|
| 52 |
labels_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
| 53 |
labels_sub = torch.zeros(bsz, 7, dtype=torch.float32)
|
| 54 |
|
| 55 |
+
# Encode text on-the-fly using sentence-transformers only if a record is missing
|
| 56 |
+
# its pre-computed embedding. This avoids loading the encoder inside forked
|
| 57 |
+
# dataloader workers (which can fail on CUDA re-init).
|
| 58 |
+
text_encoder = None
|
| 59 |
+
text_embeddings = torch.zeros(bsz, 384, dtype=torch.float32)
|
| 60 |
+
|
| 61 |
for i, item in enumerate(batch):
|
| 62 |
n_mol = item["tokens"].size(0)
|
| 63 |
t_steps = item["physics"].size(0)
|
|
|
|
| 67 |
labels_obj[i, :t_steps] = item["target_obj"]
|
| 68 |
labels_sub[i] = item["target_sub"]
|
| 69 |
|
| 70 |
+
if "text_embedding" in item:
|
| 71 |
+
text_embeddings[i] = item["text_embedding"].clone().detach().float() if torch.is_tensor(item["text_embedding"]) else torch.tensor(item["text_embedding"], dtype=torch.float32)
|
| 72 |
+
elif "text_conditioning" in item:
|
| 73 |
+
if text_encoder is None:
|
| 74 |
+
text_encoder = get_text_encoder()
|
| 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, 145) tensor for HF Trainer.
|
| 79 |
labels_sub_t = labels_sub.unsqueeze(1).expand(-1, max_timesteps, -1)
|
| 80 |
labels = torch.cat([labels_obj, labels_sub_t], dim=-1)
|
|
|
|
| 83 |
"tokens": tokens,
|
| 84 |
"physics": physics,
|
| 85 |
"src_key_padding_mask": src_key_padding_mask,
|
| 86 |
+
"text_embedding": text_embeddings,
|
| 87 |
"labels": labels,
|
| 88 |
}
|
| 89 |
|
|
|
|
| 153 |
|
| 154 |
|
| 155 |
def main() -> None:
|
| 156 |
+
# Use spawn for dataloader workers so CUDA is safe with multiprocessing.
|
| 157 |
+
try:
|
| 158 |
+
mp.set_start_method("spawn", force=True)
|
| 159 |
+
except Exception:
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
logging.basicConfig(
|
| 163 |
level=logging.INFO,
|
| 164 |
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
|
|
|
| 190 |
|
| 191 |
training_args = TrainingArguments(
|
| 192 |
output_dir="./models/pino_publication_run",
|
|
|
|
| 193 |
do_train=True,
|
| 194 |
do_eval=True,
|
| 195 |
evaluation_strategy="epoch",
|