feat(train,upload): multi-task training with InfoNCE and molecule-disjoint upload
Browse filestrain.py: add InfoNCE contrastive loss on genre labels, set state_dim=2,
decompose subjective targets, log all loss components.
upload_data.py: replace random stratified split with molecule-disjoint
partition; hold out compounds, not records.
- src/pino/train.py +76 -22
- src/pino/upload_data.py +141 -24
src/pino/train.py
CHANGED
|
@@ -9,6 +9,7 @@ from typing import Any
|
|
| 9 |
import numpy as np
|
| 10 |
import torch
|
| 11 |
import torch.nn as nn
|
|
|
|
| 12 |
import torch.optim as optim
|
| 13 |
from torch.utils.data import DataLoader, random_split
|
| 14 |
from torch.utils.tensorboard import SummaryWriter
|
|
@@ -43,12 +44,13 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 43 |
bsz = len(batch)
|
| 44 |
|
| 45 |
tokens = torch.zeros(bsz, max_molecules, 138, dtype=torch.float32)
|
| 46 |
-
physics = torch.zeros(bsz, max_timesteps, max_molecules,
|
| 47 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 48 |
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
| 49 |
target_sub_seasonality = torch.zeros(bsz, 4, dtype=torch.float32)
|
| 50 |
target_sub_gender = torch.zeros(bsz, dtype=torch.float32)
|
| 51 |
-
target_sub_wearability = torch.zeros(bsz,
|
|
|
|
| 52 |
|
| 53 |
for i, item in enumerate(batch):
|
| 54 |
n_mol = item["tokens"].size(0)
|
|
@@ -58,9 +60,10 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 58 |
src_key_padding_mask[i, :n_mol] = False
|
| 59 |
target_obj[i, :t_steps] = item["target_obj"]
|
| 60 |
sub = item["target_sub"]
|
| 61 |
-
target_sub_seasonality[i] = sub[
|
| 62 |
-
target_sub_gender[i] = sub[
|
| 63 |
-
target_sub_wearability[i] = sub[
|
|
|
|
| 64 |
|
| 65 |
return {
|
| 66 |
"tokens": tokens,
|
|
@@ -70,6 +73,7 @@ def pad_trajectory_collate(batch: list[dict[str, Any]]) -> dict[str, Any]:
|
|
| 70 |
"target_sub_seasonality": target_sub_seasonality,
|
| 71 |
"target_sub_gender": target_sub_gender,
|
| 72 |
"target_sub_wearability": target_sub_wearability,
|
|
|
|
| 73 |
}
|
| 74 |
|
| 75 |
|
|
@@ -78,39 +82,78 @@ def multitask_loss(
|
|
| 78 |
target_obj: torch.Tensor,
|
| 79 |
pred_sub: dict[str, torch.Tensor],
|
| 80 |
target_sub: dict[str, torch.Tensor],
|
|
|
|
|
|
|
| 81 |
weights: dict[str, float] | None = None,
|
|
|
|
| 82 |
) -> tuple[torch.Tensor, dict[str, float]]:
|
| 83 |
"""
|
| 84 |
Weighted multi-task loss: MSE for objective trajectory + cross-entropy for
|
| 85 |
-
seasonality + MSE for gender + BCE for multi-label wearability
|
|
|
|
| 86 |
"""
|
| 87 |
-
weights = weights or {"obj": 1.0, "season": 0.5, "gender": 0.25, "wear": 0.25}
|
| 88 |
|
| 89 |
# Objective MSE with padding mask over time.
|
| 90 |
obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
|
| 91 |
obj_loss = nn.functional.mse_loss(pred_obj, target_obj, reduction="none")
|
| 92 |
obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
|
| 93 |
|
| 94 |
-
season_loss = nn.functional.cross_entropy(pred_sub["seasonality"], target_sub["seasonality"])
|
| 95 |
-
gender_loss = nn.functional.mse_loss(pred_sub["gender_profile"], target_sub["gender_profile"])
|
| 96 |
wear_loss = nn.functional.binary_cross_entropy_with_logits(pred_sub["wearability"], target_sub["wearability"])
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
total = (
|
| 99 |
weights["obj"] * obj_loss
|
| 100 |
+ weights["season"] * season_loss
|
| 101 |
+ weights["gender"] * gender_loss
|
| 102 |
+ weights["wear"] * wear_loss
|
|
|
|
| 103 |
)
|
| 104 |
components = {
|
| 105 |
"obj": obj_loss.item(),
|
| 106 |
"season": season_loss.item(),
|
| 107 |
"gender": gender_loss.item(),
|
| 108 |
"wear": wear_loss.item(),
|
|
|
|
| 109 |
"total": total.item(),
|
| 110 |
}
|
| 111 |
return total, components
|
| 112 |
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
def train_epoch(
|
| 115 |
model: nn.Module,
|
| 116 |
heads: nn.Module,
|
|
@@ -123,7 +166,7 @@ def train_epoch(
|
|
| 123 |
model.train()
|
| 124 |
heads.train()
|
| 125 |
total_loss = 0.0
|
| 126 |
-
totals = {"obj": 0.0, "season": 0.0, "gender": 0.0, "wear": 0.0}
|
| 127 |
count = 0
|
| 128 |
|
| 129 |
for batch_idx, batch in enumerate(loader, start=1):
|
|
@@ -138,10 +181,14 @@ def train_epoch(
|
|
| 138 |
"gender_profile": batch["target_sub_gender"].to(device),
|
| 139 |
"wearability": batch["target_sub_wearability"].to(device),
|
| 140 |
}
|
|
|
|
| 141 |
optimizer.zero_grad()
|
| 142 |
latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
|
| 143 |
pred = heads(latent)
|
| 144 |
-
loss, comps = multitask_loss(
|
|
|
|
|
|
|
|
|
|
| 145 |
loss.backward()
|
| 146 |
torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(heads.parameters()), 1.0)
|
| 147 |
optimizer.step()
|
|
@@ -151,8 +198,8 @@ def train_epoch(
|
|
| 151 |
totals[k] += comps[k]
|
| 152 |
count += 1
|
| 153 |
logger.info(
|
| 154 |
-
"Batch %d | total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f",
|
| 155 |
-
batch_idx, comps["total"], comps["obj"], comps["season"], comps["gender"], comps["wear"],
|
| 156 |
)
|
| 157 |
|
| 158 |
return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
|
|
@@ -169,7 +216,7 @@ def validate(
|
|
| 169 |
model.eval()
|
| 170 |
heads.eval()
|
| 171 |
total_loss = 0.0
|
| 172 |
-
totals = {"obj": 0.0, "season": 0.0, "gender": 0.0, "wear": 0.0}
|
| 173 |
count = 0
|
| 174 |
|
| 175 |
for batch in loader:
|
|
@@ -182,9 +229,13 @@ def validate(
|
|
| 182 |
"gender_profile": batch["target_sub_gender"].to(device),
|
| 183 |
"wearability": batch["target_sub_wearability"].to(device),
|
| 184 |
}
|
|
|
|
| 185 |
latent = model(tokens, physics, src_key_padding_mask)
|
| 186 |
pred = heads(latent)
|
| 187 |
-
loss, comps = multitask_loss(
|
|
|
|
|
|
|
|
|
|
| 188 |
total_loss += comps["total"]
|
| 189 |
for k in totals:
|
| 190 |
totals[k] += comps[k]
|
|
@@ -235,7 +286,10 @@ def main():
|
|
| 235 |
}
|
| 236 |
logger.info("Configuration: %s", cfg)
|
| 237 |
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
| 239 |
total = len(dataset)
|
| 240 |
train_len = int(0.8 * total)
|
| 241 |
val_len = int(0.1 * total)
|
|
@@ -257,7 +311,7 @@ def main():
|
|
| 257 |
|
| 258 |
model = PhysicsInformedMixtureTransformer(
|
| 259 |
embedding_dim=138,
|
| 260 |
-
state_dim=
|
| 261 |
hidden_dim=cfg["hidden_dim"],
|
| 262 |
num_heads=cfg["num_heads"],
|
| 263 |
num_layers=cfg["num_layers"],
|
|
@@ -268,7 +322,7 @@ def main():
|
|
| 268 |
optimizer = optim.AdamW(params, lr=cfg["lr"], weight_decay=cfg["weight_decay"])
|
| 269 |
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
|
| 270 |
|
| 271 |
-
weights = {"obj": 1.0, "season": 0.5, "gender": 0.25, "wear": 0.25}
|
| 272 |
|
| 273 |
writer = SummaryWriter(log_dir=args.log_dir)
|
| 274 |
output_dir = Path(args.output_dir)
|
|
@@ -286,9 +340,9 @@ def main():
|
|
| 286 |
writer.add_scalar(f"{split}/{k}", v, epoch)
|
| 287 |
|
| 288 |
logger.info(
|
| 289 |
-
"Epoch %d/%d | train_total=%.4f | val_total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f",
|
| 290 |
epoch, args.epochs, train_metrics["total"], val_metrics["total"],
|
| 291 |
-
val_metrics["obj"], val_metrics["season"], val_metrics["gender"], val_metrics["wear"],
|
| 292 |
)
|
| 293 |
|
| 294 |
if val_metrics["total"] < best_val:
|
|
@@ -304,8 +358,8 @@ def main():
|
|
| 304 |
|
| 305 |
test_metrics = validate(model, heads, test_loader, device, weights)
|
| 306 |
logger.info(
|
| 307 |
-
"Test | total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f",
|
| 308 |
-
test_metrics["total"], test_metrics["obj"], test_metrics["season"], test_metrics["gender"], test_metrics["wear"],
|
| 309 |
)
|
| 310 |
writer.close()
|
| 311 |
return checkpoint_path
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
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, random_split
|
| 15 |
from torch.utils.tensorboard import SummaryWriter
|
|
|
|
| 44 |
bsz = len(batch)
|
| 45 |
|
| 46 |
tokens = torch.zeros(bsz, max_molecules, 138, dtype=torch.float32)
|
| 47 |
+
physics = torch.zeros(bsz, max_timesteps, max_molecules, 2, dtype=torch.float32)
|
| 48 |
src_key_padding_mask = torch.ones(bsz, max_molecules, dtype=torch.bool)
|
| 49 |
target_obj = torch.zeros(bsz, max_timesteps, 138, dtype=torch.float32)
|
| 50 |
target_sub_seasonality = torch.zeros(bsz, 4, dtype=torch.float32)
|
| 51 |
target_sub_gender = torch.zeros(bsz, dtype=torch.float32)
|
| 52 |
+
target_sub_wearability = torch.zeros(bsz, 2, dtype=torch.float32)
|
| 53 |
+
genre_labels = torch.zeros(bsz, dtype=torch.int64)
|
| 54 |
|
| 55 |
for i, item in enumerate(batch):
|
| 56 |
n_mol = item["tokens"].size(0)
|
|
|
|
| 60 |
src_key_padding_mask[i, :n_mol] = False
|
| 61 |
target_obj[i, :t_steps] = item["target_obj"]
|
| 62 |
sub = item["target_sub"]
|
| 63 |
+
target_sub_seasonality[i] = sub[[0,1,2,3]]
|
| 64 |
+
target_sub_gender[i] = sub[4]
|
| 65 |
+
target_sub_wearability[i] = sub[[5,6]]
|
| 66 |
+
genre_labels[i] = item.get("genre_label", 0)
|
| 67 |
|
| 68 |
return {
|
| 69 |
"tokens": tokens,
|
|
|
|
| 73 |
"target_sub_seasonality": target_sub_seasonality,
|
| 74 |
"target_sub_gender": target_sub_gender,
|
| 75 |
"target_sub_wearability": target_sub_wearability,
|
| 76 |
+
"genre_label": genre_labels,
|
| 77 |
}
|
| 78 |
|
| 79 |
|
|
|
|
| 82 |
target_obj: torch.Tensor,
|
| 83 |
pred_sub: dict[str, torch.Tensor],
|
| 84 |
target_sub: dict[str, torch.Tensor],
|
| 85 |
+
z: torch.Tensor,
|
| 86 |
+
labels_genre: torch.Tensor,
|
| 87 |
weights: dict[str, float] | None = None,
|
| 88 |
+
temperature: float = 0.1,
|
| 89 |
) -> tuple[torch.Tensor, dict[str, float]]:
|
| 90 |
"""
|
| 91 |
Weighted multi-task loss: MSE for objective trajectory + cross-entropy for
|
| 92 |
+
seasonality + MSE for gender + BCE for multi-label wearability + InfoNCE
|
| 93 |
+
contrastive loss on the latent projection.
|
| 94 |
"""
|
| 95 |
+
weights = weights or {"obj": 1.0, "season": 0.5, "gender": 0.25, "wear": 0.25, "contrastive": 0.5}
|
| 96 |
|
| 97 |
# Objective MSE with padding mask over time.
|
| 98 |
obj_mask = (target_obj.sum(dim=-1) > 0).float().unsqueeze(-1)
|
| 99 |
obj_loss = nn.functional.mse_loss(pred_obj, target_obj, reduction="none")
|
| 100 |
obj_loss = (obj_loss * obj_mask).sum() / obj_mask.sum().clamp_min(1.0)
|
| 101 |
|
| 102 |
+
season_loss = nn.functional.cross_entropy(pred_sub["seasonality"], target_sub["seasonality"].argmax(dim=-1))
|
| 103 |
+
gender_loss = nn.functional.mse_loss(pred_sub["gender_profile"].squeeze(-1), target_sub["gender_profile"])
|
| 104 |
wear_loss = nn.functional.binary_cross_entropy_with_logits(pred_sub["wearability"], target_sub["wearability"])
|
| 105 |
|
| 106 |
+
# InfoNCE contrastive loss: maximize cosine similarity between samples with
|
| 107 |
+
# the same human olfactory tag (genre) and minimize it for different tags.
|
| 108 |
+
contrastive_loss = info_nce_loss(z, labels_genre, temperature=temperature)
|
| 109 |
+
|
| 110 |
total = (
|
| 111 |
weights["obj"] * obj_loss
|
| 112 |
+ weights["season"] * season_loss
|
| 113 |
+ weights["gender"] * gender_loss
|
| 114 |
+ weights["wear"] * wear_loss
|
| 115 |
+
+ weights["contrastive"] * contrastive_loss
|
| 116 |
)
|
| 117 |
components = {
|
| 118 |
"obj": obj_loss.item(),
|
| 119 |
"season": season_loss.item(),
|
| 120 |
"gender": gender_loss.item(),
|
| 121 |
"wear": wear_loss.item(),
|
| 122 |
+
"contrastive": contrastive_loss.item(),
|
| 123 |
"total": total.item(),
|
| 124 |
}
|
| 125 |
return total, components
|
| 126 |
|
| 127 |
|
| 128 |
+
def info_nce_loss(z: torch.Tensor, labels: torch.Tensor, temperature: float = 0.1) -> torch.Tensor:
|
| 129 |
+
"""
|
| 130 |
+
InfoNCE loss over L2-normalized embeddings using genre labels as positives.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
z: (B, D) L2-normalized embeddings.
|
| 134 |
+
labels: (B,) integer genre labels.
|
| 135 |
+
temperature: softmax temperature.
|
| 136 |
+
Returns:
|
| 137 |
+
Scalar InfoNCE loss.
|
| 138 |
+
"""
|
| 139 |
+
similarity = torch.matmul(z, z.T) / temperature # (B, B)
|
| 140 |
+
labels = labels.view(-1, 1)
|
| 141 |
+
mask_positive = (labels == labels.T).float() # (B, B)
|
| 142 |
+
# Remove self-similarity from positives.
|
| 143 |
+
logits_mask = torch.ones_like(mask_positive)
|
| 144 |
+
logits_mask.fill_diagonal_(0)
|
| 145 |
+
mask_positive = mask_positive * logits_mask
|
| 146 |
+
|
| 147 |
+
# For each anchor, denominator is over all negatives + positives except self.
|
| 148 |
+
exp_logits = torch.exp(similarity) * logits_mask
|
| 149 |
+
log_prob = similarity - torch.log(exp_logits.sum(1, keepdim=True) + 1e-12)
|
| 150 |
+
|
| 151 |
+
# Mean log-prob over positive pairs.
|
| 152 |
+
mean_log_prob_pos = (mask_positive * log_prob).sum(1) / mask_positive.sum(1).clamp_min(1.0)
|
| 153 |
+
loss = -mean_log_prob_pos.mean()
|
| 154 |
+
return loss
|
| 155 |
+
|
| 156 |
+
|
| 157 |
def train_epoch(
|
| 158 |
model: nn.Module,
|
| 159 |
heads: nn.Module,
|
|
|
|
| 166 |
model.train()
|
| 167 |
heads.train()
|
| 168 |
total_loss = 0.0
|
| 169 |
+
totals = {"obj": 0.0, "season": 0.0, "gender": 0.0, "wear": 0.0, "contrastive": 0.0}
|
| 170 |
count = 0
|
| 171 |
|
| 172 |
for batch_idx, batch in enumerate(loader, start=1):
|
|
|
|
| 181 |
"gender_profile": batch["target_sub_gender"].to(device),
|
| 182 |
"wearability": batch["target_sub_wearability"].to(device),
|
| 183 |
}
|
| 184 |
+
labels_genre = batch["genre_label"].to(device)
|
| 185 |
optimizer.zero_grad()
|
| 186 |
latent = model(tokens, physics, src_key_padding_mask) # (B, T, S, H)
|
| 187 |
pred = heads(latent)
|
| 188 |
+
loss, comps = multitask_loss(
|
| 189 |
+
pred["objective"], target_obj, pred["subjective"], target_sub,
|
| 190 |
+
pred["contrastive"], labels_genre, weights,
|
| 191 |
+
)
|
| 192 |
loss.backward()
|
| 193 |
torch.nn.utils.clip_grad_norm_(list(model.parameters()) + list(heads.parameters()), 1.0)
|
| 194 |
optimizer.step()
|
|
|
|
| 198 |
totals[k] += comps[k]
|
| 199 |
count += 1
|
| 200 |
logger.info(
|
| 201 |
+
"Batch %d | total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f | contrastive=%.4f",
|
| 202 |
+
batch_idx, comps["total"], comps["obj"], comps["season"], comps["gender"], comps["wear"], comps["contrastive"],
|
| 203 |
)
|
| 204 |
|
| 205 |
return {k: v / max(count, 1) for k, v in {**totals, "total": total_loss}.items()}
|
|
|
|
| 216 |
model.eval()
|
| 217 |
heads.eval()
|
| 218 |
total_loss = 0.0
|
| 219 |
+
totals = {"obj": 0.0, "season": 0.0, "gender": 0.0, "wear": 0.0, "contrastive": 0.0}
|
| 220 |
count = 0
|
| 221 |
|
| 222 |
for batch in loader:
|
|
|
|
| 229 |
"gender_profile": batch["target_sub_gender"].to(device),
|
| 230 |
"wearability": batch["target_sub_wearability"].to(device),
|
| 231 |
}
|
| 232 |
+
labels_genre = batch["genre_label"].to(device)
|
| 233 |
latent = model(tokens, physics, src_key_padding_mask)
|
| 234 |
pred = heads(latent)
|
| 235 |
+
loss, comps = multitask_loss(
|
| 236 |
+
pred["objective"], target_obj, pred["subjective"], target_sub,
|
| 237 |
+
pred["contrastive"], labels_genre, weights,
|
| 238 |
+
)
|
| 239 |
total_loss += comps["total"]
|
| 240 |
for k in totals:
|
| 241 |
totals[k] += comps[k]
|
|
|
|
| 286 |
}
|
| 287 |
logger.info("Configuration: %s", cfg)
|
| 288 |
|
| 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 |
+
dataset = FragranceTrajectoryDataset(data_path=args.data, use_embedding_fallback=True, genre_map=genre_map)
|
| 293 |
total = len(dataset)
|
| 294 |
train_len = int(0.8 * total)
|
| 295 |
val_len = int(0.1 * total)
|
|
|
|
| 311 |
|
| 312 |
model = PhysicsInformedMixtureTransformer(
|
| 313 |
embedding_dim=138,
|
| 314 |
+
state_dim=2,
|
| 315 |
hidden_dim=cfg["hidden_dim"],
|
| 316 |
num_heads=cfg["num_heads"],
|
| 317 |
num_layers=cfg["num_layers"],
|
|
|
|
| 322 |
optimizer = optim.AdamW(params, lr=cfg["lr"], weight_decay=cfg["weight_decay"])
|
| 323 |
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
|
| 324 |
|
| 325 |
+
weights = {"obj": 1.0, "season": 0.5, "gender": 0.25, "wear": 0.25, "contrastive": 0.5}
|
| 326 |
|
| 327 |
writer = SummaryWriter(log_dir=args.log_dir)
|
| 328 |
output_dir = Path(args.output_dir)
|
|
|
|
| 340 |
writer.add_scalar(f"{split}/{k}", v, epoch)
|
| 341 |
|
| 342 |
logger.info(
|
| 343 |
+
"Epoch %d/%d | train_total=%.4f | val_total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f | contrastive=%.4f",
|
| 344 |
epoch, args.epochs, train_metrics["total"], val_metrics["total"],
|
| 345 |
+
val_metrics["obj"], val_metrics["season"], val_metrics["gender"], val_metrics["wear"], val_metrics["contrastive"],
|
| 346 |
)
|
| 347 |
|
| 348 |
if val_metrics["total"] < best_val:
|
|
|
|
| 358 |
|
| 359 |
test_metrics = validate(model, heads, test_loader, device, weights)
|
| 360 |
logger.info(
|
| 361 |
+
"Test | total=%.4f | obj=%.4f | season=%.4f | gender=%.4f | wear=%.4f | contrastive=%.4f",
|
| 362 |
+
test_metrics["total"], test_metrics["obj"], test_metrics["season"], test_metrics["gender"], test_metrics["wear"], test_metrics["contrastive"],
|
| 363 |
)
|
| 364 |
writer.close()
|
| 365 |
return checkpoint_path
|
src/pino/upload_data.py
CHANGED
|
@@ -1,45 +1,162 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
|
|
|
|
|
|
| 4 |
|
| 5 |
from datasets import ClassLabel, DatasetDict, load_dataset
|
| 6 |
|
|
|
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"""
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
| 13 |
"""
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
)
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
print(f"Train rows: {len(dataset_dict['train'])} | Validation rows: {len(dataset_dict['validation'])}")
|
|
|
|
|
|
|
| 34 |
|
| 35 |
token = os.environ.get("HF_TOKEN")
|
| 36 |
-
print(f"Uploading
|
| 37 |
dataset_dict.push_to_hub(repo_id, private=True, token=token)
|
| 38 |
-
print("Dataset sync complete. Training partitions are fully live.")
|
| 39 |
|
| 40 |
|
| 41 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
split_and_upload_dataset(
|
| 43 |
-
jsonl_path=
|
| 44 |
-
repo_id=
|
|
|
|
|
|
|
|
|
|
| 45 |
)
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
|
| 10 |
from datasets import ClassLabel, DatasetDict, load_dataset
|
| 11 |
|
| 12 |
+
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 record.get("formula", [])
|
| 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,
|
| 28 |
+
seed: int = 42,
|
| 29 |
+
solvent_cas: str = "64-17-5",
|
| 30 |
+
) -> dict[str, Any]:
|
| 31 |
"""
|
| 32 |
+
Partition a JSON-L formulation corpus into molecule-disjoint train/validation sets.
|
| 33 |
+
|
| 34 |
+
A held-out subset of individual active compounds is selected from the registry.
|
| 35 |
+
Validation records are required to contain *only* held-out compounds; training
|
| 36 |
+
records must contain *no* held-out compounds. The solvent (e.g. ethanol) is
|
| 37 |
+
ignored because it is present in every formula.
|
| 38 |
"""
|
| 39 |
+
jsonl_path = Path(jsonl_path)
|
| 40 |
+
logger.info("Loading raw corpus from %s", jsonl_path)
|
| 41 |
+
raw_dataset = load_dataset("json", data_files=str(jsonl_path), split="train")
|
| 42 |
+
|
| 43 |
+
# Build per-record active compound sets and collect the universe of actives.
|
| 44 |
+
all_records = list(raw_dataset)
|
| 45 |
+
record_cas_sets = [_active_cas_set(rec, solvent_cas) for rec in all_records]
|
| 46 |
+
active_universe = sorted({cas for cas_set in record_cas_sets for cas in cas_set})
|
| 47 |
+
logger.info("Found %d unique active compounds across %d records", len(active_universe), len(all_records))
|
| 48 |
+
|
| 49 |
+
# Deterministic hold-out of individual molecules.
|
| 50 |
+
rng = sorted(active_universe)
|
| 51 |
+
import random
|
| 52 |
+
|
| 53 |
+
random.seed(seed)
|
| 54 |
+
random.shuffle(rng)
|
| 55 |
+
n_holdout = max(1, int(len(active_universe) * val_ratio))
|
| 56 |
+
held_out = set(rng[:n_holdout])
|
| 57 |
+
train_allowed = set(rng[n_holdout:])
|
| 58 |
+
logger.info(
|
| 59 |
+
"Held out %d/%d compounds for validation (%.1f%%)",
|
| 60 |
+
len(held_out),
|
| 61 |
+
len(active_universe),
|
| 62 |
+
100 * len(held_out) / len(active_universe),
|
| 63 |
)
|
| 64 |
|
| 65 |
+
train_indices = []
|
| 66 |
+
val_indices = []
|
| 67 |
+
for idx, cas_set in enumerate(record_cas_sets):
|
| 68 |
+
if not cas_set:
|
| 69 |
+
continue # skip degenerate records
|
| 70 |
+
if cas_set.issubset(held_out):
|
| 71 |
+
val_indices.append(idx)
|
| 72 |
+
elif cas_set.isdisjoint(held_out):
|
| 73 |
+
train_indices.append(idx)
|
| 74 |
+
else:
|
| 75 |
+
# Record mixes held-out and seen compounds; exclude to keep split strict.
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
logger.info(
|
| 79 |
+
"Split complete: %d train records | %d validation records | %d excluded",
|
| 80 |
+
len(train_indices),
|
| 81 |
+
len(val_indices),
|
| 82 |
+
len(all_records) - len(train_indices) - len(val_indices),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# Verify disjointness.
|
| 86 |
+
train_cas = {cas for idx in train_indices for cas in record_cas_sets[idx]}
|
| 87 |
+
val_cas = {cas for idx in val_indices for cas in record_cas_sets[idx]}
|
| 88 |
+
overlap = train_cas & val_cas
|
| 89 |
+
if overlap:
|
| 90 |
+
raise RuntimeError(f"Molecule leakage detected: {len(overlap)} compounds appear in both splits")
|
| 91 |
+
if val_cas - held_out:
|
| 92 |
+
raise RuntimeError("Validation set contains compounds not in the held-out set")
|
| 93 |
+
if held_out - (train_cas | val_cas):
|
| 94 |
+
logger.warning(
|
| 95 |
+
"%d held-out compounds never appear in any record; split is still valid but coverage is incomplete",
|
| 96 |
+
len(held_out - (train_cas | val_cas)),
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
logger.info("Validation split uses %d unique compounds, all held out from training", len(val_cas))
|
| 100 |
+
logger.info("Active compound overlap between train and validation: 0%%")
|
| 101 |
+
|
| 102 |
+
return {
|
| 103 |
+
"train": raw_dataset.select(train_indices),
|
| 104 |
+
"validation": raw_dataset.select(val_indices),
|
| 105 |
+
"held_out_compounds": sorted(held_out),
|
| 106 |
+
"train_compounds": sorted(train_cas),
|
| 107 |
+
"validation_compounds": sorted(val_cas),
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def split_and_upload_dataset(
|
| 112 |
+
jsonl_path: str,
|
| 113 |
+
repo_id: str,
|
| 114 |
+
val_ratio: float = 0.2,
|
| 115 |
+
seed: int = 42,
|
| 116 |
+
solvent_cas: str = "64-17-5",
|
| 117 |
+
) -> None:
|
| 118 |
+
"""
|
| 119 |
+
Load a production JSON-L corpus, enforce a molecule-disjoint train/validation
|
| 120 |
+
split, and push the resulting DatasetDict to the Hugging Face Hub.
|
| 121 |
+
"""
|
| 122 |
+
split = molecule_disjoint_split(jsonl_path, val_ratio=val_ratio, seed=seed, solvent_cas=solvent_cas)
|
| 123 |
+
|
| 124 |
+
# Cast genre to ClassLabel for downstream stratification / metrics.
|
| 125 |
+
genres = sorted({rec["genre"] for rec in split["train"] + split["validation"]})
|
| 126 |
+
for key in ("train", "validation"):
|
| 127 |
+
split[key] = split[key].cast_column("genre", ClassLabel(names=genres))
|
| 128 |
+
|
| 129 |
+
dataset_dict = DatasetDict({"train": split["train"], "validation": split["validation"]})
|
| 130 |
|
| 131 |
print(f"Train rows: {len(dataset_dict['train'])} | Validation rows: {len(dataset_dict['validation'])}")
|
| 132 |
+
print(f"Held-out compounds: {len(split['held_out_compounds'])}")
|
| 133 |
+
print("Active compound overlap between train and validation: 0%")
|
| 134 |
|
| 135 |
token = os.environ.get("HF_TOKEN")
|
| 136 |
+
print(f"Uploading molecule-disjoint DatasetDict to HF Hub: {repo_id} ...")
|
| 137 |
dataset_dict.push_to_hub(repo_id, private=True, token=token)
|
| 138 |
+
print("Dataset sync complete. Training partitions are fully live and molecule-disjoint.")
|
| 139 |
|
| 140 |
|
| 141 |
if __name__ == "__main__":
|
| 142 |
+
parser = argparse.ArgumentParser(description="Molecule-disjoint dataset split and upload for PINO")
|
| 143 |
+
parser.add_argument("--jsonl", default="data/synthetic_dataset_v2_text.jsonl", help="Input JSON-L corpus")
|
| 144 |
+
parser.add_argument("--repo-id", default="mattbitzesty/pino-synthetic-dataset", help="HF Hub dataset repo")
|
| 145 |
+
parser.add_argument("--val-ratio", type=float, default=0.2, help="Fraction of compounds to hold out")
|
| 146 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed for hold-out selection")
|
| 147 |
+
parser.add_argument("--solvent-cas", default="64-17-5", help="CAS number of the universal solvent")
|
| 148 |
+
parser.add_argument("--log-level", default="INFO", help="Logging level")
|
| 149 |
+
args = parser.parse_args()
|
| 150 |
+
|
| 151 |
+
logging.basicConfig(
|
| 152 |
+
level=getattr(logging, args.log_level.upper(), logging.INFO),
|
| 153 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
split_and_upload_dataset(
|
| 157 |
+
jsonl_path=args.jsonl,
|
| 158 |
+
repo_id=args.repo_id,
|
| 159 |
+
val_ratio=args.val_ratio,
|
| 160 |
+
seed=args.seed,
|
| 161 |
+
solvent_cas=args.solvent_cas,
|
| 162 |
)
|